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.
. ├── cache ├── contracts ├── index.ts ├── test └── package.json
The complete example can be found on GitHub here.
Open your terminal and create a directory called my-hedera-project.
mkdir my-hedera-project && cd my-hedera-project
Initialize a node project and accept all defaults
npm install --save @hashgraph/sdk
Create your .env file and fill the contents with your account Id and private key. They will be used to create your Hedera client.
Head over to portal.hedera.com to create a testnet account and receive 10,000 test HBAR every 24 hours!
OPERATOR_ACCOUNT_ID=<account id> OPERATOR_PRIVATE_KEY=<private key>
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));
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
Open a new terminal window and Create a sample Foundry project by running the following command in the new terminal:
forge init <project-name>
Your foundry project will have the following directory structure
. ├── lib ├── script ├── src └── test
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
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'
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/
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”;
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; } }
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); } }
In your terminal, ensure you are in your forge project directory and run the following command to build
forge build
To run your tests run the following command
forge test
Step 1: Compile your smart contract using solc
solcjs --bin contracts/TodoList.sol -o binaries
import fs from "fs"; const bytecode = fs.readFileSync("binaries/contracts_ERC20FungibleToken_sol_ERC20FungibleToken.bin");
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]; }
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();
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"]
In order to generate a gas report run the following command in your vscode terminal.
forge test –gas-report
Your output will show you an estimated gas average, median, and max for each contract function and total deployment cost and size.
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: