4.3.1 使用remix调用合约获取data
在使用remix执行合约方法时,每次交易都有对应的交易详情,可以在控制台看到交易信息里的函数调用的input,以及对应的decodeInput和decodeOutput。
input就是调用函数时向区块链环境发送的JSON里的data。对应开放平台,在使用合约调用时,传入的data可以直接使用remix的data。
4.3.2 使用ethers.js实现编码和解码
var ethers = require('ethers')
var abi = [
{
"constant": false,
"inputs": [
{
"name": "_str",
"type": "string"
}
],
"name": "saySomething",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
"inputs": [
"name": "_owner",
"type": "address"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"constant": true,
"inputs": [],
"name": "info",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"name": "owner",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
];
var interface = new ethers.Interface(abi)
var abiInstance = interface.functions[abi[0].name] // abi[0]即saySomething function的abi
return abiInstance.sighash // 0xfe6b3783
获取函数参数编码data的方法:
使用ethers.utils.ABICoder的encode方法,如
0xfe6b37830000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000
可对比上面使用remix调用方法时的input值,两者结果一致。
var ethers = require('ethers')
var outputTypes = ['string']
var response = "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000"
var abiCoder = new ethers.utils.AbiCoder()
abiCoder.decode(outputTypes, response)
decode结果根据传入的outputTypes数组长度,解析对应的参数。