4.3.1 使用remix调用合约获取data

    在使用remix执行合约方法时,每次交易都有对应的交易详情,可以在控制台看到交易信息里的函数调用的input,以及对应的decodeInput和decodeOutput。
    input就是调用函数时向区块链环境发送的JSON里的data。对应开放平台,在使用合约调用时,传入的data可以直接使用remix的data。

    4.3.2 使用ethers.js实现编码和解码

    1. var ethers = require('ethers')
    2. var abi = [
    3. {
    4. "constant": false,
    5. "inputs": [
    6. {
    7. "name": "_str",
    8. "type": "string"
    9. }
    10. ],
    11. "name": "saySomething",
    12. "outputs": [
    13. {
    14. "name": "",
    15. "type": "string"
    16. }
    17. ],
    18. "payable": false,
    19. "stateMutability": "nonpayable",
    20. "type": "function"
    21. },
    22. "inputs": [
    23. "name": "_owner",
    24. "type": "address"
    25. }
    26. ],
    27. "payable": false,
    28. "stateMutability": "nonpayable",
    29. "type": "constructor"
    30. },
    31. {
    32. "constant": true,
    33. "inputs": [],
    34. "name": "info",
    35. "outputs": [
    36. {
    37. "name": "",
    38. "type": "string"
    39. }
    40. ],
    41. "payable": false,
    42. "stateMutability": "view",
    43. "type": "function"
    44. },
    45. {
    46. "name": "owner",
    47. "outputs": [
    48. {
    49. "name": "",
    50. "type": "address"
    51. }
    52. ],
    53. "payable": false,
    54. "stateMutability": "view",
    55. "type": "function"
    56. }
    57. ];
    58. var interface = new ethers.Interface(abi)
    59. var abiInstance = interface.functions[abi[0].name] // abi[0]即saySomething function的abi
    60. return abiInstance.sighash // 0xfe6b3783

    获取函数参数编码data的方法:
    使用ethers.utils.ABICoder的encode方法,如

    1. 0xfe6b37830000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000

    可对比上面使用remix调用方法时的input值,两者结果一致。

    1. var ethers = require('ethers')
    2. var outputTypes = ['string']
    3. var response = "0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20576f726c64000000000000000000000000000000000000000000"
    4. var abiCoder = new ethers.utils.AbiCoder()
    5. abiCoder.decode(outputTypes, response)

    decode结果根据传入的outputTypes数组长度,解析对应的参数。