Solidity

如何為函式生成呼叫數據

  • February 27, 2020

我已經為函式生成方法 ID:

function transfer(address src, address dst, uint256 amount);

方法 ID 為:

bytes4(keccak256("transfer(address,address,uint256)")) // 0xbeabacc8

如何將函式變數(鏈上)與方法 ID 一起傳遞給函式:

function execute(address _target, bytes _data)

_data函式的呼叫數據在哪裡transfer

您可以通過以下方式執行呼叫(地址成員abi.encode*低級呼叫)):

範例 1:使用已計算的函式簽名進行呼叫(這回答了您的問題)


bytes memory transferPayload = abi.encodeWithSelector(bytes4(0xbeabacc8), param1, param2, param3);
bytes memory executePayload = abi.encodeWithSignature("execute(address,bytes)", transferContractAdr, transferPayload);
(bool success, bytes memory returnData) = address(executeContractAdr).call(executePayload);
require(success, "low-level call of function execute failed [transfer(address,address,uint256), param1, param2, param3]");

範例 2:呼叫函式並讓 Solidity 自動計算函式簽名


只需更換

bytes memory transferPayload = abi.encodeWithSelector(bytes4(0xbeabacc8), param1, param2, param3);

bytes memory transferPayload = abi.encodeWithSignature("transfer(address,address,uint256)", param1, param2, param3);

注意 1:請考慮哪種呼叫(call、callcode、delegatecall、staticcall)適合您的場景

注 2:將 require 語句替換為適當的try-catch

注3:如果你在同一個合約中呼叫一個函式,你可以使用address(this)

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