var account_one = "0x1234..."; // an address
var meta;
MetaCoin.deployed().then(function(instance) {
meta = instance;
return meta.getBalance.call(account_one, {from: account_one});
}).then(function(balance) {
// If this callback is called, the call was successfully executed.
// Note that this returns immediately without any waiting.
// Let's print the return value.
console.log(balance.toNumber());
}).catch(function(e) {
// There was an error! Handle it.
})
上面查询一个账号的余额,调用函数getBanalce,里面传一个参数,address
但是由于这个操作是读的操作,我们使用call来作为一个修饰告诉truffle这是一个读操作,那么就不会产生gas
如果是个写操作,正常调用即可。
*上面的函数增加了一个参数 {from:add},可以看作truffle给合约实例一个特殊的权利,在调用任何函数的时候可以在原来函数参数的最后多传一个{from:xxx}参数,from的值是一个用户的address,表示这个函数的调用者
transaction 操作实例:
var account_one = "0x1234..."; // an address
var account_two = "0xabcd..."; // another address
var meta;
MetaCoin.deployed().then(function(instance) {
meta = instance;
return meta.sendCoin(account_two, 10, {from: account_one});
}).then(function(result) {
// result is an object with the following values:
//
// result.tx => transaction hash, string
// result.logs => array of decoded events that were triggered within this transaction
// result.receipt => transaction receipt object, which includes gas used
// We can loop through result.logs to see if we triggered the Transfer event.
for (var i = 0; i < result.logs.length; i++) {
var log = result.logs[i];
if (log.event == "Transfer") {
// We found the event!
break;
}
}
}).catch(function(err) {
// There was an error! Handle it.
});
transaction的操作会返回一个对象 result,这个对象包含三个数据:
result.tx => 操作的hash值
result.logs => 一个event数组,transaction执行过程中操作涉及的事件
result.receipt => transaction操作的收据对象
在上方的代码中可以看到 通过遍历“result.logs”可以了解这个transaction涉及到哪些call(读取)和transfer(写入)操作
作者:大都废