Network
Launch Date
Consensus
Note
Sepolia
Oct 2021
PoW
Like-for-like representation of Ethereum
Görli
Jan 2019
PoA
Proof-of-Authority
Kiln
Mar 2022
PoS
Post-Merge (for ETH2), shadow fork of the mainnet
Kintsugi
Dec 2021
PoS
DEPRECATED, use Kiln; post-Merge (for ETH2)
Ropsten
Nov 2016
PoW
DEPRECATED, use Sepolia; the Merge to happen on Jun 8, 2022
Rinkeby
Apr 2017
PoA
DEPRECATED, use Görli and Görli Faucet
Kovan
Mar 2017
PoA
DEPRECATED, use Sepolia or Görli
List of active and deprecated Ethereum testnets, including Kintsugi.
Features
Optimistic rollup 
ZK-rollup 
Proof
Uses fraud proofs to prove transaction validity. 
Uses validity (zero-knowledge) proofs to prove transaction validity. 
Capital efficiency
Requires waiting through a 1-week delay (dispute period) before withdrawing funds. 
Users can withdraw funds immediately because validity proofs provide incontrovertible evidence of the authenticity of off-chain transactions. 
Data compression
Publishes full transaction data as calldata to Ethereum Mainnet, which increases rollup costs. 
Doesn't need to publish transaction data on Ethereum because ZK-SNARKs and ZK-STARKs already guarantee the accuracy of the rollup state. 
EVM compatibility
Uses a simulation of the Ethereum Virtual Machine (EVM), which allows it to run arbitrary logic and support smart contracts. 
Doesn't widely support EVM computation, although a few EVM-compatible ZK-rollups have appeared. 
Rollup costs
Reduces costs since it publishes minimal data on Ethereum and doesn't have to post proofs for transactions, except in special circumstances. 
Faces higher overhead from costs involved in generating and verifying proofs for every transaction block. ZK proofs require specialized, expensive hardware to create and have high on-chain verification costs. 
Trust assumptions
Doesn't require a trusted setup. 
Requires a trusted setup to work. 
Liveness requirements
Verifiers are needed to keep tabs on the actual rollup state and the one referenced in the state root to detect fraud. 
Users don't need someone to watch the L2 chain to detect fraud. 
Security properties 
Relies on cryptoeconomic incentives to assure users of rollup security. 
Relies on cryptographic guarantees for security. 
Start building
on Alchemy.
Sign up for free
Start building on Optimism.
Sign up for free
Start building on Arbitrum.
Sign up for free
Start building on Ethereum.
Sign up for free
Start building on Polygon.
Sign up for free
Start building on Starknet.
Sign up for free
Start building on Flow.
Sign up for free
kiln faucet
Get free Kiln ETH.
Start building today
Goerli faucet
Get free Goerli ETH.
Start building today
mumbai faucet
Get free Mumbai Matic.
Start building today
rinkeby faucet
Get free Rinkeby
ETH.
Start building today
Start building on Ethereum.
Get started for free
Start building on Ethereum.
Get started for free
Start building on Flow.
Get started for free
Start building on Polygon.
Get started for free
Start building on Starknet.
Get started for free
Start building on Optimism.
Get started for free
Start building on Solana.
Get started for free
Start building on Solana.
Sign up for beta access
Start building on Solana.
Join the waitlist
Arbitrum logo
Start building on Arbitrum.
Get started for free
Learn
Solidity at
Alchemy
University
Get started today
curl 
https://release.solana.com/v1.10.32/solana-install-init-x86_64-pc-windows-msvc.exe 
--output 
C:\solana-install-tmp\solana-install-init.exe 
--create-dirs
Learn Solidity
SOLIDITY CONSOLE LOG OVERVIEW

Everything Solidity Developers Need to Know About the console.log Function

Print Logs and Debug Smart Contracts with Hardhat, Foundry, and More
Last Updated:
October 4, 2022
Table of Contents
Table of Contents
Table of Contents

{{learn-solidity}}

Debugging is a vital and reoccurring step in learning how to write Solidity smart contracts, patch vulnerabilities, and fix problematic bugs. The two typical development errors in smart contracts consist of runtime errors and logic errors.

Leveraging tools that empower the understanding of developers allows for an easier developer experience, especially when it comes to fixing errors in programs. Similar to JavaScript development, the console.log() function is used to return an output message to the web console, which helps the debugging process.

The console.log() is the primary tool to identify a bug within the code by supporting developers to print a variable or a message to the user. It accepts a parameter (i.e. array, object or message) and returns the value of the parameter. This method enables developers to navigate the issue that may occur through outlining the output of the code step-by-step.

In this article, we’ll show you the main way to debug Solidity, review debugging tools in Hardhat, Foundry, Truffle, and Brownie, and then provide debugging tips.

What is the Solidity console log?

Logging to the console is a common tool used to debug code, and console.log() is a function from a contract library provided by Hardhat. Logging outputs information to the console helps developers understand and troubleshoot issues in their program. In Solidity, this would be referred to as an event.

Ethereum offers a logging functionality which stores data in the transaction’s log data structure in the blockchain. Solidity events provide an abstraction to this functionality as it enables developers to output data on the blockchain.

Because the logs stay intact with the contract address in the blockchain and remain accessible with the block, Solidity developers can query and reference the blockchain for the specific transaction data.

Use Cases for Using Solidity Events

Solidity events can be used in a variety of methods including testing smart contracts, indexing for transaction data, referencing for frontend development and more. Most commonly, developers will use events in three uses cases:

  1. In smart contracts to return values that can be used in the frontend
  2. Asynchronous trigger for the smart contract to emit an event that triggers the frontend to do an action
  3. Cheaper form of storage as the data is stored in the transaction log.

Within events, the parameters can be specified as indexed or non-indexed. The transaction data within a log will be viewed as encoded if the contract is verified, otherwise it will display as non-indexed or hashed.

In other cases, if the development process takes place within supportive environments such as Hardhat, the console.log() function can be used in addition to events and this would function similarly to JavaScript development.

Why are console logs important?

Console logs serve as a necessary tool for developers in the smart contract debugging process. Console log is a combination of the testing environment of the program (console) and a function used to output data (log()).

In essence, console log provides an output of the program in a test environment that can be leveraged in the development and debugging process. If an error or issue arises in the program, the console log would be used as a primary step to inspect the code and identify the root cause of a bug.

While writing Solidity smart contracts, console logs similarly serve as an effective step in the debugging process to extract the code and understand the logic.

How does logging in Solidity work?

Logging, otherwise known as event-watching protocol or event, results in signals that are generated by transactions and blocks, which are used to provide information that cannot be obtained by the smart contract.

Solidity has a concept of an 'event'. Events can be emitted in smart contract functions and can have 0 to 4 topics which are indexed for quick lookup. In Solidity the 'emit' keyword is used to emit events. This is translated into one of the EVM's opcodes, LOG0, LOG1, ... , LOG4. 

Because contact data lives in the States trie and event data is stored in the Transaction Receipts trie, smart contracts cannot read event data.

The transaction data or log entries consist of the:

  • Address - the address of the contract
  • Topic - the indexed values of the event
  • Data - the ABI encoded values or non-indexed values of the event

Solidity Debugging Tools in Hardhat

Hardhat is an Ethereum development environment focused on enabling developers to locally develop Solidity smart contracts and empower them with essential Solidity debugging tools. 

Hardhat provides a suite of tools for testing, compiling, deploying and debugging dApps. By leveraging the Hardhat Network, developers are able to create, compile, and deploy smart contracts from their local machine through the Solidity interface.

1. Console.log

Within the Hardhat Network, the console.log() function can be used as a reliable tool to output logging messages and extract details directly from the Solidity code. The Hardhat Network is designed to provide flexible and comprehensive execution inspection regardless of transaction failures.

How to Print to Solidity Console Logs

Solidity console logs can be printed in a structure similar to JavaScript. Once the import is completed, the console.log() function can be used within the function to print specific output depending on the context of the smart contract. The following code outlines the process.

First, import hardhat/console.sol into the smart contract



pragma solidity ^0.8.9;
import "hardhat/console.sol";
contract BookStore {
  //...
}

Next, add the console.log() function into a specific function within the smart contract:



function transfer(address to, uint256 amount) external {
    require(balances[msg.sender] >= amount, "Not enough tokens");

    console.log(
        "Transferring %s tokens to %s",
	Amount,
to,
            msg.sender
    );

    balances[msg.sender] -= amount;
    balances[to] += amount;

    emit Transfer(amount, to, msg.sender);
}

Note: Hardhat's console log tool can only be used once hardhat/console.sol is imported into the smart contract.

2. Solidity Stack Traces

Hardhat's stack trace tool is a combination of JavaScript and Solidity that provides a report when a transaction occurs or a call fails. This automated error reporting provides developers with valuable information to evaluate and debug their smart contract.

3. Explicit Errors

Hardhat provides a variety of possible errors that can help developers simplify the debugging process including:

  • general
  • network
  • task definition
  • arguments
  • dependencies resolution
  • built-in tasks
  • artifacts
  • plugins
  • internal
  • source names
  • contract names

Solidity Console Log Tip: Use Events and Functions to Improve Debugging

Events can be used to output data from the transaction logs to the console for both debugging and production stages. An event serves as a marker to indicate if a process takes place. Additionally, events will indicate if an issue has occurred at particular steps. Such a process is similar to the “require” keyword in Solidity, which checks if a condition is true and allows code to flow only if and when the required condition is true.

To start using events and functions to improve debugging, create an event that is properly defined and emit the event in the function. These two steps ensure that the event will occur once the function is called.

Additional Solidity Console Log Tools

While Hardhat is the industry standard Solidity development tool for building, testing, and debugging smart contracts, there are a few alternative tools for troubleshooting Solidity code including Foundry, Truffle, and Brownie.

1. Foundry

Foundry offers a suite of Ethereum smart contract development tools that enables the management of dependencies, smart contract compilation, deployment, testing, and on-chain interactions.

The Foundry toolkit can be integrated with Hardhat to leverage its console.log() function for the debugging process. Developers can call the function with up to 4 parameters, including uint, string, bool and address.

Forge

Forge is a command-line (CLI) tool integrated with Foundry to test, build, and deploy smart contracts. This testing framework enables developers to create tests in Solidity using JavaScript or TypeScript as well as unlock numerous features for the debugging process.

The forge test command automates the Solidity tests and further provides a summary of the results including logs and stack traces. The forge debug command is also an interactive debugger that reviews a single smart contract as a script to identify any errors in the program.

Cast

Cast is a command-line interface (CLI) tool that interacts with Ethereum RPC calls. This consists of smart contracts calls, transactions, or chain data retrieval via the command line.

Anvil

Anvil is a local testnet node integrated with Foundry to enable smart contract deploying and testing from the frontend or via interactions over RPC (Remote Procedure Calls) with EVM (Ethereum Virtual Machine) compatible networks.

2. Truffle

Truffle offers three Ethereum smart contract developer tools: a development environment, a testing framework and an asset pipeline for blockchains. Truffle’s inclusive ecosystem provides developers with various tools to create, test, and debug end-to-end decentralized applications (dApps). 

These tool sets offered by Truffle are:

  • Smart contract toolkit - compilation, linking, deployment, etc.
  • Debugging - breakpoints, variable analysis, step functionality, automated contract testing
  • Management - network, package, migrations frameworks

Learn More: https://trufflesuite.com/docs/truffle/

3. Brownie

Brownie is a Python-based development and testing framework for smart contracts in Ethereum with support for Solidity and Vyper, and it is divided into 4 categories: testing, debugging, interaction and deployment. Each step supports developers in creating flexible programs.

Developers can access various debugging tools to gather detailed information about transaction failures and to locate, replicate, and troubleshoot Solidity errors.

  • TransactionReceipt.revert_ms - get a direct explanation message for the transaction failure‍
  • TransactionReceipt.error() - locate the root cause and section of the smart contract that caused a failed transaction‍
  • TransactionReceipt.events - view events that fired in reverted transactions‍
  • TransactionReceipt.trace - view a list of dictionaries containing the transaction information‍
  • TransactionReceipt.call_trace() - view a full map (trace) of the transaction steps

Developers can also leverage pytest for unit testing smart contracts, then review the stack trace report that is provided.

Learn More: https://eth-brownie.readthedocs.io/en/v1.2.1/index.html 

Learn About the Solidity Console Log with Alchemy University

This article has introduced you to the most popular logging and debugging tools for developing Solidity smart contracts. If you’re learning Solidity, selecting the best tools for smart contract debugging is essential for solving the issues you face in Solidity development.

To start or accelerate your Solidity development training, explore Alchemy University's free, 7-week Solidity developer bootcamp, originally a $3,000 certification course taught by ChainShot, is now fully integrated with Alchemy! If you are new to development in general, Alchemy's 3-week JavaScript crash course is a great prerequisite before starting an Ethereum bootcamp.

ALCHEMY SUPERNODE - ETHEREUM NODE API

Scale to any size, without any errors

Alchemy Supernode finally makes it possible to scale blockchain applications without all the headaches. Plus, our legendary support will guide you every step of the way.

Get started for free
Supernode footer
Learn Solidity
SOLIDITY CONSOLE LOG OVERVIEW

Learn Solidity: What is the console log?

Print Logs and Debug Smart Contracts with Hardhat, Foundry, and More
Last Updated:
October 4, 2022
Don't miss an update
Sign up for our newsletter to get alpha, key insights, and killer resources.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Table of Contents
Table of Contents

{{learn-solidity}}

Debugging is a vital and reoccurring step in learning how to write Solidity smart contracts, patch vulnerabilities, and fix problematic bugs. The two typical development errors in smart contracts consist of runtime errors and logic errors.

Leveraging tools that empower the understanding of developers allows for an easier developer experience, especially when it comes to fixing errors in programs. Similar to JavaScript development, the console.log() function is used to return an output message to the web console, which helps the debugging process.

The console.log() is the primary tool to identify a bug within the code by supporting developers to print a variable or a message to the user. It accepts a parameter (i.e. array, object or message) and returns the value of the parameter. This method enables developers to navigate the issue that may occur through outlining the output of the code step-by-step.

In this article, we’ll show you the main way to debug Solidity, review debugging tools in Hardhat, Foundry, Truffle, and Brownie, and then provide debugging tips.

What is the Solidity console log?

Logging to the console is a common tool used to debug code, and console.log() is a function from a contract library provided by Hardhat. Logging outputs information to the console helps developers understand and troubleshoot issues in their program. In Solidity, this would be referred to as an event.

Ethereum offers a logging functionality which stores data in the transaction’s log data structure in the blockchain. Solidity events provide an abstraction to this functionality as it enables developers to output data on the blockchain.

Because the logs stay intact with the contract address in the blockchain and remain accessible with the block, Solidity developers can query and reference the blockchain for the specific transaction data.

Use Cases for Using Solidity Events

Solidity events can be used in a variety of methods including testing smart contracts, indexing for transaction data, referencing for frontend development and more. Most commonly, developers will use events in three uses cases:

  1. In smart contracts to return values that can be used in the frontend
  2. Asynchronous trigger for the smart contract to emit an event that triggers the frontend to do an action
  3. Cheaper form of storage as the data is stored in the transaction log.

Within events, the parameters can be specified as indexed or non-indexed. The transaction data within a log will be viewed as encoded if the contract is verified, otherwise it will display as non-indexed or hashed.

In other cases, if the development process takes place within supportive environments such as Hardhat, the console.log() function can be used in addition to events and this would function similarly to JavaScript development.

Why are console logs important?

Console logs serve as a necessary tool for developers in the smart contract debugging process. Console log is a combination of the testing environment of the program (console) and a function used to output data (log()).

In essence, console log provides an output of the program in a test environment that can be leveraged in the development and debugging process. If an error or issue arises in the program, the console log would be used as a primary step to inspect the code and identify the root cause of a bug.

While writing Solidity smart contracts, console logs similarly serve as an effective step in the debugging process to extract the code and understand the logic.

How does logging in Solidity work?

Logging, otherwise known as event-watching protocol or event, results in signals that are generated by transactions and blocks, which are used to provide information that cannot be obtained by the smart contract.

Solidity has a concept of an 'event'. Events can be emitted in smart contract functions and can have 0 to 4 topics which are indexed for quick lookup. In Solidity the 'emit' keyword is used to emit events. This is translated into one of the EVM's opcodes, LOG0, LOG1, ... , LOG4. 

Because contact data lives in the States trie and event data is stored in the Transaction Receipts trie, smart contracts cannot read event data.

The transaction data or log entries consist of the:

  • Address - the address of the contract
  • Topic - the indexed values of the event
  • Data - the ABI encoded values or non-indexed values of the event

Solidity Debugging Tools in Hardhat

Hardhat is an Ethereum development environment focused on enabling developers to locally develop Solidity smart contracts and empower them with essential Solidity debugging tools. 

Hardhat provides a suite of tools for testing, compiling, deploying and debugging dApps. By leveraging the Hardhat Network, developers are able to create, compile, and deploy smart contracts from their local machine through the Solidity interface.

1. Console.log

Within the Hardhat Network, the console.log() function can be used as a reliable tool to output logging messages and extract details directly from the Solidity code. The Hardhat Network is designed to provide flexible and comprehensive execution inspection regardless of transaction failures.

How to Print to Solidity Console Logs

Solidity console logs can be printed in a structure similar to JavaScript. Once the import is completed, the console.log() function can be used within the function to print specific output depending on the context of the smart contract. The following code outlines the process.

First, import hardhat/console.sol into the smart contract



pragma solidity ^0.8.9;
import "hardhat/console.sol";
contract BookStore {
  //...
}

Next, add the console.log() function into a specific function within the smart contract:



function transfer(address to, uint256 amount) external {
    require(balances[msg.sender] >= amount, "Not enough tokens");

    console.log(
        "Transferring %s tokens to %s",
	Amount,
to,
            msg.sender
    );

    balances[msg.sender] -= amount;
    balances[to] += amount;

    emit Transfer(amount, to, msg.sender);
}

Note: Hardhat's console log tool can only be used once hardhat/console.sol is imported into the smart contract.

2. Solidity Stack Traces

Hardhat's stack trace tool is a combination of JavaScript and Solidity that provides a report when a transaction occurs or a call fails. This automated error reporting provides developers with valuable information to evaluate and debug their smart contract.

3. Explicit Errors

Hardhat provides a variety of possible errors that can help developers simplify the debugging process including:

  • general
  • network
  • task definition
  • arguments
  • dependencies resolution
  • built-in tasks
  • artifacts
  • plugins
  • internal
  • source names
  • contract names

Solidity Console Log Tip: Use Events and Functions to Improve Debugging

Events can be used to output data from the transaction logs to the console for both debugging and production stages. An event serves as a marker to indicate if a process takes place. Additionally, events will indicate if an issue has occurred at particular steps. Such a process is similar to the “require” keyword in Solidity, which checks if a condition is true and allows code to flow only if and when the required condition is true.

To start using events and functions to improve debugging, create an event that is properly defined and emit the event in the function. These two steps ensure that the event will occur once the function is called.

Additional Solidity Console Log Tools

While Hardhat is the industry standard Solidity development tool for building, testing, and debugging smart contracts, there are a few alternative tools for troubleshooting Solidity code including Foundry, Truffle, and Brownie.

1. Foundry

Foundry offers a suite of Ethereum smart contract development tools that enables the management of dependencies, smart contract compilation, deployment, testing, and on-chain interactions.

The Foundry toolkit can be integrated with Hardhat to leverage its console.log() function for the debugging process. Developers can call the function with up to 4 parameters, including uint, string, bool and address.

Forge

Forge is a command-line (CLI) tool integrated with Foundry to test, build, and deploy smart contracts. This testing framework enables developers to create tests in Solidity using JavaScript or TypeScript as well as unlock numerous features for the debugging process.

The forge test command automates the Solidity tests and further provides a summary of the results including logs and stack traces. The forge debug command is also an interactive debugger that reviews a single smart contract as a script to identify any errors in the program.

Cast

Cast is a command-line interface (CLI) tool that interacts with Ethereum RPC calls. This consists of smart contracts calls, transactions, or chain data retrieval via the command line.

Anvil

Anvil is a local testnet node integrated with Foundry to enable smart contract deploying and testing from the frontend or via interactions over RPC (Remote Procedure Calls) with EVM (Ethereum Virtual Machine) compatible networks.

2. Truffle

Truffle offers three Ethereum smart contract developer tools: a development environment, a testing framework and an asset pipeline for blockchains. Truffle’s inclusive ecosystem provides developers with various tools to create, test, and debug end-to-end decentralized applications (dApps). 

These tool sets offered by Truffle are:

  • Smart contract toolkit - compilation, linking, deployment, etc.
  • Debugging - breakpoints, variable analysis, step functionality, automated contract testing
  • Management - network, package, migrations frameworks

Learn More: https://trufflesuite.com/docs/truffle/

3. Brownie

Brownie is a Python-based development and testing framework for smart contracts in Ethereum with support for Solidity and Vyper, and it is divided into 4 categories: testing, debugging, interaction and deployment. Each step supports developers in creating flexible programs.

Developers can access various debugging tools to gather detailed information about transaction failures and to locate, replicate, and troubleshoot Solidity errors.

  • TransactionReceipt.revert_ms - get a direct explanation message for the transaction failure‍
  • TransactionReceipt.error() - locate the root cause and section of the smart contract that caused a failed transaction‍
  • TransactionReceipt.events - view events that fired in reverted transactions‍
  • TransactionReceipt.trace - view a list of dictionaries containing the transaction information‍
  • TransactionReceipt.call_trace() - view a full map (trace) of the transaction steps

Developers can also leverage pytest for unit testing smart contracts, then review the stack trace report that is provided.

Learn More: https://eth-brownie.readthedocs.io/en/v1.2.1/index.html 

Learn About the Solidity Console Log with Alchemy University

This article has introduced you to the most popular logging and debugging tools for developing Solidity smart contracts. If you’re learning Solidity, selecting the best tools for smart contract debugging is essential for solving the issues you face in Solidity development.

To start or accelerate your Solidity development training, explore Alchemy University's free, 7-week Solidity developer bootcamp, originally a $3,000 certification course taught by ChainShot, is now fully integrated with Alchemy! If you are new to development in general, Alchemy's 3-week JavaScript crash course is a great prerequisite before starting an Ethereum bootcamp.

Debugging is a vital and reoccurring step in learning how to write Solidity smart contracts, patch vulnerabilities, and fix problematic bugs. The two typical development errors in smart contracts consist of runtime errors and logic errors.

Leveraging tools that empower the understanding of developers allows for an easier developer experience, especially when it comes to fixing errors in programs. Similar to JavaScript development, the console.log() function is used to return an output message to the web console, which helps the debugging process.

The console.log() is the primary tool to identify a bug within the code by supporting developers to print a variable or a message to the user. It accepts a parameter (i.e. array, object or message) and returns the value of the parameter. This method enables developers to navigate the issue that may occur through outlining the output of the code step-by-step.

In this article, we’ll show you the main way to debug Solidity, review debugging tools in Hardhat, Foundry, Truffle, and Brownie, and then provide debugging tips.

What is the Solidity console log?

Logging to the console is a common tool used to debug code, and console.log() is a function from a contract library provided by Hardhat. Logging outputs information to the console helps developers understand and troubleshoot issues in their program. In Solidity, this would be referred to as an event.

Ethereum offers a logging functionality which stores data in the transaction’s log data structure in the blockchain. Solidity events provide an abstraction to this functionality as it enables developers to output data on the blockchain.

Because the logs stay intact with the contract address in the blockchain and remain accessible with the block, Solidity developers can query and reference the blockchain for the specific transaction data.

Use Cases for Using Solidity Events

Solidity events can be used in a variety of methods including testing smart contracts, indexing for transaction data, referencing for frontend development and more. Most commonly, developers will use events in three uses cases:

  1. In smart contracts to return values that can be used in the frontend
  2. Asynchronous trigger for the smart contract to emit an event that triggers the frontend to do an action
  3. Cheaper form of storage as the data is stored in the transaction log.

Within events, the parameters can be specified as indexed or non-indexed. The transaction data within a log will be viewed as encoded if the contract is verified, otherwise it will display as non-indexed or hashed.

In other cases, if the development process takes place within supportive environments such as Hardhat, the console.log() function can be used in addition to events and this would function similarly to JavaScript development.

Why are console logs important?

Console logs serve as a necessary tool for developers in the smart contract debugging process. Console log is a combination of the testing environment of the program (console) and a function used to output data (log()).

In essence, console log provides an output of the program in a test environment that can be leveraged in the development and debugging process. If an error or issue arises in the program, the console log would be used as a primary step to inspect the code and identify the root cause of a bug.

While writing Solidity smart contracts, console logs similarly serve as an effective step in the debugging process to extract the code and understand the logic.

How does logging in Solidity work?

Logging, otherwise known as event-watching protocol or event, results in signals that are generated by transactions and blocks, which are used to provide information that cannot be obtained by the smart contract.

Solidity has a concept of an 'event'. Events can be emitted in smart contract functions and can have 0 to 4 topics which are indexed for quick lookup. In Solidity the 'emit' keyword is used to emit events. This is translated into one of the EVM's opcodes, LOG0, LOG1, ... , LOG4. 

Because contact data lives in the States trie and event data is stored in the Transaction Receipts trie, smart contracts cannot read event data.

The transaction data or log entries consist of the:

  • Address - the address of the contract
  • Topic - the indexed values of the event
  • Data - the ABI encoded values or non-indexed values of the event

Solidity Debugging Tools in Hardhat

Hardhat is an Ethereum development environment focused on enabling developers to locally develop Solidity smart contracts and empower them with essential Solidity debugging tools. 

Hardhat provides a suite of tools for testing, compiling, deploying and debugging dApps. By leveraging the Hardhat Network, developers are able to create, compile, and deploy smart contracts from their local machine through the Solidity interface.

1. Console.log

Within the Hardhat Network, the console.log() function can be used as a reliable tool to output logging messages and extract details directly from the Solidity code. The Hardhat Network is designed to provide flexible and comprehensive execution inspection regardless of transaction failures.

How to Print to Solidity Console Logs

Solidity console logs can be printed in a structure similar to JavaScript. Once the import is completed, the console.log() function can be used within the function to print specific output depending on the context of the smart contract. The following code outlines the process.

First, import hardhat/console.sol into the smart contract



pragma solidity ^0.8.9;
import "hardhat/console.sol";
contract BookStore {
  //...
}

Next, add the console.log() function into a specific function within the smart contract:



function transfer(address to, uint256 amount) external {
    require(balances[msg.sender] >= amount, "Not enough tokens");

    console.log(
        "Transferring %s tokens to %s",
	Amount,
to,
            msg.sender
    );

    balances[msg.sender] -= amount;
    balances[to] += amount;

    emit Transfer(amount, to, msg.sender);
}

Note: Hardhat's console log tool can only be used once hardhat/console.sol is imported into the smart contract.

2. Solidity Stack Traces

Hardhat's stack trace tool is a combination of JavaScript and Solidity that provides a report when a transaction occurs or a call fails. This automated error reporting provides developers with valuable information to evaluate and debug their smart contract.

3. Explicit Errors

Hardhat provides a variety of possible errors that can help developers simplify the debugging process including:

  • general
  • network
  • task definition
  • arguments
  • dependencies resolution
  • built-in tasks
  • artifacts
  • plugins
  • internal
  • source names
  • contract names

Solidity Console Log Tip: Use Events and Functions to Improve Debugging

Events can be used to output data from the transaction logs to the console for both debugging and production stages. An event serves as a marker to indicate if a process takes place. Additionally, events will indicate if an issue has occurred at particular steps. Such a process is similar to the “require” keyword in Solidity, which checks if a condition is true and allows code to flow only if and when the required condition is true.

To start using events and functions to improve debugging, create an event that is properly defined and emit the event in the function. These two steps ensure that the event will occur once the function is called.

Additional Solidity Console Log Tools

While Hardhat is the industry standard Solidity development tool for building, testing, and debugging smart contracts, there are a few alternative tools for troubleshooting Solidity code including Foundry, Truffle, and Brownie.

1. Foundry

Foundry offers a suite of Ethereum smart contract development tools that enables the management of dependencies, smart contract compilation, deployment, testing, and on-chain interactions.

The Foundry toolkit can be integrated with Hardhat to leverage its console.log() function for the debugging process. Developers can call the function with up to 4 parameters, including uint, string, bool and address.

Forge

Forge is a command-line (CLI) tool integrated with Foundry to test, build, and deploy smart contracts. This testing framework enables developers to create tests in Solidity using JavaScript or TypeScript as well as unlock numerous features for the debugging process.

The forge test command automates the Solidity tests and further provides a summary of the results including logs and stack traces. The forge debug command is also an interactive debugger that reviews a single smart contract as a script to identify any errors in the program.

Cast

Cast is a command-line interface (CLI) tool that interacts with Ethereum RPC calls. This consists of smart contracts calls, transactions, or chain data retrieval via the command line.

Anvil

Anvil is a local testnet node integrated with Foundry to enable smart contract deploying and testing from the frontend or via interactions over RPC (Remote Procedure Calls) with EVM (Ethereum Virtual Machine) compatible networks.

2. Truffle

Truffle offers three Ethereum smart contract developer tools: a development environment, a testing framework and an asset pipeline for blockchains. Truffle’s inclusive ecosystem provides developers with various tools to create, test, and debug end-to-end decentralized applications (dApps). 

These tool sets offered by Truffle are:

  • Smart contract toolkit - compilation, linking, deployment, etc.
  • Debugging - breakpoints, variable analysis, step functionality, automated contract testing
  • Management - network, package, migrations frameworks

Learn More: https://trufflesuite.com/docs/truffle/

3. Brownie

Brownie is a Python-based development and testing framework for smart contracts in Ethereum with support for Solidity and Vyper, and it is divided into 4 categories: testing, debugging, interaction and deployment. Each step supports developers in creating flexible programs.

Developers can access various debugging tools to gather detailed information about transaction failures and to locate, replicate, and troubleshoot Solidity errors.

  • TransactionReceipt.revert_ms - get a direct explanation message for the transaction failure‍
  • TransactionReceipt.error() - locate the root cause and section of the smart contract that caused a failed transaction‍
  • TransactionReceipt.events - view events that fired in reverted transactions‍
  • TransactionReceipt.trace - view a list of dictionaries containing the transaction information‍
  • TransactionReceipt.call_trace() - view a full map (trace) of the transaction steps

Developers can also leverage pytest for unit testing smart contracts, then review the stack trace report that is provided.

Learn More: https://eth-brownie.readthedocs.io/en/v1.2.1/index.html 

Learn About the Solidity Console Log with Alchemy University

This article has introduced you to the most popular logging and debugging tools for developing Solidity smart contracts. If you’re learning Solidity, selecting the best tools for smart contract debugging is essential for solving the issues you face in Solidity development.

To start or accelerate your Solidity development training, explore Alchemy University's free, 7-week Solidity developer bootcamp, originally a $3,000 certification course taught by ChainShot, is now fully integrated with Alchemy! If you are new to development in general, Alchemy's 3-week JavaScript crash course is a great prerequisite before starting an Ethereum bootcamp.

Build web3 with Alchemy

Alchemy combines the most powerful web3 developer products and tools with resources, community and legendary support.

Get started for free