Chainlink

執行 UpKeep 命令直到 Balance 達到 0

  • December 16, 2021

我們希望一直performUpkeep執行到錢包餘額在一組 Chainlink Keepers 上達到 0。

我們設法以合理的語法嘗試在混音上無錯誤地執行。但是仍然想知道解決方案是正確的還是過度設計的。


// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;

interface KeeperCompatibleInterface {
   function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData);
   function performUpkeep(bytes calldata performData) external;
}

contract Counter is KeeperCompatibleInterface {

   uint public counter;    // Public counter variable

   // Use an interval in seconds and a timestamp to slow execution of Upkeep
   uint public immutable interval;
   uint public lastTimeStamp;    

   constructor(uint updateInterval) {
     interval = updateInterval;
     lastTimeStamp = block.timestamp;
     counter = 0;
   }

   function checkUpkeep(bytes calldata checkData) external view override returns (bool upkeepNeeded, bytes memory performData) {
       upkeepNeeded = (block.timestamp - lastTimeStamp) > interval;
       performData = checkData;
   }

   function balance() public view returns (uint256) {
       return address(this).balance;

   }

   function performUpkeep(bytes calldata) external override {
       lastTimeStamp = block.timestamp;
       require(address(this).balance > 0);
      
   }

}

如果您希望在餘額達到 0 之前進行維護,則需要在checkUpkeepand中量化performUpkeep,例如:

   function checkBalance() public view returns(bool){
       return address(this).balance >= 0;
   } 
   function checkUpkeep(bytes calldata /** checkData **/ ) external view override returns (bool upkeepNeeded, bytes memory performData) {
       upkeepNeeded = checkBalance();
   }

   function performUpkeep(bytes calldata) external override {
       require(checkBalance(), "Balance not 0");
   }

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