0
0
Blockchain / Solidityprogramming~5 mins

Timelock pattern in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

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.

When you want to delay important contract changes to give users time to react.
When you want to schedule a transaction to happen only after a certain time.
When you want to add a safety buffer before executing sensitive operations.
When you want to improve trust by making contract upgrades visible before they happen.
Syntax
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.

Examples
This sets the unlock time to 1 day from now.
Blockchain / Solidity
uint public unlockTime = block.timestamp + 1 days;
This checks if the current time is past the unlock time before continuing.
Blockchain / Solidity
require(block.timestamp >= unlockTime, "Action locked");
This function lets you set a custom delay before the action can run.
Blockchain / Solidity
function scheduleAction(uint delaySeconds) public {
    unlockTime = block.timestamp + delaySeconds;
}
Sample Program

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.

Blockchain / Solidity
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!";
    }
}
OutputSuccess
Important Notes

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.

Summary

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.