15 min read

How to use Foundry

1.0 Foundry (2021)

Foundry issa Solidity native development toolkit that handles compiling, testing, deploying and interacting with smart contracts
before Foundry hardhat and truffle was used which had slower compilation and consisted of more tooling
Foundry was created by paradigm (crypto venture capital & research firm)

Foundry written in rust and targets unix like workflows

traditionally web3 dev looks fragmented:
compiler → separate tool
testing → JavaScript framework
deployment → scripts + plugins
Foundry merges all of that into:
forge → build + test
case → interact with blockchain
anvil → local blockchain
forge script → deploy scripts

Foundry is based in rust, compiles and tests much faster than older JS based frameworks

0x0000000000000000000000000000000000000000 is usually the default value of an address and it means no owner set

1.1 Project setup

foundry init —force

text
My Foundry Project
│
├── lib/           external libraries
├── script/        contains deployment and automation scripts
├── src/           every smart contract lives here
├── test/          testcases
└── foundry.toml   foundry settings

1.2 WSL (windows subsystem for linux)

microsoft feature that lets you run a real linux environment inside windows
its not a VM, WSL shares windows kernel infrastructure and integrates tightly with windows making it much faster than trad VM

1.3 Compilation

inputs .sol file and outputs bytecode + ABI + Metadata

forge build
or
forge compile

compiles all Solidity contracts in the project, checks for syntax and compilation errors and generates build artifacts

1.4 Build artifacts

after successful compilation, Foundry creates new directories.
out/ will contain all compiled output for each contract
cache/ will contain temporary compilation data

1.5 Bytecode

machine readable code generated by Solidity compiler
executed by EVM, deployed onto blockchain and cannot be easily read by humans

1.6 Anvil

is Foundry’s built in Ethereum blockchain (local testnet node), simulates a real Ethereum network on your computer
before deploying to a public blockchain like Ethereum mainnet or sepolia, devs first deploy contracts onto a local blockchain

running: anvil
creates a fresh blockchain with
10 pre funded accounts
10,000 fake ETH per account
private key for each account
local blockchain state

when anvil starts, it exposes and RPC endpoint

text
http://127.0.0.1:8545

metamask -> rpc url -> anvil blockchain

1.7 Ganache (guh-nash)

is another local Ethereum blockchain
it was popular long before Foundry existed, people now prefer anvil because it integrates with Foundry toolchain

1.8 Network configuration

normally MetaMask connects to Ethereum mainnet/sepiola/base/arbitrum
here we connect MetaMask to anvil

text
                  Foundry
                     │
                     ▼
                  Anvil
(Local Ethereum Blockchain Node)
                     │
        RPC URL (127.0.0.1:8545)
                     │
      ┌──────────────┴──────────────┐
      │                             │
      ▼                             ▼
  MetaMask                    Frontend / Scripts
      │                             │
      └──────────────┬──────────────┘
                     ▼
              Smart Contracts

1.9 EVM compatibility

EVM compatible means blockchain uses EVM and supports Ethereum smart contracts

Different smart contracts exist on different blockchains
MetaMask already knows confirugation of many popular EVM compatible blockchains (Ethereum mainnet, sepolia, arbitrum one, optimisum, base)
when adding one of these, MetaMask automatically fills in
RPC url, chain ID, currency, block explorer

if MetaMask doesnt knows a blockchain, you must enter its details manually:-
network name
rpc url
chain id
currency symbl
block explorer URL

2.0 Deploying a smart contract to localnet

  1. create your smart contract
    SimpleStorage.sol
  2. compile it
    forge build
  3. bytecode will be generated, still waiting on your computer
  4. forge create SimpleStorage --rpc-url http://127.0.0.1:7545
    you tell Foundry where to connect to
  5. deploying is a blockchain transaction, every blockchain transaction needs someone to sign it
    so you have to add your wallet
  6. forge signs the contract using your private key (you should provide the private key)

2.1 Private key safety

if someone has your private key, they can sign all transactions/transfer your tokens/deploy contracts from your account/approve token spending/interact with defi protocols
dont use anvil keys on mainnet, if someone sends you eth then everyone has that private key and can access your wallet
avoid storing private keys in: source code, txt files, git repos, screenshots, chat messages, notes apps, shared docs
dont paste your key in terminal, any app with terminal history access can look up your keys
store keys in hardware wallets, cloud secret managers, encrypted keystores
major cryptocurrency losses have been caused by poor private key management rather than flaws in blockchain technology

2.1.1 ERC-2335 keystore

is an encrypted file that securely stores your private key. private key → encryption → keystore file → protected by password

Foundry provides option to import wallet
cast wallet import myAccount --interactive

- Foundry asks for private key once
- asks for a password, you create a password and then Foundry encrypts the key using password
- you dont need to type private key again
- Foundry will decrypt it automatically and then sign the transactions by itself

2.2 Blockchain transactions

blockchain transaction is a signed instruction sent to blockchain requesting it to perform an operation
every blockchain state change happens through a transaction

state is the blockchain current snapshot
it includes:
- account balances
- smart contract storage
- nonces
- deployed contracts

whenever Foundry broadcast a transaction, it saves a record
if you execute a script without a running blockchain, Foundry cannot broadcast it, instead it performs a simulation which are stored in dry-run folder

text
transaction_object = {
  "from": "...",        // Sender's wallet address
  "to": "...",          // Recipient address (null if deploying a contract)
  "value": "...",       // Amount of ETH to send (in wei)
  "input": "...",       // Data payload
                         // - Empty for a normal ETH transfer
                         // - Encoded function call when interacting with a contract
                         // - Contract bytecode when deploying a contract
  "gas": "...",         // Maximum gas the sender allows this transaction to consume
  "nonce": "...",       // Sender's transaction number
                         // Prevents replay attacks and keeps transactions ordered
  "chainId": "...",     // Which blockchain this transaction belongs to
                         // e.g. 1 = Ethereum Mainnet
                         //      11155111 = Sepolia
                         //      31337 = Anvil
  "accessList": null    // Optional list of storage slots/accounts
                         // Used by EIP-2930 to reduce gas in certain cases
                         // Usually left null
}

2.3 Foundry’s cast Tool

cast is a Foundry CLI utility for interacting with Ethereum compatible blockchains
it allows you to
- read blockchain data
- send transactions
- queyr balances
- call smart contract functions
- convert values (hex ↔ decimal)
- encode decode ABI data

bash
cast <command> [arguments] [options]
cast call <contract_address> // used to read data
cast send <contract_address> amount --account acc_name --rpc_url url //used to write data

3.0 ZKsync

is a layer 2 blockchain built on top of Ethereum
Instead of executing everything directly on Ethereum, ZKsync processes transactions off-chain and periodically proves them to Ethereum using zero-knowledge proofs (ZK proofs).

ZKsync executes contracts using the ZKsync VM instead on EVM

Foundry-zksync is a fork of Foundry maintained for ZKsync.

3.1 Transaction types in EVM and ZKsync

transaction types even have versions, newer versions come with extra features

text
legacy transactions:
nonce
gasPrice
gasLimit
to
value
data
v,r,s


type 2 transactions:
chainId
nonce
maxPriorityFeePerGas
maxFeePerGas
gasLimit
destination
value
data
accessList
signature

3.1 Gas Costs

when deploying Ethereum has to permanently store your contract
receive transaction → execute constructor → store runtime bytecode forever → assign new address

gas used ≠ transaction fee, gas price changes every minute, gas used is constant
Ethereum doesnt charges dollars only Ethereum
most people think smart contract execution is expensive, publishing transaction data back to Ethereum is the dominant cost
deployment cost is mostly a one time cost, users pay transaction fees repeatedly, devs pay deployment cost once.

3.2 Alchemy

cloud provider for blockchain infrastructure
instead of hosting web servers, alchemy hosts blockchain nodes

alchemy already runs thousands of nodes, else run your own server

alchemy provides blockchain nodes and APIs on top of them

text
Your App
      │
      ▼
Ethereum Node
text
             Load Balancer
                  │
   ┌──────────────┼──────────────┐
   ▼              ▼              ▼
Node A         Node B         Node C

alchemy also has load balancers, for high availability, the architecture is referred to as super node

Benefits:
- instead of manually making each rpc for different functionality, alchemy provides multiple APIs out of box
- has a dashboard/logging
- lets you inspect mempool before transactions are actually processed
- supports many chains

3.3 file extensions

  • *.s.sol - scripting files
  • *.t.sol - testing files, contains test suites that assert whether your smart contracts behave as intended
  • *.i.sol - interfaces files,
  • *.l.sol - libraries
  • *.m.sol - mock contracts for testing

3.4 Foundry cheatcodes

1. makeAddr()

solidity
address alice = makeAddr("alice");

Think of this as creating a test user named Alice with a corresponding address.

2. deal()

solidity
vm.deal(alice,10 ether);

In the local test environment, Alice’s balance is now 10 ETH.

3. prank()

text
prank()

Pretends that the next function call comes from a different address.

---- without prank() ------------------
Test Contract
      │
      ▼
deposit()

msg.sender (the person who actually called the contract)
      │
      ▼
Test Contract

---- with prank() ---------------------
Test Contract
      │
      ▼
vm.prank(alice)
      │
      ▼
deposit()

msg.sender
      │
      ▼
Alice
Foundry lies (only within the test) about who the caller is.

used when we want to test for only a specific user (owner, admin, teacher etc.)

4. startPrank() and stopPrank()

text
instead of pranking again and again:-

vm.prank(alice);
deposit();

vm.prank(alice);
vote();

vm.prank(alice);
withdraw();


you simply do:-
vm.startPrank(alice);

deposit();
vote();
withdraw();

vm.stopPrank();

5. expectRevert()

text
used when creating a failing testcase

require(msg.value >= 1 ether);

vm.expectRevert();

fund();

the line just below the expectRevert is supposed to fail
if it fails -> PASS ✅

6. hoax()

text
instead of 
deal () + prank()

just use 
hoax()

3.5 Testing philosophy

text
FundMeTest
│
├── Constants
│
├── Users
│
├── State Variables
│
├── setUp()
│
├── Modifiers
│
├── Helper Functions
│
├── Funding Tests
│
├── Withdrawal Tests
│
├── Access Control Tests
│
├── Edge Case Tests
│
├── Fuzz Tests
│
└── Invariant Tests

3.6 Chisel

Think of Chisel as a Solidity REPL (Read-Eval-Print Loop).

text
without chisel:-
Want to test one line
↓
Open Remix
↓
Create contract
↓
Paste code
↓
Compile
↓
Deploy
↓
Call function
text
with chisel:-
Want to test one line
↓
chisel
↓
Paste code
↓
Done

3.7 Calculating gas costs

use forge snapshot to calculate gas cost for a component

bash
forge snapshot --mt testWithdrawFromASingleFunder

gasleft() calculates the gas inside Solidity

reading a gas during a transaction costs gas, while reading a blockchain state is usually free. this is why we should cache variables inside a smart contract to save gas

4.0 Storage in Solidity

SLOAD → expensive
SSTORE → VERY expensive
gas optimizations mostly means reducing storage operations

every storage slot = 32 bytes
variables are assigned to each slot exactly in the way they were defined

4.0.1 Packing

solidity
uint128 a;
uint128 b;

Each value uses 16 bytes. Together they fit into one 32-byte storage slot instead of occupying separate slots.

4.0.2 Bad Ordering

text
uint128 a;
uint256 b;
uint128 c;

slot0 -> a
slot1 -> b
slot2 -> c

a leaves 16 bytes unused
b needs 32 bytes
so c cannot go back

Better:
uint128 a;
uint128 c;
uint256 b;

4.0.3 Dynamic arrays

solidity
uint[] arr;

The declared storage slot holds array metadata; the array elements are stored separately.

4.0.4 Constants and Immutable

constant variables are replaced by their actual values during compile time
immutable variables are also baked into bytecode once

4.1 Storage inspection tools

there are three ways:

  1. forge inspect
    shows variables, slot numbers, offsets, types
  2. vm.load(contract, slot)
    tests cheatcodes, reads raw storage.
  3. cast storage
    reads storage directly from blockchain

NOTE!: private variable doesn’t mean secret variable and no one can read. it only means another contract cannot directly access it, anyone can read storage using cast vmload or eth_getStorageAt and since everything on-chain is public, anyone can read it

4.2 Opcodes

Solidity compiles to opcodes, each opcode has associated gas costs which you can preview at https://www.evm.codes/

forge snapshot creates a .gas-snapshot this lets you compare functions

4.3 Makefile

is an automation file, instead of typing long commands repeatedly you create a script. instead of remembering 20 different commands you use
make build/test/deploy/snapshot/clean

5.0 Foundry devops

normal Foundry targets the EVM, ZKsync uses its own VM called EraVM, they are not identical and some Solidity features behave differently, some opcodes are unsupported, some cheatcodes behave differently

cyfrin created Foundry-devops to detect which blockchain youre testing on, which Foundry version youre using

5.0.1 chain modifiers

chain modifiers are helper modifiers that decide whether a test should run depending on the blockchain you're using.

skipZkSync → run everywhere but not on Zksync
onlyZkSync → run only on Zksync

solidity
function testSomething() public skipZkSync {
    ...
}

5.1 Browser Wallet

is a software that connects your browser → MetaMask → blockchain. without it your browser has no way to communicate with Ethereum.

normally a browser has a window object which stores browser related objects.
MetaMask injects a window.ethereum

window
├── document
├── location
├── history
└── Ethereum ← added by MetaMask

this is how websites detect that a wallet exist

with MetaMask, contains wallet functionality like accounts, networks, RPC provider, transaction requests

!this doesnt gives your website a private key, seed phrase. only gives permission to view selected address/request transaction signatures

Provider = connection between your app and the blockchain
Signer = represents currently connected wallet/account

5.1.1 Making transactions on smart contract based frontends

  1. A browser wallet (e.g., MetaMask) lets websites interact with the blockchain.
  2. MetaMask injects window.ethereum into the browser.
  3. Websites check for window.ethereum to detect whether a wallet is installed.
  4. eth_requestAccounts asks the user to connect their wallet but does not expose the private key.
  5. A Provider connects your application to a blockchain through an RPC URL.
  6. A Signer represents the user's wallet and signs transactions.
  7. Reading blockchain data uses the provider and is free.
  8. Writing blockchain data requires a signer, gas fees, and user approval in MetaMask.
  9. The frontend interacts with contracts using ethers.Contract(contractAddress, abi, signer).
  10. The transaction flow is: Frontend → MetaMask → RPC → Blockchain → Smart Contract.

5.2 Function selectors

humans understand function names, EVM doesnt. Before execution Solidity converts function names into machine readable identifiers called function selectors.
function selector = first 4 bytes of hash of a function signature
function signature = fund(params, …)
hashed using keccak-256, keccak(”fund(params, …)”)
take first 4 bytes
now instead of communicating using the function signature, EVM/wallet refers to the function selectors

5.3 Calldata

when calling a function, the transaction sends
function selectors and function arguments → these are your calldata

EVM also doesnt understand arguments, it only understands bytes, so all params are converted into bytes even ETHs

cast sig “function_name()” - command calculates the function selector and prints on the terminal
cast —calldata-decode - command takes raw calldata and converts it back into readable arguments

text
User clicks Fund
        ↓
MetaMask builds transaction
        ↓
Function selector generated
        ↓
Arguments encoded
        ↓
Calldata created
        ↓
Transaction sent
        ↓
Contract receives calldata
        ↓
Reads first 4 bytes
        ↓
Matches selector
        ↓
Executes corresponding function

5.4 Events

event is a blockchain log used to notify off chain apps taht something happened inside a smart contract
events do not modify state, they simply record information
instead of repeatedly checking a condition, frontend simply listens for an event.

expectEmit keyword used to expect a event before executing a function for testing purposes

5.4.1 Indexed params

builds searchable indexes for parameters so wallets, block explorers and applications can quickly find events matching this value instead of scanning every event.

solidity
event Transfer(
    address indexed from,
    address indexed to,
    uint256 indexed tokenId
);

generating purely random numbers is hard in blockchain because blockchain is deterministic

Verifiable Random Function is a chainlink service that provides true randomness, cryptographic proof that the randomness wasnt manipulated. many apps require fair randomess (lotteries, Dice games, Card games, loot boxes), without VRF attackers may influence outcomes

process:
1. requestRandomWords() sends a request to chainlink VRF coordinator
2. chainlink oracle generates a random number off-chain, produces cryptographic proof showing randomness is valid
3. chainlink calls your contract’s callback passing request ID, random numbers
4. fulfillRandomWords() recieves the results

5.6 VRF Consumer

your contract cannot simply ask chainlink for randomness, it must become a VRF consumer by inheriting.
VRF consumer = allows chainlink to securely call your contract back

5.7 VRF coordinator

chainlink randomness manager

interface = any object that claims to implement me must have these functions.
vrf_coordinator is an interface
gas lane: is an identifier which tells chainlinke which VRF configuration/gas price policy to use when fulfilling randomness request
subscription id: every chainlink request costs money, this id tells chainlink to carge this id

solidity
uint256 requestId = COORDINATOR.requestRandomWords(
    keyHash,
    s_subscriptionId,
    requestConfirmations,
    callbackGasLimit,
    numWords
);

5.8 Enum

user defined data type in Solidity, allows variable to store only one value from a predefined list.

solidity
enum RaffleState {
    OPEN,         // 0
    CALCULATING   // 1
}

5.9 CEI pattern

the primary purpose of CEI is to protect smart contracts against reentrancy attacks

checks - verifies that execution is allowed
effects - updates the contract’s internal state
interactions - involve communicating with something outside the current contract

A secure smart contract should:
1. Perform all validations.
2. Update internal state.
3. Interact with external contracts.

5.10 reentrancy attack

when external contract calls back into your contract before the original function finishes executing

External interactions transfer control to another contract. If internal state still reflects the old balance, a callback can observe inconsistent state before the original operation finishes. Apply Checks–Effects–Interactions: validate the operation, update internal balances and other state, then perform external interactions.

decentralized automation service that automatically executes smart contract functions when predefined conditions are met.
tigger types:
a. time based triggers
b. custom logic triggers
c. event based conditions

chainlink automation required LINK tokens to pay for automated executions
LINK is Chainlink's native utility token.

5.11.1 UpKeep

is an automation job registered with chainlink, contains information such as target contract, function to execute, trigger condition, gas limit, LINK balance. each upkeep has a required minimum LINK balance, if balance falls, automation pauses until more LINK is added.

checkUpKeep() determines whether the contract should perform automated work
checkData() optional input supplied to checkUpKeep(), allows more advanced automation logic
performUpkeep() executes automated actions

5.12 vm.warp()

changes blockchains current timestamp during testing, it simulates time passing without waiting in real life.
before → block.timestamp = T
after → vm.warp(T+ Δ)

5.13 vm.roll()

changes blockchains current block number
instead of waiting for new vlocks to be mined, the test immideatly advances to a later block
before → block.number = N
after → vm.roll(N + 1)

block numbers matter because some smart contracts rely on block confirmations, block based delays, block specific logic

5.14 skip()

moves the blockchain timestamp forward by a specified number of seconds
used when only a relative time increase is needed

5.15 rewind()

moves blockchain timestamp backward by a specific number of seconds

5.16 vm.startBroadcast()

From this point onward, sign and send blockchain transactions using the configured account.

5.17 vm.stopBroadcast()

Stop sending real transactions and end the broadcast section.

5.18 vm.recordLogs()

Start recording every event that gets emitted.

5.19 vm.getRecordedLogs()

Give me all the events that were recorded.

chainlink VRF subscription is an account managed by the VRF coordinator that holds LINK to pay for randommness requets, tracks subscription owner, maintains a list of authorized consumer contracts

the VRF coordinator must know who pays for randomness, which contracts are allowed to request randomness

6.0.1 Consumer

a consumer is a smart contract authorized to request random numbers VRF subscription

6.1 transferAndCall()

performs two operations atomically,
transfers LINK tokens and calls a function on the receiving contract

7.0 Fuzz testing

testing technique where a program is executed with many automatically generated inputs instead of manually chosen ones.
if a testing function accepts params, Foundry automatically generates random values, calls the test repeatedly checks whether any input causes failure.