Timers

智能合約中的倒計時

  • May 7, 2018

我想在我的合約中添加一個東西,每 10 分鐘將合約中的所有 ETH 發送到我的錢包。我不知道該怎麼做。任何幫助表示讚賞

沒有辦法在智能合約中設置計時器。你必須編寫一個鏈下腳本,將交易發送到合約,告訴它撤回。或者,您可以將所有支付給契約的款項轉發到您的地址。

有一種方法可以做到這一點。

合約可以直接獲取時間,但不能自行執行。

你可以使用像Chronos這樣的服務,它允許你以簡單的方式安排對你的合約的呼叫。您將在此處找到有關如何完全按照您的要求進行操作的範例,請查看範例。這可以在 Rinkeby 上用於測試。例如,您可以要求每 N 個區塊呼叫一次您的合約。

其他服務也可用,如Oraclize乙太坊鬧鐘

如何在 Chronos 中使用您所要求的範例(合約餘額應該足以支付 gas,或者您可以使用 Chronos 的功能預向您的合約地址收取費用,您可以隨時索回您不使用的東西):

pragma solidity ^0.4.20; 


contract _Chronos {
   function registerCall(address contractAddress, uint256 callOnBlock, uint256 gasAmount) public returns (uint256);
   function clientWithdraw(uint256 value) public;
   function clientFunding(address contractAddress) public payable;

}

contract Client {
   function setCallrequest(uint256 blockNumber, uint256 gasAmount) public;
   function callBack() public;
   function withdrawFromChronos(uint value) public;
   function getDepositsFromChronos() public payable;
}



contract YourContract is Client {
   address public chronosAddress;
   address public admin;

   function YourContract() public {
       chronosAddress = address(0x4896FE22970B06b778592F9d56F7003799E7400f);
       admin = msg.sender;
   }




   function setCallrequest(uint256 blockNumber, uint256 gasAmount) public {
       _Chronos ChronosInstance = _Chronos(chronosAddress);
       uint256 costs = ChronosInstance.registerCall(address(this), blockNumber, gasAmount);
       require(address(this).balance >= costs);
       ChronosInstance.clientFunding.value(costs)(address(this));
   }


   function callBack() public {
       setCallrequest(block.number + 40, 200000); // 40 indicated how many blocks to wait to receive the call, 40 blocks * 15sec/block = 600 sec = 10 min

       admin.transfer(this.balance); // you may want to leave some ether in your contract to pay for the next call. The gas used is small but is not zero, in this example 200000 gas is passed. If this is not consumed the contract will save it and you can withdraw what you do not use. if the gas you pass is not enough the call is not executed. 
   }



   function () public payable {}



}

**免責聲明:**我為 Chronos 編寫了程式碼。

讓我知道這是否適合您。希望能幫助到你

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