Solidity

將文字字元串“”傳遞給以字節呼叫數據作為參數的函式時出錯

  • June 21, 2022

我正在嘗試在我的契約中實施chainlink keeper。實際上我想使用以這種方式定義的函式 checkUpkeep :

function checkUpKeep(bytes calldata /* */) public returns (bool /* */, bytes memory /* */)

當我嘗試使用文字字元串“”作為參數呼叫此函式時,solidity 編譯器(0.8.8)向我拋出此錯誤:

TypeError: Invalid type for argument in function call. Invalid implicit conversion from literal_string "" to bytes calldata requested.

我以這種方式呼叫此函式:

checkUpKeep("")

我的程式碼:

function checkUpkeep(bytes calldata /* checkData */) public override returns (bool upkeepNeeded, bytes memory/* performData*/ ) {
       bool isOpen = (RaffleState.OPEN == s_raffleState);
       bool timePassed = ((block.timestamp - s_lastTimeStamp) > i_interval);
       bool hasPlayers = (s_players.length > 0);
       bool hasBalance = address(this).balance > 0;
       upkeepNeeded = (isOpen && timePassed && hasPlayers && hasBalance);
   }

   function performUpkeep(bytes calldata /* performData */) external override{
       (bool upkeepNeeded, ) = checkUpkeep(""); // Error here
       ...
   }

有一些問題。該函式checkUpkeep接受bytes calldata但它是public. Solc 使用該組合生成錯誤。

function checkUpkeep(bytes calldata /* checkData */) public override returns ... {

使用的問題calldata是該類型的數據不能由合約創建。它只是可以轉發該類型的現有數據。

一種可能的解決方案是將類型更改為memory,然後(bool upkeepNeeded, ) = checkUpkeep("")將起作用。

function checkUpkeep(bytes memory /* checkData */) public override returns ... {

其他函式是將函式聲明為外部函式並修改對 的呼叫(bool upkeepNeeded, ) = this.checkUpkeep(""),因為外部函式是以這種方式呼叫的。

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