- 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);
}
}