README.md Updated
Some checks are pending
CI / Foundry project (push) Waiting to run

This commit is contained in:
hoelee 2024-08-16 12:41:38 +08:00
parent 3e168a9594
commit 47393f36ad
7 changed files with 355 additions and 108 deletions

15
.gas-snapshot Normal file
View File

@ -0,0 +1,15 @@
RaffleTest:testCheckUpkeepReturnsFalseIfEnoughTimeHasntPassed() (gas: 71651)
RaffleTest:testCheckUpkeepReturnsFalseIfItHasNoBalance() (gas: 19116)
RaffleTest:testCheckUpkeepReturnsFalseIfRaffleIsntOpen() (gas: 220192)
RaffleTest:testCheckUpkeepReturnsTrueWhenParametersGood() (gas: 74771)
RaffleTest:testDontAllowPlayersToEnterWhileRaffleIsCalculating() (gas: 225100)
RaffleTest:testEmitsEventOnEntrance() (gas: 68726)
RaffleTest:testFulfillRandomWordsCanOnlyBeCalledAfterPerformUpkeep(uint256) (runs: 256, μ: 80495, ~: 80495)
RaffleTest:testFulfillRandomWordsPicksAWinnerResetsAndSendsMoney() (gas: 335011)
RaffleTest:testHoelee() (gas: 334948)
RaffleTest:testPerformUpkeepCanOnlyRunIfCheckUpkeepIsTrue() (gas: 216510)
RaffleTest:testPerformUpkeepRevertsIfCheckUpkeepIsFalse() (gas: 74015)
RaffleTest:testPerformUpkeepUpdatesRaffleStateAndEmitsRequestId() (gas: 222486)
RaffleTest:testRaffleInitializesInOpenState() (gas: 7665)
RaffleTest:testRaffleRecordsPlayerWhenTheyEnter() (gas: 68271)
RaffleTest:testRaffleRevertsWHenYouDontPayEnough() (gas: 10873)

85
Foundry.md Normal file
View File

@ -0,0 +1,85 @@
## 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/
## 1. Setup Foundry Development Environment
```
Install Foundry
curl -L https://foundry.paradigm.xyz | bash
Install ZKsync
git clone https://github.com/matter-labs/foundry-zksync
./install-foundry-zksync
Use of L1 / L2 Compiler
foundryup
foundryup-zksync
Start Local Blockchain Node
anvil
```
### Usage of forge:
```
Library Installation
forge install smartcontractkit/chainlink-brownie-contracts@1.1.1 --no-commit
forge install Rari-Capital/solmate --no-commit
forge install cyfrin/foundry-devops --no-commit
forge install transmissions11/solmate@v6 --no-commit
Usage
forge build / forge compile
forge test
forge test -mt functionNameWithAnyBehind* -vvvv
forge coverage --report debug > coverage.txt
forge create Raffle --rpc-url HTTP://127.0.0.1:7545 --interactive --private-key 0x074a2cf34f5c15acec32ff0f95190b865ee8d2c448ae505e1a791404d6ce1da5
This should avoid, better with use of keystore
forge script script/DeployContract.s.sol --rpc-url HTTP://127.0.0.1:7545 --broadcast --account localAccountName
forge snapshot
See Gas Usage For Each Function
```
### Usage of cast:
```
Convert HEX to DEC
cast --to-base 0x714c2 dec
Encrypt Private Key Locally
cast wallet import keyStoreName --interactive
Sign Public Transaction (Testnet / Mainnet)
Ensure .env readed into CMD
source .env
Call contract store() function
cast send 0Xabcdefabcdef "store(uint256)" 123 --rpc-url $RPC_URL --private-key $PRIVATE_KEY
Call contract retrieve() function, using previous keystore locally (Need enter local password)
cast call 0xabcdefabcdef "retrieve()" --rpc-url $RPC_URL --account keyStoreName
```
### Flow of the execution
1. Terminal Execution of Command:
> forge test
> forge script script/DeployRaffle.s.sol
2. HelperConfig.s.sol Initialized
> if is local network, chainID == 31337, then create VRF Coordinator MOCK
3. DeployRaffle.s.sol
> if subscription ID is 0, then use created VRF Coordinator Mock To create subscription, fund it & add consumer
4. If is test command, then will run setUp()
> add player
> if local network, then will fund VRF Coordinator
> Then continue for the rest of test functions()

120
Hardhat.md Normal file
View File

@ -0,0 +1,120 @@
# Hardhat Smart Contract Project
## 1. Setup Visual Studio Code Development Environment
Windows need to download install WSL
```
wsl --set-default Ubuntu-22.04
mkdir theProjectFolderName
cd theProjectFolderName
code .
// Install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
nvm install 16.14.2
nvm install node.js
nvm install 18 // Update node JS to v18
```
Visual Studio need to update code setting
```
"[solidity]": {
"editor.defaultFormatter":"NomicFoundation.hardhat-solidity"
}
```
Preparing of solidity development environment:
```
corepack enable // Enable yarn
yarn install solc
yarn add solc@0.8.7fixed
yarn solcjs --bin --abi --include-path node_modules/ --base-path . -o . SimpleStorage.sol
yarn add ethers // Compiler Error, Downgraded to v5.7.2
yarn add fs-extra
yarn add dotenv
yarn add prettier
yarn add prettier-plugin-solidity
```
Preparing of Hardhat Development Environment
```
yarn init
// Manual delete main: index.js in package.json
yarn add --dev hardhat // Production no need --dev
nvm install 18
nvm use 18
nvm alias default 18
corepack enable // Enable yarn
yarn hardhat
yarn add --dev prettier prettier-plugin-solidity
yarn add --dev dotenv
yarn add --dev @nomiclabs/hardhat-etherscan // Auto verify Etherscan Samrt Contract
yarn add --dev @nomiclabs/hardhat-waffle
yarn add --dev solhint
yarn add --dev @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers
yarn add --dev hardhat-gas-reporter
yarn add --dev solidity-coverage
yarn add --dev solhint
```
Other Terminal Useful Command 1:
```
// For Debuging Hardhat
npx hardhat --versose
// For Recompile
yarn hardhat clean // Or manual delete artifacts & cache folder
npm install
// For Listing Hardhat Local Blockchain node
yarn hardhat accounts
yarn hardhat node // Run in Dedicated Terminal, Getting Blockchain server
yarn hardhat console --network localhost // Short Life To Test Solidity Code In Terminal
yarn hardhat compile
yarn hardhat run scripts/deploy.js --network localhost
yarn hardhat custom-task-name
// Need create file in /tasks/custom-task-name.js
// Add import in hardhat.config.js -> requir("/tasks/custom-task-name");
yarn hardhat test
yarn hardhat test --grep customSearchKeyword
// Only will run the test with describe test that contain "customSearchKeyword"
```
Other Terminal Useful Command 2:
```
// For Getting Gas Used & Gas Price
yarn hardhat test
// Will create a file in ./gas-report.txt
// With .env of etherscan API key
// For Getting Coverage
yarn hardhat coverage
// Checking code usage & tested percentage
// For Checking Code Best Practice
yarn solhint contracts/*.sol
// For Get Fake Price Feed On Localhost & Ganache
yarn hardhat deploy --tags mocks --network localhost
```
Debug `Node.js` need to open **Javascript Debug Terminal** first, via `ctrl + shift + p`
#### Reduce Gas Used:
- Prioritize use `private` instead of `public`
- Use `constant` which declare once in constructor
- Use `immutable ` which declare once only
This is because blockchain will have higher `read` and `store` gas fee on storage block, lesser in bytes code block.
## 2. Known Issues
- Dependencies combination is old, require some updates...
- ...
### Find a bug?
If you found an issue or would like to submit an improvement to this demo project, please submit an issue using the issues tab above.

42
Hoelee.md Normal file
View File

@ -0,0 +1,42 @@
# Hoelee Note Section
## 1. Git Version Control -> Own Gitea Server
First time initialize:
```
git config --global user.name "hoelee"
git config --global user.email "me@hoelee.com"
git init .
git add .
git checkout -b main
git commit -m "Initial Commit"
git remote set-url origin https://username:accessToken@git.hoelee.com/hoelee/ethers-simple-storage.git
git credential-cache exit // Fix Credential Error
```
Standard Update:
```
git add .
git commit -m "Describe what changes"
git push -u origin main
// After set this, later easier usage via below line
git push
git pull
```
Development need exlude file can create root file with name .gitignore
```
node_modules
package.json
img
artifacts
cache
coverage
.env
.*
README.md
coverage.json
```

159
README.md
View File

@ -1,69 +1,96 @@
## Foundry
# Hoelee Smart Contract - Automate Lottery
**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
```
## Grand Porject Overview
This Project Smart Contract Created With
1. ```Solidity``` Contract + ```Hardhat``` + ```node.js``` for Test
2. ```Solidity``` Contract & Test + ```Foundry```
cast --to-base 0x714c2 dec
># Hardhat Project
A fully functional Smart Contract wrriten with ```solidity```, ```node.js``` and using ```Hardhat``` to show usage of all kinds of standard development features, including:
* running blockchain node in localhost - ```hardhat``` & ```ganache```
* solidity prettier code beautifier setup
* standard of developing Smart Contract with ```solidity```
* standard of developing ```node.js``` script to use ```hardhat``` library efficiently
* check gas fee & gas price in real-time, with usage of ```coverage```
* auto verify contract on Etherscan.io
* creating automate test cases - unit test & staging test
* creating tasks etc.
* refactor codes to reduce gas fee
* write code in best practice, with usage of ```solhint```
* prettier ```solidity``` & ```node.js``` code
* gitea version control
This project mainly to keep as a reference for future Web 3.0 Developments.
>Read More in [Hardhat Project's Note Page](./Hardhat.md).
---
># Foundry Project
Same Lottery Project, Use Of ```Solidity``` to test smart contract, ensure high coverage of function correctness. Feature included:
* Modular Enable Test In Multiple Networks With Different Conditions
* Local Network Using Of Anvil + Mock VRF (Verifiable Randomness Function)
* Testnet Use of Latest V2.5 Chainlink VRF Subscription With Consumer Subscription
* Use of Custom LinkToken on Sepolia Testnet
* Smart Contract Test With High Coverage To Ensure Correctness
* Private Key Encrypted With Keystore, Safer Usage With Password
* Smart Contract Layer-2 Ready (ZKsync)
>Read More In [Foundry Project's Note Page](./Foundry.md).
### Success Deploy & Verified Smart Contract In Sepolia Testnet
0xc2022b56eBC140B5FebCf9FBaB14c17db4C315C4
https://sepolia.etherscan.io/address/0xc2022b56eBC140B5FebCf9FBaB14c17db4C315C4#code
Via deploy.js
https://sepolia.etherscan.io/address/0x3a827C119e1D746bb3C7bcbbf95c55246C8CcBdd#code
Via yarn hardhat deploy --network sepolia
### Public Reported Hacked Code References:
This website is records of all kind previous hacked smart contract:
https://rekt.news/leaderboard/
## 1. Understanding Of Known Vulnerabilities
* Reentrancy Attack
* Locked with modifier while running withdraw function
* Update variable immediately before call external function
* Integer Overflow / Underflow
* Use compiler version >0.8.0 have check in place
* Front-Running
* Use average gas fee / off peak times
* Use commit-reveal schema
* Use submarine send
## 2. Other Explored Features
1. Generate Random Words
* Create subscription at https://vrf.chain.link/ (MetaMask #1)
* Add Fund To The Created Subsciption Contract (MetaMask #2)
* Add Consumer
* Get Subscription ID
* Open Remix To Prepare Deploy Consumer Contract https://docs.chain.link/vrf/v2-5/migration-from-v2
* Change To Correct gwei limit hash address at https://docs.chain.link/vrf/v2/subscription/supported-networks
* Adjust Setting - random words count, confirmation blocks etc.
* Insert Subscription ID - v2 is uint64 BUT **v2.5 is uint256**
* Deploy And Get hash address (MetaMask #3)
* Insert in chainlink consumer (Metamask #4)
* Ready to use, record down the consumer contract address
2. New Time Based Trigger Automation Through Chainlink UpKeep
* Same As VRF Subscription, V2.5 Optional Reduced Steps
* Setup At https://automation.chain.link/
* After Subscription Created, Funded, & Setup Interval:
* VRFCoordinator will call checkUpkeep(bytes memory checkData)
* checkUpkeep true will call internal contract performUpkeep(bytes calldata performData)
## 3. Looking Web 3.0 Developer For Your Project?
**Mr Hoelee** is Welcome Web 3.0 Remote Job, Contact Me Immediately Via WhatsApp <a href="https://wa.me/60175885290">+60175885290</a>
Or You can email <a href="mailto:me@hoelee.com">me@hoelee.com</a> now. Thanks.
## 4. Like this project?
If you are feeling generous, buy me a coffee! - <a href="https://buymeacoffee.com/hoelee">buymeacoffee.com/hoelee</a>

View File

@ -1,29 +0,0 @@
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.9.0;
import {DeployRaffle} from "script/DeployRaffle.s.sol";
contract DbgEntry {
event EvmPrint(string);
constructor() {
emit EvmPrint("DbgEntry.constructor");
// Here you can either deploy your contracts via `new`, eg:
// Counter counter = new Counter();
// counter.increment();
// or interact with an existing deployment by specifying a `fork` url in `dbg.project.json`
// eg:
// ICounter counter = ICounter(0x12345678.....)
// counter.increment();
//
// If you have correct symbols (`artifacts`) for the deployed contract, you can step-into calls.
uint256 abc = 123;
uint256 def = abc + 5;
DeployRaffle deployRaffle = new DeployRaffle();
emit EvmPrint("DbgEntry return");
}
}

View File

@ -1,13 +0,0 @@
{
"entryPoint": "DbgEntry",
"solc": "0.8.26",
"sourceDirs": [
"."
],
"breakOnEntry": false,
"fork": {
"enable": false,
"url": "",
"blockNumber": 0
}
}