← Back to the blog
Lesson 6: Event Listening and Full-Stack Optimization

X ArticleWeb3

Lesson 6: Event Listening and Full-Stack Optimization

Source: https://x.com/i/status/2110719246892507496

Learning goals: build a check-in DApp, and handle events, transaction states, caching, and network switching.

Previous lesson

Lesson outline

An intuitive mapping from Web2 to Web3

The project plan and MVP structure

Environment setup and minimal dependencies

The contract: first make one that is good enough, without chasing bells and whistles

Core frontend configuration

Step 1: connect a wallet first

Step 2: read on-chain state; don’t start by hand-rolling requests

Step 3: send a transaction; don’t treat “clicking the button” as “already succeeded”

Step 4: listen to events, and do real-time updates

Step 5: wire the page together into a complete flow

BigInt, precision conversion, and async timing: these pitfalls have to be explained thoroughly

Full-stack optimization: take the user experience from “it works” to “it feels natural”

Pitfalls you will definitely hit in production

Pitfall 1: events fire more than once, and the same record appears twice in the list

Pitfall 2: after the user switches networks, the page still shows data from the old chain

Pitfall 3: the event arrived, but “my status” did not update

One more cut: changes that make it more like a production project

A more solid way to organize the page

What you actually learned in this project

An intuitive mapping from Web2 to Web3

Don’t rush to memorize terms. First switch the model in your head.

Don’t rush to memorize terms. First switch the model in your head.

The project plan and MVP structure

This project has three parts:

The contract: a minimal check-in contract

The frontend: React + Vite

Wallet and chain interaction: wagmi + viem

I’m not going for fancy tricks with the stack. I chose the set that is currently the most solid for connecting a frontend to Web3:

React

Vite

TypeScript

wagmi

viem

TanStack Query

What the project does

The page only does 4 things:

Connect a wallet

Show whether the current address has checked in today

Click a button to submit a check-in

Display a real-time stream of the latest check-in records

Environment setup and minimal dependencies

First scaffold a React project.

If you want to bring styles along as well:

The focus of this article is not styles, so I won’t expand on that.

The contract: first make one that is good enough, without chasing bells and whistles

A frontend tutorial also needs a target you can interact with, so first here is a minimal Solidity contract. You don’t need to know how to write Solidity immediately; you only need to know what the events and state look like.

Contract features

Each address can check in only once per day

The contract records whether someone has checked in on a given day

On a successful check-in, it emits the event CheckedIn(address user, uint256 day, uint256 timestamp)

The Solidity contract

You can deploy with Remix, which is convenient. Deploy to a testnet, for example Sepolia.

After deployment you will get two things:

The contract address

The ABI

Core frontend configuration

First configure the wallet and the chain.

src/web3/config.ts

src/main.tsx

Contract information: src/web3/checkin.ts

Step 1: connect a wallet first

The first step of a Web3 page is never “call an API”; it is getting the current user’s address and connection state.

The wallet-connect component

Here are two pitfalls beginners often hit

  1. There isn’t necessarily only one connector

You assumed there would only be MetaMask. In fact, depending on the wallet environment, multiple connectors may appear in the browser. Don’t hard-code it.

  1. A successful connection does not mean the network is right

The user may be on mainnet, Polygon, or BSC. If your contract is deployed on Sepolia, you have to prompt them to switch networks, or both reads and writes will be useless.

Step 2: read on-chain state; don’t start by hand-rolling requests

This step needs to read two values:

The current day on-chain

Whether the current address has already checked in on that day

Why read currentDay first

Because the concept of “today” on-chain is not your local time. The “today” your local Date computes is not necessarily the same as block.timestamp / 1 days on-chain. As long as the rule is written on-chain, the frontend follows the chain.

src/hooks/useCheckInStatus.ts

Why it is written this way

enabled is critical

A lot of people, when they first start, will pass args: [address, currentDay] directly. The result is that the address hasn’t been obtained yet, currentDay hasn’t come back either, and the request blows up first.

The point of enabled is: don’t send the request until the conditions are all in place.

staleTime is not just decoration

An on-chain read is not a purely local computation. If several components on your page all read the same state, and you don’t configure caching, then switching the page or a little state jitter will hit the RPC repeatedly. You may not feel it in local development; once you have more users in production, RPC rate limits will school you in no time.

Step 3: send a transaction; don’t treat “clicking the button” as “already succeeded”

The transaction flow is very different from an ordinary form submission. The normal order is:

The user clicks the button

The wallet pops up a confirmation

The user signs

The transaction is broadcast

Wait for it to be included in a block

The transaction succeeds or fails

The frontend refreshes state

The easiest mistake here is that as soon as the wallet returns a hash, you treat the UI as a success. That won’t do. That only means “the transaction has been sent”, not that it has been confirmed.

The check-in button component

These states need to be kept distinct

isPending: the wallet layer is still handling it; the user may not have clicked confirm yet

isConfirming: the transaction has already been sent, waiting to be included in a block

isSuccess: at least a receipt has been obtained, and it has been confirmed on-chain

If you mix these three stages, the user experience will be poor. Don’t be lazy with the button copy and write it all as “Submitting...”; users will have no idea which step it is stuck on.

Step 4: listen to events, and do real-time updates

This is the core theme of the article. After a check-in succeeds, it is not only the current user’s status that needs to update; the site-wide list of latest check-ins should also change in real time.

Why not use pure polling

Of course you can poll. But polling brings several problems:

Frequent requests

A fixed delay

Heavy RPC pressure when there are many users

The page doesn’t look “alive”

Event listening is more like message subscription in Web2. As soon as the contract emits CheckedIn, the frontend can receive it.

Listening for check-in events

The event-list component

Step 5: wire the page together into a complete flow

The real development order should be like this:

Connect the wallet first

Then read the current state

Then decide whether the button can be clicked

After a successful transaction, refresh the state

At the same time, listen to the event stream for real-time updates

src/App.tsx

At this point, the MVP is working end to end.

BigInt, precision conversion, and async timing: these pitfalls have to be explained thoroughly

A Web3 frontend is not hard because there are many APIs. It is hard because you didn’t usually have to be this cautious about these details in Web2.

BigInt is not a drop-in replacement for Number

On-chain numeric values are basically all large integers. As long as it is a uint256, what the frontend gets is very likely a bigint.

The wrong way to write it

If the value is large, or if you later handle amounts, there is a direct precision risk. In the check-in project, day is not a big problem, but if you form this bad habit, you will definitely get into trouble later when you work with balances, prices, and token amounts.

The right approach

When displaying to the user: convert to a string

When taking part in on-chain parameters: keep it as a bigint

When token amounts are involved: use parseUnits / formatUnits

For example:

Don’t scramble the async timing

You will be facing these states at the same time:

The wallet connected successfully

The address changed

The chain switched

A read request returned

A transaction was sent

A receipt returned

An event arrived

The order of these states is not fixed. So the code must have a few principles:

Principle 1: if the dependencies are not all in place, don’t send the request

Rely on enabled.

Principle 2: after a transaction succeeds, actively refresh the key state

Don’t only trust events.

Principle 3: the event stream is only for “incremental updates”; authoritative state is calibrated by read APIs

This is a lot like Web2: data pushed from a message queue is fast, but eventual consistency still needs a fallback query against the store.

Full-stack optimization: take the user experience from “it works” to “it feels natural”

This is the part of the project that is truly valuable. Just getting it to run isn’t special; running stably, with interactions that feel natural, is what makes it feel like something you’d actually ship.

  1. Do optimistic updates, but don’t oversell them

After the user clicks check-in, in theory you can immediately switch the UI to “submitted”. But you cannot switch it directly to “already checked in successfully”, because it has not been confirmed on-chain yet.

A more solid approach:

After wallet confirmation: show “Submitted successfully, waiting to land on-chain”

After the receipt succeeds: switch to “Checked in”

Lock the button at the same time, to prevent repeated clicks

  1. Cache on-chain read requests

staleTime has already been configured above. Add another idea: if several components all need the current address’s state, don’t have each component query on its own. Extract a hook, read in one place, and cache in one place.

This is the old approach you used for a state layer in Web2, and it is equally valid in Web3.

  1. Don’t let the event list grow without limit

If the event stream appends without limit, the page will start to stutter after being used for a while. Keeping only the most recent 20–50 items on the frontend is enough. If you really need to look up old data, do paginated historical queries; don’t expect a single listening list to do everything.

Pitfalls you will definitely hit in production

If I don’t cover this part, you will definitely get burned when you go live.

Pitfall 1: events fire more than once, and the same record appears twice in the list

This is very common. The causes may include:

The wallet / node reconnecting

React Strict Mode triggering a side effect twice in development

Multiple subscription instances existing at the same time

The node returning duplicate logs

The fix

Deduplicate on the frontend by a unique key

The most solid choice is:

transactionHash

logIndex

Plus business fields as a fallback

If you can get logIndex, prefer using it.

Don’t listen to the same event repeatedly in multiple places

A lot of people listen once in a page component, and listen again in a dialog. That is just making things harder for yourself. For the same event source, try to manage it in one place.

Pitfall 2: after the user switches networks, the page still shows data from the old chain

This kind of bug is insidious. On the surface the page has data, but what it is actually reading is a cache from the old chain, and transactions cannot be sent.

The fix

Listen for changes to the chain ID, and actively invalidate the related cache

If your project is a bit more complex, the suggestion is to include chainId and address in the query key.

For example:

['checkin-status', chainId, address]

['current-day', chainId]

Once the chain changes, the caches are naturally isolated. Don’t mix Sepolia and mainnet data in the same pot.

Pitfall 3: the event arrived, but “my status” did not update

Beginners are especially likely to ask this: “I already heard the CheckedIn event, so why does the page still say I haven’t checked in?”

Because the event stream updates your list state; it does not necessarily automatically refresh the hasCheckedIn query cache.

The fix

After the transaction succeeds, manually refetch the key read requests. You can think of it as:

Event listening: responsible for being fast

An active refetch: responsible for being accurate

You need both. Don’t choose only one.

One more cut: changes that make it more like a production project

If you really want to push this demo toward production, the suggestion is to add these things as well.

  1. Add network checks and a prompt to switch networks

In the current example, the network is only displayed. In a real product you need to judge explicitly:

If it is not Sepolia, disable the check-in button

Give a clear prompt: “Please switch to Sepolia”

If you can, call the network-switching capability directly

  1. Pull a stretch of historical events at initialization

Right now this listening list can only see “new events after the page was opened”. If you want users to see recent check-in records as soon as they come in, you need to pull historical logs once at initialization, and then stitch them together with the live subscription.

The general idea is:

getLogs when the page loads

watchEvent while the page is running

Merge the two parts and deduplicate

This combination is much more solid than relying on listening alone.

  1. Make error messages human

Wallet signature rejection, insufficient user balance, the wrong network, a contract revert — these errors are best prompted separately. Don’t show users the raw error in every case; that stuff often looks like gibberish.

For example:

The user cancelled the signature: you cancelled this transaction

The network is wrong: please switch to the Sepolia testnet first

Already checked in today: you have already checked in today

The RPC is down: the network had a lapse; try again later

A more solid way to organize the page

At this point, you should be able to feel a pattern:

Wallet state is one layer

On-chain read state is one layer

Transaction write state is one layer

Event-stream state is yet another layer

So in a real project, don’t pile all the logic into App.tsx. A recommended way to split it:

That way, when you later add “consecutive check-in days”, a “leaderboard”, or “personal history”, it won’t fall apart after two changes.

What you actually learned in this project

It is not “I wrote a check-in button”. What is truly useful is the following sequence, which you can basically reuse later for minting, voting, check-ins, claiming rewards, or signing up for on-chain events:

Get the wallet state first

Then query on-chain read-only data

Clearly distinguish “confirming in the wallet” from “confirming on-chain”

Use the event stream for a real-time UI

Use an active refetch to keep key state accurate

Use caching to reduce repeated RPC calls

Use bigint and unit conversion to avoid precision pitfalls

Put in production fallbacks for chain switching, duplicate events, and error messages

One sentence to close: a Web3 frontend is not finished when you “know how to call a contract”. What is truly hard is wrapping an unstable on-chain async world into a normal product that users can click naturally, whose feedback they can understand, and that won’t leave them staring in confusion.

At this point, this tutorial’s MVP, event-listening approach, and production-optimization skeleton are all in place.

Code snippets from the article

The following code comes from code blocks in the original X Article, arranged in the order they appeared.

// src/components/WalletSection.tsx
import { useAccount, useConnect, useDisconnect } from 'wagmi'

export function WalletSection() {
  const { address, isConnected, chain } = useAccount()
  const { connect, connectors, isPending } = useConnect()
  const { disconnect } = useDisconnect()

  if (isConnected) {
    return (
      <div>
        <p>Current address: {address}</p>
        <p>Current network: {chain?.name ?? 'Unknown network'}</p>
        <button onClick={() => disconnect()}>Disconnect wallet</button>
      </div>
    )
  }

  return (
    <div>
      {connectors.map((connector) => (
        <button
          key={connector.uid}
          onClick={() => connect({ connector })}
          disabled={isPending}
        >
          Connect {connector.name}
        </button>
      ))}
    </div>
  )
}
import { createConfig, http } from 'wagmi'
import { sepolia } from 'wagmi/chains'

export const config = createConfig({
  chains: [sepolia],
  transports: {
    [sepolia.id]: http(), // A default public RPC is enough to get it running first; in production, don't cut corners — configure a stable RPC yourself
  },
})
// src/components/LiveFeed.tsx
import { useCheckInEvents } from '../hooks/useCheckInEvents'

export function LiveFeed() {
  const events = useCheckInEvents()

  return (
    <div>
      <h3>Latest check-ins</h3>

      {events.length === 0 ? (
        <p>No new events have been heard yet</p>
      ) : (
        <ul>
          {events.map((item, index) => (
            <li key={`${item.txHash}-${index}`}>
              Address {item.user} checked in on day={item.day.toString()}, timestamp {item.timestamp.toString()}
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}
const day = Number(currentDay)
npm i -D tailwindcss @tailwindcss/vite
import React from 'react'
import ReactDOM from 'react-dom/client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { WagmiProvider } from 'wagmi'
import App from './App'
import { config } from './web3/config'

const queryClient = new QueryClient()

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <WagmiProvider config={config}>
      <QueryClientProvider client={queryClient}>
        <App />
      </QueryClientProvider>
    </WagmiProvider>
  </React.StrictMode>,
)
src/
  components/
    WalletSection.tsx
    CheckInAction.tsx
    CheckInStatus.tsx
    LiveFeed.tsx
  hooks/
    useCheckInStatus.ts
    useCheckInEvents.ts
    useCheckInAction.ts
  web3/
    config.ts
    checkin.ts
  pages/
    Home.tsx
import { formatUnits, parseUnits } from 'viem'

const rawAmount = parseUnits('1.5', 18) // bigint
const display = formatUnits(rawAmount, 18) // "1.5"
// src/components/CheckInAction.tsx
import { useEffect } from 'react'
import { useWriteContract, useWaitForTransactionReceipt } from 'wagmi'
import { CHECKIN_ADDRESS, checkInAbi } from '../web3/checkin'

type Props = {
  disabled?: boolean
  onSuccess?: () => void
}

export function CheckInAction({ disabled, onSuccess }: Props) {
  const { data: hash, writeContract, isPending, error } = useWriteContract()

  const {
    isLoading: isConfirming,
    isSuccess,
    error: receiptError,
  } = useWaitForTransactionReceipt({
    hash,
  })

  useEffect(() => {
    if (isSuccess) {
      onSuccess?.()
    }
  }, [isSuccess, onSuccess])

  return (
    <div>
      <button
        disabled={disabled || isPending || isConfirming}
        onClick={() =>
          writeContract({
            address: CHECKIN_ADDRESS,
            abi: checkInAbi,
            functionName: 'checkIn',
          })
        }
      >
        {isPending ? 'Confirm in wallet...' : isConfirming ? 'Confirming on-chain...' : 'Check in today'}
      </button>

      {error && <p>Failed to submit: {error.shortMessage || error.message}</p>}
      {receiptError && <p>Failed to land on-chain: {receiptError.message}</p>}
      {hash && <p>Transaction hash: {hash}</p>}
    </div>
  )
}
export const CHECKIN_ADDRESS = '0xYourContractAddressHere'

export const checkInAbi = [
  {
    type: 'function',
    name: 'checkIn',
    stateMutability: 'nonpayable',
    inputs: [],
    outputs: [],
  },
  {
    type: 'function',
    name: 'hasCheckedIn',
    stateMutability: 'view',
    inputs: [
      { name: 'user', type: 'address' },
      { name: 'day', type: 'uint256' },
    ],
    outputs: [{ name: '', type: 'bool' }],
  },
  {
    type: 'function',
    name: 'currentDay',
    stateMutability: 'view',
    inputs: [],
    outputs: [{ name: '', type: 'uint256' }],
  },
  {
    type: 'event',
    name: 'CheckedIn',
    inputs: [
      { name: 'user', type: 'address', indexed: true },
      { name: 'day', type: 'uint256', indexed: true },
      { name: 'timestamp', type: 'uint256', indexed: false },
    ],
    anonymous: false,
  },
] as const
import { WalletSection } from './components/WalletSection'
import { CheckInAction } from './components/CheckInAction'
import { LiveFeed } from './components/LiveFeed'
import { useCheckInStatus } from './hooks/useCheckInStatus'

function App() {
  const { currentDay, hasCheckedIn, isLoading, refetch } = useCheckInStatus()

  return (
    <div style={{ padding: 24 }}>
      <h1>Onchain Check-in Board</h1>

      <WalletSection />

      <hr />

      <section>
        <h2>My check-in status</h2>

        {isLoading ? (
          <p>Loading status...</p>
        ) : (
          <>
            <p>Current on-chain day: {currentDay?.toString() ?? '-'}</p>
            <p>Checked in today: {hasCheckedIn ? 'Yes' : 'Not yet'}</p>
          </>
        )}

        <CheckInAction
          disabled={!!hasCheckedIn}
          onSuccess={() => {
            // Actively refresh once after the transaction is confirmed
            // Event listening can update the list, but the “have I checked in” state is best refetched manually — don't leave it to chance with events
            refetch()
          }}
        />
      </section>

      <hr />

      <LiveFeed />
    </div>
  )
}

export default App
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract CheckIn {
    mapping(address => mapping(uint256 => bool)) public checkedIn;

    event CheckedIn(address indexed user, uint256 indexed day, uint256 timestamp);

    function checkIn() external {
        uint256 day = block.timestamp / 1 days;
        require(!checkedIn[msg.sender][day], "Already checked in today");

        checkedIn[msg.sender][day] = true;
        emit CheckedIn(msg.sender, day, block.timestamp);
    }

    function hasCheckedIn(address user, uint256 day) external view returns (bool) {
        return checkedIn[user][day];
    }

    function currentDay() external view returns (uint256) {
        return block.timestamp / 1 days;
    }
}
import { useAccount, useReadContract } from 'wagmi'
import { CHECKIN_ADDRESS, checkInAbi } from '../web3/checkin'

export function useCheckInStatus() {
  const { address, isConnected } = useAccount()

  const { data: currentDay, isLoading: isDayLoading } = useReadContract({
    address: CHECKIN_ADDRESS,
    abi: checkInAbi,
    functionName: 'currentDay',
    query: {
      staleTime: 10_000, // Treat the data as fresh for 10 seconds; don't hit the chain on every render
    },
  })

  const { data: hasCheckedIn, isLoading: isStatusLoading, refetch } = useReadContract({
    address: CHECKIN_ADDRESS,
    abi: checkInAbi,
    functionName: 'hasCheckedIn',
    args: address && currentDay !== undefined ? [address, currentDay] : undefined,
    query: {
      enabled: isConnected && !!address && currentDay !== undefined,
      staleTime: 5_000,
    },
  })

  return {
    currentDay,
    hasCheckedIn,
    isLoading: isDayLoading || isStatusLoading,
    refetch,
  }
}
// src/hooks/useCheckInEvents.ts
import { useState } from 'react'
import { useWatchContractEvent } from 'wagmi'
import { CHECKIN_ADDRESS, checkInAbi } from '../web3/checkin'

type CheckInEventItem = {
  user: string
  day: bigint
  timestamp: bigint
  txHash?: string
}

export function useCheckInEvents() {
  const [events, setEvents] = useState<CheckInEventItem[]>([])

  useWatchContractEvent({
    address: CHECKIN_ADDRESS,
    abi: checkInAbi,
    eventName: 'CheckedIn',
    onLogs(logs) {
      const parsed = logs.map((log) => ({
        user: log.args.user!,
        day: log.args.day!,
        timestamp: log.args.timestamp!,
        txHash: log.transactionHash,
      }))

      setEvents((prev) => {
        const merged = [...parsed, ...prev]

        // An easy pitfall here: events may arrive more than once, so you must deduplicate by txHash
        const uniqueMap = new Map<string, CheckInEventItem>()

        for (const item of merged) {
          const key = `${item.txHash}-${item.user}-${item.day.toString()}`
          if (!uniqueMap.has(key)) {
            uniqueMap.set(key, item)
          }
        }

        return Array.from(uniqueMap.values()).slice(0, 20)
      })
    },
  })

  return events
}
npm create vite@latest onchain-checkin-board -- --template react-ts
cd onchain-checkin-board
npm i wagmi viem @tanstack/react-query
const key = `${log.transactionHash}-${log.logIndex}`

This article was imported from an X Article. Original: https://x.com/i/status/2110719246892507496