演示:使用ChainlinkAutomation自动化智能合约
让我们研究一下如何用Chainlink Automation来自动执行智能合约。
我们将使用一个建立在Remix IDE上的Solidity合约,并部署到测试网络。该智能合约将实现ChainlinkAutomation GitHub仓库中定义的接口。
为了与Chainlink Automation兼容,我们的智能合约必须包括以下两个方法:
checkUpKeep():在链下间隔执行调用该函数,该方法返回一个布尔值,告诉网络是否需要自动化执行。
performUpKeep():这个方法接受从checkUpKeep()方法返回的信息作为参数。ChainlinkAutomation 会触发对它的调用。函数应该先进行一些检查,再执行链上其他计算。
要想开始,请添加以下代码,在Remix IDE中创建一个简单的反欺诈合约:
// SPDX-License-Identifier: MITpragma solidity ^0.8.7;contract Counter { uint public counter; uint public immutable interval; uint public lastTimeStamp; constructor(uint updateInterval) { interval = updateInterval; lastTimeStamp = block.timestamp; counter = 0; } function checkUpkeep(bytes calldata /* checkData */) external view returns (bool upkeepNeeded /* bytes memory performData */) { upkeepNeeded = (block.timestamp - lastTimeStamp) > interval; // We don't use the checkData in this example. The checkData is defined when the Upkeep was registered } function performUpkeep(bytes calldata /* performData */) external { //We highly recommend revalidating the upkeep in the performUpkeep function if ((block.timestamp - lastTimeStamp) > interval ) { lastTimeStamp = block.timestamp; counter = counter + 1; } // We don't use the performData in this example. The performData is generated by the Keeper's call to your checkUpkeep function }}该合约有一个公有变量counter,当新区块和上一个区块之间的差值大于一个区间时,该变量会递增1。它实现了两个Automation要求实现的方法。
现在,导航到Remix菜单按钮(从顶部开始的第三个按钮),点击Compile按钮(用绿色验证标记表示)来编译合约: