区块链学堂(28):用Mapping来实现一个简单的代币合约

在上一节里面我们通过mapping (bytes32 => uint) public balances; 实现了一个简单的mapping的hashtable. 但这样的hashTable无法部署在geth上面,也无法完成互相之间的代币转化。

这一节中我们将从0开始,撰写一个简单的合约

  • Step 1: 创建一个基础合约
pragma solidity 0.4.7;

contract Coin {
    address public minter;
    mapping (address => uint) public balances;
}

这里我们定义了一个address 作为key, uint做为value的hashTable balances; 我们还定义了一个address的变量minter;

  • Step 2: 添加一个构造函数Coin()
    function Coin() {
        minter = msg.sender;
    }

这里的代码minter = msg.sender; 代表创建这个合约的账户地址,被赋值给变量minter.

  • Step 3: 添加一个挖矿合约
      function mint(address receiver, uint amount) {
          if (msg.sender != minter) throw;
          balances[receiver] += amount;
      }
    

这里的核心代码在于,如果调用这个方法的账户,不是minter, 也就是创建合约的账户的话,这个mint()将无法被执行。 只有是创建合约的账户,也就是minter 才可以执行它

  • Step 4: 添加一个function send() 也就是从A转移X代币到B账户。代码如下:
      function send(address receiver, uint amount) {
          if (balances[msg.sender] < amount) return;
          balances[msg.sender] -= amount;
          balances[receiver] += amount;
      }
    

这个非常简单的转移货币的代码,也就是说msg.sender减少一定代币,接受者receiver增加一定代币

  • Step 5: 定义一个事件 Sent()
      event Sent(address from, address to, uint amount);
    
      function send(address receiver, uint amount) {
          if (balances[msg.sender] < amount) return;
          balances[msg.sender] -= amount;
          balances[receiver] += amount;
          Sent(msg.sender, receiver, amount);
      }
    
完整代码如下:
pragma solidity 0.4.7;

contract Coin {
    address public minter;
    mapping (address => uint) public balances;

    event Sent(address from, address to, uint amount);

    function Coin() {
        minter = msg.sender;
    }

    function mint(address receiver, uint amount) {
        if (msg.sender != minter) throw;
        balances[receiver] += amount;
    }

    function send(address receiver, uint amount) {
        if (balances[msg.sender] < amount) return;
        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        Sent(msg.sender, receiver, amount);
    }
}

QQ群:559649971 (区块链学堂粉丝群)
个人微信:steven_k_colin

获取最新区块链咨询,请关注《以太中文网》微信公众号:以太中文网

 

为您推荐