假如我们在钱包里部署了一个智能合约,那么在geth客户端该怎么调用这个智能合约呢?(使用web3.js操作智能合约)
1、首先在钱包中部署智能合约,合约代码如下:
pragma solidity ^0.4.11;
contract MetaCoin {
mapping (address => uint) balances;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
function MetaCoin() {
balances[tx.origin] = 10000;
}
function sendCoin(address receiver, uint amount) returns(bool sufficient) {
if (balances[msg.sender] < amount) return false;
balances[msg.sender] -= amount;
balances[receiver] += amount;
Transfer(msg.sender, receiver, amount);
return true;
}
function getBalance(address addr) returns(uint) {
return balances[addr];
}
}
2、在geth客户端定义该智能合约的interface,在钱包中可以找到
var abi = [{"constant":false,"inputs":[{"name":"receiver","type":"address"},{"name":"amount","type":"uint256"}],"name":"sendCoin","outputs":[{"name":"sufficient","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"addr","type":"address"}],"name":"getBalance","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"}];
3、定义该智能合约的地址
var address = "0xb2cdd356e58280906ce53e1665697b50f88aac56";
4、取得智能合约的实例,通过abi和合约地址取得智能合约的实例
var metacoin = web3.eth.contract(abi).at(address);
5、调用合约函数
metaCoin合约有两个函数:getBalance和sendCoin,可以通过metacoin对象直接调用这两个函数。
首先来看getBalance,由于getBalance函数只是从区块链中读数据,而不是修改数据,因此我们通过在getBalance后面加上.call()的方式调用:
var account_one = web3.eth.accounts[0];
var account_one_balance = metacoin.getBalance.call(account_one);
console.log("account one balance: ", account_one_balance.toNumber());
下面来看sendCoin函数,由于sendCoin要修改合约内部的数据,所以要使sendCoin生效,必须向区块链发送交易,可以在sendCoin后面加上.sendTransaction()来指明这是一笔交易:
var account_one = web3.eth.accounts[0];
var account_two = web3.eth.accounts[1];
// 提交交易到区块链,会立即返回交易hash,但是交易要等到被矿工收录到区块中后才生效
var txhash = metacoin.sendCoin.sendTransaction(account_two, 100, {from:account_one});
console.log(txhash);
6、使用事件
在web3中使用事件,要首先获取事件对象,然后监听事件,如果事件发生,就会在回调函数中获取到事件信息:
// 获取事件对象
var myEvent = metacoin.Transfer();
// 监听事件,监听到事件后会执行回调函数
myEvent.watch(function(err, result) {
if (!err) {
console.log(result);
} else {
console.log(err);
}
myEvent.stopWatching();
});
// 输出:
{ address: '0xb2cdd356e58280906ce53e1665697b50f88aac56',
blockNumber: 651,
transactionIndex: 0,
transactionHash: '0xcc71bc2824cc84d1ee831c46189e3a80cf0af05697ba0370693aa97390c8067b',
blockHash: '0x1d53f04206f3926d0f311b1230a9dd0b0c5aadac35b169a6a609e384ab130c6f',
logIndex: 0,
removed: false,
event: 'Transfer',
args:
{ _from: '0x68b73956d704007514e9257813bdc58cdf3c969a',
_to: '0x9c3c1a2f5ef913fac44f0348a78f68d835f3f26e',
_value: { [String: '100'] s: 1, e: 2, c: [Object] } } }
watch中的回调函数如果被执行,说明事件已被触发,也就是说某笔交易已经处理完,检查交易hash是否一致,可以判定产生这个事件的交易是否是自己发送的交易,如果是,就可以进行其他操作,比如查询最新的余额。