Skip to content

walletOpsDemo ​

Real World Example: Token Faucet ​

This example demonstrates how to combine the useClient, useReadContract, and useWriteContract hooks we built earlier to interact with a smart contract in a live dApp. The use case is a token faucet, where a user can:

  • Read their current token balance
  • Claim tokens by calling a smart contract method

πŸ“¦ Code Example ​

tsx
import React from 'react'
import useReadContract from '@/hooks/useReadContract'
import useWriteContract from '@/hooks/useWriteContract'
import { abi } from './abi/TokenFaucet' // Replace with your token contract ABI

const TOKEN_CONTRACT_ADDRESS = '0xYourContractAddressHere'

function TokenFaucet() {
  const { data: balance, refetch, isLoading: isReading } = useReadContract({
    address: TOKEN_CONTRACT_ADDRESS,
    abi,
    functionName: 'balanceOf',
    args: ['0xUserWalletAddress'], // Replace with connected MatchID address
  })

  const {
    writeContract,
    isLoading: isWriting,
    isError,
    error,
    hash,
  } = useWriteContract()

  const handleClaim = async () => {
    try {
      await writeContract({
        address: TOKEN_CONTRACT_ADDRESS,
        abi,
        functionName: 'claim',
        args: [],
      })
      refetch()
    } catch (err) {
      console.error('Claim failed:', err)
    }
  }

  return (
    <div>
      <h2>πŸͺ™ Token Faucet</h2>
      <p>Balance: {isReading ? 'Loading...' : `${balance} Tokens`}</p>
      <button onClick={handleClaim} disabled={isWriting}>
        {isWriting ? 'Claiming...' : 'Claim Free Tokens'}
      </button>
      {isError && <p style={{ color: 'red' }}>Error: {error}</p>}
      {hash && <p>Tx Hash: {hash}</p>}
    </div>
  )
}

export default TokenFaucet

🧠 What’s Going On ​

FeatureHook UsedPurpose
Read contract datauseReadContractReads current token balance
Write contract actionuseWriteContractClaims tokens from the faucet
Wait & refresh read staterefetch()Ensures UI updates after claiming tokens
Client managementuseClient()Used internally by the read/write hooks

πŸ’‘ Tips ​

  • You can get the logged-in user’s address from useWallet() and pass it into args when calling balanceOf
tsx
const { address } = useWallet()
// args: [address]

βœ… Summary ​

This demo shows a simple, real-world way to combine the MatchID on-chain wallet capabilities to deliver a seamless on-chain interaction β€” no external wallet needed. Works with any EVM-compatible contract.