1. Abstract

[Objective of this paper]

Lead a technical expert step by step to complete the presentation and online transaction of a digital currency (TOKEN, TOKEN, TOKEN) through step-by-step guidance and screenshot proof.

【 Environmental preconditions 】

Refer to “Lesson 6 How to Develop a DAPP Blockchain Application (Take Pet Store as an example)”, have completed the installation and configuration of MetaMask light wallet client in local WIDOWS environment; The authors suggest that it is best to follow the order of the course from the beginning. However, if you want to halfway insert practical learning, the problem is not big, when encountering obstacles to find the corresponding article reverse guidance content can be completed.

[Technology Harvest]

From this practice, you can learn: ERC20 Token definition and practice writing smart contracts and compiling and debugging using the Remix Solidity IDE Complete wallet accounts using MetaMask View Complete Token transactions using the Web Wallet demo

[List of Practical Courses]

The first lesson is how to build the Ethereum development environment in the WINDOWS environment. The second lesson is how to realize the operation of the simplest ethereum smart contract “Hello World”. The fourth lesson is the Ethereum development framework Truffle from the entry to the actual combat. Lesson 7 How to debug smart contract crowdfunding for ethereum In 45 minutes Lesson 9 How to debug Solidity code in a Remix environment Lesson 10 Solidity Language editor

[Note] The courses not listed are non-practical courses for knowledge popularization. All blockchain articles refer to the “Blockchain Entry” column.

2. ERC20 Token definition and interface description

define

The ERC20 contract is a contract standard, a standard for token definition, which was proposed in EIP in November 2015. Tokens represent digital assets and have value, but not all conform to specific specifications. Erc20-based currencies are more interchangeable and work equally well on Dapps. The new standard could make tokens more compatible and allow for other features, including vote tokenization. The operation is more like a voting operation where Token holders have full control over the asset and ERC20 compliant tokens can track how many tokens anyone has at any one time. Eth contract based sub-currency, so easy to implement.

ERC20 Token interface description

methods

Note: The caller must handle returns (bool success) that return false. The caller must never assume that a return of false does not exist.

name

Return the name of the token, such as “MyToken”. Optional – This method can be used to improve availability, but interfaces and other contracts cannot expect these values to exist.

function name() constant returns (string name)
Copy the code

symbol

Return token symbols, such as HIX. Optional – This method can be used to improve availability, but interfaces and other contracts cannot expect these values to exist.

function symbol() constant returns (string symbol)
Copy the code

decimals

Returns the number of decimal places to which the token is used, such as 8, indicating that the number of tokens allocated is 100000000

Optional – This method can be used to improve availability, but interfaces and other contracts cannot expect these values to exist.

function decimals() constant returns (uint8 decimals)
Copy the code

totalSupply

Returns the total supply of tokens.

function totalSupply() constant returns (uint256 totalSupply)
Copy the code

balanceOf

Return the account balance for the account with address _owner.

function balanceOf(address _owner) constant returns (uint256 balance)
Copy the code

transfer

Transfer _value token quantity to address _to, and Transfer event must be triggered. If the _from account balance does not have enough tokens to spend, the function should be thrown.

The token contract that creates the new token should set the _FROM address to 0x0 when the token is created to trigger the transport event.

Note that the transfer of a value of 0 must be treated as a normal transfer and trigger the transfer event.

function transfer(address _to, uint256 _value) returns (bool success)
Copy the code

transferFrom

A Transfer event must be triggered to send tokens of value _from to address _to.

The transferFrom method is used to extract the workflow, allowing the contract to transfer tokens on your behalf. This can be used for example to allow contracts to transfer tokens on your behalf and/or charge fees in sub-currencies. This function should throw, except that the _from account has intentionally authorized the sender of the message through some mechanism.

Note that the transfer of a value of 0 must be treated as a normal transfer and trigger the transfer event.

function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
Copy the code

approve

Allow _spender to retrieve your account multiple times, up to a _value amount. If this function is called again, it overrides the current margin with _value.

Note: To prevent vector attacks, the client needs to make sure that the user interfaces are created in such a way that they are set to 0 and then set to another value for the same spender. Although the contract itself should not be enforced, backward compatibility with previously deployed contract compatibility is allowed

function approve(address _spender, uint256 _value) returns (bool success)
Copy the code

allowance

Returns the amount that _spender is still allowed to extract from _owner.

function allowance(address _owner, address _spender) constant returns (uint256 remaining)
Copy the code

Events

Transfer

When a token is transferred (including a value of 0), it must be triggered.

event Transfer(address indexed _from, address indexed _to, uint256 _value)
Copy the code

Approval

Must be triggered after any successful call to approve(address _spender, uint256 _value).

event Approval(address indexed _owner, address indexed _spender, uint256 _value)
Copy the code

[website interface description click to view],(github.com/ethereum/EI…) The interface file erc20interface. sol is as follows:

contract ERC20Interface {

    string public constant name = "Token Name";
    string public constant symbol = "SYM"; uint8 public constant decimals = 18; // 18 is the most common number of Decimal Places // 0.0000000000000000001 tokensfunction totalSupply() public constant returns (uint);

    function balanceOf(address tokenOwner) public constant returns (uint balance);

    function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
    function approve(address spender, uint tokens) public returns (bool success);

    function transfer(address to, uint tokens) public returns (bool success);
    function transferFrom(address from, address to, uint tokens) public returns (bool success);


    event Transfer(address indexed from, address indexed to, uint tokens);
    event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
Copy the code

The contract file tokenerC20.sol is as follows:

Pragma solidity ^ 0.4.16; interface tokenRecipient {functionreceiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 { string public name; string public symbol; uint8 public decimals = 18; // decimals The number of decimal points available, the smallest token unit. Uint256 public totalSupply; Mapping (address => uint256) public balanceOf; Mapping (address => mapping (address => uint256)) public allowance; // the hash is used to notify the client of the transaction event Transfer(Address indexed from, Address indexed to, uint256 value); // Event Burn(Address indexed from, uint256 value); /** * initializes the construct */functionTokenERC20(uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply * 10 ** uint256(decimals); // The quota of the supply, which is related to the smallest token, is = number of coins * 10 ** decimals. balanceOf[msg.sender] = totalSupply; Name = tokenName; // symbol = tokenSymbol; // token token} /** * internal implementation of token transaction transfer */function_transfer(address _from, address _to, uint _value) internal {// Ensure that the target address is not 0x0, because 0x0 represents the destruction of require(_to! = 0x0); // check the sender balance require(balanceOf[_from] >= _value); // require(balanceOf[_to] + _value > balanceOf[_to]); Balances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Use assert to check code logic. assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * token transfer * Send '_value' tokens from create trader account to '_to' account ** @param _to receiver address * @param _value Transfer amount */functiontransfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * transfer of tokens between accounts * @param _from sender address * @param _to receiver address * @param _value Transfer amount */function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
        require(_value <= allowance[_from][msg.sender]);     // Check allowance
        allowance[_from][msg.sender] -= _value;
        _transfer(_from, _to, _value);
        return true; } /** * Sets the number of tokens that an address (contract) can nominally spend. * * @param _spender The address authorized to spend * @param _value The Max amount they can spend */function approve(address _spender, uint256 _value) public
        returns (bool success) {
        allowance[msg.sender][_spender] = _value;
        return true; } /** * Sets the maximum number of tokens that an address (contract) can spend on behalf of the trader. * * @param _spender authorized address (contract) * @param _value Maximum number of tokens that can be spent * @param _extraData Additional data sent to the contract */function approveAndCall(address _spender, uint256 _value, bytes _extraData)
        public
        returns (bool success) {
        tokenRecipient spender = tokenRecipient(_spender);
        if (approve(_spender, _value)) {
            spender.receiveApproval(msg.sender, _value, this, _extraData);
            return true; }} /** * destroys the token specified in the creator's account */function burn(uint256 _value) public returns (bool success) {
        require(balanceOf[msg.sender] >= _value);   // Check if the sender has enough
        balanceOf[msg.sender] -= _value;            // Subtract from the sender
        totalSupply -= _value;                      // Updates totalSupply
        Burn(msg.sender, _value);
        return true; } /** * tokens from the system irreversibly on behalf of '_from'. ** @param _from the address of the sender * @param _value the amount of money to burn */function burnFrom(address _from, uint256 _value) public returns (bool success) {
        require(balanceOf[_from] >= _value);                // Check if the targeted balance is enough
        require(_value <= allowance[_from][msg.sender]);    // Check allowance
        balanceOf[_from] -= _value;                         // Subtract from the targeted balance
        allowance[_from][msg.sender] -= _value;             // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; }}Copy the code

Function function reference function description description and code self-interpretation.

4. Contract compile deployment and release

MetaMask wallet network

** The author assumes that the learner has completed the installation and configuration of MetaMask. For those that have not been completed, please refer to the chapter “lesson 6 How to Develop a DAPP blockchain Application (taking pet Store as an example)”. Install MetaMask and configure blockchain network “in local WIDOWS environment complete MetaMask light wallet client installation and configuration.

Open the MetaMask wallet and click “Ropsten Test Network” in the upper left corner to connect successfully.

0xD1F7922e8b78cBEB182250753ade8379d1E09949

Click on the menu “Create Account” in the top right corner of MetaMask’s circular avatar to Create a new wallet Account, Account 8.

The wallet address of Account 8 is recorded as

0x3D7DfB80E71096F2c4Ee63C42C4D849F2CBBE363

Click the “BUY” button on Account 8 to get some free Test ETH from the “Ropsten Test Network”.

[Troubleshooting]

Using the “Hello World” smart contract in lesson 2 as an example, see the following figure for compilation and syntax error finding.

2. Contract creation
Web link

3. Contract execution

** Therefore, without Ubuntu+Ganache, you can also use Remix+MetaMask+Ropsten Test Network to complete a complete set of Ethereum Test environment. Refer to lesson 10 Solidity Language Editor REMIX Guide for more detailed REMIX help documents

Open the Remix Solidity IDE for CHROME, open the previously written “Tokenerc20.sol” smart contract and click the “Start to compile” button on the right. As you can see, the smart contract compiled successfully, except for some Warning.

## Run ERC20 smart contract

Click the transaction record of Account 8 to jump to the display page of smart contract deployment information:

0x5eeec41dc08d7caece17c4a349635934637036f1

Click the “ADD TOKENS” button on the TOKENS page of MetaMask’s Account 8. The tokens, smart Contract Address Token Contract Address 0 x5eeec41dc08d7caece17c4a349635934637036f1, scrip identifier Token Symbol for CB, you can create your tokens.

Token query page

At the time of writing, the price of Ethereum is 2,559 yuan per unit, and you have 100 million CB coins, are you approaching the peak of your life? Ha ha, it was just a dream. The real blockchain application should have ecology and create value for human society, rather than telling stories and cutting leeks!

5. Token transactions

Since the MetaMask plugin doesn’t offer token transactions, and considering that many people don’t have ethereum wallets or suffer from network synchronization issues with Ethereum wallets, TODAY I’m going to use web wallets to explain token transactions. 1. Entering the webpage Wallet address There are some security tips that need to be confirmed by users when entering the webpage for the first time. 2. Set the parameters according to the following figure

3, adding custom tokens Fill in the address Token Contract of 0 x5eeec41dc08d7caece17c4a349635934637036f1 and other information, click save button.

infura.com

4. Transfer to the Account to fill in the Account 1 address xd1f7922e8b78cbeb182250753ade8379d1e09949 “0” to “sent to the address input box”,

6. Summarize the reference documents

This article is the operation practice standing on the shoulders of giants, thanks to the help of the following article authors:

  • Step by step guide to creating your own digital currency (token) for ICO
  • Tokens standard
  • Create your own crypto-currency with ethereum

Knowledge docking service: Brother Hui and Brother Ouyang have opened a block chain entry column in knowledge Planet, which is used to store the project source code and other content of the block chain entry column, and establish a special wechat group for technical exchange. Welcome to join.