ERC20 Token Solidity 0.4.23

Netkiller Blockchain 手札

本文作者最近在找工作,有意向致电 13113668890

Mr. Neo Chan, 陈景峯(BG7NYT)

中国广东省深圳市龙华新区民治街道溪山美地 518131 +86 13113668890 <netkiller@msn.com>

文档始创于2018-02-10

版权 © 2018 Netkiller(Neo Chan). All rights reserved.

版权声明

转载请与作者联系,转载时请务必标明文章原始出处和作者信息及本声明。

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

http://www.netkiller.cn

http://netkiller.github.io

http://netkiller.sourceforge.net

微信订阅号 netkiller-ebook (微信扫描二维码)QQ:13721218 请注明“读者”QQ群:128659835 请注明“读者”

微信订阅号 netkiller-ebook (微信扫描二维码)

QQ:13721218 请注明“读者”

QQ群:128659835 请注明“读者”

http://www.netkiller.cn

http://netkiller.github.io

http://netkiller.sourceforge.net

微信订阅号 netkiller-ebook (微信扫描二维码)

QQ:13721218 请注明“读者”

QQ群:128659835 请注明“读者”

$Data$

内容摘要

这一部关于区块链开发及运维的电子书。

为什么会写区块链电子书?因为2018年是区块链年,区块链是一个风口,前几个风口我都错过了。例如web2.0, 云, 大数据等等,都从身旁擦肩而过。所以我要抓住这次。

这本电子书是否会出版(纸质图书)? 不会,因为互联网技术更迭太快,纸质书籍的内容无法实时更新,一本书动辄百元,很快就成为垃圾,你会发现目前市面的上区块链书籍至少是一年前写的,内容已经过时,很多例子无法正确运行。所以我不会出版,电子书的内容会追逐技术发展,及时跟进软件版本的升级,做到内容最新,至少是主流。

这本电子书与其他区块链书籍有什么不同?市面上大部分区块链书籍都是用2/3去讲区块链原理,只要不到 1/3 的干货,干货不够理论来凑,通篇将理论或是大谈特谈区块链行业,这些内容更多是头脑风暴,展望区块链,均无法落地实施。本书与那些书籍完全不同,不讲理论和原理,面向应用落地,注重例子,均是干货。

写作原则,无法落地的项目作者绝对不会写。凡是写入电子的内容均具备可操作,可落地。

电子书更新频率?每天都会有新内容加入,更新频率最迟不会超过一周,更新内容请关注 https://github.com/netkiller/netkiller.github.io/commits/master

本文采用碎片化写作,原文会不定期更新,请尽量阅读原文。

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

您的打赏是我的写作动力:http://www.netkiller.cn/blockchain/donations.html

接受 ETH 打赏:0x3e827461Cc53ed7c75A29187CfF39629FCAE3661

5.2. ERC20 Token Solidity 0.4.23

5.2.1. 构造方法

原合约

pragma solidity ^0.4.21;

contract NetkillerToken {
  address public owner;
  string public name;
  string public symbol;
  uint public decimals;
  uint256 public totalSupply;

  event Transfer(address indexed from, address indexed to, uint256 value);

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

  function NetkillerToken(uint256 initialSupply, string tokenName, string tokenSymbol, uint decimalUnits) public {
    owner = msg.sender;
    name = tokenName;
    symbol = tokenSymbol;
    decimals = decimalUnits;
    totalSupply = initialSupply * 10 ** uint256(decimals);
    balanceOf[msg.sender] = totalSupply;
  }

  /* Send coins */
  function transfer(address _to, uint256 _value) public {
    /* Check if the sender has balance and for overflows */
    require(balanceOf[msg.sender] >= _value && balanceOf[_to] + _value >= balanceOf[_to]);

    /* Add and subtract new balances */
    balanceOf[msg.sender] -= _value;
    balanceOf[_to] += _value;

    /* Notify anyone listening that this transfer took place */
    emit Transfer(msg.sender, _to, _value);
  }
}

新版合约

pragma solidity ^0.4.23;

contract NetkillerToken {
  address public owner;
  string public name;
  string public symbol;
  uint public decimals;
  uint256 public totalSupply;

  event Transfer(address indexed from, address indexed to, uint256 value);

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

  constructor(uint256 initialSupply, string tokenName, string tokenSymbol, uint decimalUnits) public {
    owner = msg.sender;
    name = tokenName;
    symbol = tokenSymbol;
    decimals = decimalUnits;
    totalSupply = initialSupply * 10 ** uint256(decimals);
    balanceOf[msg.sender] = totalSupply;
  }

  /* Send coins */
  function transfer(address _to, uint256 _value) public {
    /* Check if the sender has balance and for overflows */
    require(balanceOf[msg.sender] >= _value && balanceOf[_to] + _value >= balanceOf[_to]);

    /* Add and subtract new balances */
    balanceOf[msg.sender] -= _value;
    balanceOf[_to] += _value;

    /* Notify anyone listening that this transfer took place */
    emit Transfer(msg.sender, _to, _value);
  }
}

5.2.2. 官方规定 Method 方法

所有的ERC20代币都是按照下面这些方法来定义的。下面我们讲解一下每个方法的作用。

5.2.2.1. name

function name() view public returns (string name)

返回string类型的ERC20代币的名字,例如:Netkiller Reader Coin

5.2.2.2. symbol

function symbol() view public returns (string symbol)

返回string类型的ERC20代币的符号,也就是代币的简称,例如:NRC。

5.2.2.3. decimals

function decimals() view public returns (uint decimals)

支持几位小数点后几位。如果设置为3。也就是支持0.001表示。

5.2.2.4. totalSupply

function totalSupply() view public returns (uint256 totalSupply)

发行代币的总量,可以通过这个函数来获取。所有智能合约发行的代币总量是一定的,totalSupply必须设置初始值。

5.2.2.5. balanceOf

function balanceOf(address _owner) public returns (uint256 balance)

输入地址,可以获取该地址代币的余额。

5.2.2.6. transfer

function transfer(address _to, uint256 _value) public returns (bool success)

调用transfer函数将自己的token转账给_to地址,_value为转账金额

5.2.2.7. approve

function approve(address _spender, uint256 _value) public returns (bool success)

批准_spender账户从自己的账户转移_value个token。可以分多次转移。

5.2.2.8. transferFrom

function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)

与approve搭配使用,approve批准之后,调用transferFrom函数来转移token。

5.2.2.9. allowance

function allowance(address _owner, address _spender) public returns (uint256 remaining)

返回_spender还能提取token的个数。

approve、transferFrom及allowance解释:账户A有1000个代币,想允许B账户随意调用100个代币。A账户按照以下形式调用approve函数approve(B,100)。当B账户想用这100个代币中的10个代币给C账户时,则调用transferFrom(A, C, 10)。这时调用allowance(A, B)可以查看B账户还能够调用A账户多少个token。

5.2.3. 事件

5.2.3.1. Transfer

event Transfer(address indexed _from, address indexed _to, uint256 _value)

当成功转移token时,一定要触发Transfer事件

5.2.3.2. Approval

event Approval(address indexed _owner, address indexed _spender, uint256 _value)

当调用approval函数成功时,一定要触发Approval事件

完整的例子

https://etherscan.io/address/0x6333050c7a025027b51a8039cbafd2584933299d#code

pragma solidity ^0.4.21;

/******************************************/
/*       Netkiller ADVANCED TOKEN         */
/******************************************/
/* Author netkiller <netkiller@msn.com>   */
/* Home http://www.netkiller.cn           */
/* Version 2018-05-09 - Add Global lock   */
/******************************************/

contract NetkillerToken {
    address public owner;
    // Public variables of the token
    string public name;
    string public symbol;
    uint public decimals;
    // 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);
    event Approval(address indexed owner, address indexed spender, uint256 value);
    
    mapping (address => bool) public frozenAccount;

    /* This generates a public event on the blockchain that will notify clients */
    event FrozenFunds(address target, bool frozen);

    bool lock = false;

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

    modifier onlyOwner {
        require(msg.sender == owner);
        _;
    }

    modifier isLock {
        require(!lock);
        _;
    }
    
    function setLock(bool _lock) onlyOwner public{
        lock = _lock;
    }

    function transferOwnership(address newOwner) onlyOwner public {
        if (newOwner != address(0)) {
            owner = newOwner;
        }
    }
 
    /* Internal transfer, only can be called by this contract */
    function _transfer(address _from, address _to, uint _value) isLock internal {
        require (_to != 0x0);                               // Prevent transfer to 0x0 address. Use burn() instead
        require (balanceOf[_from] >= _value);               // Check if the sender has enough
        require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
        require(!frozenAccount[_from]);                     // Check if sender is frozen
        require(!frozenAccount[_to]);                       // Check if recipient is frozen
        balanceOf[_from] -= _value;                         // Subtract from the sender
        balanceOf[_to] += _value;                           // Add the same to the recipient
        emit Transfer(_from, _to, _value);
    }

    /**
     * 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` in 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 in 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;
        emit Approval(msg.sender, _spender, _value);
        return true;
    }

    /**
     * Destroy tokens
     *
     * Remove `_value` tokens from the system irreversibly
     *
     * @param _value the amount of money to burn
     */
    function burn(uint256 _value) onlyOwner 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
        emit 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) onlyOwner 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
        emit Burn(_from, _value);
        return true;
    }

    /// @notice Create `mintedAmount` tokens and send it to `target`
    /// @param target Address to receive the tokens
    /// @param mintedAmount the amount of tokens it will receive
    function mintToken(address target, uint256 mintedAmount) onlyOwner public {
        uint256 _amount = mintedAmount * 10 ** uint256(decimals);
        balanceOf[target] += _amount;
        totalSupply += _amount;
        emit Transfer(this, target, _amount);
    }

    /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
    /// @param target Address to be frozen
    /// @param freeze either to freeze it or not
    function freezeAccount(address target, bool freeze) onlyOwner public {
        frozenAccount[target] = freeze;
        emit FrozenFunds(target, freeze);
    }
}

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏web前端教室

对JS要有爱;JS才会活过来

(今天又喝酒去了,所以今晚的文章写的有点飘~~) 从某种程度上来讲,写JS脚本,和写文章是一样的。都是有时间、地点、人物、事件。 时间用Date()获取;地点用...

20470
来自专栏Python小屋

使用Python对图像进行中值滤波

首先解答上一篇文章Python使用标准库subprocess调用外部程序中的问题,该题答案为['1', '2', '3', '4'],在正则表达式中,问号(?)...

2.4K110
来自专栏Kirito的技术分享

中文文案排版指南

目录 空格 中英文之间需要增加空格 中文与数字之间需要增加空格 数字与单位之间需要增加空格 全角标点与其他字符之间不加空格 -ms-text-autospac...

51880
来自专栏算法+

音频压缩编码 opus 附完整C++代码示例

绝大数人都知道mp3格式编码,以及aac,amr等压缩格式编码。 而在语音通信界有一个强悍的音频格式编码opus. 经过实测,压缩比最高可以达到1:10。 10...

91870
来自专栏java一日一条

Java常见异常及解释

常见 Java 异常解释:(译者注:非技术角度分析。阅读有风险,理解需谨慎:))

19520
来自专栏小樱的经验随笔

基于AOE网的关键路径的求解

【1】关键路径 在我的经验意识深处,“关键”二字一般都是指临界点。 凡事万物都遵循一个度的问题,那么存在度就会自然有临界点。 关键路径也正是研究这个临界点的问题...

83760
来自专栏CSDN技术头条

黑客与C语言

“黑客”这个词想必我们已经如雷贯耳了。我们一听到黑客通常在大脑中的印象就是一群穿着黑衣,躲在小屋里偷偷用着数台电脑针对某组计算机,神不知鬼不觉地进行攻击。他们通...

1.3K80
来自专栏区块链大本营

快讯 | 新型constructor函数使用漏洞,可致合约权限丢失、代币增发

据悉,Solidity 0.4.22版本在更新后,引入一种新的构造函数声明形式:constructor()public {},通过这种写法,可以避免在合约开发过...

11220
来自专栏java一日一条

Java常见异常及解释

11430
来自专栏数据结构与算法

03:不高兴的津津

03:不高兴的津津 总时间限制:1000ms内存限制:65536kB描述 津津上初中了。妈妈认为津津应该更加用功学习,所以津津除了上学之外,还要参加妈妈为她报名...

40850

扫码关注云+社区

领取腾讯云代金券