solidityABI编码函数

solidityABI编码函数

  • abi.encode(…) returns (bytes):计算参数的 ABI 编码。自动补全32位字节
  • abi.encodePacked(…) returns (bytes):计算参数的紧密打包编码
  • abi. encodeWithSelector(bytes4 selector, …) returns (bytes):
    计算函数选择器和参数的 ABI 编码
  • abi.encodeWithSignature(string signature, …) returns (bytes): 等价于*
  • abi.encodeWithSelector(bytes4(keccak256(signature), …)

对函数打包处理,但是处理方式不一样,对于小于32字节类型的参数,前者会将所有参数自动补全到32个字节,后者不会自动补全

contract TestDifference {
  function testUint(
    uint8 _num1,
    uint32 _num2
    )
    public view returns (bytes memory, bytes memory) {
    return (
      abi.encode(_num1),
      abi.encodePacked(_num2)
      );
  }

  function testBytes() public view returns (bytes memory, bytes memory) {
      bytes memory _bts ="Hello,world!";
    return (abi.encodePacked(_bts),abi.encode(_bts));
  }
}

solidityABI编码函数_第1张图片

contract testABI {
    uint storedData;

    function set(uint x) public {
        storedData = x;
    }

    function abiEncode() public pure returns (bytes memory) {
        abi.encode(1);  // 计算1的ABI编码
        return abi.encodeWithSignature("set(uint256)", 1); //计算函数set(uint256) 及参数1 的ABI 编码
    }
}

pragma solidity ^0.8.0;
contract Encode {
    function encode(string memory _string1, uint _uint, string memory _string2) public pure returns (bytes memory) {
        return (abi.encode(_string1, _uint, _string2));
    }
    function decode(bytes memory data) public pure returns (string memory _str1, uint _number, string memory _str2) {
        (_str1, _number, _str2) = abi.decode(data, (string, uint, string));            
    }
}

参考资料

你可能感兴趣的:(solidity,solidity)