How to Set Up Foundry to Test Smart Contracts on Hedera
IMG 2356
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: Hashiothe 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
      Code Snippet Background
      .
      ├── cache
      ├── contracts
      ├── index.ts
      ├── test
      └── package.json
      
      • 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.

      Code Snippet Background
      mkdir my-hedera-project && cd my-hedera-project
      

      Initialize a node project and accept all defaults

      Code Snippet Background
      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.

      Need a Testnet Account?

      Head over to portal.hedera.com to create a testnet account and receive 10,000 test HBAR every 24 hours!

      Code Snippet Background
      
      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

      Code Snippet Background
      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:

      Code Snippet Background
      .
      ├── cache
            ├──forge-cache
      ├── contracts
      ├── test
      ├──foundry
      ├── .env
      ├── .gitignore
      ├── index.ts
      ├── package-lock.json
      ├── package.json
      └── tsconfig.json
      
      

      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:

      Code Snippet Background
      forge init <project-name>
      

      Your foundry project will have the following directory structure

      Code Snippet Background
      .
      ├── lib
      ├── script
      ├── src
      └── test
      
      

      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:

      Code Snippet Background
      .
      ├── cache
            ├──forge-cache
      ├── contracts
      ├── lib
      ├── test
      ├──foundry
      ├── .env
      ├── .gitignore
      ├── index.ts
      ├── package-lock.json
      ├── package.json
      └── tsconfig.json
      

      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:


      Code Snippet Background
      [profile.default]
      src = 'contracts'
      out = 'out'
      libs = ['node_modules', 'lib']
      test = 'test/foundry'
      cache_path = 'forge-cache'
      
      

      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:

      Code Snippet Background
      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”;

      Step 7. Create a smart contract

      Create a smart contract file named TodoList.sol under the contracts directory

      Code Snippet Background
      // 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;
        }
      }
      

      Step 8. Create tests written in Solidity

      Create a file named TodoList.t.sol under test/foundry and write the following test:

      Code Snippet Background
      // 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);
          }
      }
      

      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

      Code Snippet Background
      forge build
      
      Forge build

      To run your tests run the following command

      Code Snippet Background
      forge test
      
      Forge test

      Deploy your Smart Contract

      Step 1: Compile your smart contract using solc

      Code Snippet Background
      solcjs --bin contracts/TodoList.sol -o binaries 
      

      Step 2: Read the compiled bytecode

      In your index.ts file import fs in order to read your smart contracts bytecode.
      Code Snippet Background
      import fs from "fs";
      const bytecode = fs.readFileSync("binaries/contracts_ERC20FungibleToken_sol_ERC20FungibleToken.bin");
      

      Step 3: Create a function to deploy your smart contract

      Code Snippet Background
      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];
      }
      
      

      Step 4: Call your function that deploys your smart contract to the Hedera network

      Code Snippet Background
      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 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

      Code Snippet Background
      gas_reports = ["TodoList"]
      
      Toml file

      In order to generate a gas report run the following command in your vscode terminal.

      Code Snippet Background
      forge test –gas-report
      
      Gas report first article

      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: