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);What a contract instance needs
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.
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()); // 12nNote 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().
call() or send()?
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.
When a call fails
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.
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.
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.