如何使用数字货币开发工具来做智能合约的测试驱动开发

来源:互联网 发布:翡翠台在线直播软件 编辑:程序博客网 时间:2024/05/16 11:16

区块链爱好者(QQ:53016353)  

数字货币用来做智能合约的测试驱动开发(TDD)非常棒,我强烈推荐你在学习中使用它。它也是学习使用JavaScript Promise的一个好途径,例如deferred和异步调用。Promise机制有点像是说“做这件事,如果结果是这样,做甲,如果结果是那样,做乙... 与此同时不要在那儿干等着结果返回,行不?”。数字货币使用了包装web3.js的一个JS Promise框架Pudding(因此它为为你安装web3.js)。(译注:Promise是流行于JavaScript社区中的一种异步调用模式。它很好的封装了异步调用,使其能够灵活组合,而不会陷入callback hell.)



Transaction times. Promise对于DApp非常有用,因为交易写入以太坊区块链需要大约12-15秒的时间。即使在测试网络上看起来没有那么慢,在正式网络上却可能会要更长的时间(例如你的交易可能用光了Gas,或者被写入了一个孤儿块)。


下面让我们给一个简单的智能合约写测试用例吧。


使用数字货币


首先确保你 1.安装好了solc以及 2.testrpc。(testrpc需要Python和pip。如果你是Python新手,你可能需要用virtualenv来安装,这可以将Python程序库安装在一个独立的环境中。)


接下来安装 3.数字货币(你可以使用NodeJS's npm来安装:npm install -g 数字货币, -g开关可能会需要sudo)。安装好之后,在命令行中输入数字货币 list来验证安装成功。然后创建一个新的项目目录(我把它命名为'conference'),进入这个目录,运行数字货币 init。该命令会建立如下的目录结构:






现在让我们在另一个终端里通过执行testrpc来启动一个节点(你也可以用geth):






回到之前的终端中,输入数字货币 deploy。这条命令会部署之前数字货币 init产生的模板合约到网络上。任何你可能遇到的错误信息都会在testrpc的终端或者执行数字货币的终端中输出。


在开发过程中你随时可以使用数字货币 compile命令来确认你的合约可以正常编译(或者使用solc YourContract.sol),数字货币 deploy来编译和部署合约,最后是数字货币 test来运行智能合约的测试用例。


第一个合约


下面是一个针对会议的智能合约,通过它参会者可以买票,组织者可以设置参会人数上限,以及退款策略。本文涉及的所有代码都可以在这个代码仓库找到。


contract Conference {
  address public organizer;
  mapping (address => uint) public registrantsPaid;
  uint public numRegistrants;
  uint public quota;


  event Deposit(address _from, uint _amount);  // so you can log these events
  event Refund(address _to, uint _amount); 


  function Conference() { // Constructor
    organizer = msg.sender;
    quota = 500;
    numRegistrants = 0;
  }
  function buyTicket() public returns (bool success) {
    if (numRegistrants >= quota) { return false; }
    registrantsPaid[msg.sender] = msg.value;
    numRegistrants++;
    Deposit(msg.sender, msg.value);
    return true;
  }
  function changeQuota(uint newquota) public {
    if (msg.sender != organizer) { return; }
    quota = newquota;
  }
  function refundTicket(address recipient, uint amount) public {
    if (msg.sender != organizer) { return; }
    if (registrantsPaid[recipient] == amount) { 
      address myAddress = this;
      if (myAddress.balance >= amount) { 
        recipient.send(amount);
        registrantsPaid[recipient] = 0;
        numRegistrants--;
        Refund(recipient, amount);
      }
    }
  }
  function destroy() { // so funds not locked in contract forever
    if (msg.sender == organizer) { 
      suicide(organizer); // send funds to organizer
    }
  }
}


接下来让我们部署这个合约。(注意:本文写作时我使用的是Mac OS X 10.10.5, solc 0.1.3+ (通过brew安装),数字货币 v0.2.3, testrpc v0.1.18 (使用venv))
阅读全文
0 0
原创粉丝点击