智能合约中具有一定条件的交易自动化



我现在正在开发区块链游戏服务,我想在游戏结束时和特定时间自动向获胜者发送一些代币。

/*
* This function should be called every X days
*/
function sendTokens() public {
// We send some tokens to an array of players
}

目前,我正在使用传统的后端技术(如setInterval和WebSocket(来完成这项工作——然而,这是一种集中的方法。

最好的方法是什么?专业的方式是什么?

链上发生的每个状态更改都需要由事务触发。因此,要在特定事件或其他事件触发后按计划运行智能合约功能,您需要有人花费汽油。

话虽如此,你有两个选择:

1.分散自动化

你可以使用去中心化的预言机网络来调用智能合约。使用Chainlink Keepers可以随时调用您指定的函数或以事件触发器为中心。oracles支付与调用相关的gas,而您支付Chainlink节点的订阅模型。

这样,你的合同一直保持去中心化,一直到自动化级别,你永远不必担心集中的参与者故意不发送交易。

您可以使用checkUpkeep设置触发器,方法是在合同中定义要等待的事件(如基于时间的、基于某些事件的等(,然后在performUpkeep中触发时要做什么。

例如:

此合约每interval秒运行一次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.集中自动化

你也可以有";传统的";基础设施按时间表调用您的函数,请记住,这意味着您在合同中依赖于一个集中的参与者。

您可以采取以下形式的集中自动化:

  • 您自己的服务器/脚本集
  • Openzeppelin Defender
  • 温柔
  • 激励机制,让人们调用您的功能等等

免责声明:我在Chainlink实验室工作

最新更新