Web3js – Using encodeFunctionCall with Nested, Array, or Non-String Parameters

abiencodefunctioncallstructweb3js

Web3.js has a method named encodefunctioncall with the following signature:

encodeFunctionCall(abiItem: AbiItem, params: string[]): string;

The first parameter is ABI interface of that function and the seconds one is a string array of function parameters. My problem is with the second parameter, it only accepts string array, while my method gets a struct and some address and int arrays as input. If I use encodeParameters to encode my input parameters, it returns a single string that can't be passed to encodefunctioncall since it only accepts string array as its second input:

encodeParameters(types: any[], paramaters: any[]): string;

How can I create my function call with non-string (e.g. nested structs or arrays) using web3.js?

Best Answer

The workaround is to calculate function signature and parameters separately using web3 ABI encoder functions and then simply concatenate them:

const callData = web3.eth.abi.encodeFunctionSignature(abiItem) + web3.eth.abi.encodeParameters(types, params).substr(2)/* remove preceding 0x */;

More info is available at this link.

Related Topic