The Timelock pattern helps control when certain actions can happen in a blockchain contract. It adds a waiting period before changes take effect, making things safer and more transparent.
Timelock pattern in Blockchain / Solidity
contract Timelock {
uint public unlockTime;
address public owner;
constructor(uint _waitTime) {
owner = msg.sender;
unlockTime = block.timestamp + _waitTime;
}
function execute() public {
require(block.timestamp >= unlockTime, "Too early to execute");
// perform the action
}
}block.timestamp gives the current time in seconds since Unix epoch.
The require statement stops the action if the time is not reached yet.
uint public unlockTime = block.timestamp + 1 days;require(block.timestamp >= unlockTime, "Action locked");function scheduleAction(uint delaySeconds) public {
unlockTime = block.timestamp + delaySeconds;
}This contract sets a time lock when created. The execute function can only run after the unlock time. If called too early, it stops with an error.
pragma solidity ^0.8.0; contract SimpleTimelock { uint public unlockTime; address public owner; constructor(uint _waitTime) { owner = msg.sender; unlockTime = block.timestamp + _waitTime; } function execute() public view returns (string memory) { require(block.timestamp >= unlockTime, "Too early to execute"); return "Action executed!"; } }
The Timelock pattern helps protect users by giving them time to react before changes happen.
Always test your time calculations carefully to avoid mistakes.
Remember that block timestamps can be influenced slightly by miners, so don't rely on exact precision.
The Timelock pattern delays actions until a set time, improving security and trust.
It uses the blockchain's current time to check if the delay has passed.
This pattern is useful for upgrades, sensitive transactions, and scheduled operations.