Detailed explanation of Ethereum token development

Detailed explanation of Ethereum token development

This article is excerpted from the Netkiller Blockchain Notebook

Netkiller Blockchain 手札

The author of this article is looking for a job recently and is interested in calling 13113668890

Mr. Neo Chan, Chen Jingfeng (BG7NYT)

Xishan Meidi, Minzhi Street, Longhua New District, Shenzhen, Guangdong, China 518131 +86 13113668890<[email protected]>

The document was created on 2018-02-10

Copyright © 2018 Netkiller(Neo Chan). All rights reserved.

Copyright Notice

Please contact the author for reprinting. When reprinting, please be sure to indicate the original source of the article, author information and this statement.

 

 

http: //www.netkiller.cnhttp: //netkiller.github.iohttp: //netkiller.sourceforge.net

http://www.netkiller.cn

http://netkiller.github.io

http://netkiller.sourceforge.net

 

 

WeChat subscription number netkiller-ebook (Scan QR code on WeChat) QQ: 13721218 Please indicate "reader" QQ group: 128659835 Please indicate "reader"

WeChat subscription account netkiller-ebook (Scan QR code on WeChat)

QQ: 13721218 Please indicate "reader"

QQ group: 128659835 Please indicate "reader"

 

http://www.netkiller.cn

http://netkiller.github.io

http://netkiller.sourceforge.net

 

WeChat subscription account netkiller-ebook (Scan QR code on WeChat)

QQ: 13721218 Please indicate "reader"

QQ group: 128659835 Please indicate "reader"

$Data$

abstract

This e-book about blockchain development and operations.

Why write a blockchain e-book? Because 2018 is the year of blockchain.

Will this ebook be published (paper book)? No, because Internet technology is changing too fast, the content of paper books cannot be updated in real time. A book can easily become rubbish at a cost of 100 yuan. You will find that the current blockchain books on the market were written at least a year ago. , the content is outdated, and many examples do not work correctly. So I will not publish, the content of the e-book will follow the technological development, follow up the upgrade of the software version in time, and keep the content up-to-date, at least mainstream.

How is this eBook different from other blockchain books? Most of the blockchain books on the market use 2/3 to talk about the principles of blockchain. As long as less than 1/3 of the dry goods are not enough for theory, the whole article will discuss the theory or talk about the blockchain industry. , these contents are more of brainstorming and looking forward to the blockchain, but they cannot be implemented. This book is completely different from those books. It does not talk about theories and principles. It is application-oriented and focuses on examples. They are all dry goods.

How often are eBooks updated? New content will be added every day, and the update frequency will not exceed one week at the latest. Please follow https://github.com/netkiller/netkiller.github.io/commits/master for updated content

This article is written in fragments, the original text will be updated from time to time, please try to read the original text.

http://www.netkiller.cn/blockchain/index.html

9.4. Creating Tokens

https://ethereum.org/token

9.4.1. Contract Documents

pragma solidity ^ 0.4.16;

interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }

contract TokenERC20 {
    // Public variables of the token
    string public name;
    string public symbol;
    uint8 public decimals = 18;
    // 18 decimals is the strongly suggested default, avoid changing it
    uint256 public totalSupply;

    // This creates an array with all balances
    mapping (address => uint256) public balanceOf;
    mapping (address => mapping (address => uint256)) public allowance;

    // This generates a public event on the blockchain that will notify clients
    event Transfer(address indexed from, address indexed to, uint256 value);

    // This notifies clients about the amount burnt
    event Burn(address indexed from, uint256 value);

    /**
     * Constrctor function
     *
     * Initializes contract with initial supply tokens to the creator of the contract
     */
    function TokenERC20(
        uint256 initialSupply,
        string tokenName,
        string tokenSymbol
    ) public {
        totalSupply = initialSupply * 10 ** uint256(decimals);  // Update total supply with the decimal amount
        balanceOf[msg.sender] = totalSupply;                // Give the creator all initial tokens
        name = tokenName;                                   // Set the name for display purposes
        symbol = tokenSymbol;                               // Set the symbol for display purposes
    }

    /**
     * Internal transfer, only can be called by this contract
     */
    function _transfer(address _from, address _to, uint _value) internal {
        // Prevent transfer to 0x0 address. Use burn() instead
        require(_to != 0x0);
        // Check if the sender has enough
        require(balanceOf[_from] >= _value);
        // Check for overflows
        require(balanceOf[_to] + _value > balanceOf[_to]);
        // Save this for an assertion in the future
        uint previousBalances = balanceOf[_from] + balanceOf[_to];
        // Subtract from the sender
        balanceOf[_from] -= _value;
        // Add the same to the recipient
        balanceOf[_to] += _value;
        Transfer(_from, _to, _value);
        // Asserts are used to use static analysis to find bugs in your code. They should never fail
        assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
    }

    /**
     * Transfer tokens
     *
     * Send `_value` tokens to `_to` from your account
     *
     * @param _to The address of the recipient
     * @param _value the amount to send
     */
    function transfer(address _to, uint256 _value) public {
        _transfer(msg.sender, _to, _value);
    }

    /**
     * Transfer tokens from other address
     *
     * Send `_value` tokens to `_to` on behalf of `_from`
     *
     * @param _from The address of the sender
     * @param _to The address of the recipient
     * @param _value the amount to send
     */
    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;
    }

    /**
     * Set allowance for other address
     *
     * Allows `_spender` to spend no more than `_value` tokens on your behalf
     *
     * @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;
    }

    /**
     * Set allowance for other address and notify
     *
     * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
     *
     * @param _spender The address authorized to spend
     * @param _value the max amount they can spend
     * @param _extraData some extra information to send to the approved contract
     */
    function approveAndCall(address _spender, uint256 _value, bytes _extraData)
        public
        returns (bool success) {
        tokenRecipient dispenser = tokenRecipient(_spender);
        if (approve(_spender, _value)) {
            spender.receiveApproval(msg.sender, _value, this, _extraData);
            return true;
        }
    }

    /**
     * Destroy tokens
     *
     * Remove `_value` tokens from the system irreversibly
     *
     * @param _value the amount of money to burn
     */
    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;
    }

    /**
     * Destroy tokens from other account
     *
     * Remove `_value` 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;
    }
}

9.4.2. Deploying contracts

Start Ethereum Wallet, click the CONTRACTS button to enter the contract management interface

 

Click the DEPLOY NEW CONTRACT button to deploy a new contract

Copy and paste the contract file under SOLIDITY CONTRACT SOURCE CODE

SELECT CONTRACT TO DEPLOY list select "Token ERC 20"

Initial supply is the initial issued currency amount

Token name is the token name

Token symbol is the token symbol

 

Pull the scroll button, find the "DEPLOY" button below, and click the button.

 

Enter the account password and click the "SEND TRANSACTION" button.

 

ERC20 token creation completed

9.4.3. Token transfer

Enter the wallet to see the amount of ether in the current account, and you can also see the ERC20 tokens below.

 

Click the SEND button

 

Fill in the TO address and 500 tokens, click the SEND button

 

Enter the target account to check the balance.

 

So far, we have completed the deployment of the token contract and realized the account-to-account transfer. Let's talk about how to develop it.

Ethereum development refers to the use of programs to transfer tokens, because it is impossible for us to manually transfer money using wallets. Landing the token needs to be done in the program.

Usually the program is deployed on the WEB server. For example, in such a scenario, the user registers and opens an account on the website and presents a certain amount of token rewards.

At this time, we need to use WEB3.js (Node) or WEB3J (Java API) to complete the website or mobile APP to access Ethereum and complete the token transfer.

 

6.10.4. ERC20 Example

Token transfer via Web3

fs = require('fs');
const Web3 = require('web3');
const web3 = new Web3('http://localhost:8545');
web3.version
const abi = fs.readFileSync('netkiller/TokenERC20.abi', 'utf-8');

const contractAddress = "0x05A97632C197a0496bc939C4e666c2E03Cb95DD4";
const toAddress = "0x2C687bfF93677D69bd20808a36E4BC2999B4767C";

var coinbase;

web3.eth.getCoinbase().then(function (address){
  coinbase = address;
  console.log(address);
});

const contract = new web3.eth.Contract(JSON.parse(abi), contractAddress, { from: coinbase , gas: 100000});

contract.methods.balanceOf('0x5c18a33DF2cc41a1bedDC91133b8422e89f041B7').call().then(console.log).catch(console.error);
contract.methods.balanceOf('0x2C687bfF93677D69bd20808a36E4BC2999B4767C').call().then(console.log).catch(console.error);

web3.eth.personal.unlockAccount(coinbase, "Netkiller").then(console.log);
contract.methods.transfer('0x2C687bfF93677D69bd20808a36E4BC2999B4767C', 100).send().then(console.log).catch(console.error);

contract.methods.balanceOf('0x2C687bfF93677D69bd20808a36E4BC2999B4767C').call().then(console.log).catch(console.error);

The above code is pure dry goods. The most common example you see on the Internet is that the wallet completes the contract. No one provides web3 code to complete the same operation. I also scoured the Internet and couldn't find any information. This is what I have worked hard to figure out. If there is something I don't understand, go to my QQ group to discuss it.

The above examples use the latest version

geth 1.8.1

web3.js 1.0.0-beta30

groove Version: 0.4.20

If the above information is useful to you, reward the address: http://www.netkiller.cn/home/donations.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324413859&siteId=291194637