Lesson 3 of 5 Interacting with Contracts Using web3.js

Contract Instances, Calls and Transactions

Interacting with contracts is the core of the web3.js objective. This lesson explains how to create contract instances from an ABI, deploy contracts, choose between call and send, estimate gas and handle reverts and custom errors.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe how to create contract instances and deploy contracts.
  • Distinguish call() from send().
  • Explain how to obtain results of state-changing functions.
  • Describe how web3.js reports reverts and custom errors.

Creating a contract instance

A contract instance is created from the contract's ABI and, for an existing contract, its address. Each function in the ABI becomes a method under contract.methods.

import { readFileSync } from "node:fs";

const { abi } = JSON.parse(readFileSync("artifacts/contracts/Counter.sol/Counter.json", "utf8"));
const counter = new web3.eth.Contract(abi, "0x5FbDB2315678afecb367f032d93F642f64180aa3");

The ABI can come from a Hardhat artifact, Remix's compilation details or a verified contract on a block explorer. To deploy a new contract, create the instance without an address and use deploy:

const { abi, bytecode } = JSON.parse(readFileSync(artifactPath, "utf8"));
const deployed = await new web3.eth.Contract(abi)
  .deploy({ data: bytecode, arguments: [initialOwner] })
  .send({ from: deployer });
console.log(deployed.options.address);
Select all that apply

What a contract instance needs

Exam skills 1.3.1

Identify what web3.js needs to work with a contract.

Log in to try this activity Interactive activities are free with an account.

call() versus send()

Every contract method can be invoked in two ways. The following comparison shows the difference, which is one of the most tested points of the objective.

call()
JSON-RPC methodeth_call
Runs onOne node, locally
Changes stateNo (changes are discarded)
Costs gasNo
Needs an accountNo (from is optional)
ReturnsThe function's return value
Choose when Reading data; simulating a transaction
send()
JSON-RPC methodeth_sendTransaction or eth_sendRawTransaction
Runs onEvery node, when included in a block
Changes stateYes, permanently
Costs gasYes
Needs an accountYes
ReturnsA transaction receipt
Choose when Changing state; sending ether
console.log(await counter.methods.x().call());              // 5n
const gas = await counter.methods.incBy(7).estimateGas({ from });   // 27624n
const receipt = await counter.methods.incBy(7).send({ from });
console.log(receipt.status, receipt.gasUsed);               // 1n 27624n
console.log(receipt.events.Increment.returnValues.by);      // 7n
console.log(await counter.methods.x().call());              // 12n

Note that send() does not return the function's return value: the result exists only inside the transaction's execution. Contracts expose results to applications through events, as the Increment event above does, or through state that can be read afterwards with call().

Sort into groups

call() or send()?

Exam skills 1.3.2

Choose how to invoke each contract method from web3.js.

Log in to try this activity Interactive activities are free with an account.

Sending ether and setting options

Options passed to send() include from, value (wei sent to a payable function), gas, and the fee fields. For example, bank.methods.deposit().send({ from, value: web3.utils.toWei("1", "ether") }) deposits one ether. Setting contract.options.from or adding a key to web3.eth.accounts.wallet avoids repeating the sender.

Handling reverts and custom errors

When a call reverts, web3.js v4 throws a ContractExecutionError. If the contract used a revert string, the error carries the reason; if it used a custom error, web3.js decodes its name and arguments from the ABI.

try {
  await counter.methods.incBy(0).send({ from });
} catch (e) {
  console.log(e.constructor.name);        // ContractExecutionError
  console.log(e.cause?.errorName);         // ZeroIncrement
}

Because send() estimates gas first, a transaction that would revert normally fails during estimation, before anything is broadcast, so no fee is paid. Applications should also handle a user rejecting the request in their wallet, insufficient funds and nonce errors.

Scenario questions

When a call fails

Exam skills 1.3.3

Handle the errors web3.js raises when a contract call fails.

Log in to try this activity Interactive activities are free with an account.
Worked example

The missing return value

A createOrder() function returns the new order ID. A front end calls const id = await market.methods.createOrder(item).send({ from }) and finds that id is a receipt object, not a number. How should it get the ID?

Return values of state-changing functions are not available to the sender of a transaction. The contract should emit an event such as OrderCreated(uint256 indexed id, address indexed buyer), and the front end reads receipt.events.OrderCreated.returnValues.id. Calling createOrder(item).call() first would only simulate the call and predict an ID that could differ by the time the transaction is mined.

Worked example

A view function that costs gas

A developer uses token.methods.balanceOf(user).send({ from }) to read a balance and notices that each read costs a fee and returns a receipt. What should they use?

call(). balanceOf is a view function; invoking it with send() creates a pointless transaction that pays gas and returns a receipt without the balance. await token.methods.balanceOf(user).call() is free and returns the value.

Check yourself

Which web3.js method returns a view function's value without a transaction?

Show answer

call(), for example await contract.methods.totalSupply().call(). It uses eth_call, costs nothing and changes no state.

Exam Tips

Remember for the exam

  • new web3.eth.Contract(abi, address) creates an instance; deploy({ data, arguments }) deploys.
  • call(): free, local, returns values. send(): costs gas, changes state, returns a receipt.
  • Get results of transactions from events in the receipt or by reading state afterwards.
  • Reverts raise ContractExecutionError with the reason or decoded custom error.