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 β
Feature | Hook Used | Purpose |
---|---|---|
Read contract data | useReadContract | Reads current token balance |
Write contract action | useWriteContract | Claims tokens from the faucet |
Wait & refresh read state | refetch() | Ensures UI updates after claiming tokens |
Client management | useClient() | Used internally by the read/write hooks |
π‘ Tips β
- You can get the logged-in userβs address from
useWallet()
and pass it intoargs
when callingbalanceOf
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.