Skip to main content
edited body
Source Link
Wyctus
  • 226
  • 2
  • 7
const encodeAddressArray = addresses => {
    let hex = "0x";
    hex += addresses.map(address => address.substr(2, 40)).join("");

    return web3.utils.hexToAsciihexToBytes(hex);
}
const encodeAddressArray = addresses => {
    let hex = "0x";
    hex += addresses.map(address => address.substr(2, 40)).join("");

    return web3.utils.hexToAscii(hex);
}
const encodeAddressArray = addresses => {
    let hex = "0x";
    hex += addresses.map(address => address.substr(2, 40)).join("");

    return web3.utils.hexToBytes(hex);
}
Added `web3.js` encoder.
Source Link
Wyctus
  • 226
  • 2
  • 7

This encoding is also pretty simple in web3.js:

const encodeAddressArray = addresses => {
    let hex = "0x";
    hex += addresses.map(address => address.substr(2, 40)).join("");

    return web3.utils.hexToAscii(hex);
}

This encoding is also pretty simple in web3.js:

const encodeAddressArray = addresses => {
    let hex = "0x";
    hex += addresses.map(address => address.substr(2, 40)).join("");

    return web3.utils.hexToAscii(hex);
}
Summerized it in a library to make it more reusable.
Source Link
Wyctus
  • 226
  • 2
  • 7

Finally the whole process is summarized in the following tiny library:


library AddressCoder{
    function bytesToAddress(bytes calldata data) private pure returns (address addr) {
        bytes memory b = data;
        assembly {
          addr := mload(add(b, 20))
        } 
    }

    
    function decodeAddressArray(bytes calldata data)external pure returns(address[] memory addresses){
        uint n = data.length/20;
        addresses = new address[](n);
        
        for(uint i=0; i<n; i++){
            addresses[i] = bytesToAddress(data[i*20:(i+1)*20]);
        }
    }
    
    
    function encodeAddressArray(address[] calldata addresses) external pure returns(bytes memory data){
        for(uint i=0; i<addresses.length; i++){
            data = abi.encodePacked(data, addresses[i]);
        }
    }
}

Finally the whole process is summarized in the following tiny library:


library AddressCoder{
    function bytesToAddress(bytes calldata data) private pure returns (address addr) {
        bytes memory b = data;
        assembly {
          addr := mload(add(b, 20))
        } 
    }

    
    function decodeAddressArray(bytes calldata data)external pure returns(address[] memory addresses){
        uint n = data.length/20;
        addresses = new address[](n);
        
        for(uint i=0; i<n; i++){
            addresses[i] = bytesToAddress(data[i*20:(i+1)*20]);
        }
    }
    
    
    function encodeAddressArray(address[] calldata addresses) external pure returns(bytes memory data){
        for(uint i=0; i<addresses.length; i++){
            data = abi.encodePacked(data, addresses[i]);
        }
    }
}
Source Link
Wyctus
  • 226
  • 2
  • 7
Loading