How to pass bytes to smart contract function from web3.js

bitsanitybitsanity Member Posts: 8
I have this function in a smart contract:

contract MyToken {
  function approveAndCall( address spender, uint256 value, bytes context ) returns (bool success) { ... }
I'm trying to call it using web3.js. My test code tries to pass an array as the third parameter:

var context = [];
token.methods.approveAndCall( sca, 10000, context ).send( {from:accounts[0]} ).then( () => { ... } )
It throws an exception - seems to be where it marshals the array parameter:

Unhandled rejection TypeError: value.replace is not a function
    at SolidityTypeDynamicBytes.formatInputDynamicBytes [as _inputFormatter] (/home/me/node_modules/web3/packages/web3-eth-abi/src/types/formatters.js:83:24)
    at SolidityTypeDynamicBytes.SolidityType.encode (/home/me/node_modules/web3/packages/web3-eth-abi/src/types/type.js:188:17)
    at /home/me/node_modules/web3/packages/web3-eth-abi/src/index.js:255:29
    at (native)
    at ABICoder.encodeParameters (/home/me/node_modules/web3/packages/web3-eth-abi/src/index.js:254:34)
    at /home/me/node_modules/web3/packages/web3-eth-contract/src/index.js:451:24
    at (native)
    at Object._encodeMethodABI (/home/me/node_modules/web3/packages/web3-eth-contract/src/index.js:450:12)
I have tried a few other things: an array with one byte set to 0x00, an array of characters, web3.utils.hexToBytes(val), etc.

Anyone know the right way to pass bytes?


  • bitsanitybitsanity Member Posts: 8
    Additional note: found the unit test in github and using a string literal like '0x42' seems to work.

    token.methods.approveAndCall( sca, 10000, '0x42' ).send( {from:accounts[0]} ).then( () => { ... } )
Sign In or Register to comment.