Solidity

address.call{}(abi.encodeWithSignature()) 在solidity中返回布爾值和其他哪些參數?

  • June 21, 2022

我從這個文件https://docs.soliditylang.org/en/v0.8.15/contracts.html和這個討論中學到了How to use address.call{}() insolidity about abi.encodeWithSignature().

我對下面的這個片段有疑問。

contract TestPayable {
uint x;
uint y;
// This function is called for all messages sent to
// this contract, except plain Ether transfers
// (there is no other function except the receive function).
// Any call with non-empty calldata to this contract will execute
// the fallback function (even if Ether is sent along with the call).
fallback() external payable { x = 1; y = msg.value; }

// This function is called for plain Ether transfers, i.e.
// for every call with empty calldata.
receive() external payable { x = 2; y = msg.value; }
}

然後我們有呼叫者

contract Caller {

function callTestPayable(TestPayable test) public returns (bool) {
   (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()"));
   require(success);
   // results in test.x becoming == 1 and test.y becoming 0.
   (success,) = address(test).call{value: 1}(abi.encodeWithSignature("nonExistingFunction()"));
   require(success);
   // results in test.x becoming == 1 and test.y becoming 1.
   return true;
}
}
  1. 我想知道這條線(bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()"));

逗號後面會出現什麼(bool success, **What other parameters could fit here?**)? 2. 如果該行只返回bool success,那麼為什麼我們需要用逗號將其放在括號中(bool success,)?為什麼我們不能把bool success = address(test).call(abi.encodeWithSignature("nonExistingFunction()")); 3. 是否有nonExistingFunction()一個預設的保留函式名來呼叫其他智能合約的無名回退函式?

我在官方文件中找不到此資訊。

  1. 這是低級呼叫。你可以直接呼叫一個函式,也可以用呼叫函式(最好是導入合約的介面來呼叫它上面的函式)。推薦使用 call 來呼叫合約的fallback和receive函式。
  2. 因為它返回一個元組。call 函式的返回值是一個 bool 和 bytes 數組的元組。第一個是呼叫的狀態,字節數組有呼叫的合約函式的返回值。(見this
  3. 不,這是一個不存在的函式名稱 :) 如果您的 msg.data(第一次呼叫參數)為空,則呼叫 receive(),對於任何不匹配的數據呼叫 fallback()。看到這個

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