Foundry Tutorial: The Ultimate Quick Start Guide to Deploying Smart Contracts

Table Of Contents
- What is Foundry?
- Prerequisites
- Installing Foundry
- Creating Your First Foundry Project
- Understanding the Project Structure
- Writing Your First Smart Contract
- Testing Your Smart Contract
- Deploying Your Smart Contract
- Verifying Your Contract
- Common Issues and Troubleshooting
- Next Steps with Foundry
Foundry Tutorial: The Ultimate Quick Start Guide to Deploying Smart Contracts
Blockchain development has evolved significantly over the past few years, with new tools continually emerging to make smart contract development more efficient and accessible. Among these tools, Foundry has quickly established itself as a preferred choice for Ethereum developers. If you're looking to speed up your development workflow and enhance your testing capabilities, Foundry is the toolkit you need to master.
In this comprehensive tutorial, we'll walk through the process of setting up Foundry and deploying your first smart contract. Whether you're a seasoned Solidity developer exploring new tools or a Web2 developer taking your first steps into Web3, this guide will provide you with the knowledge to get up and running with Foundry quickly.
By the end of this tutorial, you'll have a functioning smart contract deployed to a blockchain network of your choice, and you'll understand the core features that make Foundry such a powerful development environment.
Foundry Smart Contract Development
The Ultimate Ethereum Development Toolkit
What is Foundry?
A blazing fast toolkit for Ethereum development written in Rust, consisting of Forge (testing), Cast (CLI interactions), and Anvil (local node).
Key Benefits
Foundry lets you write tests in Solidity (not JavaScript), offers faster compilation speeds, and provides a seamless development workflow with powerful debugging tools.
Installation Quick Guide
macOS/Linux
foundryup
Windows (via Scoop)
scoop install foundry
Foundry Development Workflow
1. Initialize
forge init my_project
2. Build
forge build
3. Test
forge test -vvv
4. Deploy
forge script --broadcast
Project Structure
src/
Your smart contract source files
script/
Deployment scripts (.s.sol files)
test/
Test files (.t.sol files)
lib/
Dependencies managed by Forge
Tips for Success
- Use Environment Variables for private keys and API URLs
- Test Locally First with Anvil before deploying to testnets
- Increase Verbosity (-vvv flag) for detailed test output
- Check Gas Usage with Forge's detailed gas reports
Comprehensive learning tracks across major blockchain ecosystems
What is Foundry?
Foundry is a blazing fast, portable, and modular toolkit for Ethereum application development written in Rust. Unlike other development environments like Hardhat or Truffle that use JavaScript, Foundry leverages Rust's performance advantages to offer significantly faster compilation and testing speeds.
The Foundry toolkit consists of three main components:
- Forge - A testing framework for Ethereum smart contracts
- Cast - A command-line tool for interacting with EVM smart contracts
- Anvil - A local Ethereum node designed for development
Foundry's key advantage is that it allows developers to write tests in Solidity rather than JavaScript, enabling you to stay within the same language ecosystem throughout your development process. This makes testing more intuitive and closer to the actual contract execution environment.
Prerequisites
Before getting started with Foundry, ensure you have the following:
- Basic understanding of Solidity and smart contracts
- Familiarity with command-line interfaces
- Git installed on your system
- A code editor (VSCode recommended with Solidity extensions)
- (Optional) An Ethereum wallet with testnet ETH for deployment
If you're new to blockchain development or need to strengthen your foundation, consider exploring HackQuest's learning tracks to gain comprehensive knowledge across major blockchain ecosystems.
Installing Foundry
The installation process for Foundry varies slightly depending on your operating system. Follow the appropriate instructions below.
Installation on macOS/Linux
The simplest way to install Foundry on macOS or Linux is using the Foundryup installation script:
bash curl -L https://foundry.paradigm.xyz | bash
After running this command, restart your terminal session or run:
bash source ~/.bashrc # or ~/.zshrc depending on your shell
Then, execute the foundryup command to complete the installation:
bash foundryup
Installation on Windows
For Windows users, you have two options:
-
Using WSL (Windows Subsystem for Linux) - This is the recommended approach as it provides a Linux environment within Windows:
- Install WSL by following Microsoft's official instructions
- Once WSL is set up, follow the macOS/Linux installation instructions above
-
Native Windows installation - For a direct Windows installation:
- Open PowerShell with administrator privileges
- Run the following command:
powershell irm get.scoop.sh | iex scoop install git scoop bucket add extras scoop install foundry
To verify your installation, run:
bash forge --version
You should see the version number of Forge displayed in your terminal, confirming that Foundry has been successfully installed.
Creating Your First Foundry Project
Now that Foundry is installed, let's create a new project. Foundry provides a convenient command to initialize a new project with a standard template:
bash forge init my_first_foundry_project cd my_first_foundry_project
This command creates a new directory with a basic project structure and template files. The default template includes a simple Counter contract that we'll use as a starting point.
Understanding the Project Structure
Let's take a moment to understand the structure of a Foundry project:
my_first_foundry_project/ ├── .gitignore ├── foundry.toml # Foundry configuration file ├── lib/ # Dependencies directory ├── script/ # Deployment scripts │ └── Counter.s.sol ├── src/ # Source contracts │ └── Counter.sol └── test/ # Test files └── Counter.t.sol
The key directories are:
- src/ - Where your smart contracts live
- test/ - Contains your test files (note the
.t.sol
extension for test files) - script/ - Holds deployment scripts (with
.s.sol
extension) - lib/ - Contains dependencies managed by Forge
The foundry.toml
file is the configuration file for your Foundry project, where you can customize various settings for compilation, testing, and deployment.
Writing Your First Smart Contract
For this tutorial, we'll modify the default Counter contract to add more functionality. Open src/Counter.sol
in your code editor and replace its contents with the following:
solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.13;
contract Counter { uint256 public count; address public owner;
event CounterIncremented(address indexed user, uint256 newCount);
event CounterDecremented(address indexed user, uint256 newCount);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor(uint256 _initialCount) {
count = _initialCount;
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, \"Counter: caller is not the owner\");
_;
}
function increment() public {
count += 1;
emit CounterIncremented(msg.sender, count);
}
function decrement() public {
require(count > 0, \"Counter: cannot decrement below zero\");
count -= 1;
emit CounterDecremented(msg.sender, count);
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), \"Counter: new owner is the zero address\");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function reset() public onlyOwner {
count = 0;
}
}
This enhanced Counter contract includes:
- An initial count parameter in the constructor
- Ownership functionality with a transfer mechanism
- Events for better off-chain tracking
- A decrement function with underflow protection
- A reset function accessible only to the owner
Testing Your Smart Contract
One of Foundry's greatest strengths is its robust testing framework. Let's update the test file to cover our enhanced Counter contract. Open test/Counter.t.sol
and replace its contents with:
solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.13;
import "forge-std/Test.sol"; import "../src/Counter.sol";
contract CounterTest is Test { Counter counter; address user = address(1);
function setUp() public {
counter = new Counter(10);
}
function testIncrement() public {
counter.increment();
assertEq(counter.count(), 11);
}
function testDecrement() public {
counter.decrement();
assertEq(counter.count(), 9);
}
function testFailDecrementBelowZero() public {
// Create a counter starting at 0
Counter zeroCounter = new Counter(0);
// This should fail
zeroCounter.decrement();
}
function testOwnership() public {
assertEq(counter.owner(), address(this));
}
function testTransferOwnership() public {
counter.transferOwnership(user);
assertEq(counter.owner(), user);
}
function testFailNonOwnerReset() public {
// Transfer ownership away from test contract
counter.transferOwnership(user);
// This should fail as we're no longer the owner
counter.reset();
}
function testReset() public {
counter.reset();
assertEq(counter.count(), 0);
}
}
To run these tests, execute the following command in your terminal:
bash forge test
You should see output indicating that all tests have passed. Foundry provides detailed information about gas usage and execution time for each test, which is valuable for optimization.
For more verbose output, you can use:
bash forge test -vvv
The -vvv
flag increases verbosity, showing you call traces and more detailed information about each test execution.
Deploying Your Smart Contract
Now that we have a working and tested contract, let's deploy it to a blockchain network. Foundry makes this process straightforward with deployment scripts.
Setting Up Environment Variables
First, let's set up environment variables for secure management of private keys and RPC URLs. Create a .env
file in your project root (make sure to add this to .gitignore
to prevent accidentally committing sensitive information):
PRIVATE_KEY=your_private_key_here ETHERSCAN_API_KEY=your_etherscan_api_key_here SEPOLIA_RPC_URL=your_sepolia_rpc_url_here
To load these environment variables, you'll need to install a tool called dotenv
:
bash forge install --no-commit smartcontractkit/chainlink-brownie-contracts
Now, update the deployment script. Open script/Counter.s.sol
and modify it as follows:
solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.13;
import "forge-std/Script.sol"; import "../src/Counter.sol";
contract CounterScript is Script { function run() external { uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");
vm.startBroadcast(deployerPrivateKey);
Counter counter = new Counter(5); // Deploy with initial count of 5
vm.stopBroadcast();
console.log(\"Counter deployed at:\", address(counter));
console.log(\"Initial count:\", counter.count());
console.log(\"Owner:\", counter.owner());
}
}
Deployment to a Local Network
Before deploying to a testnet, it's good practice to deploy to a local network first. Foundry provides Anvil for this purpose:
- Start a local blockchain in a separate terminal:
bash anvil
This will spin up a local Ethereum node and display a list of available accounts with their private keys.
- In your original terminal, deploy the contract to the local network:
bash forge script script/Counter.s.sol --fork-url http://localhost:8545 --private-key 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 --broadcast
The private key here is the first one provided by Anvil when it starts up. If you're using a different account, replace this with the appropriate private key.
Deployment to a Testnet
For deploying to a testnet like Sepolia, you'll need testnet ETH. You can obtain testnet ETH from HackQuest's faucets if needed.
Once you have testnet ETH, deploy your contract with:
bash forge script script/Counter.s.sol --rpc-url $SEPOLIA_RPC_URL --private-key $PRIVATE_KEY --broadcast --verify -vvvv
This command will:
- Load your environment variables
- Deploy the contract to the Sepolia testnet
- Attempt to verify the contract on Etherscan (if you provided an Etherscan API key)
Verifying Your Contract
If the automatic verification during deployment doesn't work, you can manually verify your contract using Forge:
bash forge verify-contract --chain-id 11155111 --compiler-version 0.8.13 <DEPLOYED_ADDRESS> src/Counter.sol:Counter --etherscan-api-key $ETHERSCAN_API_KEY --constructor-args $(cast abi-encode "constructor(uint256)" 5)
Replace <DEPLOYED_ADDRESS>
with your contract's address. The --constructor-args
flag provides the encoded constructor arguments, which in our case is the initial count value of 5.
Common Issues and Troubleshooting
Here are some common issues you might encounter when using Foundry and how to resolve them:
-
Dependency Issues: If you're having trouble with dependencies, try: bash forge install --no-commit
-
Compilation Errors: Ensure your Solidity version in the contract matches the one in
foundry.toml
. You can set the Solidity version with: bash forge config --use solc:0.8.13 -
Gas Estimation Failures: Sometimes deployments fail due to gas estimation issues. You can specify gas limits manually: bash forge script script/Counter.s.sol --gas-limit 3000000 [...other options]
-
Network Connection Issues: If you're having trouble connecting to a testnet, check your RPC URL and try a different provider if necessary.
-
Contract Verification Failures: For complex contracts, you might need to flatten the source code first: bash forge flatten src/Counter.sol > Flattened.sol
Then use the flattened code for manual verification on Etherscan.
Next Steps with Foundry
Now that you have successfully deployed your first contract with Foundry, here are some advanced topics to explore:
- Fuzz Testing: Foundry provides powerful property-based testing capabilities
- Debugging: Learn to use Forge's debugging tools with
--debug
flags - Contract Optimization: Explore gas optimization techniques with Foundry's detailed gas reports
- Scripting: Create more complex deployment scripts for multi-contract systems
- Integration with Other Tools: Integrate Foundry with frontends, subgraphs, and other Web3 infrastructure
To deepen your understanding of blockchain development across various ecosystems, check out HackQuest's learning tracks which provide comprehensive, certified courses on major blockchain platforms including Ethereum, Solana, Arbitrum, and Mantle.
Conclusion
In this tutorial, we've covered the essential steps for getting started with Foundry, from installation to deploying and verifying a smart contract. Foundry's speed, Solidity-native testing, and powerful tooling make it an excellent choice for both beginners and experienced developers looking to streamline their Ethereum development workflow.
By mastering Foundry, you're adding a valuable tool to your blockchain development arsenal that can significantly increase your productivity. The ability to write tests in Solidity rather than JavaScript keeps you in the same mental model throughout development and testing, reducing context-switching and potential errors.
Remember that while we've covered the basics here, Foundry offers many more advanced features worth exploring as you grow more comfortable with the toolkit. Its modular design allows you to use as much or as little of it as you need for your specific projects.
Ready to take your blockchain development skills to the next level? Explore HackQuest's certified learning tracks covering major blockchain ecosystems. From fundamentals to advanced topics, our interactive, project-based courses will help you become a proficient Web3 developer. Join our vibrant community of builders today at HackQuest.io!