从智能合约安排调用函数

Schedule call function from smart contract

每次我的农场通过我的智能合约运行时,我都希望 运行。 如何每 3 小时处理一次 运行 函数?

语言中没有实现本地方式,因为 Solidity 函数是作为事务的结果执行的。但您可以安排每 3 小时发送一次交易。


其中一种方法是使用 Chainlink 作业的 cron 启动程序。

包含作业配置示例的文档:


或者 运行 服务器上直接发送交易的脚本(不使用 Chainlink 作为中介)。

const Web3 = require('web3');
const web3 = new Web3(providerUrl);
const myContract = new web3.eth.Contract(jsonAbi, contractAddress);
web3.eth.accounts.wallet.add(senderPrivateKey);

async function sendTransaction() {
    myContract.methods.myFunction().send({from: senderAddress});
}

setInterval('sendTransaction', 3 * 60 * 60 * 1000); // 3 hours in milliseconds

您可以使用 Chainlink Keepers 完全在链上完成此类 'smart contract cron' 或 'smart contract scheduler'。我建议遵循 Chinalink 文档中的示例 Keepers 合同,您可以在其中设置时间间隔(在您的情况下,每 3 小时)。 3 小时间隔过去后,您可以在 performUpkeep 函数中定义要自动化的智能合约函数:https://docs.chain.link/docs/chainlink-keepers/compatible-contracts/#example-contract

一旦您编写了该合约,请在 keepers.chain.link 的 Keepers 网络上注册它以开始自动化。