Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 47 ยท Working With Contracts From Outside

Talking to Contracts with JavaScript

Learn how JavaScript connects to Ethereum: providers, signers, the ABI, reading and writing contracts and listening to events, with ethers.js and viem.

A contract on its own is just code sitting at an address. Users meet it through a website, a script or a bot, and all of those talk to the chain with a library. In JavaScript the two popular choices are ethers.js and viem. They differ in style, but the concepts are the same: a provider to read, a signer to write, an ABI that describes the contract, and events to listen to.

This lesson explains those four ideas and shows them in both libraries. The library code is read-only, because running it needs a real network connection and, for writes, a funded account. To let you see the moving parts anyway, the runnable stand-ins build a tiny fake chain with a provider, a signer and a contract wrapper that is generated from an ABI, the same trick the real libraries use.

The four ideas

Provider A read-only connection to a node.
Signer An account that can sign and send.
ABI A description of the contract's functions.
Events Logs you can query and subscribe to.
1 / 2

Providers: reading the chain

A provider talks to a node over JSON-RPC, usually through an HTTPS URL from a service such as Alchemy, Infura or QuickNode, or from your own node. It can read anything that is public: balances, blocks, contract state, logs. It cannot change anything, because it holds no keys.

JavaScript
// ethers v6
import { ethers } from "ethers";

const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
const blockNumber = await provider.getBlockNumber();
const wei = await provider.getBalance("0x0000000000000000000000000000000000000001");
console.log(blockNumber, ethers.formatEther(wei), "ETH");
TypeScript
// viem
import { createPublicClient, http, formatEther } from "viem";
import { sepolia } from "viem/chains";

const publicClient = createPublicClient({ chain: sepolia, transport: http(process.env.RPC_URL) });
const blockNumber = await publicClient.getBlockNumber();
const wei = await publicClient.getBalance({ address: "0x0000000000000000000000000000000000000001" });
console.log(blockNumber, formatEther(wei), "ETH");

Both return balances as bigint, in wei (1 ether is 10^18 wei). Never convert them to a regular JavaScript number for maths, because numbers lose precision above 2^53. Use formatEther / parseEther for display and input, and formatUnits / parseUnits for tokens with other decimals.

Signers: writing to the chain

A signer (ethers) or account and wallet client (viem) holds a private key, or asks a wallet extension such as MetaMask to sign. Sending a transaction costs gas and changes state, so it needs a funded account.

JavaScript
// ethers v6, on a server or in a script
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);

// ethers v6, in a browser with a wallet extension
const browserProvider = new ethers.BrowserProvider(window.ethereum);
const signer = await browserProvider.getSigner();   // the user approves each action
TypeScript
// viem, in a script
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const walletClient = createWalletClient({ account, chain: sepolia, transport: http(process.env.RPC_URL) });

A private key is the account. Never write one into source code, a front-end bundle or a public repository, and never reuse a mainnet key for tests. Load keys from environment variables or a secrets manager, and use throwaway keys on testnets. In a browser, never ask for the key at all: let the user's wallet sign. See Deploying to Testnet and Mainnet for key safety in scripts.

The ABI: how the library knows what to call

Contract functions are called by sending encoded bytes, a 4-byte selector followed by the arguments (ABI Encoding and Low-Level Calls). The ABI (application binary interface) is a JSON description of every function, event and error in the contract: names, parameter types and whether a function is view or changes state. The compiler produces it. With the ABI, a library can encode your call and decode the result.

You can pass the full JSON, or, in ethers and viem, a human-readable shortcut that lists only what you use:

JavaScript
const abi = [
  "function balanceOf(address owner) view returns (uint256)",
  "function transfer(address to, uint256 amount) returns (bool)",
  "event Transfer(address indexed from, address indexed to, uint256 value)",
];

(viem wraps such strings with parseAbi([...]).) Using the right ABI matters: a wrong one makes calls fail or, worse, decode garbage.

Reading and writing

Reading uses a free eth_call, which runs the function on a node without a transaction. Writing sends a signed transaction that miners or validators include in a block, so it takes time, costs gas and can fail. A write returns a transaction hash straight away; you then wait for the receipt, which says in which block it landed and whether it succeeded.

JavaScript
// ethers v6
const token = new ethers.Contract(tokenAddress, abi, wallet);   // wallet = signer, so writes work

const balance = await token.balanceOf(wallet.address);          // read (eth_call)
const tx = await token.transfer(recipient, ethers.parseUnits("10", 18)); // write
const receipt = await tx.wait();                                // wait for inclusion
console.log(receipt.status, receipt.blockNumber);
TypeScript
// viem
import { parseAbi, parseUnits } from "viem";
const abi = parseAbi([
  "function balanceOf(address owner) view returns (uint256)",
  "function transfer(address to, uint256 amount) returns (bool)",
]);

const balance = await publicClient.readContract({
  address: tokenAddress, abi, functionName: "balanceOf", args: [account.address],
});
const hash = await walletClient.writeContract({
  address: tokenAddress, abi, functionName: "transfer", args: [recipient, parseUnits("10", 18)],
});
const receipt = await publicClient.waitForTransactionReceipt({ hash });

When a write would revert, both libraries usually find out while estimating gas and throw before anything is sent, so wrap writes in try/catch and show the user the revert reason or custom error.

Events

Events are how a contract tells the outside world what happened (Events and Logs). You can subscribe to new ones, or query old ones by block range and filter on indexed parameters:

JavaScript
// ethers v6
token.on("Transfer", (from, to, value) => {
  console.log(`${from} sent ${value} to ${to}`);
});

const latest = await provider.getBlockNumber();
const past = await token.queryFilter(token.filters.Transfer(null, recipient), latest - 1000, latest);
TypeScript
// viem
const unwatch = publicClient.watchContractEvent({
  address: tokenAddress, abi: eventAbi, eventName: "Transfer",
  onLogs: (logs) => console.log(logs),
});

Public RPC providers limit how large a block range you may query in one request, so long histories are fetched in chunks or taken from an indexer.

A fake chain with the same shape

The stand-in below mirrors the structure: a FakeProvider for reads, a Signer bound to an address, and a Contract class that reads an ABI and generates one method per function. View functions call the provider; other functions need a signer and return a transaction whose wait() gives a receipt. It is plain JavaScript with no cryptography and no real network.

JS A provider, a signer and an ABI-driven contract

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the shape: the same Contract object can read with a provider but must be given a signer before it can write; a failing write throws before any block is mined; and the listener fires when the transaction lands. The real libraries add encoding, gas estimation, nonces, signatures, chain ids and dozens of other details.

Units without surprises

Token amounts are integers in the smallest unit. One token with 18 decimals is 10n ** 18n base units. The helpers parseUnits and formatUnits convert between decimal strings and bigint. Writing them yourself once shows why Number is the wrong tool:

JS parseUnits and formatUnits by hand

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real: the roles of provider, signer, ABI and events, and the ethers v6 and viem snippets (both libraries evolve, so check their documentation for exact current signatures). Stand-in: the fake chain has no encoding, signatures, gas, consensus or network, and its names only imitate the real APIs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What can a provider do that a signer is needed for?

    A provider is read-only. Changing state requires a signed transaction, so you need a signer or wallet client.
  2. 2. What is the ABI for?

    The ABI is a JSON description produced by the compiler. Without it the library does not know how to encode a call or decode a result.
  3. 3. Why should token amounts not be handled as regular JavaScript numbers?

    Numbers lose precision above 2^53, and base-unit amounts easily exceed that. bigint keeps every digit.
  4. 4. After a write call returns a transaction hash or response, how do you know it succeeded?

    A hash only means the transaction was submitted. The receipt reports the block and whether execution succeeded.

Summary

  • A provider reads the chain; a signer (or wallet client) signs and sends transactions.
  • The ABI tells the library how to encode calls and decode results; human-readable ABIs list just what you need.
  • Reads are free eth_calls; writes return a hash first, then a receipt you wait for.
  • Subscribe to events with on or watchContractEvent, and query history in limited block ranges.
  • Use bigint with parseUnits and formatUnits for amounts, and keep private keys out of code.

Next: Deploying to Testnet and Mainnet.