Timelock Contracts and DeFi Security: Lessons from Compound
Hey, fabulous folks of the web! 👋
Buckle up, because in this article, we’re taking a stroll down the Timelock smart contract lane. We’ll be peeling back the layers on:
- Timelock contracts — what exactly are they?
- The ‘why’ behind their existence.
- A balanced view of their pros and cons.
- And, of course, how the Compound protocol puts Timelocks to work.
Timelock Contracts in Plain English
Smart contract timelocks introduce a mechanism to delay the execution of functions.
These contracts use modifiers that modify how functions operate, ensuring they remain inactive until a predefined time period has elapsed.
Example of a modifier :
modifier onlyBefore(uint time) {
if (block.timestamp >= time) revert TooLate(time);
_;
}
The Motivation
In the blockchain world, on-chain governance is the go-to method for making changes to smart contracts. But there’s a catch — it can be a bit risky.
Imagine an attacker swooping in with a flash loan and pushing through a sneaky proposal, or a founder going rogue and making changes without asking anyone. To avoid these nightmares, projects like Uniswap and Compound employ timelocks.⏰
Here’s how it works: When there’s a proposal to tweak protocol settings, it has to pass through the timelock. This timelock puts a set waiting period (usually two days) on executing the proposal.
This gives the community time to react — they can cancel the proposal or exit the system if needed. Timelocks are like the safety net for on-chain governance.⛓️
But it doesn’t stop there.Let’s say you’ve got a lending platform that uses an on-chain price oracle to calculate how much users can borrow.
An attacker could manipulate this oracle to inflate collateral values. To stop this, you can impose a short delay (like one block) between deposits and loans.
This delay makes it harder for the attacker to pull off their shenanigans, keeping your system safe and sound.🤌
Timelock Drawbacks
- Short Delays: Timelocks are only effective if the delay period is adequate. A too-short delay might let malicious proposals slip by unnoticed, as seen in the case of Beanstalk’s one-day delay.
- Privileged Control: The entity that deploys the timelock can maintain control. This could lead to abuse, with someone altering the delay for their benefit.
- Timestamp Reliance: Depending on block timestamps for execution can be problematic. Block producers can manipulate timestamps.
Code Crunch
Let’s take a closer look at the Timelock code from the Compound protocol. You can access the code by following this link: here
Our main goals with this contract are to:
- Manage Transactions: Understand how transactions are queued, executed, and canceled.
- Adjust the Delay: Learn how to update the delay period for transaction execution.
- Change Admin: See how contract control changes.
Code :
contract Timelock {
using SafeMath for uint;
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint indexed newDelay);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
}
We’ve implemented SafeMath in our code, to ensure secure arithmetic operations and have events listed for the smart contracts.
uint public constant GRACE_PERIOD = 14 days;
uint public constant MINIMUM_DELAY = 2 days;
uint public constant MAXIMUM_DELAY = 30 days;
address public admin;
address public pendingAdmin;
uint public delay;
mapping (bytes32 => bool) public queuedTransactions;
This code sets constants for grace, minimum, and maximum delay periods, defines admin and pending admin addresses, stores the current delay, and maintains a mapping to track queued transactions by their hash.
constructor(address admin_, uint delay_) public {
require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
admin = admin_;
delay = delay_;
}
fallback() external payable { }
function setDelay(uint delay_) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NewDelay(delay);
}
The above functions are self explanatory.
function setPendingAdmin(address pendingAdmin_) public {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
function acceptAdmin() public {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
These to functions manage the ownership of the contract.
Observation : Only the contract can call the setPendingAdmin
🧐?
Yes! This control over admin changes aligns with the concept of on-chain governance, where such actions are treated as transactions and require queuing.
function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public {
require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CancelTransaction(txHash, target, value, signature, data, eta);
}
function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) {
require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, target, value, signature, data, eta);
return returnData;
}
function getBlockTimestamp() internal view returns (uint) {
// solium-disable-next-line security/no-block-members
return block.timestamp;
}
Onto the main functionality :
- Queue Transaction: Admin can request to queue a transaction by specifying the target address, value, function signature, data, and estimated execution time (eta). The request is hashed, marked as queued, and an event is emitted to log the action.
- Cancel Transaction: The admin can cancel a queued transaction by providing the same parameters used during queuing. This action simply marks the transaction as unqueued and logs it.
- Execute Transaction: Again, only the admin can execute a queued transaction. The contract checks if the transaction has been queued, if it’s within the set time frame, and if it’s not too late (within the grace period). If all checks pass, the transaction is executed, and its outcome is logged.
It’s as straightforward as that, and now you’ve got the scoop on how timelock smart contracts work in various protocols. 🕒💡
I really hope this post was informative and helped you understand Timelock. Thank you so much for taking the time to read it!
If you found this post useful, please consider sharing it with your friends and colleagues. Your support means a lot to me 🥳.
Follow me on twitter!