简单实现一个艾西欧

前面两篇文章,介绍了一个发布一个ERC20 Token,以及实现Token的流转问题。这次让我们来实现一个简单的艾西欧。艾西欧我们知道,当我们给以太坊智能合约地址发送ETH的时候,我们可以获得相应的Token。这个是怎么实现的呢?

在这之前,你需要掌握的基本知识:

  1. ERC20 Tokens 是什么
  2. 智能合约
  3. Solidity
  4. MetaMask 钱包

这些知识之前都有提到过,大家可以自行去查找相应的文档学习,这里就不在多坐介绍了。

首先一个艾西欧,其实也是一个智能合约,只不过这个智能合约在接受ETH后会给发送ETH的地址增加Token数量(此处只是简单的处理)。下面来看下代码:

pragma solidity ^0.4.4;

contract Token {

    /// @return total amount of tokens
    function totalSupply() constant returns (uint256 supply) {}

    /// @param _owner The address from which the balance will be retrieved
    /// @return The balance
    function balanceOf(address _owner) constant returns (uint256 balance) {}

    /// @notice send `_value` token to `_to` from `msg.sender`
    /// @param _to The address of the recipient
    /// @param _value The amount of token to be transferred
    /// @return Whether the transfer was successful or not
    function transfer(address _to, uint256 _value) returns (bool success) {}

    /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
    /// @param _from The address of the sender
    /// @param _to The address of the recipient
    /// @param _value The amount of token to be transferred
    /// @return Whether the transfer was successful or not
    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}

    /// @notice `msg.sender` approves `_addr` to spend `_value` tokens
    /// @param _spender The address of the account able to transfer the tokens
    /// @param _value The amount of wei to be approved for transfer
    /// @return Whether the approval was successful or not
    function approve(address _spender, uint256 _value) returns (bool success) {}

    /// @param _owner The address of the account owning tokens
    /// @param _spender The address of the account able to transfer the tokens
    /// @return Amount of remaining tokens allowed to spent
    function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}

    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    event Approval(address indexed _owner, address indexed _spender, uint256 _value);

}

contract StandardToken is Token {

    function transfer(address _to, uint256 _value) returns (bool success) {
        //Default assumes totalSupply can't be over max (2^256 - 1).
        //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
        //Replace the if with this one instead.
        //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
        if (balances[msg.sender] >= _value && _value > 0) {
            balances[msg.sender] -= _value;
            balances[_to] += _value;
            Transfer(msg.sender, _to, _value);
            return true;
        } else { return false; }
    }

    function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
        //same as above. Replace this line with the following if you want to protect against wrapping uints.
        //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
        if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
            balances[_to] += _value;
            balances[_from] -= _value;
            allowed[_from][msg.sender] -= _value;
            Transfer(_from, _to, _value);
            return true;
        } else { return false; }
    }

    function balanceOf(address _owner) constant returns (uint256 balance) {
        return balances[_owner];
    }

    function approve(address _spender, uint256 _value) returns (bool success) {
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);
        return true;
    }

    function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
      return allowed[_owner][_spender];
    }

    mapping (address => uint256) balances;
    mapping (address => mapping (address => uint256)) allowed;
    uint256 public totalSupply;
}

contract MyTestCoin is StandardToken { 

    /* Public variables of the token */

    /*
    NOTE:
    The following variables are OPTIONAL vanities. One does not have to include them.
    They allow one to customise the token contract & in no way influences the core functionality.
    Some wallets/interfaces might not even bother to look at this information.
    */
    string public name;                   // Token Name
    uint8 public decimals;                // How many decimals to show. To be standard complicant keep it 18
    string public symbol;                 // An identifier: eg SBX, XPR etc..
    string public version = '1.0'; 
    uint256 public unitsOneEthCanBuy;     // 1 eth 可以购买的token数量?
    uint256 public totalEthInWei;         // 募集到的所有ETH  
    address public fundsWallet;           // 保存资金的地址

    // This is a constructor function 
    // which means the following function name has to match the contract name declared above
    function MyTestCoin() {
        balances[msg.sender] = 1000000000000000000000;               // 合约创建者获得所有的token吗,这里是1000
        totalSupply = 1000000000000000000000;                        // 1000 总量
        name = "MyTestCoin";                                         // token名称
        decimals = 18;                                               // 小数点位
        symbol = "MTC";                                             // 标识
        unitsOneEthCanBuy = 10;                                      // 一个ETH 可以购买的token数量
        fundsWallet = msg.sender;                                    // 合约创建者默认是资金账户
    }

    // 其他地址向合约发送ETH,默认会执行这个方法
    function() payable{
        // 更新募集到的ETH总量
        totalEthInWei = totalEthInWei + msg.value;
        // 计算购买token的数量
        uint256 amount = msg.value * unitsOneEthCanBuy;
        // 检测资金账户的token余额大于或等于购买的数量
        require(balances[fundsWallet] >= amount);

        // 资金账户token减少购买的数量
        balances[fundsWallet] = balances[fundsWallet] - amount;
        // 发送ETH的账户增加购买token的数量
        balances[msg.sender] = balances[msg.sender] + amount;

        // 广播购买事件
        Transfer(fundsWallet, msg.sender, amount); 

        // 把ETH转给资金账户
        fundsWallet.transfer(msg.value);                               
    }

    /* Approves and then calls the receiving contract */
    function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
        allowed[msg.sender][_spender] = _value;
        Approval(msg.sender, _spender, _value);

        //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
        //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
        //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
        if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
        return true;
    }
}

在这里我写了一个MyTestCoin的智能合约也是一个ERC20 的Token。实现ERC20 Token的代码跟上一篇差不多,唯一不同的是增加了接收ETH的代码。

// 其他地址向合约发送ETH,默认会执行这个方法
    function() payable{
        // 更新募集到的ETH总量
        totalEthInWei = totalEthInWei + msg.value;
        // 计算购买token的数量
        uint256 amount = msg.value * unitsOneEthCanBuy;
        // 检测资金账户的token余额大于或等于购买的数量
        require(balances[fundsWallet] >= amount);

        // 资金账户token减少购买的数量
        balances[fundsWallet] = balances[fundsWallet] - amount;
        // 发送ETH的账户增加购买token的数量
        balances[msg.sender] = balances[msg.sender] + amount;

        // 广播购买事件
        Transfer(fundsWallet, msg.sender, amount); 

        // 把ETH转给资金账户
        fundsWallet.transfer(msg.value);                               
    }

当其他地址向这个合约地址发送ETH的时候,默认会执行这个方法,注释里面写的很清楚了,总共做了三件事:

  1. 给发送者地址增加Token数量
  2. 给发布Token的地址减少Token数量
  3. 把发送过来的ETH发送给募集地址

代码里面写的一个ETH可以购买10个MTC的Token,也就是说,当一个以太坊地址发送1ETH到合约地址后,他可以获得10个MTC的Token。

现在让我们发布我们的艾西欧合约:

  1. 打开 remix 新建MyTestCoin.sol,把代码复制进去。编译。
  2. 打开MetaMask钱包, 注意连接入Ropsten网络。
  3. 在remix的 Run tab中 选择MyTestCoin 点击 create 按钮,这时候MetaMask会弹出弹框让你确定,确定提交。等待交易打包完成。如下图


    简单实现一个艾西欧_第1张图片
    image.png
  4. 点击上面提交的交易信息,可以看到我们的合约发布情况,可以看到我们的合约地址也已经生成了。


    简单实现一个艾西欧_第2张图片
    image.png
  5. 在MetaMask钱包的Tokens tab中点击Add Token,把上一步的合约地址复制到Token Contract Address 输入框中,点击添加。


    简单实现一个艾西欧_第3张图片
    image.png
  6. 添加后可以看到我们新发布的Token。


    简单实现一个艾西欧_第4张图片
    image.png

    因为默认是使用第一个账户发布的合约,所以第一个账户拥有所有的token。总量应该是1000,因为之前测试过一次,截图看到总量少了10个。

  7. 现在让我们在MetaMask上新建一个账号。


    简单实现一个艾西欧_第5张图片
    image.png
  8. 新建的账号是没有ETH, 点击Buy 按钮申请一点ETH来测试。申请ETH跟上一篇文章一样,这里也就不多介绍了。
  9. 等申请ETH到账后,点击Send 按钮。可以看到我们新申请的账号有1ETH的余额。发送0.9ETH到合约地址。


    简单实现一个艾西欧_第6张图片
    image.png
  10. 等交易打包后可以看到我们获得了9 个Token。


    简单实现一个艾西欧_第7张图片
    image.png
  11. 在看下我们第一个账号的ETH余额和Token余额。


    简单实现一个艾西欧_第8张图片
    image.png

    可以看到ETH增加了0.9。 Token减少了9个。

这样我们就简单实现了一个艾西欧。

这样简单实现的艾西欧肯定是不能发布上去给大家用户,了解一些艾西欧的肯定也听说过什么软顶,硬顶,开始时间,结束时间,发行总量等名词,这些在智能合约里面又是如何实现的?后面我会继续探索下去,尽请期待!

你可能感兴趣的:(简单实现一个艾西欧)