← Back to the blog
Lesson 4: Foundry Engineering and Testing

X ArticleWeb3

Lesson 4: Foundry Engineering and Testing

Source: https://x.com/i/status/2110719173743804513

Learning goals: use Foundry to complete development, testing, debugging, and deployment.

Previous lesson

Lesson outline

1. A brief introduction to Foundry

2. Why choose Foundry

3. Foundry’s core components

4. Installation and configuration

5. A hands-on project: an NFT project

6. Testing and debugging

7. Contract deployment and verification

8. On-chain interaction

9. Applications in security research

10. Common problems and best practices

Conclusion

1. A brief introduction to Foundry

Foundry official site

Foundry is a smart-contract development toolkit written in Rust, designed for Ethereum and EVM-compatible chains. It provides a complete toolchain for development, testing, and deployment.

Main features

High performance: implemented in Rust, and much faster to execute than traditional tools

Native Solidity tests: write test code directly in Solidity

Rich debugging features: detailed execution traces and state information

Modular design: includes several specialized tools

2. Why choose Foundry

2.1 Five core advantages

1. Write tests in Solidity

Traditional tools such as Truffle use JavaScript, and Brownie uses Python, to write tests, which has the following problems:

A language abstraction layer adds complexity

JavaScript needs a BigNumber library to handle large-number arithmetic

The learning cost is high, because you need to master several languages

Foundry writes tests directly in Solidity, keeping the language consistent.

2. Fuzzing

It automatically generates random input parameters and finds edge cases the developer did not consider:

3. VM state overrides

You can modify blockchain state for testing:

Simulate being the contract owner

Directly modify a token balance

Change the block time and height

4. Testing against live network state

It supports forking mainnet state for testing:

5. Detailed debugging information

It provides rich logs and execution traces, helping you locate problems quickly.

3. Foundry’s core components

3.1 Forge

The main build and test tool. Its features include:

Project creation and management

Contract compilation

Test execution

Contract deployment

Code coverage analysis

3.2 Cast

A command-line RPC interaction tool, supporting:

Sending transactions

Calling contract functions

Querying on-chain data

ABI encoding and decoding

Unit conversion

3.3 Anvil

A local testnet node, similar to Ganache but with better performance.

3.4 Chisel

A Solidity REPL environment, in which you can quickly test code snippets.

4. Installation and configuration

4.1 Installing Foundry

Install Foundry:

4.2 Verifying the installation

4.3 Updating Foundry

4.4 Initializing a project

4.5 Project structure

4.6 A closer look at the config file

A foundry.toml configuration example:

https://www.getfoundry.sh/config

5. A hands-on project: an NFT project

5.1 Creating the project

5.2 Installing dependencies

5.3 Writing the NFT contract

Create src/NFT.sol:

5.4 Compiling the contract

6. Testing and debugging

6.1 Writing a test contract

Create test/NFT.t.sol:

6.2 Running tests

6.3 A fuzz-testing example

Add a function that is easy to get wrong to the NFT contract:

The test function:

6.4 Debugging features

Use forge debug to debug a failed transaction:

6.5 Gas reports

7. Contract deployment and verification

7.1 Deploying to a testnet

First set environment variables:

Deploy the contract:

7.2 Verifying the contract code

7.3 Deploying with a script

Create script/Deploy.s.sol:

Run the script:

8. On-chain interaction

8.1 Using Cast for on-chain interaction

Query contract state

Send a transaction

8.2 Forking mainnet for testing

Fork mainnet in a test:

8.3 Using a local Anvil node

Start a local node:

9. Applications in security research

9.1 An incident-reproduction example

The following is an example structure for reproducing a security incident:

9.2 Using cheat codes

Commonly used cheat codes:

9.3 Advanced debugging techniques

Use vm.getCode to deploy an old contract:

10. Common problems and best practices

10.1 Common problems

Compilation errors

Check Solidity version compatibility

Confirm that dependency libraries are installed correctly

Look at the remappings.txt configuration

Test failures

Use the -vvv flag to get detailed logs

Check the gas-limit settings

Verify the test logic and assertions

Deployment problems

Confirm that the private key and RPC URL are correct

Check whether the account balance is sufficient

Verify the constructor arguments

10.2 Best practices

Project structure

Testing strategy

Unit tests: test individual functions

Integration tests: test contract interactions

Fuzz tests: find edge cases

Invariant tests: verify system properties

Security considerations

Use environment variables to store sensitive information

Test thoroughly on a testnet before deploying to mainnet

Update dependency libraries regularly

Conduct a code audit

10.3 Performance optimization

Compilation optimization

Test optimization

10.4 Integration with other tools

Integration with Hardhat

Foundry can be integrated with an existing Hardhat project, remaining compatible.

CI/CD integration

Conclusion

Foundry is a powerful smart-contract development tool, especially suited to:

Projects that need high-performance testing

Security research and vulnerability analysis

Complex DeFi protocol development

Scenarios that need precise control over the test environment

Through this tutorial, you should already have a grasp of Foundry’s core features and how to use them. The suggestion is to practice more in real projects, and gradually get familiar with the various advanced features.

Recommended resources

Foundry Book

Foundry GitHub

A collection of example projects

🛠️

Code snippets from the article

The following code comes from code blocks in the original X Article, arranged in the order they appeared.

anvil --fork-url $MAINNET_RPC_URL --fork-block-number 17000000
forge init my-project
cd my-project
# Basic tests
forge test

# Verbose output
forge test -vvv

# Run a specific test
forge test --match-test testMintSuccess
forge test --gas-report
project/
├── src/
│   ├── interfaces/
│   ├── libraries/
│   └── contracts/
├── test/
│   ├── unit/
│   ├── integration/
│   └── fuzz/
├── script/
└── lib/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import {ERC721} from "openzeppelin-contracts/contracts/token/ERC721/ERC721.sol";
import {Ownable} from "openzeppelin-contracts/contracts/access/Ownable.sol";
import {Strings} from "openzeppelin-contracts/contracts/utils/Strings.sol";

contract NFT is ERC721, Ownable {
    using Strings for uint256;

    uint256 public constant MINT_PRICE = 0.08 ether;
    uint256 public constant MAX_SUPPLY = 1000;
    uint256 public totalSupply;
    string private _baseTokenURI;

    constructor(
        string memory name,
        string memory symbol,
        string memory baseURI,
        address initialOwner
    ) ERC721(name, symbol) Ownable(initialOwner) {
        _baseTokenURI = baseURI;
    }

    function mintTo(address recipient) public payable returns (uint256) {
        require(msg.value == MINT_PRICE, "Insufficient payment");
        require(totalSupply < MAX_SUPPLY, "Max supply reached");

        uint256 tokenId = totalSupply;
        totalSupply++;

        _safeMint(recipient, tokenId);
        return tokenId;
    }

    function withdrawPayments() public onlyOwner {
        (bool success, ) = payable(owner()).call{value: address(this).balance}("");
        require(success, "Transfer failed");
    }

    function _baseURI() internal view override returns (string memory) {
        return _baseTokenURI;
    }
}
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
solc_version = "0.8.19"

[rpc_endpoints]
mainnet = "https://eth-mainnet.alchemyapi.io/v2/YOUR-API-KEY"
goerli = "https://eth-goerli.alchemyapi.io/v2/YOUR-API-KEY"

[fuzz]
runs = 1000

[invariant]
runs = 256
depth = 15
my-project/
├── lib/                # Dependencies
├── src/               # Contract source
├── test/              # Test files
├── script/            # Deployment scripts
├── foundry.toml       # Config file
└── remappings.txt     # Path remappings
function testForkMainnet() public {
    // Fork mainnet at a specific block
    vm.createSelectFork("mainnet", 17_000_000);

    // You can now interact with mainnet contracts
    IERC20 usdc = IERC20(0xA0b86a33E6441e5f3e8b8e5e5e5e5e5e5e5e5e5);
    uint256 balance = usdc.balanceOf(0x...);

    console.log("USDC Balance:", balance);
}
forge debug --target-contract NFT --sig "mintTo(address)" 0x123...
forge create --rpc-url $GOERLI_RPC_URL \
  --private-key $PRIVATE_KEY \
  --constructor-args "My NFT" "MNFT" "https://api.example.com/metadata/" \
  src/NFT.sol:NFT
// Change the caller
vm.prank(address);

// Change the time
vm.warp(timestamp);

// Change the block height
vm.roll(blockNumber);

// Set a balance
vm.deal(address, amount);

// Modify storage
vm.store(address, slot, value);

// Expect a revert
vm.expectRevert("Error message");
forge init nft-project
cd nft-project
forge build
curl -L https://foundry.paradigm.xyz | bash
foundryup
function testFuzz_AddNumbers(uint256 x) public {
    uint256 result = nft.addNumbers(x);
    assertGt(result, x); // This will fail on overflow
}
# .github/workflows/test.yml
name: Test
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Install Foundry
        uses: foundry-rs/foundry-toolchain@v1
      - name: Run tests
        run: forge test
# Mint NFT
cast send $CONTRACT_ADDRESS \
  "mintTo(address)" $USER_ADDRESS \
  --value 0.08ether \
  --private-key $PRIVATE_KEY \
  --rpc-url $GOERLI_RPC_URL
forge --version
cast --version
anvil --version
chisel --version
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import "forge-std/Test.sol";

interface IVulnerableContract {
    function vulnerableFunction(bytes32 root) external returns (bool);
}

contract ExploitTest is Test {
    IVulnerableContract target;

    function setUp() public {
        // Fork to the block before the attack
        vm.createSelectFork("mainnet", 16_800_000);
        target = IVulnerableContract(0x...);
    }

    function testExploit() public {
        console.log("Balance before:", address(this).balance);

        // Reproduce the attack logic
        bool result = target.vulnerableFunction(bytes32(0));
        assertTrue(result);

        console.log("Balance after:", address(this).balance);
    }
}
function testFuzz_AddNumbers(uint256 x) public {
    // Foundry will automatically generate various x values for testing
    uint256 result = myContract.addNumber(x);
    // Test logic
}
export PRIVATE_KEY=0x...
export GOERLI_RPC_URL=https://eth-goerli.alchemyapi.io/v2/YOUR-API-KEY
forge install OpenZeppelin/openzeppelin-contracts
forge install transmissions11/solmate
# Query total supply
cast call $CONTRACT_ADDRESS "totalSupply()" --rpc-url $GOERLI_RPC_URL

# Query the NFT owner
cast call $CONTRACT_ADDRESS "ownerOf(uint256)" 0 --rpc-url $GOERLI_RPC_URL
[fuzz]
runs = 10000
max_test_rejects = 65536
function addNumbers(uint256 x) public pure returns (uint256) {
    return x + 1000;
}
forge verify-contract \
  --chain-id 5 \
  --num-of-optimizations 200 \
  --watch \
  --constructor-args $(cast abi-encode "constructor(string,string,string)" "My NFT" "MNFT" "https://api.example.com/metadata/") \
  --etherscan-api-key $ETHERSCAN_API_KEY \
  0x... \
  src/NFT.sol:NFT
vm.createSelectFork("mainnet", blockNumber);
function deployOldContract() internal {
    bytes memory bytecode = vm.getCode("OldContract.sol:OldContract");
    bytes memory initcode = abi.encodePacked(bytecode, abi.encode(arg1, arg2));

    address deployed;
    assembly {
        deployed := create2(0, add(initcode, 0x20), mload(initcode), salt)
    }

    // Or set it directly on a specific address
    vm.etch(targetAddress, bytecode);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

// Import the Foundry test framework
import "forge-std/Test.sol";
// Import the NFT contract under test
import "../src/NFT.sol";

/**
 * @title NFTTest
 * @dev Test suite for the NFT contract
 * @notice Inherits Foundry's Test contract to get testing features and cheat codes
 */
contract NFTTest is Test {
    // Instance of the NFT contract under test
    NFT public nft;

    // Test address: contract owner
    address public owner = address(0x1);
    // Test address: regular user
    address public user = address(0x2);

    /**
     * @dev Test setup function, called automatically before each test function
     * @notice Initialize the test environment and deploy the NFT contract
     */
    function setUp() public {
        // Use a cheat code to simulate a transaction from the owner address
        vm.prank(owner);
        // Deploy the NFT contract, setting the name, symbol, and base URI
        nft = new NFT("Test NFT", "TNFT", "https://example.com/");
    }

    /**
     * @dev Test the scenario of successfully minting an NFT
     * @notice Verify that a user can successfully mint an NFT after paying the correct amount
     */
    function testMintSuccess() public {
        // Simulate a transaction from the user address
        vm.prank(user);
        // Give the user address a balance of 1 ether
        vm.deal(user, 1 ether);

        // The user pays 0.08 ether to mint an NFT to themselves
        uint256 tokenId = nft.mintTo{value: 0.08 ether}(user);

        // Assert: verify that the owner of the NFT is the user
        assertEq(nft.ownerOf(tokenId), user);
        // Assert: verify that total supply is 1
        assertEq(nft.totalSupply(), 1);
    }

    /**
     * @dev Test the scenario in which minting fails when the payment is insufficient
     * @notice The testFail prefix means this test is expected to fail (revert)
     * @notice Verify that the transaction reverts when the payment is insufficient
     */
    function test_RevertWhen_MintInsufficientPayment() public {
        // Simulate a transaction from the user address
        vm.deal(user, 1 ether);
        vm.prank(user);
        vm.expectRevert("Insufficient payment");
        // Try to mint an NFT with 0.01 ether (insufficient), expecting failure
        nft.mintTo{value: 0.01 ether}(user);
    }

    /**
     * @dev Test the scenario in which only the owner can withdraw funds
     * @notice Verify access control and the fund-withdrawal feature
     */
    function testWithdrawOnlyOwner() public {
        // === Step 1: generate revenue ===
        // Simulate a user minting an NFT to generate contract revenue
        vm.prank(user);
        vm.deal(user, 1 ether);
        nft.mintTo{value: 0.08 ether}(user);

        // === Step 2: withdraw funds ===
        // Only the owner can withdraw funds from the contract
        vm.prank(owner);
        nft.withdrawPayments();

        // === Verify the result ===
        // Assert: the contract balance should be 0 (funds have been withdrawn)
        assertEq(address(nft).balance, 0);
    }

    /**
     * @dev Fuzz test: test all cases that are not the correct price
     * @param price A randomly generated price parameter
     * @notice Use fuzz testing to verify that only the correct price can mint successfully
     */
    function testFuzz_MintPrice(uint256 price) public {
        // Assumption: exclude the correct mint price of 0.08 ether
        vm.assume(price != 0.08 ether);

        // Simulate a user transaction
        vm.prank(user);
        // Give the user a balance of the corresponding amount
        vm.deal(user, price);

        // Expect the transaction to revert, with a specific error message
        vm.expectRevert("Insufficient payment");
        // Try to mint an NFT at the wrong price
        nft.mintTo{value: price}(user);
    }
}
foundryup
forge script script/Deploy.s.sol:DeployScript --rpc-url $GOERLI_RPC_URL --broadcast
[profile.default]
optimizer = true
optimizer_runs = 200
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import "forge-std/Script.sol";
import "../src/NFT.sol";

contract DeployScript is Script {
    function run() external {
        uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");
        vm.startBroadcast(deployerPrivateKey);

        NFT nft = new NFT(
            "Scripted NFT",
            "SNFT",
            "https://api.example.com/metadata/"
        );

        console.log("NFT deployed to:", address(nft));

        vm.stopBroadcast();
    }
}

This article was imported from an X Article. Original: https://x.com/i/status/2110719173743804513