Lesson 1 of 5 Interacting with Contracts Using web3.js

web3.js Fundamentals and Providers

web3.js is the JavaScript library the exam objective names. This lesson explains what the library does, how it relates to the JSON-RPC interface of Ethereum nodes, and how to connect it to a node through HTTP, WebSocket and browser wallet providers.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe what web3.js does and how it is organised.
  • Relate web3.js calls to JSON-RPC methods.
  • Compare HTTP, WebSocket and injected providers.
  • Explain how a browser DApp connects through a wallet.

What web3.js does

web3.js is a JavaScript library for interacting with Ethereum nodes. It wraps the node's JSON-RPC interface in a JavaScript API, converts between JSON-RPC's hexadecimal strings and JavaScript values, encodes contract calls with the ABI and decodes results and events, and signs transactions with local keys. It runs in Node.js and in browsers. Version 4, the current major version, is written in TypeScript, uses promises throughout and returns numbers as BigInt.

The main entry point is a Web3 instance. Its eth module holds most functionality: blocks, balances, transactions, accounts (web3.eth.accounts), contracts (web3.eth.Contract) and ABI tools (web3.eth.abi). web3.utils provides unit conversion and hashing, such as web3.utils.toWei and web3.utils.keccak256.

JSON-RPC underneath

Every web3.js call becomes one or more JSON-RPC requests. The following table maps common library calls to the methods they use.

web3.js callJSON-RPC method
web3.eth.getBlockNumber()eth_blockNumber
web3.eth.getBalance(address)eth_getBalance
web3.eth.getChainId()eth_chainId
contract.methods.f().call()eth_call
contract.methods.f().estimateGas()eth_estimateGas
web3.eth.sendSignedTransaction(raw)eth_sendRawTransaction
contract.getPastEvents(...)eth_getLogs
contract.events.E()eth_subscribe (logs)
curl -s -X POST -H "content-type: application/json" \
  --data '{"jsonrpc":"2.0","id":1,"method":"eth_chainId","params":[]}' \
  http://127.0.0.1:8545
# {"jsonrpc":"2.0","id":1,"result":"0x7a69"}   (31337 in hexadecimal)
Match the pairs

web3.js calls and JSON-RPC

Exam skills 1.1.1

Match each web3.js call with the JSON-RPC method it sends.

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

Providers

A provider carries JSON-RPC requests to a node. The following comparison sets out the three provider types.

HTTP
Created withnew Web3("http://...")
ConnectionOne request per call
SubscriptionsNo (polling only)
Who signsThe application (local keys) or the node
Choose when Scripts and back ends that only read or sign locally
WebSocket
Created withnew Web3("ws://...")
ConnectionPersistent, two-way
SubscriptionsYes
Who signsThe application or the node
Choose when Applications that need live blocks or events
Injected (EIP-1193)
Created withnew Web3(window.ethereum)
ConnectionThrough the user's wallet
SubscriptionsDepends on the wallet
Who signsThe wallet, after user approval
Choose when Browser DApps where users hold their own keys
import { Web3 } from "web3";

const web3 = new Web3("http://127.0.0.1:8545");
console.log(await web3.eth.getChainId());      // 31337n
console.log(await web3.eth.getBlockNumber());  // 2n
Sort into groups

Which provider?

Exam skills 1.1.2

Choose the provider type each application needs.

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

Connecting a browser DApp

In a browser, wallets such as MetaMask inject an EIP-1193 provider at window.ethereum. The DApp asks the user to connect and then sends transactions through the wallet.

if (!window.ethereum) throw new Error("Please install a wallet");
const web3 = new Web3(window.ethereum);
const [account] = await window.ethereum.request({ method: "eth_requestAccounts" });
const chainId = await web3.eth.getChainId();
if (chainId !== 11155111n) { /* ask the user to switch to Sepolia */ }

The private key never leaves the wallet. Every transaction or signature request opens a wallet prompt, and the user can reject it, which the DApp must handle. Wallets also emit accountsChanged and chainChanged events, which DApps listen to so their state stays correct.

Put in order

Connecting to a wallet

Exam skills 1.1.2

Arrange the steps a browser DApp follows before sending a transaction.

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

Live updates that never arrive

A dashboard creates new Web3("https://sepolia.example/rpc") and subscribes to a contract's Transfer events, but no events arrive and an error says subscriptions are not supported. What should change?

HTTP providers cannot receive pushed messages, so eth_subscribe is unavailable. The dashboard should connect with a WebSocket URL (wss://...) from the same provider, or poll with getPastEvents on an interval if WebSocket is not available.

Worked example

Where is the private key?

A developer building a browser DApp asks users to paste their private key into a form so that web3.js can sign transactions. What is wrong with this design?

It exposes users' keys to the website, any injected script and anyone who compromises the server, and trains users to give away keys. A DApp should use the injected wallet provider: the wallet keeps the key, shows each transaction and signs only with the user's approval.

Check yourself

Which provider type must an application use to receive contract events as they happen?

Show answer

A WebSocket (or IPC) provider. HTTP providers cannot receive pushed messages, so eth_subscribe is not available over HTTP.

Exam Tips

Remember for the exam

  • web3.js wraps JSON-RPC: every call becomes eth_ methods such as eth_call and eth_sendRawTransaction.
  • HTTP providers cannot subscribe; use WebSocket for live events and blocks.
  • Browser DApps use the wallet's injected EIP-1193 provider; keys stay in the wallet.
  • Check the chain ID before sending transactions.