编写solidity智能合约并调用(testrpc)输出结果

1、编写合约代码

pragma solidity ^0.4.2; 
contract test { 
    function add(uint a,uint b) public pure returns(uint c) { return a + b ; } 
}

2、编译合约

打开网站:https://ethereum.github.io/browser-solidity

输入合约代码:

编写solidity智能合约并调用(testrpc)输出结果_第1张图片

点击:Start to compile -> Details

编写solidity智能合约并调用(testrpc)输出结果_第2张图片

[{"constant":true,"inputs":[{"name":"a","type":"uint256"},{"name":"b","type":"uint256"}],"name":"add","outputs":[{"name":"c","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"}];

以上就是合约的二进制接口内容。

data:"0x608060405234801561001057600080fd5b5060c58061001f6000396000f300608060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063771602f7146044575b600080fd5b348015604f57600080fd5b5060766004803603810190808035906020019092919080359060200190929190505050608c565b6040518082815260200191505060405180910390f35b60008183019050929150505600a165627a7a7230582083fb3cb7384702887027283b6ed40fb473b10daf5f58bd2ab3f65f8709eaeec40029"}

以上就是合约的二进制编码。

3、定义abi(应用程序二进制接口)

> abi
abi=[{"constant":true,"inputs":[{"name":"a","type":"uint256"},{"name":"b","type":"uint256"}],"name":"add","outputs":[{"name":"c","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"}];

4、创建合约

> addmethodContract=eth.contract(abi);

5、部署合约到区块链上

from:发起交易的账户地址,在以太坊区块链上的每一步操作,都被看成是一次交易,需要矿工挖矿确认(testrpc模式下不需要挖矿确认)。

data:合约的二进制编码

gas:本次交易花费的成本,即:总成本 = gasUsed * gasPrice

> addmethodContract.new({from:eth.coinbase , data:"0x608060405234801561001057600080fd5b5060c58061001f6000396000f300608060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063771602f7146044575b600080fd5b348015604f57600080fd5b5060766004803603810190808035906020019092919080359060200190929190505050608c565b6040518082815260200191505060405180910390f35b60008183019050929150505600a165627a7a7230582083fb3cb7384702887027283b6ed40fb473b10daf5f58bd2ab3f65f8709eaeec40029",gas:3141592});

挖矿确认方法:

 > miner.start(2);admin.sleepBlocks(1);miner.stop();

6、完成以上步骤,一个合约在区块链上就创建好了。接下来就是如何使用合约了。

7、实例化一个智能合约

> myAddMethod=addmethodContract.at("0x6f1acb090c7c717321e06623c13cca3e13e16cbc");

8、调用合约

> myAddMethod.add.call(10,20);

编写solidity智能合约并调用(testrpc)输出结果_第3张图片

大功告成。

你可能感兴趣的:(区块链技术)