Unicorn Ultra
  • Welcome to unicorn ultra — let’s build the future
  • Getting Started
    • Introduction
    • Environment Setup
    • Create an Account
    • Transfer U2U
    • Query Ledger Data
  • Tutorials
    • Smart Contracts
      • Deploy Your First Smart Contract
      • Deploy a Contract Using the Hedera Token Service
      • Send and Receive HBAR Using Solidity Smart Contracts
      • Create an HBAR Faucet App Using React and MetaMask
      • Deploy By Leveraging Ethereum Developer Tools On Hedera
      • Deploy a Smart Contract Using Hardhat
      • Deploy a Subgraph Using The Graph and JSON-RPC
      • How to Set Up Foundry to Test Smart Contracts on Hedera
      • Deploy Smart Contracts on Hedera Using Truffle
    • Consensus
      • Submit Your First Message
      • Submit Message to Private Topic
      • Query Messages with Mirror Node
    • Tokens
      • Create and Transfer Your First NFT
      • Create and Transfer Your First Fungible Token
      • Create and Transfer an NFT using a Solidity Contract
      • Structure Your Token Metadata Using JSON Schema V2
    • More Tutorials
      • How to Auto-Create Hedera Accounts with HBAR and Token Transfers
      • How to Configure a Mirror Node and Query Data
      • How to Generate a Random Number on Hedera
      • Get Started with the Hedera Consensus Service Fabric Plugin
        • Virtual Environment Setup
      • Schedule Your First Transaction
      • How to Connect to Hedera Networks Over RPC
        • Configuring Hashio RPC endpoints
        • Configuring Arkhia RPC endpoints
        • Configuring Hedera JSON-RPC Relay endpoints
    • Demo Applications
    • Starter Projects
  • Networks
    • Mainnet
      • Mainnet Accounts
      • Mainnet Consensus Nodes
        • Node Requirements
          • Reference Configuration
          • FAQ
      • Fees
        • Transaction Records
    • Testnets
      • Testnet Accounts
      • Testnet Consensus Nodes
    • Network Explorers and Tools
    • Release Notes
      • Hedera Services
      • Hedera Mirror Node
  • Core Concepts
    • Accounts
      • Account Creation
      • Auto Account Creation
      • Account Properties
    • Keys and Signatures
    • Scheduled Transaction
    • Smart Contracts
      • Hyperledger Besu EVM
      • Gas and Fees
      • Solidity Variables and Opcodes
      • Supported ERC Token Standards
      • Hedera Services Integration with Smart Contracts
      • JSON-RPC Relay
      • Hethers
      • Smart Contract Security
    • Staking
      • Staking Program
      • Stake HBAR
    • Hashgraph Consensus Algorithm
      • Gossip About Gossip
      • Virtual Voting
    • Transactions and Queries
    • State and History
    • Mirror Nodes
      • Hedera Mirror Node
      • One Click Mirror Node Deployment
      • Run Your Own Mirror Node
        • Run Your Own Mirror Node with Google Cloud Storage (GCS)
        • Run Your Mirror Node with Amazon Web Services S3 (AWS)
      • Hedera ETL
  • SDKs & APIs
    • SDKs
      • Build Your Hedera Client
      • Set Up Your Local Network
      • Network Address Book
      • Keys
        • Generate a new key pair
        • Import an existing key
        • Create a key list
        • Create a threshold key
        • Generate a mnemonic phrase
        • Recover keys from a mnemonic phrase
      • HBAR
      • Specialized Types
      • Pseudorandom Number Generator
      • Transactions
        • Transaction ID
        • Modify transaction fields
        • Create an unsigned transaction
        • Manually sign a transaction
        • Submit a transaction
        • Sign a multisignature transaction
        • Get a transaction receipt
        • Get a transaction record
      • Schedule Transaction
        • Schedule ID
        • Create a scheduled transaction
        • Sign a scheduled transaction
        • Delete a scheduled transaction
        • Get schedule info
        • Network Response Messages
        • Schedule FAQ
      • Queries
      • General Network Response Messages
      • Accounts and HBAR
        • Create an account
        • Update an account
        • Transfer cryptocurrency
        • Approve an allowance
        • Delete an allowance
        • Delete an account
        • Get account balance
        • Get account info
        • Network Response Messages
      • Consensus Service
        • Create a topic
        • Update a topic
        • Submit a message
        • Delete a topic
        • Get topic messages
        • Get topic info
        • Network Response
      • Token Service
        • Token ID
        • NFT ID
        • Token types
        • Create a token
        • Custom token fees
        • Update a token
        • Update token custom fees
        • Transfer tokens
        • Delete a token
        • Mint a token
        • Burn a token
        • Freeze an account
        • Unfreeze an account
        • Enable KYC account flag
        • Disable KYC account flag
        • Associate tokens to an account
        • Dissociate tokens from an account
        • Pause a token
        • Unpause a token
        • Wipe a token
        • Atomic swaps
        • Get account token balance
        • Get token info
        • Get NFT info
        • Network Response Messages
      • File Service
        • Create a file
        • Append to a file
        • Update a file
        • Delete a file
        • Get file contents
        • Get file info
        • Network Response Messages
      • Smart Contract Service
        • Delegate Contract ID
        • Create a smart contract
        • Update a smart contract
        • Delete a smart contract
        • Call a smart contract function
        • Ethereum transaction
        • Get a smart contract function
        • Get smart contract bytecode
        • Get smart contract info
        • Hedera Service Solidity Libraries
        • Network Response Messages
      • Signature Provider
        • Provider
        • Signer
        • Wallet
        • Local Provider
    • REST API
    • Hedera Consensus Service gRPC API
    • Hedera APIs
      • Basic Types
        • AccountAmount
        • AccountID
        • ContractID
        • CryptoAllowance
        • CurrentAndNextFeeSchedule
        • FeeComponents
        • FeeData
        • FeeSchedule
        • FileID
        • Fraction
        • HederaFunctionality
        • Key
        • KeyList
        • NftAllowance
        • NftTransfer
        • NodeAddress
        • NodeAddressBook
        • RealmID
        • ScheduleID
        • SemanticVersion
        • ServicesConfigurationList
        • ServiceEndpoint
        • Setting
        • ShardID
        • Signature
        • SignatureList
        • SignatureMap
        • SignaturePair
        • SubType
        • TransferList
        • TransactionID
        • ThresholdKey
        • ThresholdSignature
        • TokenAllowance
        • TokenBalance
        • TokenBalances
        • TokenFreezeStatus
        • TokenPauseStatus
        • TokenID
        • TokenKycStatus
        • TokenRelationship
        • TokenTransferList
        • TokenType
        • TokenSupplyType
        • TopicID
        • TransactionFeeSchedule
      • Cryptocurrency Accounts
        • CryptoService
        • CryptApproveAllowance
        • CryptoDeleteAllowance
        • CryptoCreate
        • CryptoTransfer
        • CryptoUpdate
        • CryptoDelete
        • CryptoGetAccountBalance
        • CryptoGetAccountRecords
        • CryptoGetInfo
        • CryptoGetStakers
      • Consensus Service
        • Consensus Service
        • ConsensusCreateTopic
        • ConsensusUpdateTopic
        • ConsensusSubmitMessage
        • ConsensusDeleteTopic
        • ConsensusTopicInfo
        • ConsensusGetTopicInfo
      • Schedule Service
        • ScheduleService
        • SchedulableTransactionBody
        • ScheduleCreate
        • ScheduleDelete
        • ScheduleSign
        • ScheduleGetInfo
      • Token Service
        • TokenService
        • CustomFees
          • AssessedCustomFee
          • CustomFee
          • FractionalFee
          • FixedFee
          • RoyaltyFee
        • TokenCreate
        • TokenUpdate
        • TokenFeeScheduleUpdate
        • TokenDelete
        • TokenMint
        • TokenBurn
        • TokenFreezeAccount
        • TokenUnfreezeAccount
        • TokenGrantKyc
        • TokenRevokeKyc
        • TokenAssociate
        • TokenDissociate
        • TokenWipeAccount
        • TokenPause
        • TokenUnpause
        • TokenGetInfo
        • TokenGetNftInfo
        • TokenGetNftInfos
        • TokenGetAccountNftInfo
      • File Service
        • FileService
        • FileCreate
        • FileAppend
        • FileUpdate
        • FileDelete
        • FileGetContents
        • FileGetInfo
      • Smart Contracts
        • SmartContractService
        • ContractCall
        • ContractCallLocal
        • ContractCreate
        • ContractUpdate
        • ContractDelete
        • ContractGetByteCode
        • ContractGetInfo
        • ContractGetRecords
      • Miscellaneous
        • Duration
        • ExchangeRate
        • Freeze
        • FreezeType
        • GetByKey
        • GetBySolidityID
        • NetworkGetVersionInfo
        • NetworkService
        • Query
        • QueryHeader
        • Response
        • ResponseCode
        • ResponseHeader
        • SystemDelete
        • SystemUndelete
        • TimeStamp
        • Transaction
        • TransactionBody
        • TransactionContents
        • TransactionGetFastRecord
        • TransactionGetReceipt
        • TransactionGetRecord
        • TransactionReceipt
        • TransactionRecord
        • TransactionResponse
        • UncheckedSubmit
    • Deprecated
      • SDKs (V1)
        • Build your Hedera client
        • Set-up Your Local Network
        • Network address book
        • Keys
          • Generate a new key pair
          • Import an existing key
          • Create a key list
          • Create a threshold key
          • Generate a mnemonic phrase
          • Recover keys from a mnemonic phrase
        • Hbars
        • Specialized Types
        • Pseudorandom Number Generator
        • Transactions
          • Transaction ID
          • Modify transaction fields
          • Create an unsigned transaction
          • Manually sign a transaction
          • Submit a transaction
          • Sign a multisignature transaction
          • Get a transaction receipt
          • Get a transaction record
        • Scheduled Transaction
          • Schedule ID
          • Create a scheduled transaction
          • Sign a scheduled transaction
          • Delete a scheduled transaction
          • Get schedule info
          • Network Response Messages
          • Schedule FAQ
        • Queries
        • General Network Response Messages
        • Accounts and hbar
          • Create an account
          • Update an Account
          • Transfer cryptocurrency
          • Approve an allowance
          • Delete an allowance
          • Delete an account
          • Get account balance
          • Get account info
          • Network Response Messages
        • Consensus Service
          • Create a topic
          • Update a topic
          • Submit a message
          • Delete a topic
          • Get topic messages
          • Get topic info
        • Token Service
          • Token ID
          • NFT ID
          • Token types
          • Create a token
          • Custom token fees
          • Update a token
          • Update token custom fees
          • Transfer tokens
          • Delete a token
          • Mint a token
          • Burn a token
          • Freeze an account
          • Unfreeze an account
          • Enable KYC account flag
          • Disable KYC account flag
          • Associate tokens to an account
          • Dissociate tokens from an account
          • Pause a token
          • Unpause a token
          • Wipe a token
          • Atomic swaps
          • Get account token balance
          • Get token info
          • Get NFT info
          • Network Response Messages
        • File Service
          • Create a file
          • Append to a file
          • Update a file
          • Delete a file
          • Get file contents
          • Get file info
          • Network Response Messages
  • Support & Community
    • Glossary
    • Discord
    • GitHub
    • Stack Overflow
    • Hedera Blog
    • Bug Bounty
    • Hedera Help
    • Meetups
    • Contributing Guide
    • Brand Guidelines
    • Status Page
Powered by GitBook
On this page
  • Prerequisites
  • Create a Hedera Project and Install the Hedera JS SDK
  • Configure Foundry in your Hedera project
  • Create Tests
  • Deploy Your Smart Contract
  • Forge Gas Reports
  • Summary
  1. Tutorials
  2. Smart Contracts

How to Set Up Foundry to Test Smart Contracts on Hedera

PreviousDeploy a Subgraph Using The Graph and JSON-RPCNextDeploy Smart Contracts on Hedera Using Truffle

Last updated 1 year ago

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: , the SwirldsLabs hosted version of the , is in beta. If issues are encountered while using Foundry and Hashio, please create an issue in the JSON-RPC Relay GitHub .

Prerequisites

  • and .

  • Basic understanding of and .

  • Basic understanding of and framework.

  • Basic understanding of the Hedera .

Create a Hedera Project and Install the Hedera JS SDK

Open your terminal and create a directory called my-hedera-project by running the following command:

mkdir my-hedera-project && cd my-hedera-project

Initialize a node project and accept all defaults:

npm init -y

Install dependencies and the Hedera JavaScript SDK:

npm install --save @hashgraph/sdk 
OPERATOR_ACCOUNT_ID=<account id>
OPERATOR_PRIVATE_KEY=<private key>

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

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 <project-name>

Your foundry project will have the following directory structure

.
├── lib
├── script
├── src
└── test

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

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'

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 project's 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 Tests

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;
  }
}

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);
    }
}

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

To run your tests run the following command:

forge test

Deploy Your Smart Contract

Step 1: Compile your smart contract using solc

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.

import fs from "fs";
const bytecode = fs.readFileSync("binaries/contracts_ERC20FungibleToken_sol_ERC20FungibleToken.bin");

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];
}

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();

Forge Gas Reports

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.

Summary

Happy Building! Feel free to reach out if you have any questions:

In your project root directory, create your .env file and fill the contents with your account Id and private key from the where you created your Hedera Testnet account. They will be used to create your Hedera client.

Forge has functionality built in to give you of your contracts. First, configure your foundry.toml to specify which contracts should generate a gas report.

In this tutorial, we have learned how to configure Foundry to work with a Hedera project to test our smart contracts using the framework. We also learned how to generate gas reports for our smart contracts.

developer portal
gas reports
forge
Foundry
Hashio
JSON-RPC Relay
repository
Install Foundry
a Hedera Testnet account
TypeScript
Solidity
Foundry
Forge
JSON-RPC Relay

Writer: Abi, DevRel Engineer

Editor: Krystal, Technical Writer

1.

2.

3.

4.

5.

6.

|

|

PROJECT REPO
GitHub
LinkedIn
GitHub
Twitter
PREREQUISITES
CREATE PROJECT
CONFIGURE FOUNDRY
TEST CONTRACT
DEPLOY CONTRACT