4

What is the equivalent of abi.encodePacked in web3?

I am trying to generate the equivalent of (solidity)

keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", domainHash, functionHash));

with web3, to test from truffle.

So far I know that

keccack256 = web3.utils.soliditySha3

abi.encode = web3.eth.abi.encodeParameters

abi.encodePacked = ????????

2

3 Answers 3

1

If you have the contract's ABI you can use encodeABI.

If you don't have the contract's ABI then you can use web3.eth.abi.encodeFunctionCall, or combine some of the other functions from web3.eth.abi.*.

You can also use ethereumjs-abi that implements this functionality.

0
1

Web3.js has a function called encodePacked which should do what you have in mind. I couldn't find any information about it in the official docs, but found it while poking around in the source code. You can call it with web3.utils.encodePacked(...args).

As you'll see from the source code, you can pass it a series of objects in order to specify the types that you intend, e.g.:

web3.utils.encodePacked(
  {value: 42, type: 'uint128'},
  {value: 'trombone', type: 'string'}
);
'0x0000000000000000000000000000002a74726f6d626f6e65'

Contrast this with the return value of encodeParameters, which is not packed:

web3.eth.abi.encodeParameters(['uint128', 'string'], [42, 'trombone']);
0x000000000000000000000000000000000000000000000000000000000000002a0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000874726f6d626f6e65000000000000000000000000000000000000000000000000
0
const ethers = require("ethers");
ethers.utils.solidityPack // nodejs equivalent of solidity's abi.encodePacked

Your Answer

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

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