Deploying a Smart Contract with Foundry
This guide explains how to deploy a smart contract using Foundry, a fast and flexible toolkit for Ethereum application development. Follow these steps to set up your environment, write a smart contract, and deploy it.
Prerequisites
- Foundry installed on your machine (Foundry Installation Guide)
- An Ethereum wallet with test Ether (e.g., MetaMask)
- Basic knowledge of Solidity and command line usage
Step 1: Set Up the Project
-
Initialize a Foundry Project
forge init my-smart-contract
cd my-smart-contract -
Install Dependencies
Foundry handles dependencies automatically. You just need to ensure you are in the project directory.
Step 2: Write Your Smart Contract
Create src/MyContract.sol
:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyContract {
string public message;
constructor(string memory _message) {
message = _message;
}
function setMessage(string memory _message) public {
message = _message;
}
}
Step 3: Compile Your Smart Contract
Run the following command to compile your contract:
forge build
Ensure there are no errors. The compiled contract artifacts will be stored in the out/
directory.
Step 4: Deploy Your Smart Contract
Create scripts/Deploy.s.sol
:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "forge-std/Script.sol";
import "../src/MyContract.sol";
contract DeployScript is Script {
function run() external {
vm.startBroadcast();
MyContract myContract = new MyContract("Hello, World!");
console.log("Contract deployed at:", address(myContract));
vm.stopBroadcast();
}
}
Step 5: Configure Foundry for Deployment
Ensure you have a .env
file in the root directory with your private key:
PRIVATE_KEY=your_private_key_here
Update foundry.toml
to include your network configuration:
[profile.rinkeby]
rpc_url = "https://rinkeby.infura.io/v3/YOUR_INFURA_PROJECT_ID"
private_key = "${PRIVATE_KEY}"
Step 6: Deploy the Contract
Run the deployment script:
forge script scripts/Deploy.s.sol --rpc-url https://rinkeby.infura.io/v3/YOUR_INFURA_PROJECT_ID --private-key $PRIVATE_KEY --broadcast
Replace YOUR_INFURA_PROJECT_ID
with your actual Infura project ID.
Conclusion
You've successfully deployed a smart contract using Foundry. For more information and advanced usage, refer to the Foundry Book.
This documentation should help you get started with deploying smart contracts using Foundry. If you encounter any issues, refer to the official documentation or community forums for assistance.