Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ node_modules
**/target
artifacts/
cache/
lib/
out/
typechain-types/

# Logs
Expand Down
38 changes: 38 additions & 0 deletions assignments/foundry-test/timelock/.github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
name: CI

permissions: {}

on:
push:
pull_request:
workflow_dispatch:

env:
FOUNDRY_PROFILE: ci

jobs:
check:
name: Foundry project
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v5
with:
persist-credentials: false
submodules: recursive

- name: Install Foundry
uses: foundry-rs/foundry-toolchain@v1

- name: Show Forge version
run: forge --version

- name: Run Forge fmt
run: forge fmt --check

- name: Run Forge build
run: forge build --sizes

- name: Run Forge tests
run: forge test -vvv
14 changes: 14 additions & 0 deletions assignments/foundry-test/timelock/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Compiler files
cache/
out/

# Ignores development broadcast logs
!/broadcast
/broadcast/*/31337/
/broadcast/**/dry-run/

# Docs
docs/

# Dotenv file
.env
3 changes: 3 additions & 0 deletions assignments/foundry-test/timelock/.gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "lib/forge-std"]
path = lib/forge-std
url = https://github.com/foundry-rs/forge-std
66 changes: 66 additions & 0 deletions assignments/foundry-test/timelock/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
## Foundry

**Foundry is a blazing fast, portable and modular toolkit for Ethereum application development written in Rust.**

Foundry consists of:

- **Forge**: Ethereum testing framework (like Truffle, Hardhat and DappTools).
- **Cast**: Swiss army knife for interacting with EVM smart contracts, sending transactions and getting chain data.
- **Anvil**: Local Ethereum node, akin to Ganache, Hardhat Network.
- **Chisel**: Fast, utilitarian, and verbose solidity REPL.

## Documentation

https://book.getfoundry.sh/

## Usage

### Build

```shell
$ forge build
```

### Test

```shell
$ forge test
```

### Format

```shell
$ forge fmt
```

### Gas Snapshots

```shell
$ forge snapshot
```

### Anvil

```shell
$ anvil
```

### Deploy

```shell
$ forge script script/Counter.s.sol:CounterScript --rpc-url <your_rpc_url> --private-key <your_private_key>
```

### Cast

```shell
$ cast <subcommand>
```

### Help

```shell
$ forge --help
$ anvil --help
$ cast --help
```
8 changes: 8 additions & 0 deletions assignments/foundry-test/timelock/foundry.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"lib/forge-std": {
"tag": {
"name": "v1.15.0",
"rev": "0844d7e1fc5e60d77b68e469bff60265f236c398"
}
}
}
6 changes: 6 additions & 0 deletions assignments/foundry-test/timelock/foundry.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[profile.default]
src = "src"
out = "out"
libs = ["lib"]

# See more config options https://github.com/foundry-rs/foundry/blob/master/crates/config/README.md#all-options
5 changes: 5 additions & 0 deletions assignments/foundry-test/timelock/remappings.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/
erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/
forge-std/=lib/forge-std/src/
halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/
openzeppelin-contracts/=lib/openzeppelin-contracts/
19 changes: 19 additions & 0 deletions assignments/foundry-test/timelock/script/Counter.s.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import {Script} from "forge-std/Script.sol";
import {Counter} from "../src/Counter.sol";

contract CounterScript is Script {
Counter public counter;

function setUp() public {}

function run() public {
vm.startBroadcast();

counter = new Counter();

vm.stopBroadcast();
}
}
14 changes: 14 additions & 0 deletions assignments/foundry-test/timelock/src/Counter.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

contract Counter {
uint256 public number;

function setNumber(uint256 newNumber) public {
number = newNumber;
}

function increment() public {
number++;
}
}
14 changes: 14 additions & 0 deletions assignments/foundry-test/timelock/src/IERC20.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IErc20 is IERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256 balance);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
}
182 changes: 182 additions & 0 deletions assignments/foundry-test/timelock/src/TimelockV2.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;

import {IErc20} from "./IERC20.sol";

contract TimeLockV2 {
IErc20 public immutable henToken;
address public owner;

struct Vault {
uint256 balance;
uint256 tokenBalance;
uint256 unlockTime;
bool active;
}

constructor(address _token) {
henToken = IErc20(_token);
owner = msg.sender;
}

modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}

mapping(address => Vault[]) private vaults;

event Deposited(address indexed user, uint256 vaultId, uint256 amount, uint256 unlockTime);
event Withdrawn(address indexed user, uint256 vaultId, uint256 amount);

// Internal function
function _depositRatio(uint256 _totalDeposit) internal pure returns (uint256 _tokenAmount) {
_tokenAmount = _totalDeposit * 10; // Token Ratio
}

function deposit(uint256 _unlockTime) external payable returns (uint256) {
require(msg.value > 0, "Deposit must be greater than zero");
require(_unlockTime > block.timestamp, "Unlock time must be in the future");

uint256 tokenBal = _depositRatio(msg.value);
require(henToken.transfer(msg.sender, tokenBal), "Token transfer failed");

// Create new vault
vaults[msg.sender].push(
Vault({balance: msg.value, unlockTime: _unlockTime, tokenBalance: tokenBal, active: true})
);

uint256 vaultId = vaults[msg.sender].length - 1;
emit Deposited(msg.sender, vaultId, msg.value, _unlockTime);

return vaultId;
}

function withdraw(uint256 _vaultId) external {
require(_vaultId < vaults[msg.sender].length, "Invalid vault ID");

Vault storage userVault = vaults[msg.sender][_vaultId];
require(userVault.active, "Vault is not active");
require(userVault.balance > 0, "Vault has zero balance");
require(block.timestamp >= userVault.unlockTime, "Funds are still locked");

uint256 amount = userVault.balance;
uint256 tokenAmount = userVault.tokenBalance;

// Mark vault as inactive and clear balance
userVault.balance = 0;
userVault.tokenBalance = 0;
userVault.active = false;

require(henToken.transferFrom(msg.sender, address(this), tokenAmount), "Token transfer failed");

(bool success,) = payable(msg.sender).call{value: amount}("");
require(success, "Transfer failed");

emit Withdrawn(msg.sender, _vaultId, amount);
}

function withdrawAll() external returns (uint256) {
uint256 totalWithdrawn = 0;
Vault[] storage userVaults = vaults[msg.sender];

for (uint256 i = 0; i < userVaults.length; i++) {
if (userVaults[i].active && userVaults[i].balance > 0 && block.timestamp >= userVaults[i].unlockTime) {
uint256 amount = userVaults[i].balance;
userVaults[i].balance = 0;
userVaults[i].active = false;

totalWithdrawn += amount;
emit Withdrawn(msg.sender, i, amount);
}
}

require(totalWithdrawn > 0, "No unlocked funds available");

(bool success,) = payable(msg.sender).call{value: totalWithdrawn}("");
require(success, "Transfer failed");

return totalWithdrawn;
}

function emergencyWithdraw() external onlyOwner returns (uint256 amount) {
amount = address(this).balance;
require(amount > 0, "No funds available");

(bool success,) = payable(owner).call{value: amount}("");
if (!success) revert();
}

function getVaultCount(address _user) external view returns (uint256) {
return vaults[_user].length;
}

function getVault(address _user, uint256 _vaultId)
external
view
returns (uint256 balance, uint256 unlockTime, bool active, bool isUnlocked)
{
require(_vaultId < vaults[_user].length, "Invalid vault ID");

Vault storage vault = vaults[_user][_vaultId];
return (vault.balance, vault.unlockTime, vault.active, block.timestamp >= vault.unlockTime);
}

function getAllVaults(address _user) external view returns (Vault[] memory) {
return vaults[_user];
}

function getActiveVaults(address _user)
external
view
returns (uint256[] memory activeVaults, uint256[] memory balances, uint256[] memory unlockTimes)
{
Vault[] storage userVaults = vaults[_user];

// Count active vaults
uint256 activeCount = 0;
for (uint256 i = 0; i < userVaults.length; i++) {
if (userVaults[i].active && userVaults[i].balance > 0) {
activeCount++;
}
}

// Create arrays
activeVaults = new uint256[](activeCount);
balances = new uint256[](activeCount);
unlockTimes = new uint256[](activeCount);

// Populate arrays
uint256 index = 0;
for (uint256 i = 0; i < userVaults.length; i++) {
if (userVaults[i].active && userVaults[i].balance > 0) {
activeVaults[index] = i;
balances[index] = userVaults[i].balance;
unlockTimes[index] = userVaults[i].unlockTime;
index++;
}
}

return (activeVaults, balances, unlockTimes);
}

function getTotalBalance(address _user) external view returns (uint256 total) {
Vault[] storage userVaults = vaults[_user];
for (uint256 i = 0; i < userVaults.length; i++) {
if (userVaults[i].active) {
total += userVaults[i].balance;
}
}
return total;
}

function getUnlockedBalance(address _user) external view returns (uint256 unlocked) {
Vault[] storage userVaults = vaults[_user];
for (uint256 i = 0; i < userVaults.length; i++) {
if (userVaults[i].active && userVaults[i].balance > 0 && block.timestamp >= userVaults[i].unlockTime) {
unlocked += userVaults[i].balance;
}
}
return unlocked;
}
}
Loading