BC9: Apps that talk to the chain

Lesson 1 of 5 · reading 15–25 minutes; practice and project time is on the module page

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

📝A worked example

Input: SakhiKosh's command-line app.

Steps:

  1. Create a provider for SAKHI_RPC_URL (default http://127.0.0.1:8545).
  2. Call connect(provider, 31337): it reads the chain ID and throws "Wrong network" if it differs.
  3. Load SakhiFund's address from deployments/localhost.json and its ABI from the compiled artifacts.

Expected output: an app that refuses the wrong network before doing anything else.

🌍Where it's used

📝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

🛠️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.

← BackBC9
ProLearners Assist