RakaPoints is ready, but the JavaScript on the shop page can't simply say "check Dinda's PTS" to a node. It needs a go-between, like Raka's Shirt Shop's courier carrying a standard form to the warehouse. You say "check Dinda's PTS", the courier fills in the form in the code the warehouse understands (calldata from ABI encoding), delivers it (a JSON-RPC request over HTTP), then translates the answer back into your language (a BigInt). Two couriers are the most used: ethers.js and viem, JavaScript/TypeScript libraries for talking to the Ethereum blockchain: reading balances, calling contracts, and sending transactions. Both talk to a node over JSON-RPC, the same protocol wallets use. The versions used in this lesson: ethers 6.17.0 and viem 2.57.4, the latest as of October 2026.
Reading and writing: provider, signer and client
| ethers v6 | viem v2 | |
|---|---|---|
Read (free, eth_call) |
JsonRpcProvider, BrowserProvider |
createPublicClient |
| Write (signed, pays gas) | a Signer from provider.getSigner() |
createWalletClient |
| Call a contract | new ethers.Contract(address, abi, provider or signer) |
readContract, simulateContract, writeContract |
A provider (in viem: a public client) only reads: balances, blocks, view functions. A signer (in viem: a wallet client) has access to an account that can sign, so it's the one that sends transactions. In the browser, the signer is the user's wallet: new ethers.BrowserProvider(window.ethereum) in ethers, custom(window.ethereum) in viem, and every transaction still asks for approval through the popup (the Wallet lesson). On a local Hardhat or Anvil chain, the node itself holds the test accounts, so getSigner(0) uses account #0 directly, with no private key in the code.
Reading and writing with ethers v6
RakaPoints is already deployed on the local chain (0x5FbD...0aa3). Raka records Dinda's Coffee Print Shirt ($95, passed in cents):
import { ethers } from 'ethers'
const PTS = '0x5FbDB2315678afecb367f032d93F642f64180aa3'
const DINDA = '0x70997970C51812dc3A010C7d01b50e0d17dc79C8'
const abi = [
'function balanceOf(address) view returns (uint256)',
'function earn(address customer, uint256 cents)',
]
const provider = new ethers.JsonRpcProvider('http://127.0.0.1:8545')
const raka = await provider.getSigner(0)
const points = new ethers.Contract(PTS, abi, provider)
console.log(await points.balanceOf(DINDA))
const tx = await points.connect(raka).earn(DINDA, 9500n)
const receipt = await tx.wait()
console.log(receipt.status, receipt.gasUsed)
const balance = await points.balanceOf(DINDA)
console.log(balance, ethers.formatUnits(balance, 18))
$ node points-ethers.mjs
0n
1 71667n
95000000000000000000n 95.0
- In ethers, the
abimay be written as human-readable text. The functions you use are enough. new ethers.Contract(PTS, abi, provider)makes a contract object for reading.points.connect(raka)makes a copy of it tied to the signer, for writing.earn(...)returns a transaction that has only just been sent.await tx.wait()waits until it's in a block and returns the receipt (status1 means success).- Numbers from a contract are always
bigint(ending inn).
The same with viem v2
Dinda then buys a Coffee Print Mug ($65):
import { createPublicClient, createWalletClient, http, parseAbi, formatUnits } from 'viem'
import { hardhat } from 'viem/chains'
const abi = parseAbi([
'function balanceOf(address) view returns (uint256)',
'function earn(address customer, uint256 cents)',
])
const publicClient = createPublicClient({ chain: hardhat, transport: http() })
const walletClient = createWalletClient({
account: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',
chain: hardhat,
transport: http(),
})
const { request } = await publicClient.simulateContract({
account: walletClient.account,
address: PTS,
abi,
functionName: 'earn',
args: [DINDA, 6500n],
})
const hash = await walletClient.writeContract(request)
const receipt = await publicClient.waitForTransactionReceipt({ hash })
console.log(receipt.status, receipt.gasUsed)
const balance = await publicClient.readContract({ address: PTS, abi, functionName: 'balanceOf', args: [DINDA] })
console.log(balance, formatUnits(balance, 18))
$ node points-viem.mjs
success 37467n
160000000000000000000n 160
(PTS and DINDA are the same as in the ethers script.) viem's style is functions, not a contract object. simulateContract runs the transaction first through eth_call; if it would revert, you get the error before anything is signed. Notice formatUnits too: ethers writes 95.0, viem writes 160.
Behind the scenes: the selector and ABI encoding
A node doesn't understand balanceOf(DINDA). The library turns it into calldata: a 4-byte function selector, then every argument in a 32-byte slot. The selector is the first 4 bytes of the keccak256 of the function's signature, written with no spaces and no parameter names:
keccak256("transfer(address,uint256)") = 0xa9059cbb2ab09eb219583f4a59a5d0623ade346d962bcd4e46b11da047c9049b
selector = 0xa9059cbb
The calldata for transfer(Yoga, 20 PTS), the standard ERC-20 function PTS will have later:
0xa9059cbb selector
0000000000000000000000003c44cdddb6a900fa2b585dd299e03d12fa4293bc Yoga's address, padded with zeros on the left to 32 bytes
000000000000000000000000000000000000000000000001158e460913d00000 20 × 10^18 in hex
This is the real request viem sent for the readContract of balanceOf(DINDA) above, and the node's answer:
request: {"jsonrpc":"2.0","id":0,"method":"eth_call","params":[{"data":"0x70a0823100000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8","to":"0x5FbDB2315678afecb367f032d93F642f64180aa3"},"latest"]}
response: {"jsonrpc":"2.0","id":0,"result":"0x000000000000000000000000000000000000000000000008ac7230489e800000"}
0x70a08231 is the selector of balanceOf(address), and 0x...08ac7230489e800000 reads as 160000000000000000000n, 160 PTS. For a write the content is the same, only the method is eth_sendTransaction, with from set to Raka's account.
Amounts: BigInt and decimals
Guess first: PTS has 18 decimals. If you call transfer(yoga, 20) with the plain number 20, without parseUnits, how much PTS does Yoga receive: 20, 0.00000000000000002, or an error?
A token amount is always a whole number in the smallest unit. To write "20 PTS", convert it with parseUnits('20', 18) (or parseEther for ETH):
| You write | What's sent | What it means |
|---|---|---|
parseUnits('20', 18) |
20000000000000000000n |
20 PTS |
20n |
20n |
0.00000000000000002 PTS |
So without parseUnits, Yoga receives 0.00000000000000002 PTS, with no error at all. In the other direction, formatUnits(value, 18) turns the smallest unit into text for display.
Why BigInt and not a plain number? A number is only exact up to Number.MAX_SAFE_INTEGER (9,007,199,254,740,991). Number(95000000000000000001n) becomes 95000000000000000000: one unit lost without a word. And mixing the two fails outright:
> 95000000000000000000n + 1
TypeError: Cannot mix BigInt and other types, use explicit conversions
ethers or viem?
Both are actively developed and both are right for a new project. ethers uses objects (Contract, Signer) and has been around a long time, so there are plenty of tutorials. viem uses functions, reads its TypeScript types straight from the ABI, and is what wagmi uses for React (later in this track). The calldata both produce is the same byte for byte, because the ABI sets the rules, not the library. Pick one per project; don't mix them.
⚠️ What usually goes wrong the first time with ethers or viem
- Forgetting
parseUnits.transfer(yoga, 20)sends 20 of the smallest unit, not 20 PTS. The reverse too: showing95000000000000000000withoutformatUnits. - Treating a transaction as done once it's sent.
earn(...)orwriteContractonly returns a hash. Wait fortx.wait()orwaitForTransactionReceipt, then checkstatus. - A mistyped signature. The selector is computed from the exact text:
transfer(address,uint)gives0x6cb927d8,transfer(address, uint256)(with a space) gives0x9d61d234, and neither matches any function. Let the library compute it from the ABI. - A private key in frontend code. Everything sent to the browser can be read. In the browser the signer is the user's wallet; on a local chain, the node's test accounts; on a server, keep keys in a secret manager, never in the repo.
TL;DR: ethers v6 and viem v2 are JavaScript libraries for reading from and writing to Ethereum over JSON-RPC. A provider (viem: public client) only reads and is free; a signer (viem: wallet client) signs transactions that pay gas. ethers uses new ethers.Contract(...) and tx.wait(); viem uses readContract, simulateContract, writeContract and waitForTransactionReceipt. Behind the scenes a call becomes calldata: a 4-byte selector (keccak256("transfer(address,uint256)") starts with 0xa9059cbb) then 32-byte arguments. Token amounts are BigInts in the smallest unit: parseUnits('20', 18) = 20000000000000000000n, while 20n alone is only 0.00000000000000002 PTS. Use formatUnits for display (ethers 95.0, viem 160). Never use number for amounts, and never put a private key in a frontend.
⚡ A provider reads, a signer writes
Meaning: A provider (in viem: a public client) only reads the blockchain, for free. A signer (in viem: a wallet client) can sign transactions that pay gas. In the browser, the signer is the user's wallet.
⚡ Sent isn't the same as done
Write:
const tx = await points.connect(raka).earn(DINDA, 9500n)
const receipt = await tx.wait()
console.log(receipt.status, receipt.gasUsed)
Meaning: earn(...) returns a transaction that has only just been sent. tx.wait() waits until it's in a block, and status 1 means success.
⚡ The selector: the first 4 bytes of keccak256
Write:
keccak256("transfer(address,uint256)") = 0xa9059cbb2ab09eb219583f4a59a5d0623ade346d962bcd4e46b11da047c9049b
selector = 0xa9059cbb
Meaning: The library turns a call into calldata: a 4-byte selector, then every argument in a 32-byte slot. The signature is written with no spaces and no parameter names.
⚡ Token amounts are in the smallest unit
Guess first: you call transfer(yoga, 20) without parseUnits. How much PTS does Yoga receive?
0.00000000000000002 PTS, with no error at all. For 20 PTS, write parseUnits('20', 18), which is 20000000000000000000n.
Meaning: A token amount is a BigInt in the smallest unit. formatUnits turns it into text for display.