What is ABI: A Guide to Ethereum Smart Contract ABI

Deen Newman

Deen Newman

January 2, 2024

10 min read

article cover

Embarking on the Ethereum blockchain journey requires developers to grasp the essentials of smart contract development. Along the way, they quickly realize the value of the Application Binary Interface (ABI), a crucial tool in their toolkit.

Come along as we explore the significance of ABI in Solidity and decentralized applications development.

Highlights: ABI in the Ethereum development landscape

There are two components of a smart contract that help the outside world to communicate with its code on the blockchain: its distinctive address and ABI:

  • In programmable blockchains, the compilation of a smart contract produces two outputs — ABI and bytecode;
  • ABI can be defined as the JSON definition of a contract or a way of describing functions that users or software can access;
  • This file includes a full spec of functionality that is available to that particular smart contract;
  • Therefore, it facilitates interactions of ABI-compatible interfaces, languages, and clients with the Solidity code which is particularly beneficial in dApp development;
  • ​​In the Ethereum Virtual Machine (EVM) compatible chains, ABI serves as a fundamental mechanism for encoding Solidity or Yul contract calls and, conversely, guides the extraction of data from the blockchains.

To confidently navigate smart contract development, let’s break down what ABI is, how it works, and how it’s beneficial for Web3 application development.

What is ABI?

Different software components often need to work together to achieve complex tasks. Inter-software communication allows these components to collaborate and share information.

Application Binary Interface, in this context, serves as a conversation protocol between two programs.

It provides a shared language for software and describes how to speak to an arbitrary code, i.e. a code that can be adjusted to suit different scenarios.

​​In programmable blockchains, ABI serves as a mechanism for encoding smart contract calls and, vice versa, extracting transaction data.

Understanding smart contract ABI

In smart-contract-enabled ecosystems like Ethereum, ABI can be defined as an interface to interact with a contract deployed to this network.

Conceptually, it’s a JSON blob that describes the functions, variables, modifiers, and parameters of this contract. Let's peel back the layers on this a bit more.

Solidity_contract_ABI_JSON_file

The role of ABI in Ethereum

Diving into the purpose of ABIs in Web3 development requires a bit of context. Therefore, we’ll briefly look at a smart contract’s lifecycle in the Ethereum blockchain.

A vast number of Ethereum nodes collaborate, functioning as a unified world computer. Contract codes, thus, are executed on individual nodes, collectively forming the Ethereum Virtual Machine (EVM).

Deploying contracts to EVM involves a preparatory step – compiling – that translates a human-readable source code and makes it understandable to this virtual machine.

To do that, a Solidity code is converted into a bytecode file that represents all the instructions and operations that we want EVM to understand. ABI is also produced by a Solidity compiler, which tells external applications what functions the code supports and what parameters they take.

Ethereum_contract_lifecycle

Image from Medium

Therefore, bytecode is what’s stored on the blockchain and executed, while ABI is an interface that outlines the whole scope of functions a smart contract has, what types of arguments those functions take, and what kind of values return.

Functionally, ABI acts as a bridge for users to effectively communicate with and utilize the deployed smart contract.

ABI components

If we look at the ABI property on the JSON, it’s an array of objects, each representing a function within the smart contract.

These objects share similar types of properties, such as:

  • Name: identifies the specific function;
  • Inputs: describes the arguments (if any) that a function accepts;
  • Outputs: information about the return values or output of the function
  • stateMutability: indicates whether the function can change the state of the ledger. It can be ‘view’ (read-only), ‘pure’ (no state access), or ‘nonpayable/payable’ (state-modifying).
  • Type: describes item is a regular callable function, a fallback function, or an event.

Let’s view an example:

[
    {
        "inputs": [],
        "name": "hello",
        "outputs": [
            {
                "internalType": "string",
                "name": "",
                "type": "string"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    },
    {
        "inputs": [],
        "name": "hi",
        "outputs": [
            {
                "internalType": "string",
                "name": "",
                "type": "string"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    }
]

This specific ABI corresponds to a contract with two functions: 'hello' and 'hi'. Both functions take no inputs and return a string as output. They are marked with the stateMutability "view," indicating that they do not modify the contract's state and are read-only.

This JSON file encapsulates information essential for external libraries like web3 to communicate with the smart contract. By importing this ABI in the front end of a dApp, developers can configure Web3 to communicate with and invoke functions from the smart contract.

API vs ABI

The concept of ABI bears some similarities with Application Programming Interfaces (APIs) that also provide a standard set of functions and methods that can be used to interact with another software system, application, or cryptocurrency network.

API abstracts the underlying complexity, providing a human-readable interface for developers to interact with the blockchain, making data retrieval straightforward.

Unlike the user-friendly nature of APIs, the ABI deals with binary code deployed onto the blockchain. It grants access to developers to interact with and understand the functionalities encoded within the deployed contract.

# Function API ABI
1 Data Representation Typically uses a human-readable format (such as JSON) to convey information and functions Deals with low-level binary code
2 Communication Protocols Relies on communication protocols like HTTPS/WSS for interaction between software components Primarily focuses on how data is encoded and decoded within the blockchain environment
3 Visibility of Components Exposes functionalities and services in a clear manner Often less accessible and readable

Benefits of using ABI in Ethereum development

To understand the key part ABI takes in contract and application development, It’s important to mention its main characteristic which is the standardized nature.

ABI is produced per specifications laid out in official Solidity documentation. ABI-compliant contracts adhere to these specifications, i.e. ensure that the functions, parameters, and data structures are uniformly represented.

Owing to this key feature, using ABI ensures that messages are accurately conveyed, allowing diverse programs to understand and work together despite their inherent differences.

Intercontract compatibility

ABIs serve as a lingua franca across various smart contracts, fostering seamless communication irrespective of the high-level programming language used to code them.

This standardized approach supports interoperability between contracts, ensuring that messages remain understandable even when expressed in diverse programming languages.

Smart contracts — application interoperability

Consider the scenario where your application's front end, crafted in a language like JavaScript, needs to communicate with a specific function within a smart contract. Here, the ABI acts as a vital bridge.

By parsing the ABI JSON artifact, applications gain a precise understanding of how to invoke a method, encode parameters accurately, and interpret returned values.

Compatibility with ecosystem tools

The standardized nature of ABIs extends compatibility to a plethora of ecosystem tools, including Software Development Kits (SDKs).

By providing a consistent and unified interface for building and interacting with contracts, this compatibility ensures that developers can leverage a variety of tools and frameworks seamlessly with Ethereum smart contracts.

How to get an ABI of a smart contract

After compilation, you should have access to the contract ABI, whether it's assembled using a local or web-based development environment. This ABI is often represented as part of contract artifacts, which additionally exposes a structured bytecode representation of the code.

Fetching ABI from Hardhat

Development frameworks for Ethereum automatically generate the Application Binary Interface as part of the compilation output often stored in the "artifacts" or "build" directory by default.

Hardhat typically stores artifacts in the "artifacts" directory within your project:

Retrieving_contract_ABI_from_Hardhat

Using ​​Remix to get contract ABI

Remix is a quick way to access both ABI and bytecode from within your browser. You can find and download the JSON file under the “Solidity Compiler” section of Remix by navigating to the “Compilation Details” button.

How_to_find_contract_ABI_in_Remix?

Image from Remix

Tracking ABI in Etherescan

For contracts that are already deployed and verified, it’s convenient to browse Etherscan and find ABI by simply submitting the contract address to the search bar. Let’s go and find the ABI for a simple token contract that we created within our Remix and OpenZeppeling guide on Etherescan:

Getting_contract_ABI_from_Etherscan

Image from Etherscan

ABI in Action: Examples and use cases

Now, let’s see some examples of how ABI can be put to good use, focusing on tracking smart contract transactions and application-specific usage.

Context Banner

Connecting a dApp with smart contracts

In this example, we’ll look into how to integrate a contract ABI into the application code using React to establish a communication link between the app and a code deployed on the blockchain.

Thanks to web3 libraries like ethers.js and web.js that are designed to understand and work with ABI, our dApp will be able to invoke functions from a smart contract directly and display the outputs in the UI.

N.B.: Refer to our comprehensive guide on Web3 Libraries for development on Ethereum to delve deeper into the functionalities of web3.js and ethers.js

Step 1: Generate the ABI file

Get the ABI output from each smart contract you’re interacting with using one of the methods listed in the previous section.

Step 2: Import necessary modules and libraries

Add essential modules for building a React application. We also use the ethers library to create a provider and contract instance.

Step 3: Integrate the ABI

When you get the ABI code generated, you can either hardcode it inside the app.js or add the JSON file to your working directory and import it to keep the code clean. In our case, we load ABI from the JSON file added to the project directory.

Below is a basic setup that follows common React patterns, used to interact with a simple Greeter contract using the ethers.js library:

Connecting_React_to_the_contract_with_ABIe

In summary, this React application fetches data from an Ethereum smart contract (specifically, the hello function of the contract) and dynamically updates the UI to display the obtained greeting.

Using ABI to listen to smart contract events

ABI is helpful in allowing users and developers to monitor and react to important activities within a smart contract by specifying the target smart contract's address and its ABI.

In the example below, the code sets up an event listener for a specific event named 'Transfer'. A filter is created, allowing the code to detect instances where the event is emitted. The code queries the Ethereum node for past events from a specific block (BLOCK_START) to the latest block ('latest').

Subscribing_to_contract_events_with_ABI”

Developers can use this code to automate reactions to specific events. Additionally, event listening is fundamental for creating responsive and interactive interfaces that reflect the state changes of smart contracts.

Wrapping up

ABI serves as a must-learn tool that helps to understand how contracts communicate together and how users communicate with smart contracts. Compliance with the ABI specifications ensures consistency and interoperability, allowing different components of the Ethereum ecosystem to effectively understand and work with the smart contract.

Integrate the insights gained from our guide on Smart Contract ABI into your projects and experience an efficient development process with GetBlock's reliable and developer-friendly RPC services. Create an account with MetaMask and have a gateway to 50+ blockchain nodes at your fingertips.

FAQ

  • What is ABI in Web3 development?

    plus
  • How to get ABI of a Solidity contract?

    plus
  • How can I use smart contract ABI?

    plus
  • What are some tools and libraries that facilitate ABI implementation?

    plus
Deen Newman

Deen Newman

January 2, 2024

10 min read

twittertwittertelegramtelegramLinkedinLinkedin