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: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ test: add coverage for revert conditions
4. Pull Request Checklist
- [x] Code compiles
- [x] Tests pass
- [x] README included
- [x] README
- [x] No changes outside /submissions

5. PR Review Process
Expand Down
20 changes: 20 additions & 0 deletions assignments/10-vault/vaults/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Node modules
/node_modules

# Compilation output
/dist

# pnpm deploy output
/bundle

# Hardhat Build Artifacts
/artifacts

# Hardhat compilation (v2) support directory
/cache

# Typechain output
/types

# Hardhat coverage reports
/coverage
57 changes: 57 additions & 0 deletions assignments/10-vault/vaults/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Sample Hardhat 3 Beta Project (`mocha` and `ethers`)

This project showcases a Hardhat 3 Beta project using `mocha` for tests and the `ethers` library for Ethereum interactions.

To learn more about the Hardhat 3 Beta, please visit the [Getting Started guide](https://hardhat.org/docs/getting-started#getting-started-with-hardhat-3). To share your feedback, join our [Hardhat 3 Beta](https://hardhat.org/hardhat3-beta-telegram-group) Telegram group or [open an issue](https://github.com/NomicFoundation/hardhat/issues/new) in our GitHub issue tracker.

## Project Overview

This example project includes:

- A simple Hardhat configuration file.
- Foundry-compatible Solidity unit tests.
- TypeScript integration tests using `mocha` and ethers.js
- Examples demonstrating how to connect to different types of networks, including locally simulating OP mainnet.

## Usage

### Running Tests

To run all the tests in the project, execute the following command:

```shell
npx hardhat test
```

You can also selectively run the Solidity or `mocha` tests:

```shell
npx hardhat test solidity
npx hardhat test mocha
```

### Make a deployment to Sepolia

This project includes an example Ignition module to deploy the contract. You can deploy this module to a locally simulated chain or to Sepolia.

To run the deployment to a local chain:

```shell
npx hardhat ignition deploy ignition/modules/Counter.ts
```

To run the deployment to Sepolia, you need an account with funds to send the transaction. The provided Hardhat configuration includes a Configuration Variable called `SEPOLIA_PRIVATE_KEY`, which you can use to set the private key of the account you want to use.

You can set the `SEPOLIA_PRIVATE_KEY` variable using the `hardhat-keystore` plugin or by setting it as an environment variable.

To set the `SEPOLIA_PRIVATE_KEY` config variable using `hardhat-keystore`:

```shell
npx hardhat keystore set SEPOLIA_PRIVATE_KEY
```

After setting the variable, you can run the deployment with the Sepolia network:

```shell
npx hardhat ignition deploy --network sepolia ignition/modules/Counter.ts
```
19 changes: 19 additions & 0 deletions assignments/10-vault/vaults/contracts/Counter.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;

contract Counter {
uint public x;

event Increment(uint by);

function inc() public {
x++;
emit Increment(1);
}

function incBy(uint by) public {
require(by > 0, "incBy: increment should be positive");
x += by;
emit Increment(by);
}
}
35 changes: 35 additions & 0 deletions assignments/10-vault/vaults/contracts/Counter.t.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;

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

// Solidity tests are compatible with foundry, so they
// use the same syntax and offer the same functionality.

contract CounterTest is Test {
Counter counter;

function setUp() public {
counter = new Counter();
}

function test_InitialValue() public view {
require(counter.x() == 0, "Initial value should be 0");
}

function testFuzz_Inc(uint8 x) public {
for (uint8 i = 0; i < x; i++) {
counter.inc();
}
require(
counter.x() == x,
"Value after calling inc x times should be x"
);
}

function test_IncByZero() public {
vm.expectRevert();
counter.incBy(0);
}
}
67 changes: 67 additions & 0 deletions assignments/10-vault/vaults/contracts/vaults.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract TimelockedSavingsVault {
struct Vault {
uint256 amount;
uint256 unlockTime;
}

mapping(address => Vault) private vaults;

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

error VaultAlreadyExists();
error NoActiveVault();
error UnlockTimeInPast();
error AmountMustBePositive();
error NotUnlocked();
error TransferFailed();

function deposit(uint256 unlockTime) external payable {
if (msg.value == 0) revert AmountMustBePositive();
Vault storage v = vaults[msg.sender];
if (v.amount != 0) revert VaultAlreadyExists();
if (unlockTime <= block.timestamp) revert UnlockTimeInPast();

v.amount = msg.value;
v.unlockTime = unlockTime;

emit Deposited(msg.sender, msg.value, unlockTime);
}

function withdraw() external {
Vault storage v = vaults[msg.sender];
if (v.amount == 0) revert NoActiveVault();
if (block.timestamp < v.unlockTime) revert NotUnlocked();

uint256 amount = v.amount;

// Reset vault before transfer to prevent reentrancy
v.amount = 0;
v.unlockTime = 0;

(bool sent, ) = msg.sender.call{value: amount}("");
if (!sent) revert TransferFailed();

emit Withdrawn(msg.sender, amount);
}

// Reject direct ETH transfers to force users to call `deposit`
receive() external payable {
revert("Direct transfers not allowed");
}

fallback() external payable {
revert("Direct transfers not allowed");
}

/// @notice Returns the vault details for `user`.
function getVault(
address user
) external view returns (uint256 amount, uint256 unlockTime) {
Vault storage v = vaults[user];
return (v.amount, v.unlockTime);
}
}
38 changes: 38 additions & 0 deletions assignments/10-vault/vaults/hardhat.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import hardhatToolboxMochaEthersPlugin from "@nomicfoundation/hardhat-toolbox-mocha-ethers";
import { configVariable, defineConfig } from "hardhat/config";

export default defineConfig({
plugins: [hardhatToolboxMochaEthersPlugin],
solidity: {
profiles: {
default: {
version: "0.8.28",
},
production: {
version: "0.8.28",
settings: {
optimizer: {
enabled: true,
runs: 200,
},
},
},
},
},
networks: {
hardhatMainnet: {
type: "edr-simulated",
chainType: "l1",
},
hardhatOp: {
type: "edr-simulated",
chainType: "op",
},
sepolia: {
type: "http",
chainType: "l1",
url: configVariable("SEPOLIA_RPC_URL"),
accounts: [configVariable("SEPOLIA_PRIVATE_KEY")],
},
},
});
9 changes: 9 additions & 0 deletions assignments/10-vault/vaults/ignition/modules/Counter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { buildModule } from "@nomicfoundation/hardhat-ignition/modules";

export default buildModule("CounterModule", (m) => {
const counter = m.contract("Counter");

m.call(counter, "incBy", [5n]);

return { counter };
});
20 changes: 20 additions & 0 deletions assignments/10-vault/vaults/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "vaults",
"version": "1.0.0",
"type": "module",
"devDependencies": {
"@nomicfoundation/hardhat-ethers": "^4.0.4",
"@nomicfoundation/hardhat-ignition": "^3.0.7",
"@nomicfoundation/hardhat-toolbox-mocha-ethers": "^3.0.2",
"@types/chai": "^4.3.20",
"@types/chai-as-promised": "^8.0.2",
"@types/mocha": "^10.0.10",
"@types/node": "^22.19.8",
"chai": "^5.3.3",
"ethers": "^6.16.0",
"forge-std": "github:foundry-rs/forge-std#v1.9.4",
"hardhat": "^3.1.6",
"mocha": "^11.7.5",
"typescript": "~5.8.0"
}
}
22 changes: 22 additions & 0 deletions assignments/10-vault/vaults/scripts/send-op-tx.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { network } from "hardhat";

const { ethers } = await network.connect({
network: "hardhatOp",
chainType: "op",
});

console.log("Sending transaction using the OP chain type");

const [sender] = await ethers.getSigners();

console.log("Sending 1 wei from", sender.address, "to itself");

console.log("Sending L2 transaction");
const tx = await sender.sendTransaction({
to: sender.address,
value: 1n,
});

await tx.wait();

console.log("Transaction sent successfully");
36 changes: 36 additions & 0 deletions assignments/10-vault/vaults/test/Counter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { expect } from "chai";
import { network } from "hardhat";

const { ethers } = await network.connect();

describe("Counter", function () {
it("Should emit the Increment event when calling the inc() function", async function () {
const counter = await ethers.deployContract("Counter");

await expect(counter.inc()).to.emit(counter, "Increment").withArgs(1n);
});

it("The sum of the Increment events should match the current value", async function () {
const counter = await ethers.deployContract("Counter");
const deploymentBlockNumber = await ethers.provider.getBlockNumber();

// run a series of increments
for (let i = 1; i <= 10; i++) {
await counter.incBy(i);
}

const events = await counter.queryFilter(
counter.filters.Increment(),
deploymentBlockNumber,
"latest",
);

// check that the aggregated events match the current value
let total = 0n;
for (const event of events) {
total += event.args.by;
}

expect(await counter.x()).to.equal(total);
});
});
13 changes: 13 additions & 0 deletions assignments/10-vault/vaults/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/* Based on https://github.com/tsconfig/bases/blob/501da2bcd640cf95c95805783e1012b992338f28/bases/node22.json */
{
"compilerOptions": {
"lib": ["es2023"],
"module": "node16",
"target": "es2022",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"moduleResolution": "node16",
"outDir": "dist"
}
}
Loading