4

Given a function setXY(uint256 x, uint256 y), how can I encode data parameters x and y into a single bytes data array that can be fed into abi.encodeWithSignature('setXY(uint256,uint256)', data)?

Ethers has an ABI encoder that allows for encoding array values according to array types. This allows encoding parameters via abiCoder.encode(['uint256', 'uint256'], ['1', '2']) into a bytes array.

But, feeding this as data into abi.encodeWithSignature or abi.encodeWithSelector results in data being read incorrectly, likely due to abi.encode leaving leading zeros for each argument.

Is there any way of accomplishing this correctly?

1 Answer 1

10

You cannot use bytes data because it will be encoded as an array, and you want to encode two uint256 instead.

uint256 x = 1324;
uint256 y = 4444;
abi.encodeWithSignature('setXY(uint256,uint256)', x, y);
2
  • Given I want to feed all data into abi.encodeWithSignature('setXY(uint256,uint256)', data), is there any way to encode arguments as an array? E.g. encoding x and y here as a single bytes array, with ethers tooling?
    – Leeren
    Nov 8, 2021 at 7:15
  • @Leeren Using abi.encodeWithSignature is not possible because the contract ABI encode uints and arrays are differently. You could use abi.encodePacked instead.
    – Ismael
    Nov 8, 2021 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.