Skip to content

Using Hardhat to Deploy to Your EVM Appchain

Introduction

Hardhat is an Ethereum development environment that helps developers manage and automate the recurring tasks inherent to building smart contracts and dApps. Hardhat can be used with any EVM appchain to build, compile, and deploy smart contracts, thanks to the seamless compatibility of Tanssi EVM appchains.

This guide will cover how to use Hardhat to compile, deploy, and interact with Ethereum smart contracts deployed to the demo Tanssi EVM appchain. This guide can be adapted for your own Tanssi EVM appchain by simply adding the RPC URL of your Tanssi appchain to your EVM Wallet and switching networks to it.

Checking Prerequisites

For this guide, you'll need to have MetaMask installed and configured to work with your Tanssi EVM appchain. You can follow this guide to configure MetaMask for Tanssi with the demo EVM appchain.

Creating a Hardhat Project

You will need to create a Hardhat project if you don't already have one. You can create one by completing the following steps:

  1. Create a directory for your project

    mkdir hardhat && cd hardhat
    
  2. Initialize the project which will create a package.json file

    npm init -y
    
  3. Install Hardhat

    npm install hardhat
    
  4. Create a project

    npx hardhat init
    

    Note

    npx is used to run executables installed locally in your project. Although Hardhat can be installed globally, it is recommended to install it locally in each project so that you can control the version on a project-by-project basis.

  5. A menu will appear which will allow you to create a new project or use a sample project. For this example, you can choose Create an empty hardhat.config.js

Hardhat Create Project

This will create a Hardhat config file (hardhat.config.js) in your project directory.

Once you have your Hardhat project, you can also install the Ethers plugin. This provides a convenient way to use the Ethers.js library to interact with the network. To install it, run the following command:

npm install @nomicfoundation/hardhat-ethers ethers@6

The Contract File

With your empty project created, next, you are going to create a contracts directory. You can do so by running the following command:

mkdir contracts && cd contracts

The smart contract that you'll deploy as an example will be called Box, it will let you store a value that can be retrieved later. In the contracts directory, you can create the Box.sol file:

touch Box.sol

Open the file and add the following contract to it:

// contracts/Box.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;

contract Box {
    uint256 private value;

    // Emitted when the stored value changes
    event ValueChanged(uint256 newValue);

    // Stores a new value in the contract
    function store(uint256 newValue) public {
        value = newValue;
        emit ValueChanged(newValue);
    }

    // Reads the last stored value
    function retrieve() public view returns (uint256) {
        return value;
    }
}

The Hardhat Configuration File

Before you can deploy the contract to your Tanssi appchain, you'll need to modify the Hardhat configuration file and create a secure file to store your private key in.

You can modify the hardhat.config.js file to use either the Tanssi Dancebox demo EVM appchain or your own Tanssi appchain:

// 1. Import the Ethers plugin required to interact with the contract
require('@nomicfoundation/hardhat-ethers');

// 2. Add your private key that is funded with tokens of your Tanssi appchain
// This is for example purposes only - **never store your private keys in a JavaScript file**
const privateKey = 'INSERT_PRIVATE_KEY';

module.exports = {
  // 3. Specify the Solidity version
  solidity: '0.8.1',
  networks: {
    // 4. Add the network specification for your Tanssi EVM appchain
    dancebox: {
      url: 'https://fraa-dancebox-3001-rpc.a.dancebox.tanssi.network',
      chainId: 5678, // Fill in the EVM ChainID for your Tanssi appchain
      accounts: [privateKey]
    }
  }
};

Congratulations! You are now ready for deployment!

Compiling Solidity

To compile the contract you can simply run:

npx hardhat compile

Hardhat Contract Compile

After compilation, an artifacts directory is created: it holds the bytecode and metadata of the contract, which are .json files. It’s a good idea to add this directory to your .gitignore.

Deploying the Contract

In order to deploy the Box.sol smart contract, you will need to write a simple deployment script. You can create a new directory for the script, name it scripts, and add a new file to it called deploy.js:

mkdir scripts && cd scripts
touch deploy.js

Next, you need to write your deployment script, which can be done using ethers. Because you'll be running it with Hardhat, you don't need to import any libraries.

To get started, take the following steps:

  1. Create a local instance of the contract with the getContractFactory method
  2. Define a custom gas price and gas limit (this is a temporary stopgap)
  3. Use the deploy method that exists within this instance to instantiate the smart contract
  4. Wait for the deployment by using waitForDeployment
  5. Once deployed, you can fetch the address of the contract using the contract instance
// scripts/deploy.js
async function main() {
  // 1. Get the contract to deploy
  const Box = await ethers.getContractFactory('Box');
  console.log('Deploying Box...');

  // 2. Define custom gas price and gas limit
  // This is a temporary stopgap solution to a bug
  const customGasPrice = 50000000000; // example for 50 gwei
  const customGasLimit = 1000000; // example gas limit

  // 3. Instantiating a new Box smart contract with custom gas settings
  const box = await Box.deploy({
    gasPrice: customGasPrice, 
    gasLimit: customGasLimit,
  });

  // 4. Waiting for the deployment to resolve
  await box.waitForDeployment();

  // 5. Use the contract instance to get the contract address
  console.log('Box deployed to:', box.target);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

You can now deploy the Box.sol contract using the run command and specifying dancebox as the network:

npx hardhat run --network dancebox scripts/deploy.js

If you're deploying to another Tanssi appchain, make sure that you specify the correct network. The network name needs to match how it's defined in hardhat.config.js.

After a few seconds, the contract is deployed, and you should see the address in the terminal.

Hardhat Contract Deploy

Congratulations, your contract is live! Save the address, as you will use it to interact with this contract instance in the next step.

Interacting with the Contract

To interact with your newly deployed contract on your Tanssi appchain, you can launch the Hardhat console by running:

npx hardhat console --network dancebox

Next, you can take the following steps, entering one line at a time:

  1. Create a local instance of the Box.sol contract

    const Box = await ethers.getContractFactory('Box');
    
  2. Connect the local instance to the deployed contract, using the address of the contract

    const box = await Box.attach('0x707D4Eb8B3fec49884c217A659b01238afee1697');
    
  3. Interact with the attached contract. For this example, you can call the store method and store a simple value

    await box.store(5);
    

The transaction will be signed by your EVM account and be broadcast to the network. The output should look similar to:

Transaction output

Notice your address labeled from, the address of the contract, and the data that is being passed. Now, you can retrieve the value by running:

await box.retrieve();

You should see 5 or the value you initially stored.

Note

If you run the retrieve command immediately after storing the value, you may see the old value. Running the retrieval command again after waiting a moment will return the correct value.

Congratulations, you have successfully deployed and interacted with a contract using Hardhat!

The information presented herein has been provided by third parties and is made available solely for general information purposes. Tanssi does not endorse any project listed and described on the Tanssi Doc Website (https://docs.tanssi.network/). Tanssi Foundation does not warrant the accuracy, completeness or usefulness of this information. Any reliance you place on such information is strictly at your own risk. Tanssi Foundation disclaims all liability and responsibility arising from any reliance placed on this information by you or by anyone who may be informed of any of its contents. All statements and/or opinions expressed in these materials are solely the responsibility of the person or entity providing those materials and do not necessarily represent the opinion of Tanssi Foundation. The information should not be construed as professional or financial advice of any kind. Advice from a suitably qualified professional should always be sought in relation to any particular matter or circumstance. The information herein may link to or integrate with other websites operated or content provided by third parties, and such other websites may link to this website. Tanssi Foundation has no control over any such other websites or their content and will have no liability arising out of or related to such websites or their content. The existence of any such link does not constitute an endorsement of such websites, the content of the websites, or the operators of the websites. These links are being provided to you only as a convenience and you release and hold Tanssi Foundation harmless from any and all liability arising from your use of this information or the information provided by any third-party website or service.
Last update: March 29, 2024
| Created: October 13, 2023