Creando tokens Ethereum

0
1197

Índice

  1. Introducción
  2. Creando mis propios Tokens
  3. Desplegando el código a través de MetaMask
  4. Comprobando que se ha ejecutado correctamente
  5. Enviando tokens entre cuentas
  6. Conclusión

Introducción

Vamos a crear nuestros propios tokens Ethereum ERC20 en una red de pruebas.

He empezado una cadena de tutoriales sobre criptomonedas que pedéis seguir aquí:

Cómo comprar e invertir criptomonedas en Binance: https://adictosaltrabajo.com/2022/01/14/como-comprar-e-invertir-criptomonedas-en-binance/

Entendiendo las criptomonedas: https://adictosaltrabajo.com/2022/01/24/entendiendo-las-criptomonedas/

Votación con contratos inteligentes en Remix: https://adictosaltrabajo.com/2022/01/31/votacion-con-contratos-inteligentes-en-remix/

Usando la wallet MetaMask y la red local Ganache: https://adictosaltrabajo.com/2022/02/09/usando-la-wallet-metamask-y-la-red-local-ganache/

Compilación y despliegue de contratos inteligentes con Truffle y Ganache: https://adictosaltrabajo.com/2022/02/16/compilacion-y-despliegue-de-contratos-inteligentes-con-truffle-y-ganache/

Uno de los recursos que he empezado a seguir es https://cryptozombies.io/es/ que te va enseñando como ir trabajando con la tecnología. Pero en paralelo quiero ir haciendo pruebas complementarias.

Una de esas pruebas es crear mis propios tokens y he encontrado este tutorial «How To Create Your Own Ethereum Token In An Hour (ERC20 + Verified)» que voy a tratar de reproducir.

https://steemit.com/ethereum/@maxnachamkin/how-to-create-your-own-ethereum-token-in-an-hour-erc20-verified

La cosa parece fácil y básicamente los pasos son:

  • Usar el contrato creado por https://github.com/ConsenSys/Token-Factory para crear tu propio token (simplemente cambiando el valor de unas pocas variables).
  • Compilarlo en Remix.
  • Desplegarlo desde Remix en la red de pruebas usando tu monedero con contexto inyectado por MetaMask.

Como siempre con criptomonedas te entretienes un rato hasta que consigues que funcionen las cosas y hay que hacer alguna cosita más de la que encuentras en artículos más antiguos.

Creando mis propios Tokens

Lo primero que hacemos es localizar la fuente de https://github.com/ConsenSys/Token-Factory 

Este es el fichero fuente original de HumanStandardToken.sol

/*
This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20) as well as the following OPTIONAL extras intended for use by humans.

In other words. This is intended for deployment in something like a Token Factory or Mist wallet, and then used by humans.
Imagine coins, currencies, shares, voting weight, etc.
Machine-based, rapid creation of many tokens would not necessarily need these extra features or will be minted in other manners.

1) Initial Finite Supply (upon creation one specifies how much is minted).
2) In the absence of a token registry: Optional Decimal, Symbol & Name.
3) Optional approveAndCall() functionality to notify a contract if an approval() has occurred.

.*/
pragma solidity ^0.4.4;

import "./StandardToken.sol";

contract HumanStandardToken is StandardToken {

    function () {
        //if ether is sent to this address, send it back.
        throw;
    }

    /* Public variables of the token */

    /*
    NOTE:
    The following variables are OPTIONAL vanities. One does not have to include them.
    They allow one to customise the token contract & in no way influences the core functionality.
    Some wallets/interfaces might not even bother to look at this information.
    */
    string public name;                   //fancy name: eg Simon Bucks
    uint8 public decimals;                //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
    string public symbol;                 //An identifier: eg SBX
    string public version = 'H0.1';       //human 0.1 standard. Just an arbitrary versioning scheme.

    function HumanStandardToken(
        uint256 _initialAmount,
        string _tokenName,
        uint8 _decimalUnits,
        string _tokenSymbol
        ) {
        balances[msg.sender] = _initialAmount;               // Give the creator all initial tokens
        totalSupply = _initialAmount;                        // Update total supply
        name = _tokenName;                                   // Set the name for display purposes
        decimals = _decimalUnits;                            // Amount of decimals for display purposes
        symbol = _tokenSymbol;                               // Set the symbol for display purposes
    }

    /* Approves and then calls the receiving contract */
    function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);

        //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
        //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
        //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
        if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
        return true;
    }
}

Compilamos y, antes de hacer deploy, desplegamos para poder introducir los valores al constructor: cantidad de tokens, nombre, decimales y símbolo.

Hasta aquí ha ido todo bien, la única pega es que el código es antiguo y hay un montón de advertencias a corregir o actualizar.

Comprobado que nos ha funcionado, ahora vamos a intentar desplegarlo en una red de pruebas.

Para ello, necesitamos un contexto de aplicación distribuida, por lo que podemos usar nuestro monedero MetaMask.

Desplegando el código a través de MetaMask

Aunque ya lo hemos hecho antes, lo voy a reproducir desde el principio. 

Nos vamos a descargar en chrome y el pluggin de MetaMask.

Podemos crear una cuenta o reciclar una antigua. 

Si tenemos nuestra fase secreta podemos importarla.

Ya podemos ver nuestra cuenta en la red de pruebas de Ropsten (recordad que si no veis las redes de prueba tenéis que ir a los settings a activar que se vean).

Ahora vamos a utilizar el contexto inyectado por MetaMask. Vamos a deploy en Remix.

Introducimos la contraseña de nuestra cuenta MetaMask.

De primeras vamos a hacer un pequeño cambio en el código para anular el constructor e inicializar las variables a nuestros valores deseados.

    string public name = "RCTOKEN01";    // fancy name: eg Simon Bucks
    uint8 public decimals = 2 ;          // How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
    uint8 public initialAmount = 100 ;   // Cantidad inicial.
    string public symbol = "RCT1" ;      // An identifier: eg SBX
    string public version = 'H0.1';      // human 0.1 standard. Just an arbitrary versioning scheme.


    function HumanStandardToken() {
        balances[msg.sender] = initialAmount;               // Give the creator all initial tokens
        totalSupply = initialAmount;                        // Update total supply
   }

Pulsamos la opción de deploy

Este es el fichero HumanStandardToken.sol

/*
This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20) as well as the following OPTIONAL extras intended for use by humans.

In other words. This is intended for deployment in something like a Token Factory or Mist wallet, and then used by humans.
Imagine coins, currencies, shares, voting weight, etc.
Machine-based, rapid creation of many tokens would not necessarily need these extra features or will be minted in other manners.

1) Initial Finite Supply (upon creation one specifies how much is minted).
2) In the absence of a token registry: Optional Decimal, Symbol & Name.
3) Optional approveAndCall() functionality to notify a contract if an approval() has occurred.

.*/
pragma solidity ^0.4.4;

import "./StandardToken.sol";

contract HumanStandardToken is StandardToken {

    /*
    NOTE:
    The following variables are OPTIONAL vanities. One does not have to include them.
    They allow one to customise the token contract & in no way influences the core functionality.
    Some wallets/interfaces might not even bother to look at this information.
    */
    string public name = "RCTOKEN01";    // fancy name: eg Simon Bucks
    uint8 public decimals = 2 ;          // How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
    uint8 public initialAmount = 100 ;   // Cantidad inicial.
    string public symbol = "RCT1" ;      // An identifier: eg SBX
    string public version = 'H0.1';      // human 0.1 standard. Just an arbitrary versioning scheme.


    function HumanStandardToken() {
        balances[msg.sender] = initialAmount;               // Give the creator all initial tokens
        totalSupply = initialAmount;                        // Update total supply
   }

    /* Approves and then calls the receiving contract */
    function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);

        //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
        //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
        //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
        if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
        return true;
    }
}

Ahora el fichero Token.sol (que no he tocado).

pragma solidity ^0.4.4;

contract Token {

    /// @return total amount of tokens
    function totalSupply() constant returns (uint256 supply) {}

    /// @param _owner The address from which the balance will be retrieved
    /// @return The balance
    function balanceOf(address _owner) constant returns (uint256 balance) {}

    /// @notice send `_value` token to `_to` from `msg.sender`
    /// @param _to The address of the recipient
    /// @param _value The amount of token to be transferred
    /// @return Whether the transfer was successful or not
    function transfer(address _to, uint256 _value) returns (bool success) {}

    /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
    /// @param _from The address of the sender
    /// @param _to The address of the recipient
    /// @param _value The amount of token to be transferred
    /// @return Whether the transfer was successful or not
    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}

    /// @notice `msg.sender` approves `_addr` to spend `_value` tokens
    /// @param _spender The address of the account able to transfer the tokens
    /// @param _value The amount of wei to be approved for transfer
    /// @return Whether the approval was successful or not
    function approve(address _spender, uint256 _value) returns (bool success) {}

    /// @param _owner The address of the account owning tokens
    /// @param _spender The address of the account able to transfer the tokens
    /// @return Amount of remaining tokens allowed to spent
    function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}

    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}

Y el fichero StandardToken.sol

/*
This implements ONLY the standard functions and NOTHING else.
For a token like you would want to deploy in something like Mist, see HumanStandardToken.sol.

If you deploy this, you won't have anything useful.

Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20
.*/

pragma solidity ^0.4.4;

import "./Token.sol";

contract StandardToken is Token {

    function transfer(address _to, uint256 _value) returns (bool success) {
        //Default assumes totalSupply can't be over max (2^256 - 1).
        //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
        //Replace the if with this one instead.
        //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
        if (balances[msg.sender] >= _value && _value > 0) {
            balances[msg.sender] -= _value;
            balances[_to] += _value;
            Transfer(msg.sender, _to, _value);
            return true;
        } else { return false; }
    }

    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
        //same as above. Replace this line with the following if you want to protect against wrapping uints.
        //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
        if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
            balances[_to] += _value;
            balances[_from] -= _value;
            allowed[_from][msg.sender] -= _value;
            Transfer(_from, _to, _value);
            return true;
        } else { return false; }
    }

    function balanceOf(address _owner) constant returns (uint256 balance) {
        return balances[_owner];
    }

    function approve(address _spender, uint256 _value) returns (bool success) {
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);
        return true;
    }

    function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
      return allowed[_owner][_spender];
    }

    mapping (address => uint256) balances;
    mapping (address => mapping (address => uint256)) allowed;
    uint256 public totalSupply;
}

Este es el fichero ABI que se genera para interactuar programáticamente con la aplicación (eso lo haremos en otro momento).

ABI: [
	{
		"constant": true,
		"inputs": [],
		"name": "name",
		"outputs": [
			{
				"name": "",
				"type": "string"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": false,
		"inputs": [
			{
				"name": "_spender",
				"type": "address"
			},
			{
				"name": "_value",
				"type": "uint256"
			}
		],
		"name": "approve",
		"outputs": [
			{
				"name": "success",
				"type": "bool"
			}
		],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "totalSupply",
		"outputs": [
			{
				"name": "",
				"type": "uint256"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": false,
		"inputs": [
			{
				"name": "_from",
				"type": "address"
			},
			{
				"name": "_to",
				"type": "address"
			},
			{
				"name": "_value",
				"type": "uint256"
			}
		],
		"name": "transferFrom",
		"outputs": [
			{
				"name": "success",
				"type": "bool"
			}
		],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "decimals",
		"outputs": [
			{
				"name": "",
				"type": "uint8"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "version",
		"outputs": [
			{
				"name": "",
				"type": "string"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [
			{
				"name": "_owner",
				"type": "address"
			}
		],
		"name": "balanceOf",
		"outputs": [
			{
				"name": "balance",
				"type": "uint256"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "symbol",
		"outputs": [
			{
				"name": "",
				"type": "string"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": false,
		"inputs": [
			{
				"name": "_to",
				"type": "address"
			},
			{
				"name": "_value",
				"type": "uint256"
			}
		],
		"name": "transfer",
		"outputs": [
			{
				"name": "success",
				"type": "bool"
			}
		],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"constant": false,
		"inputs": [
			{
				"name": "_spender",
				"type": "address"
			},
			{
				"name": "_value",
				"type": "uint256"
			},
			{
				"name": "_extraData",
				"type": "bytes"
			}
		],
		"name": "approveAndCall",
		"outputs": [
			{
				"name": "success",
				"type": "bool"
			}
		],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [
			{
				"name": "_owner",
				"type": "address"
			},
			{
				"name": "_spender",
				"type": "address"
			}
		],
		"name": "allowance",
		"outputs": [
			{
				"name": "remaining",
				"type": "uint256"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "initialAmount",
		"outputs": [
			{
				"name": "",
				"type": "uint8"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "constructor"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"name": "_from",
				"type": "address"
			},
			{
				"indexed": true,
				"name": "_to",
				"type": "address"
			},
			{
				"indexed": false,
				"name": "_value",
				"type": "uint256"
			}
		],
		"name": "Transfer",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"name": "_owner",
				"type": "address"
			},
			{
				"indexed": true,
				"name": "_spender",
				"type": "address"
			},
			{
				"indexed": false,
				"name": "_value",
				"type": "uint256"
			}
		],
		"name": "Approval",
		"type": "event"
	}
]

Al desplegar con MetaMask podemos elegir la cuenta.

Nos confirma la operación.

No informa que vamos a lanzar un contrato con la cuenta 1 y el coste estimado en gas.

Comprobando que se ha ejecutado correctamente

Podemos verificar que se ha ejecutado correctamente porque nos responderá a las interacciones con los botones.

Podemos ir a MetaMask para comprobar la actividad (hay que esperar un poquito e incluso refrescar).

Podemos saltar a Etherscan (ver Block explorer) para ver el contrato.

En MetaMask es muy posible que no se vean los tokens en la cuenta. Hay que pinchar un enlace de Import token.

Con el identificador del contrato, del token y decimales podemos visualizarlos.

Aparece que tengo un token (novatada de los decimales).

Enviando tokens entre cuentas

Puedo crear o importar una segunda cuenta para hacer la transferencia.

Y podemos transferir de una cuenta a otra.

Y ver el resultado de la transacción.

En Etherscan podemos ver todas las transacciones.

Y si no nos aparecen en nuestra cuenta utilizar la información del contrato para importarlo, tal como hicimos la primera vez.

Y comprobamos en MetaMask el resultado.

Conclusión

Bueno, ya hemos conseguido generar unos tokens básicos y transferirlos.

A todos los efectos hemos creado una especie de “moneda” dentro de la red de pruebas Ethereum. 

Ahora tendremos que investigar un poquito más para utilizar otros tipos de tokens o colecciones de tokens diferenciados o NFT, si queremos usarlos para asociarlos a activos concretos.

DEJA UNA RESPUESTA

Por favor ingrese su comentario!

He leído y acepto la política de privacidad

Por favor ingrese su nombre aquí

Información básica acerca de la protección de datos

  • Responsable:
  • Finalidad:
  • Legitimación:
  • Destinatarios:
  • Derechos:
  • Más información: Puedes ampliar información acerca de la protección de datos en el siguiente enlace:política de privacidad