Solidity

當我使用 abi 向其他契約發送 2 個參數時呼叫失敗?

  • September 14, 2022

我可以向契約 A (otherContract) 發送 1 個參數,並且效果很好。但是當我發送 2 個參數時,它失敗了。我做錯了什麼?

契約甲:

function sumTwoParams (uint256 _num1, uint256 _num2) pure public returns (uint256) {
       return _num1 + _num2;
   } 

契約乙:

function sumTwoParams (uint256 _num1, uint256 _num2) public {     
       bytes memory payload = abi.encodeWithSignature("sumTwoParams(uint256, uint256)", _num1, _num2);
       (bool success, bytes memory returnData) = otherContract.call(payload);
       require(success, "Failed!");
       
       (sumResult) = abi.decode(returnData, (uint256));
   } 

sumResult是合約 B 的成員,txrequire(success, "Failed!");在合約 B中恢復。

在對簽名進行編碼時,您應該使用"sumTwoParams(uint256,uint256)"(之後沒有空格)。,

問題是您在簽名參數中添加了一個空格,因此它會產生不同的簽名。

看看這段程式碼:

function encodeWithSignatureWithSpaceInParams() public pure returns(bytes memory) {
       // This produces: 0x60fb6acb00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002
       return abi.encodeWithSignature("sumTwoParams(uint256, uint256)", 1, 2);
   }

   function encodeWithSignatureWithoutSpaceInParams() public pure returns(bytes memory) {
       // This produces: 0xff19a36e00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002
       return abi.encodeWithSignature("sumTwoParams(uint256,uint256)", 1, 2);
   }

刪除空間。它應該像sumTwoParams(uint256,uint256)

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