Estimated time: 5 minutes read

Hardhat allows for easy interaction with developed Smart Contracts through its interactive JavaScript console and the execution of script files.

How to use the console with Hardhat?

Hardhat provides access to a JavaScript console that allows you to interact with the developed smart contracts. It is executed as follows:

yarn hardhat console

If necessary, the contracts will be automatically compiled before opening the console. To prevent compilation, you should use the “–no-compile” flag:

yarn hardhat console --no-compile

The console’s runtime environment, once the ‘hardhat.config.js’ file is loaded, is similar to that of tasks, tests, and scripts, the Hardhat Runtime Environment. Therefore, you have all the necessary utilities to read and write to the Hardhat Network.

As interaction with the blockchain consists of inherently asynchronous operations, the Hardhat console allows the use of the JavaScript reserved keyword ‘await’.

To exit the console, simply press ‘ctrl-c’ twice in succession.

Another execution option involves interacting with the Hardhat Network in process mode from the console:

yarn hardhat node
yarn hardhat console --network localhost

If any configuration parameters in the ‘hardhat.config.js’ file are changed, both processes would need to be restarted.

What is the Hardhat console used for?

A common use of the Hardhat console is to easily test the functions developed in a Smart Contract.

This is illustrated with the following example contract:

pragma solidity ^0.8.20;

import "@openzeppelin/contracts/access/Ownable.sol";

contract TestingContract is Ownable {  
    
	/// @dev Emitted when currentValue is updated
    event ValueUpdated(uint256 indexed newValue, uint256 indexed oldValue, address indexed sender);
	
    /// @dev value to update
    uint256 public currentValue;    
        
    constructor() Ownable(msg.sender) {        
        currentValue = 0;        
    }    

    /**
    * @dev Changes current value
    *
    * @param currentValue_ New value.
    */    
    function setCurrentValue(uint256 currentValue_) external {

		emit ValueUpdated(currentValue_, currentValue, msg.sender);        
        currentValue = currentValue_;        
    }
}

The following instructions could be executed from the console to test the execution of the ‘setCurrentValue’ function:

const testingContract = await hre.ethers.deployContract("TestingContract");

console.log("Testing contract address", testingContract.target);

await testingContract.setCurrentValue(10);

let currentValue = await testingContract.currentValue();

console.log("Current value", currentValue);

When invoking the write operation on the Hardhat Network, information about the transaction will be displayed in the console.

The method debug_traceTransaction can be used to debug the executed OPCODES. This is illustrated in the following example, replacing $HASH_ID with the transaction hash:

let trace = await network.provider.send("debug_traceTransaction", ["$HASH_ID"]);

console.log(trace);

As detailed in the article on Debugging Smart Contracts with Hardhat, to display even more debugging information in the console, you can enable the ‘loggingEnabled: true’ parameter in the ‘hardhat.config.js’ file:

networks: {
      hardhat: {
        loggingEnabled: true
      },
},

How to execute scripts with Hardhat?

Hardhat scripts are a useful mechanism for executing JavaScript files that utilize the tools available in Hardhat.

To do this, simply import the Hardhat Runtime Environment at the beginning of the script, providing access to the necessary utilities to read and write to the Hardhat Network.

They can also be used to develop targeted tests on the Smart Contracts that can be executed repeatedly at different times.

The following JavaScript file would group all the statements we saw in the previous console usage example:

const hre = require("hardhat");

async function main() {

  const testingContract = await hre.ethers.deployContract("TestingContract");

  console.log("Testing contract address", testingContract.target);

  await testingContract.setCurrentValue(10);

  let currentValue = await testingContract.currentValue();

  console.log("Current value", currentValue);
  
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

It would be invoked as follows:

yarn hardhat run .\scripts\scriptFile.js

With the parameter ‘loggingEnabled: true’, even more debugging information would be displayed.

Another option would be to invoke the script by interacting with the Hardhat Network in process mode:

yarn hardhat node 
yarn hardhat run .\scripts\scriptFile.js --network localhost

Conclusion: Interacting with Smart Contracts using JavaScript

This article has detailed two procedures for interacting with the programmed Smart Contracts using JavaScript, accessing all the functionality injected into the Hardhat Runtime Environment via the ‘hardhat.config.js’ file.

Both utilities can be used to check specific contract functions in a non-systematic manner, without the overhead of the automated test suites described in the Debugging Smart Contracts with Hardhat article.

They can also be useful for agile testing of contract functionality in the early stages of development, as functions are progressively added.


Would you prefer testing smart contracts through automated tests or do you find it sufficient to ensure correct functionality through simple scripts? Share your thoughts in the comments.

If you’re looking to develop logic through smart contracts, feel free to contact me, I’m a blockchain developer and can assist you.