Assembly

abi.encode 和 abi.decode 參數,包括可變大小的數組

  • December 8, 2021

我正在將一些參數傳遞給一個函式並abi.encode()-ing 它們。然後我將它傳遞data給另一個函式abi.decode(),但我不完全確定如何去做:

我正在編碼的參數:

uint256    quantity
uint8      addresses_array_length
address[]  addresses_array
address[]  addresses_array2
// addresses_array2.length = addresses_array.length - 1, always

然後我傳遞這些數據,並希望以完全相同的格式(即uint256uint8和)對其進行解碼。address[]``address[]

我該怎麼做?

根據我閱讀的內容,我應該執行以下操作:

assembly { //is it necessary to do all this within this assembly struct?
   quantity := mload(add(data, 32))
   addresses_array_length := mload(add(data, 1))
   // Now how should I do for the arrays?
 }

謝謝

我不確定您要實現什麼目標,但如果您正在使用,abi.encode那麼您可以使用abi.decode.

// SPDX-License-Identifier: MIT

pragma solidity 0.8.4;


contract A {

   function foo() public {
       uint256 a = 1;
       uint8 b = 2;
       address[] memory c = new address[](3);
       address[] memory d = new address[](2);
       
       c[0] = msg.sender;
       d[1] = msg.sender;
       
       bytes memory x = abi.encode(a, b, c, d);
       bar(x);
   }
   
   
   function bar(bytes memory data) public view {
       (uint256 x, uint8 y, address[] memory z, address[] memory w) = abi.decode(data, (uint256, uint8, address[], address[]));
   
       require(z[0] == msg.sender, "First array");
       require(w[1] == msg.sender, "Second array");
       
   }
}

引用自:https://ethereum.stackexchange.com/questions/101613