How to Pass bytes32[] Array to a Function in web3js

bytes32solidityweb3js

I have a function

function multiERC20TransferTightlyPacked
    (
        ERC20 _token,
        bytes32[] _addressesAndAmounts
    ) public
    {
        for (uint i = 0; i < _addressesAndAmounts.length; i++) {
            address to = address(_addressesAndAmounts[i] >> 96);
            uint amount = uint(uint96(_addressesAndAmounts[i]));
            _safeERC20Transfer(_token, to, amount);
            MultiERC20Transfer(msg.sender, to, amount, _token);
        }
    }

For exmple I want to call this function with _addressesAndAmounts of 0x2970c57fe5264caf1689bc129b41bd7ddf06b4f7 10, and 0x63F69E69857dc198AE63C1BeEe26803c50C00813 10, how can I pass these as parameter to call this function?

  const multisendTx = await contract.methods. multiERC20TransferTightlyPacked(tokenAddress, addressesAmounts).encodeABI();

How should I make the addressesAmounts?

on the solidity code it says:

address to = address(_addressesAndAmounts[i] >> 96);
uint amount = uint(uint96(_addressesAndAmounts[i]));

I don't know what does >> 96 mean how does it work in js?

Best Answer

You can use this function:

const Web3 = require("web3");

const toBN = Web3.utils.toBN;

function getArray(items) {
    return items.map(item => "0x" + toBN(item.address).shln(96).or(toBN(item.amount)).toString(16));
}

For example:

const array = getArray([
    {address: "0x2970c57fe5264caf1689bc129b41bd7ddf06b4f7", amount: "10"},
    {address: "0x63F69E69857dc198AE63C1BeEe26803c50C00813", amount: "10"},
]);

console.log(array);

The value of amount should be at most 2 ^ 96 - 1 of course.

Its type is string because it can be larger than 2 ^ 53 - 1 (Number.MAX_SAFE_INTEGER).

Related Topic