Skip to content

21. Ethers: Write Contract

Scaffold-ETH hides a lot behind convenient hooks; this lesson lifts the hood on what actually happens when a frontend writes to a contract, using ethers.js directly. Understanding the raw sequence — build a contract instance, attach a signer, call a function, wait for the receipt — makes the higher-level tooling far less mysterious and much easier to debug.

  • The three ingredients of a write — a contract’s address, its ABI (the interface describing its functions), and a signer. With those, ethers gives you a contract object whose methods send transactions.
  • ABI as the translator — the ABI tells ethers how to encode your function call and arguments into the transaction’s data field (recall Module 1, lesson 03). Wrong or missing ABI, and the call can’t be built.
  • Calling a write function — invoking a state-changing method on the signer-connected contract triggers the wallet confirmation popup; the user approves gas and the transaction is broadcast. Your app doesn’t sign — the wallet does.
  • Transaction vs. receipt — sending returns a transaction hash immediately (it’s pending); you then await the receipt to know it was mined and whether it succeeded. Designing UI around this two-phase reality (pending → confirmed) is essential.
  • Read vs. write, in code — a view call returns a value directly with no wallet prompt; a write returns a transaction to wait on. This is the lesson-14 provider/signer split expressed as actual ethers calls.
  • Handling failure — a user can reject the wallet prompt, or the transaction can revert. Robust dApps catch both and tell the user what happened.
  • Treating a sent transaction as done. It’s only pending until the receipt confirms it — updating the UI to “success” too early is a classic bug.
  • Using a stale or wrong ABI/address after redeploying a contract, so calls silently target the wrong thing.
  • Not handling the user rejecting the wallet prompt, which throws and can crash a naive handler.
  • Forgetting a write needs a signer (lesson 14) — a provider-only instance can’t send it.
  • What three things does ethers need to build a contract object that can send a write?
  • What’s the difference between the transaction hash you get immediately and the receipt you await?
  • What does the ABI actually do when you call a contract function?

Module 3: Full-Stack dApp Basics.