我现在正在开发和区块链游戏服务,我想发送一些令牌给赢家自动在游戏结束,并在特定的时间。
/*
* This function should be called every X days
*/
function sendTokens() public {
// We send some tokens to an array of players
}目前,我正在使用传统的后端技术(如setInterval和WebSocket )来完成这一任务--但是,这是一种集中的方法。
做这件事的最好方法是什么?专业的方法是什么?
发布于 2022-05-23 05:02:15
每一个发生在链上的状态变化都需要由事务触发。因此,要按计划运行智能合同功能,在某个特定事件之后,或者在其他触发事件之后,您需要有人来使用汽油。
话虽如此,你有两个选择:
1.分散自动化
您可以使用分散的神谕网络来调用智能契约。使用链环键可以调用您在任何时候指定的函数或以事件触发器为焦点的函数。神谕者支付与调用相关的气体,并为Chainlink节点支付订阅模型。
这样,您的合同就会一直分散到自动化级别,并且您不必担心集中的参与者故意不发送事务。
通过在契约中定义要等待的事件(比如基于时间的事件、基于事件的事件等)以及在performUpkeep中单击该触发器时要做的事情,从而使用performUpkeep设置触发器。
一个例子看起来是这样的:
该合同每隔一秒钟运行一次performUpkeep。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
// KeeperCompatible.sol imports the functions from both ./KeeperBase.sol and
// ./interfaces/KeeperCompatibleInterface.sol
import "@chainlink/contracts/src/v0.8/KeeperCompatible.sol";
contract Counter is KeeperCompatibleInterface {
/**
* Public counter variable
*/
uint public counter;
/**
* 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;
// We don't use the checkData in this example. The checkData is defined when the Upkeep was registered.
}
function performUpkeep(bytes calldata /* performData */) external override {
//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
}
}其他选择包括盖拉托。
2.集中自动化
您还可以让“传统”基础设施按计划调用您的功能,请记住,这意味着您在合同中依赖一个集中的参与者。
您可以采取以下几种形式的集中自动化:
免责声明:我在Chainlink实验室工作
https://stackoverflow.com/questions/71106211
复制相似问题