Intermediate

Building a Simple DApp Frontend — Hands-on lab

Connect frontend to smart contracts.

Developer Intermediate
4/6 — Building a Simple DApp Frontend — Hands-on lab

Build for production Start small—a balance and a mint/approve button—but ship it with the UX you’d trust with real funds. Instrument errors, keep buttons disabled when they should be, and always provide explorer links.

Trusted third parties are security holes.
— Nick Szabo

Resilience Simulate bad paths: user rejects a signature, gas estimation fails, chain is wrong. Make sure UI recovers gracefully and communicates next steps.

Polish Add small touches: ENS/name display, checksum formatting, copy-to-clipboard, and recent activity. These reduce mis-sends and build confidence.

import { useAccount, useContractRead, usePrepareContractWrite, useContractWrite, useWaitForTransaction } from 'wagmi';
import abi from './abi.json';

export function MintButton() {
  const { address, chain } = useAccount();
  const { data: balance } = useContractRead({
    address: '0xYourContract',
    abi,
    functionName: 'balanceOf',
    args: [address],
    watch: true,
  });
  const { config } = usePrepareContractWrite({
    address: '0xYourContract',
    abi,
    functionName: 'safeMint',
    args: [address],
    enabled: !!address && chain?.id === 11155111, // Sepolia
  });
  const { data, write, error, isLoading } = useContractWrite(config);
  const { isLoading: pending } = useWaitForTransaction({ hash: data?.hash });

  return (
    
Balance: {balance?.toString() || '—'}
{data?.hash && View tx ↗} {error &&
{error.message}
}
); }
Steps
  1. Create a Vite/React app:With wagmi/ethers; add a connect button, show account, chain, and balance; persist connection.
  2. Read contract state (e.g.,:ERC-721 balance + tokenURI preview) using hooks/caching; refresh on new blocks.
  3. Send a transaction (mint/approve):With gas estimation; show pending spinner, tx hash, and success/failure with explorer links.
  4. Handle chain mismatch:Prompt switch, disable actions, and display clear guidance; test user rejection flows.
  5. Add error handling:User rejection, underpriced gas, insufficient funds, bad nonce; log to console and show friendly toasts.
  6. Polish:Show recent activity list, handle disconnect, and guard against multiple rapid clicks.
← Previous section
Next section →