Search code examples
solidityencodeethers.js

Ethers.js: How do I encode an array of addresses into a Solidity bytes variable?


I'm testing my Solidity code using Ether.js, and the method under test requires a bytes argument, which I'm using to pass an array of addresses:

function testFunction(bytes calldata params) external {
   address[] memory addresses = abi.decode(params, (address[]));
}

How do I encode an array of addresses in Ethers.js so I can pass it as argument?


Solution

  • You can use AbiCoder.encode(types, values). To encode an array of addresses, you could do:

    const abi = ethers.utils.defaultAbiCoder;
    const params = abi.encode(
        ["address[]"], // encode as address array
        [ [addresses.tokens.weth, addresses.tokens.wbtc] ]); // array to encode