'How to set a timer in solidity?
I am launching a game that should close after exactly 3 days/72 hours of initializing & deploying the contract.
My current thoughts are:
- declare a variable,
timestamp. - in the constructor, set the variable
timestamptoblock.timestamp - add 3 days worth of time [in milliseconds i presume] to the
timestampvariable - do a
require(block.timestamp < timestamp)in the game logic [users call a write function, so I can do it in there], so users cannot write the function ifblock.timestampis pasttimestamp + 3 days
Is this is a feasible solution? Is there a better solution? Is there a more gas efficient solution?
Thanks in advance
Solution 1:[1]
I just wrote this:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
contract MyContract{
uint start;
uint end;
modifier timeIsOver{
require(block.timestamp<=end,"Time is up");
_;
}
// Firstly, call this
function startTimer() public{
start=block.timestamp;
}
// Secondly, call this
// timestamp of the current block in seconds since the epoch
// period is in seconds
function endTimer(uint period) public {
end=period+start;
}
function timeLeft() public view returns(uint){
return end-block.timestamp;
}
function callThisWhenTimeIsUp() external timeIsOver{
// write the logic here
}
}
Or you could use oracle to set up timer. Oracle is external serice that you use in ethereum. an example: https://blog.chain.link/blockchain-voting-using-a-chainlink-alarm-clock-oracle/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
