BC9: Apps that talk to the chain
Connecting to the right network
🎯You'll be able to
Connect an app to a network with ethers.js, check it's the right one, and use a contract through its ABI.
🏠The everyday picture
Before paying at a counter, you check the name on the shop's sign. Paying the right amount at the wrong shop doesn't help.
📘What it really is
-
Providers: ethers'
JsonRpcProviderconnects to a node's RPC address; on a web page, a browser wallet provides one throughwindow.ethereum(EIP-1193). -
Chain ID check: ask the provider for its network and stop if the chain ID isn't the one configured.
-
ABI: the contract's interface (functions, events, errors) produced by the compiler. With an address and ABI, ethers builds a
Contractobject whose methods match the contract's functions. -
Addresses from records: read deployed addresses from a deployment file, not from a message or a hard-coded guess.
- Other libraries: web3.js and viem do similar jobs; the ideas are the same.
📝A worked example
Input: SakhiKosh's command-line app.
Steps:
- Create a provider for
SAKHI_RPC_URL(default http://127.0.0.1:8545). - Call
connect(provider, 31337): it reads the chain ID and throws "Wrong network" if it differs. - Load SakhiFund's address from
deployments/localhost.jsonand its ABI from the compiled artifacts.
Expected output: an app that refuses the wrong network before doing anything else.
🌍Where it's used
- Wallet-connected websites.
- Back-office scripts for treasuries.
- Monitoring tools reading contract state.
📝Case scenario
A team's dashboard was pointed at a different network after a configuration change, and showed old balances as if they were current. Members made decisions on wrong numbers for a day. A chain ID check with a clear message would have flagged it at once.
🖱️Try it
Start the practice network and run npm run app -- summary <address> with one of the printed accounts after deploying. Then stop the
network and run it again. Success: a balance the first time, and a clear connection error the second.
⚠️Common mistakes
- No chain ID check. Sign: the app works on whatever it's pointed at. Fix: check and stop.
- Hard-coded addresses. Sign: addresses copied into code. Fix: deployment records.
- Old ABIs. Sign: "function not found". Fix: load the ABI from the current build.
🛠️For your project
Project 3's test 1 checks connect refuses a chain ID that isn't the expected one.
✅Quick check
What does an ABI give an app?
Show the answer
The contract's functions, events and errors, so it can call them and decode results.
Where should an app get a deployed contract's address?
Show the answer
From a deployment record, not typed or pasted into the code.
