使用truffle测试solidity中的重载函数

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函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值