-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathTimelock.sol
More file actions
55 lines (42 loc) · 2.24 KB
/
Timelock.sol
File metadata and controls
55 lines (42 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// SPDX-License-Identifier: MIT
//
// https://cryptomarketpool.com/time-lock-contract
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
// The time lock Solidity smart contract below demonstrates how to use the passing of time in a Solidity smart contract.
// Think of this contract like a weekly allowance or escrow that needs to pay out weekly.
//
// overflow and underflow examples and preventions
// one can deposit ether into this contract but you must wait 1 week before you can withdraw your funds
contract Timelock {
// calling SafeMath will add extra functions to the uint data type
using SafeMath for uint256; // you can make a call like myUint.add(123)
// amount of ether you deposited is saved in balances
mapping(address => uint256) public balances;
// when you can withdraw is saved in lockTime
mapping(address => uint256) public lockTime;
function deposit() external payable {
balances[msg.sender] += msg.value;
lockTime[msg.sender] = block.timestamp + 1 weeks;
}
// the function that is commented out is vulnerable to overflow by updating the function below with a very large number
// to prevent this use safe math to prevent overflow
// function increaseLockTime(uint _secondsToIncrease) public {
// lockTime[msg.sender] += _secondsToIncrease;
// }
function increaseLockTime(uint256 _secondsToIncrease) public {
// the add function below is from safemath and will take care of uint overflow
// if a call to add causes an error an error will be thrown and the call to the function will fail
lockTime[msg.sender] = lockTime[msg.sender].add(_secondsToIncrease);
}
function withdraw() public {
// check that the sender has ether deposited in this contract in the mapping and the balance is >0
require(balances[msg.sender] > 0, "insufficient funds");
// check that the now time is > the time saved in the lock time mapping
require(block.timestamp > lockTime[msg.sender], "lock time has not expired");
uint256 amount = balances[msg.sender];
balances[msg.sender] = 0;
(bool sent, ) = msg.sender.call{value: amount}("");
require(sent, "Failed to send ether");
}
}