How to Set Up Foundry to Test Smart Contracts on Hedera | Hedera Hedera Network Services Token Service Mint and configure tokens and accounts. Consensus Service Verifiable timestamps and ordering of events. Smart Contracts Run Solidity smart contracts. HBAR The Hedera network's native cryptocurrency. Insights How It Works Learn about Hedera from end to end. Explorers View live and historical data on Hedera. Dashboards Analyze network activity and metrics. Network Nodes Understand networks and node types. Devs Start Building Get Started Learn core concepts and build the future. Documentation Review the API and build using your favorite language. Developer Resources Integrations Plugins and microservices for Hedera. Fee Estimator Understand and estimate transaction costs. Open Source Hedera is committed to open, transparent code. Learning Center Learn about web3 and blockchain technologies. Grants Grants & accelerators for your project. Bounties Find bugs. Submit a report. Earn rewards. Ecosystem ECOSYSTEM Hedera Ecosystem Applications, developer tools, network explorers, and more. NFT Ecosystem Metrics Analyze on-chain and market NFT ecosystem metrics. CATEGORIES Web3 Applications Connect into the innovative startups decentralizing the web on Hedera. Enterprise Applications Learn about the Fortune 500 companies decentralizing the web on Hedera. Wallets & Custodians Create a Hedera account to manage HBAR, fungible tokens, and NFTs. Network Explorers Hedera mainnet and testnet graphical network explorers. Developer Tooling Third-party APIs, integrations, and plugins to build apps on Hedera. Grants & Accelerators Boost your project with support from the Hedera ecosystem. Partner Program Explore our partners to bring your vision into reality. Hedera Council Over 30 highly diversified organizations govern Hedera. Use Cases Hedera Solutions Asset Tokenization Studio Open source toolkit for tokenizing assets securely. Stablecoin Studio All-in-one toolkit for stablecoin solutions. Hedera Guardian Auditable carbon markets and traceability. Functional Use Cases Data Integrity & AI Reliable, secure, and ethically governed insights. Sustainability Enabling fair carbon markets with trust. Real-World Asset Tokenization Seamless tokenization of real-world assets and digital at scale. Consumer Engagement & Loyalty Mint, distribute, and redeem loyalty rewards. Decentralized Identity Maintain the lifecycle of credentials. Decentralized Logs Scalable, real-time timestamped events. DeFi Dapps built for the next-generation of finance. NFTs Low, fixed fees. Immutable royalties. Payments Scalable, real-time, and affordable crypto-payments. HBAR Overview Learn about Hedera's token, HBAR. Treasury Management Hedera’s report of the HBAR supply. Governance Decentralized Governance Hedera Council See the world's leading organizations that own Hedera. About Meet Hedera's Board of Directors and team. Journey Watch Hedera's journey to build an empowered digital future for all. Transparent Governance Public Policy Hedera's mission is to inform policy and regulation that impact the industry. Meeting Minutes Immutably recorded on Hedera. Roadmap Follow Hedera's roadmap in its journey to build the future. Resources Company What's New Partners Papers Careers Media Blog Technical Press Podcast Community Events Meetups Store Brand Navigation QUICKSTART How to Set Up Foundry to Test Smart Contracts on Hedera technical Jan 04, 2023 by Abi Castro Foundry provides tools to developers who are developing smart contracts. One of the 3 main components of Foundry is Forge: Foundry’s testing framework. Tests are written in Solidity and are easily run with the forge test command. This tutorial will dive into configuring Foundry with Hedera to use Forge in order to write and run tests for smart contracts. Note: Hashio, the SwirldsLabs hosted version of the JSON-RPC Relay, is in beta. If issues are encountered while using Foundry and Hashio, please create an issue in the JSON-RPC Relay GitHub repository. What we will do: Create a new Hedera project with the following directory structure . ├── cache ├── contracts ├── index.ts ├── test └── package.json Copy Create a sample smart contract Create a sample Foundry project Write Unit tests in solidity Build and run the tests Deploy the smart contract using the Hashgraph SDK The complete example can be found on GitHub here. Step 1: Create a Hedera project and install the Hashgraph JS SDK Open your terminal and create a directory called my-hedera-project. mkdir my-hedera-project && cd my-hedera-project Copy Initialize a node project and accept all defaults npm install --save @hashgraph/sdk Copy Create your .env file and fill the contents with your account Id and private key. They will be used to create your Hedera client. Need a Testnet Account? Head over to portal.hedera.com to create a testnet account and receive 10,000 test HBAR every 24 hours! OPERATOR_ACCOUNT_ID= OPERATOR_PRIVATE_KEY= Copy Note: Never share your private key with anyone or post it anywhere. Add a .gitingore file with an entry for your .env file. This will ensure you don’t accidentally push your credentials to your repository. Create a file named index.ts and create your Hedera client import { Client, AccountId, PrivateKey, Hbar, TokenId, ContractId } from "@hashgraph/sdk"; import fs from "fs"; import dotenv from "dotenv"; import { deployContract } from "./services/hederaSmatContractService"; dotenv.config(); // create your client const accountIdString = process.env.OPERATOR_ACCOUNT_ID; const privateKeyString = process.env.OPERATOR_PRIVATE_KEY; if (accountIdString === undefined || privateKeyString === undefined ) { throw new Error('account id and private key in env file are empty')} const operatorAccountId = AccountId.fromString(accountIdString); const address = operatorAccountId.toSolidityAddress(); const operatorPrivateKey = PrivateKey.fromString(privateKeyString); const client = Client.forTestnet().setOperator(operatorAccountId, operatorPrivateKey); client.setDefaultMaxTransactionFee(new Hbar(100)); Copy In the root directory, create two new empty folders: cache and test. Inside the cache folder, create the subfolder forge-cache. Inside the test folder, create a subfolder called foundry. Your Hedera project directory structure should look similar to this: . ├── cache ├──forge-cache ├── contracts ├── test ├──foundry ├── .env ├── .gitignore ├── index.ts ├── package-lock.json ├── package.json └── tsconfig.json Copy Step 2: Install Foundry by visiting their installation guide. Step 3. Create a sample Foundry Project Open a new terminal window and Create a sample Foundry project by running the following command in the new terminal: forge init Copy Your foundry project will have the following directory structure . ├── lib ├── script ├── src └── test Copy Step 4: Copy the lib/forge-std folder from the sample foundry project into your Hedera Project Foundry manages dependencies using git submodules by default. Hedera manages dependencies through npm modules. The default sample project comes with one dependency installed: Forge Standard Library. We need to get that over to our Hedera project. Copy the lib/forge folder from the sample Foundry project and put it in your Hedera project. Your Hedera project directory structure will look like this: . ├── cache ├──forge-cache ├── contracts ├── lib ├── test ├──foundry ├── .env ├── .gitignore ├── index.ts ├── package-lock.json ├── package.json └── tsconfig.json Copy Step 5: Configure Foundry in your Hedera project Foundry’s default directory for contracts is src/, but we will need it to map to contracts. Tests will map to our test/foundry path, and the cache_path will map to our cache/forge-cache directory. Let’s create a foundry configuration file to update how Foundry behaves. Create a file in the root of your Hedera project and name it foundry.toml and add the following lines: [profile.default] src = 'contracts' out = 'out' libs = ['node_modules', 'lib'] test = 'test/foundry' cache_path = 'forge-cache' Copy Step 6: Remap dependencies Foundry manages dependencies using git submodules and has the ability to remap them to make them easier to import. Let’s create a new file at the root directory called remappings.txt and write the following lines: ds-test/=lib/forge-std/lib/ds-test/src/ forge-std/=lib/forge-std/src/ Copy And what these remappings translate to is: To import from ds-test we write import “ds-test/TodoList.sol”; To import from forge-std we write import “forge-std/Contract.sol”; Step 7. Create a smart contract Create a smart contract file named TodoList.sol under the contracts directory // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; struct Todo { uint id; string description; bool completed; } contract TodoList { // need to keep count of todos as we insert into map uint256 public numberOfTodos = 0; mapping(uint => Todo) public todos; function createTodo(string memory description) public { numberOfTodos++; todos[numberOfTodos] = Todo(numberOfTodos, description, false); } function getTodoById(uint256 id) public view returns (Todo memory) { return todos[id]; } function toggleCompleted(uint _id) public { Todo memory _todo = todos[_id]; _todo.completed = !_todo.completed; todos[_id] = _todo; } } Copy Step 8. Create tests written in Solidity Create a file named TodoList.t.sol under test/foundry and write the following test: // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; import "forge-std/Test.sol"; import "contracts/TodoList.sol"; contract TodoListTest is Test { TodoList public todoList; uint256 numberOfTodos; // Arrange everything you need to run your tests function setUp() public { todoList = new TodoList(); } function test_CreateTodo() public { // arrange todoList.createTodo("Feed my dog"); // act numberOfTodos = todoList.numberOfTodos(); // assert assertEq(numberOfTodos, 1); } function test_GetTodoById() public { // arrange todoList.createTodo("Pack my bags"); // act Todo memory todo = todoList.getTodoById(1); // assert assertEq(todo.description, "Pack my bags"); } function test_ToggleCompleted() public { // arrange todoList.createTodo("Update my calendar"); // act todoList.toggleCompleted(1); // assert Todo memory todo = todoList.getTodoById(1); assertEq(todo.completed, true); } } Copy Step 9. Build and run your tests In your terminal, ensure you are in your forge project directory and run the following command to build forge build Copy To run your tests run the following command forge test Copy Deploy your Smart Contract Step 1: Compile your smart contract using solc solcjs --bin contracts/TodoList.sol -o binaries Copy Step 2: Read the compiled bytecode In your index.ts file import fs in order to read your smart contracts bytecode. import fs from "fs"; const bytecode = fs.readFileSync("binaries/contracts_ERC20FungibleToken_sol_ERC20FungibleToken.bin"); Copy Step 3: Create a function to deploy your smart contract import { ContractCreateFlow, Client} from '@hashgraph/sdk'; /* * Stores the bytecode and deploys the contract to the Hedera network. * Returns an array with the contractId and contract solidity address. * * Note: This single call handles what FileCreateTransaction(), FileAppendTransaction() and * ContractCreateTransaction() classes do. */ export const deployContract = async (client: Client, bytecode: string | Uint8Array, gasLimit: number) => { const contractCreateFlowTxn = new ContractCreateFlow() .setBytecode(bytecode) .setGas(gasLimit); console.log(`- Deploying smart contract to Hedera network`) const txnResponse = await contractCreateFlowTxn.execute(client); const txnReceipt = await txnResponse.getReceipt(client); const contractId = txnReceipt.contractId; if (contractId === null ) { throw new Error("Somehow contractId is null.");} const contractSolidityAddress = contractId.toSolidityAddress(); console.log(`- The smart contract Id is ${contractId}`); console.log(`- The smart contract Id in Solidity format is ${contractSolidityAddress}\n`); return [contractId, contractSolidityAddress]; } Copy Step 4: Call your function that deploys your smart contract to the Hedera network const hederaFoundryExample = async () => { // read the bytecode const bytecode = fs.readFileSync("binaries/contracts_Counter_sol_Counter.bin"); // Deploy contract const gasLimit = 1000000; const [contractId, contractSolidityAddress] = await deployContract(client, bytecode, gasLimit); } hederaFoundryExample(); Copy Forge Gas Reports Forge has functionality built in to give you gas reports of your contracts. First, you must configure your foundry.toml to specify which contracts should generate a gas report. Add the below line to your foundry.toml file gas_reports = ["TodoList"] Copy In order to generate a gas report run the following command in your vscode terminal. forge test –gas-report Copy Your output will show you an estimated gas average, median, and max for each contract function and total deployment cost and size. Summary In this article, we have learned how to configure Foundry to work with a Hedera project to test our Smart Contracts using the forge framework. We also learned how to generate gas reports for our smart contracts. Happy Building! Continue Learning: Create a Hedera testnet account and receive 10,000 test hbar every 24 hours!! Try Examples and Tutorials Join the Developer Discord Explore The Hedera Learning Center Share This Back to blog What is gRPC, gRPC-Web, and Proxies? Ed Marquez Pragmatic Blockchain Design Patterns – Integrating Blockchain into Business Processes Michiel Mulders Zero Cost EthereumTransaction on Success: Hedera's New Fee Model for Relay Operators Oliver Thorn Hedera Adopts Chainlink Standard for Cross-Chain Interoperability To Accelerate Ecosystem Adoption Hedera Team Hedera Developer Highlights March 2025 Michiel Mulders Hedera Release Cycle Overview Ed Marquez View All Posts Sign up for the newsletter CONNECT WITH US Transparency Open Source Audits & Standards Sustainability Commitment Carbon Offsets Governance Hedera Council Public Policy Treasury Management Meeting Minutes LLC Agreement Node Requirements Community Events Meetups HBAR Telegram Developer Discord Twitter Community Support FAQ Network Status Developer Discord StackOverflow Brand Brand Guidelines Built on Hedera Logo Hedera Store About Team Partners Journey Roadmap Careers Contact General Inquiry Public Relations © 2018-2025 Hedera Hashgraph, LLC. All trademarks and company names are the property of their respective owners. All rights in the Deutsche Telekom mark are protected by Deutsche Telekom AG. All rights reserved. Hedera uses the third party marks with permission. Terms of Use  |  Privacy Policy