ERC223标准定义了三个重载的transfer函数。这给truffle测试带来了不少麻烦——直接在测试框架中调用transfer函数会报错:参数错误之类的信息。
本文使用web3的sendTransaction方法实现重载函数的调用。
- 安装web3-eth-abi这个包(推荐1.0.0-beta.34版本)。
- 引用这个包 const Web3Abi = require(‘web3-eth-abi’);
- 准备好要调用的方法的abi
- 编码函数签名以及参数
- 放入sendTransaction发布交易
全部代码如下:
const web3Abi = require('web3-eth-abi');
async function transfer(tokenObj, _from, _to, _amount){
let transfer_abi = {
"constant": false,
"inputs": [
{
"name": "_to",
"type": "address"
},
{
"name": "_value",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"name": "success",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}
const rawData = web3Abi.encodeFunctionCall(transfer_abi,[_to, _amount]);
await web3.eth.sendTransaction({from: _from, to: tokenObj.address, data: rawData, gas:5000000});
}
contract("Test", async (accounts) => {
it('test transfer', async () => {
.....
await transfer(tokenObject, accounts[0], accounts[1], 200);
});
});
注:该方法只限于非const函数