Deploy with Foundry

Deploying a Counter Contract with Foundry

This guide will walk you through deploying a counter contract using Foundry, a fast and portable toolkit for Ethereum application development.

1. Prerequisites

Before you begin, make sure you have:

  • A code editor (e.g., VS Code)

  • MetaMask wallet for deploying to testnets

  • RPC endpoint for deploying to a network

2. Install Foundry

Open your terminal and run:

curl -L https://foundry.paradigm.xyz | bash

This installs foundryup, the Foundry installer.

Next, run:

foundryup

This will install the Foundry toolchain (forge, cast, anvil, chisel).

Check the installation:

forge --version

3. Initialize a New Project

Create a new directory for your project and initialize Foundry:

forge init Countercd Counter

This creates a project with the following structure:

  • src/ - for your smart contracts

  • test/ - for Solidity tests

  • script/ - for deployment scripts

  • lib/ - for dependencies

  • foundry.toml - project configuration file

4. Explore the Counter Contract

Foundry initializes your project with a Counter contract in src/Counter.sol:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Counter { 
uint256 private count;   
function increment() public {        
count += 1;    
}     
function decrement() public {        
count -= 1;    
}     
function getCount() public view returns (uint256) {        
return count;    
}
}

This contract stores a number and allows you to set or increment it.

5. Compile the Contract

Compile your smart contracts with:

forge build

This command compiles all contracts in src/ and outputs artifacts to the out/ directory.

6. Run Tests

Foundry supports writing tests in Solidity (in the test/ directory). To run all tests:

forge test

You’ll see output indicating which tests passed or failed. The default project includes a sample test for the Counter contract.

7. Deploying Your Contract

To deploy your contract to the LazAI testnet, you’ll need:

  • An RPC URL

  • A private key with testnet LAZAI

Example deployment command for LazAI testnet:

forge create --rpc-url https://lazai-testnet.metisdevops.link \  --private-key <YOUR_PRIVATE_KEY> \  src/Counter.sol:Counter \  --broadcast

Replace <YOUR_PRIVATE_KEY> with your actual private key. Never share your private key.

8. Interacting with Contracts

You can use cast to interact with deployed contracts, send transactions, or query data. For example, to read the number variable on LazAI testnet:

cast call <CONTRACT_ADDRESS> "number()(uint256)" --rpc-url https://lazai-testnet.metisdevops.link