October 21, 2023

Full Example Walkthrough for the eth_call RPC Method

Table of Contents
Full Example Walkthrough for the eth_call RPC Method

The eth_call method (eth_call) plays an essential role in Web3 development. After all, it allows dapps to interact with smart contracts without actually executing on-chain transactions. If you’re an ETH developer looking for an eth_call example and how to use it during your development process, you’ve come to the right place! In this article, we will showcase an example of the eth_call RPC method and show you an alternative solution as well. That said, here’s one example of the eth_call method:

const Web3 = require('web3');
const web3 = new Web3('YOUR_ETHEREUM_NODE_URL');

const contractAddress = 'YOUR_CONTRACT_ADDRESS';
const data = 'YOUR_DATA';

web3.eth.call({
    to: contractAddress,
    data: data
}).then(console.log);

Replacing the above space holders in caps with the actual values allows you to interact with a smart contract without modifying the blockchain state. Now, if you’d like to dive further into the eth_call method, read on as we explore the ins and outs of it and also highlight some use cases for this popular ETH method. However, as we progress towards the end of this article, we’ll also look at a more modern alternative – the Moralis Blockchain API!  

Overview

Although the eth_call example above is great, by examining it, we also recognize that there are more optimal ways of interacting with smart contracts. As such, moving forward, you’ll have a chance to get properly acquainted with a superior, modern alternative to the eth_call RPC method – the getBlock endpoint. However, before shifting our focus to that endpoint provided by the Moralis Blockchain API, it’s highly beneficial to be acquainted with the original eth_call method. Hence, we’ll start this article by covering that method’s basics, and you’ll have a chance to learn what eth_call is in the first place. Moreover, we’ll also ensure you know what RPC calls are.

Next, we’ll look at two additional eth_call example code clusters to further solidify your understanding of this method. Then, we’ll focus on the above-outlined example and explain how it can easily be covered with the getBlock endpoint. This is where you’ll also get a chance to learn more about the Moralis Blockchain API.

Of course, in case you’re already familiar with the eth_call method and are just looking for its modern replacement, feel free to skip the initial sections. Instead, dive into the modernized alternative of the above eth_call example immediately!   

What is eth_call + Ethereum Logo

What is eth_call?

The eth_call method is one of the JSON-RPC (remote procedure call) functions provided by Ethereum nodes. This method allows you to make a read-only or constant call to a smart contract on the Ethereum blockchain. As such, this method has been used to retrieve data from a contract without making a transaction that would change the state of the blockchain.

Here are some key points about the eth_call method:

  • Read-Only: It is a read-only operation, meaning it does not modify the blockchain in any way. It’s useful for fetching information from a contract’s state variables or executing view or pure functions in a contract.
  • No Gas Cost: Since it doesn’t create an on-chain transaction, there are no gas costs associated with eth_call.
  • Input Data: To use eth_call, you need to specify the contract address, the data (function call) you want to execute, and the block at which you want to perform the call.
  • Return Data: The method returns the output data from the contract call, typically in hexadecimal format. You may need to decode this data into a human-readable format, depending on the contract’s ABI (application binary interface).
  • Error Handling: It’s important to handle errors when using eth_call. If the function call encounters an error or reverts, you’ll need to check the response for an error condition and handle it appropriately.
  • Web3 Libraries: Many Ethereum development libraries, such as Web3.js for JavaScript or ethers.js, provide convenient interfaces for interacting with Ethereum nodes and making eth_call requests.

Overall, eth_call has been a useful tool for querying the state of smart contracts on the Ethereum blockchain and obtaining information without making a transaction.

Graph showing components and architecture of eth_call RPC method

What are RPC calls?

RPC, or remote procedure call, is a fundamental concept in computer science and network communication. In the context of blockchain and Ethereum, RPC calls play a crucial role in enabling interaction with the Ethereum network.

An RPC call is a method for one program or process to request the execution of a function or procedure in another program or process that resides on a remote server. In Ethereum, this means making requests to an Ethereum node, which serves as a gateway to the blockchain.

Ethereum nodes expose a set of RPC methods that allow developers to communicate with the Ethereum network. These methods include functions for reading data from the blockchain, sending transactions, and even deploying smart contracts. As explained above, one of the essential RPC methods in Ethereum is the eth_call method.

When you make an eth_call remote procedure call (RPC), you’re essentially asking an Ethereum node to execute a function in a smart contract without creating a transaction. This is useful for retrieving data from the contract’s state or querying the results of view and pure functions. Moreover, any eth_call example doesn’t alter the state of the blockchain and doesn’t consume any gas, making it ideal for fetching information without incurring costs.

Overall, RPC calls, including eth_call, are the bridge that connects developers and applications to the Ethereum blockchain. They enable data retrieval, interaction with smart contracts, and the creation of decentralized applications (dapps), forming the backbone of Ethereum’s programmability and utility.

Eth_call use cases and examples

Use Cases for eth_call

  • Querying Token Balances: You can use eth_call to check the token balance of an Ethereum address within a specific ERC-20 or ERC-721 token contract. This is useful for wallet applications or token explorer tools.
  • Price Oracles: The eth_call method can be used to access data from price oracles, such as fetching the latest cryptocurrency exchange rates. This data is crucial for decentralized finance (DeFi) applications, especially those involving trading or lending.
  • Checking Ownership: It’s common to use eth_call to verify ownership or permissions within a smart contract. For instance, confirming whether an address has permission to perform certain actions in a dapp.
  • On-Chain Governance: Many blockchain projects implement on-chain governance systems. As such, eth_call allows participants to check their voting power in decision-making processes.
  • Token Allowance: When interacting with DeFi protocols or decentralized exchanges (DEXs), you may use eth_call to verify if an address has granted permission to spend their tokens on their behalf.
  • Decentralized Identity: To verify identity on a blockchain, you can use eth_call to check if a specific address corresponds to a registered identity. This is important for applications like decentralized social networks or authentication systems.
  • Supply Chain Tracking: In supply chain and logistics solutions, eth_call can be employed to fetch information about product origins, shipping statuses, or authenticity verification, all stored on the blockchain.
  • Blockchain Gaming: Blockchain games often use eth_call to retrieve in-game item information, player statistics, or game state, allowing for transparency and fair gameplay.
  • Token Metrics: Investors and traders use eth_call to access token metrics, such as the total supply, circulating supply, or historical token prices. This information aids in decision-making and portfolio management.
  • Data Verification: In data verification and notarization applications, eth_call can be used to verify the authenticity of a document or data stored on the blockchain.
Title - eth_call example

Two Specific eth_call Examples

Below, you can find two simple examples of code that utilize the eth_call method in Ethereum development. These examples assume you have access to an Ethereum node and a Web3 library for interaction.

Reading a State Variable

This example reads a state variable from a smart contract using eth_call. In case you were to utilize the code, make sure to replace the contract address and ABI with your own values:

const Web3 = require('web3');
const web3 = new Web3('YOUR_ETHEREUM_NODE_URL');

const contractAddress = 'YOUR_CONTRACT_ADDRESS';
const contractABI = [
  // Contract ABI goes here
];

const contract = new web3.eth.Contract(contractABI, contractAddress);

// Define the function selector for the state variable you want to read
const functionSelector = contract.methods.myStateVariable().encodeABI();

// Make the eth_call
web3.eth.call({
  to: contractAddress,
  data: functionSelector,
}).then(result => {
  const value = web3.utils.hexToNumber(result);
  console.log(`Value of myStateVariable: ${value}`);
});

Calling a View/Pure Function

In this example, we’ll call a view or pure function on a smart contract using eth_call. If you were to utilize the code below, don’t forget to replace the contract address and ABI with your own values:

const Web3 = require('web3');
const web3 = new Web3('YOUR_ETHEREUM_NODE_URL');

const contractAddress = 'YOUR_CONTRACT_ADDRESS';
const contractABI = [
  // Contract ABI goes here
];

const contract = new web3.eth.Contract(contractABI, contractAddress);

// Define the function selector for the view function
const functionSelector = contract.methods.myViewFunction(param1, param2).encodeABI();

// Make the eth_call
web3.eth.call({
  to: contractAddress,
  data: functionSelector,
}).then(result => {
  // Handle the result as needed
  console.log(`Result of myViewFunction: ${result}`);
});

Quick Walkthrough

If you took a proper look at the above two eth_call examples, you probably noticed that they both incorporate the same lines of code as outlined at the top of this article. 

In every example, the code first requires web3 and an RPC node endpoint. Next, it defines a contract address to focus on and the specific data, which can come in the form of the contract’s ABI. Finally, the code runs web3.eth.call.

Note: Make sure to explore the JSON-RPC documentation offered by “ethereum.org”. In the “eth_call” section, you can find all the details regarding the method’s parameters:

Code walkthrough of eth_call example

An eth_call Example – Modernized Approach

While using eth_call is still a legitimate approach, it is no longer the optimal one. For one, it requires you to use RPC nodes. Plus, it comes with other limitations, including lower speed. 

As such, many advancing dapp developers have already replaced eth_call with the Moralis Blockchain API. The latter offers a very powerful getBlock endpoint. And to use it to the same end (only in a more efficient manner with better and faster results) as eth_call, you’d want to implement these lines of code:

const Moralis = require("moralis").default;
const { EvmChain } = require("@moralisweb3/common-evm-utils");

async function runApp() {
  await Moralis.start({ apiKey: "YOUR_API_KEY" });

  const blockNumberOrHash = "15863321";
  const chain = EvmChain.ETHEREUM;

  const response = await Moralis.EvmApi.block.getBlock({
    blockNumberOrHash,
    chain,
  });
  console.log(response.toJSON());
}

runApp(); 

By looking at the above lines of code, you can see that no RPC node is required. Instead, you only need to use your Moralis API key, which you can access with a free account.

We encourage you to visit the “Get block by hash” Blockchain API reference page. There, you can try the above lines of code for any of the supported blockchains. By doing so, you’ll see the immense value of the getBlock method’s response. After all, it offers a wide range of on-chain details that can be plugged into your dapp development.  

Highlighting a eth_call example alternative

The Benefits of the Modern Path of Fetching On-Chain Data

As already mentioned above, the core benefit of using Moralis’ getBlock endpoint over eth_call is efficiency. This modern approach is faster, offers enhanced security protocols, and fetches a wider range of data with a single call. What’s more, once you obtain your Moralis API key to use getBlock, you also gain access to other Moralis Web3 APIs. Those allow you to cover all of the above-listed use cases for eth_call but in a simpler, more efficient manner. 

In fact, with the Moralis Web3 API fleet on your side, you get to create all sorts of dapps with minimum fuss. These tools allow you to avoid reinventing the wheel and instead devote your time and resources to creating the best possible user experience.

For instance, you can fetch any token balance with the getWalletTokenBalances endpoint. Or, perhaps you want to query an ERC-20 token spender allowance? In that case, getTokenAllowance would be the go-to endpoint. 

The above two endpoints are just two of many other powerful and efficient shortcuts that the Moralis Token API offers. And once you plug in other APIs (see the list below), there’s simply no dapp you can’t build with time and resources to spare!

eth_call example using Moralis

Going Beyond getBlock – Moralis API Fleet

The current Moralis API fleet enables you to cover all aspects of dapp development with as few lines of code as possible. Here are some of the products that make that possible:

Moralis API alternatives to eth_call example

With few exceptions, like the Market Data API, you can use the above-listed Web3 APIs with a free Moralis account. Plus, these APIs support all the leading blockchain networks, which allows you to effortlessly build cross-chain dapps. 

Full eth_call RPC Method Example Walkthrough – Summary

Throughout the above sections, we covered quite a distance. We first ensured that you all know what eth_call and RPCs are. Thus, you now know eth_call is a JSON-RPC function provided by Ethereum nodes. As for the RPC calls, you learned that they enable interaction with the Ethereum network through Ethereum nodes.

Next, we listed many eth_call use cases, including querying token balances, price oracles, checking ownership, etc.

Then, we even provided two specific eth_call example code clusters. These examples reminded you that the eth_call method needs to be used in combination with other methods for most instances. 

Nonetheless, we explained that there’s a more efficient, superior way of fetching on-chain data with Moralis’ getBlock endpoint. We even showed you how to use that endpoint when working with JavaScript. So, you now know that this approach eliminates the need for an RPC node. Furthermore, it offers efficiency, enhanced security, and a wide range of data with a single call. 

Moving forward, we recommend you learn more about specific Moralis APIs and their endpoints. To that end, aside from the Moralis documentation, the Moralis blog can be extremely valuable. Some of the latest articles explain how to get an ERC-20 token address, what ERC-4337 is, how to get the current price of an NFT, and much more.  

So, what next? Determine which Moralis APIs to use, create your free Moralis account, and build an awesome dapp! 

Market Data API
Build amazing trading and portfolio dapps with this Market Data API. Keep users engaged with up-to-date data!
Market Data API
Related Articles
December 16, 2022

How to Call a Smart Contract Function from JavaScript

August 23, 2022

How to Use Filecoin in Unity for Storage

November 21, 2022

Amazon GameSparks Guide – What is Amazon GameSparks?

October 23, 2023

Get Transactions – How to Fetch EVM Transactional History

December 13, 2022

Ethereum Web3 API – Exploring How to Use a Web3 Ethereum JavaScript API

October 25, 2022

What is Sui Blockchain? – The Ultimate Guide

October 10, 2022

The Easiest Way to Build Dapps – 3-Step Tutorial for Developers