Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 50 additions & 25 deletions apps/web/src/features/faucet/components/faucet-page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { Skeleton } from "@workspace/ui/components/skeleton"
import { Button } from "@workspace/ui/components/button"
import { FAUCET_TOKENS } from "../data/tokens"
import { FAUCET_CONTRACT_ID } from "../lib/clients"
import { useFaucetData } from "../hooks/useFaucetData"
import { useClaim } from "../hooks/useClaim"
import type { FaucetTokenConfig } from "../data/tokens"
import { Navbar } from "@/ui/Navbar"
import { TokenIcon } from "@/shared/components/TokenIcon"
import { formatToken } from "@/shared/lib/format"
Expand All @@ -8,10 +13,6 @@ import { useWalletStore } from "@/features/wallet/store/wallet-store"
import { useNetwork } from "@/features/wallet/hooks/useNetwork"
import { NetworkMismatchBanner } from "@/features/wallet/components/NetworkMismatchBanner"
import { ConnectButton } from "@/features/wallet/components/ConnectButton"
import { FAUCET_TOKENS, type FaucetTokenConfig } from "../data/tokens"
import { FAUCET_CONTRACT_ID } from "../lib/clients"
import { useFaucetData } from "../hooks/useFaucetData"
import { useClaim } from "../hooks/useClaim"

// ── Token card ────────────────────────────────────────────────────────────────

Expand Down Expand Up @@ -48,14 +49,16 @@ function TokenCard({
<div className="flex items-center gap-3">
<TokenIcon symbol={token.symbol.replace(/^T/, "")} size={36} />
<div>
<p className="text-sm font-semibold text-foreground">{token.symbol}</p>
<p className="text-sm font-semibold text-foreground">
{token.symbol}
</p>
<p className="text-xs text-muted-foreground">{token.name}</p>
</div>
</div>

<div className="grid grid-cols-2 gap-3">
<div className="rounded-lg bg-muted/40 px-3 py-2.5">
<p className="mb-0.5 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
<p className="mb-0.5 text-[11px] font-medium tracking-wider text-muted-foreground uppercase">
Your balance
</p>
{isLoading ? (
Expand All @@ -68,7 +71,7 @@ function TokenCard({
</div>

<div className="rounded-lg bg-muted/40 px-3 py-2.5">
<p className="mb-0.5 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
<p className="mb-0.5 text-[11px] font-medium tracking-wider text-muted-foreground uppercase">
Claim amount
</p>
{isLoading ? (
Expand All @@ -82,15 +85,24 @@ function TokenCard({
</div>

<div className="flex items-center justify-between gap-3">
<p className="min-w-0 truncate text-[12px] text-muted-foreground">{cooldownText}</p>
<p className="min-w-0 truncate text-[12px] text-muted-foreground">
{cooldownText}
</p>
<Button
variant="outline"
size="sm"
className="h-8 shrink-0"
disabled={isDisabled || isPending}
onClick={() => onClaim(token)}
>
Claim
{isPending ? (
<span className="flex items-center gap-2">
<span className="h-3 w-3 animate-spin rounded-full border-2 border-current border-t-transparent" />
Claiming…
</span>
) : (
"Claim"
)}
</Button>
</div>
</div>
Expand All @@ -104,21 +116,24 @@ export function FaucetPage() {
const isConnected = useWalletStore((state) => state.status === "connected")
const { mismatch } = useNetwork()
const { data, isLoading } = useFaucetData(address)
const { claim, isPending } = useClaim()
const { claim, isBulkPending, isTokenPending } = useClaim()

const isTestnet = NETWORK.name === "testnet"
const claimDisabled = !isConnected || isPending || mismatch
const globalClaimDisabled = !isConnected || mismatch
const bulkClaimDisabled = globalClaimDisabled || isBulkPending

return (
<div className="flex min-h-svh flex-col bg-background text-foreground">
<Navbar variant="app" />
<NetworkMismatchBanner />

<div className="mx-auto w-full max-w-2xl px-4 pb-16 pt-8 sm:px-6">
<div className="mx-auto w-full max-w-2xl px-4 pt-8 pb-16 sm:px-6">
{/* Header */}
<header className="mb-8">
<div className="flex items-center gap-3">
<h1 className="text-[22px] font-semibold tracking-tight">Testnet Faucet</h1>
<h1 className="text-[22px] font-semibold tracking-tight">
Testnet Faucet
</h1>
<span className="inline-flex items-center gap-1.5 rounded-full border border-yellow-500/30 bg-yellow-500/10 px-2.5 py-0.5 text-[11px] font-medium text-yellow-600 dark:text-yellow-400">
<span className="h-1.5 w-1.5 rounded-full bg-yellow-500" />
Stellar Testnet
Expand Down Expand Up @@ -148,8 +163,8 @@ export function FaucetPage() {
lastClaimLedger={data?.lastClaimLedgers[token.symbol]}
cooldownLedgers={data?.cooldownLedgers}
isLoading={isLoading}
isPending={isPending}
isDisabled={claimDisabled}
isPending={isTokenPending(token.contractId)}
isDisabled={globalClaimDisabled}
onClaim={(selectedToken) => claim([selectedToken.contractId])}
/>
))}
Expand All @@ -159,10 +174,12 @@ export function FaucetPage() {
<div className="rounded-xl border border-border bg-card p-5">
<div className="flex flex-col gap-4">
<div>
<p className="text-sm font-medium text-foreground">Claim test tokens</p>
<p className="text-sm font-medium text-foreground">
Claim test tokens
</p>
<p className="mt-0.5 text-[13px] text-muted-foreground">
Receive TUSDC, TWBTC, TETH, and TXLM in a single transaction. A cooldown
applies between claims.
Receive TUSDC, TWBTC, TETH, and TXLM in a single
transaction. A cooldown applies between claims.
</p>
</div>

Expand All @@ -174,17 +191,19 @@ export function FaucetPage() {

{!isConnected ? (
<div className="flex flex-col items-center gap-2">
<p className="text-[13px] text-muted-foreground">Connect your wallet to claim test tokens.</p>
<p className="text-[13px] text-muted-foreground">
Connect your wallet to claim test tokens.
</p>
<ConnectButton />
</div>
) : (
<Button
variant="default"
className="w-full"
disabled={claimDisabled}
disabled={bulkClaimDisabled}
onClick={() => claim()}
>
{isPending ? (
{isBulkPending ? (
<span className="flex items-center gap-2">
<span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-current border-t-transparent" />
Claiming…
Expand All @@ -197,15 +216,16 @@ export function FaucetPage() {

{data?.cooldownLedgers != null && data.cooldownLedgers > 0 && (
<p className="text-center text-[12px] text-muted-foreground">
Cooldown: {data.cooldownLedgers.toLocaleString()} ledgers between claims
Cooldown: {data.cooldownLedgers.toLocaleString()} ledgers
between claims
</p>
)}
</div>
</div>

{/* Info panel */}
<div className="rounded-xl border border-border bg-muted/20 px-5 py-4">
<p className="mb-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
<p className="mb-2 text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
Contract addresses
</p>
<dl className="space-y-1.5">
Expand All @@ -216,8 +236,13 @@ export function FaucetPage() {
id: token.contractId,
})),
].map(({ label, id }) => (
<div key={label} className="flex items-center justify-between gap-3">
<dt className="w-12 shrink-0 text-[12px] text-muted-foreground">{label}</dt>
<div
key={label}
className="flex items-center justify-between gap-3"
>
<dt className="w-12 shrink-0 text-[12px] text-muted-foreground">
{label}
</dt>
<dd className="min-w-0 truncate font-mono text-[11px] text-foreground/70">
{id}
</dd>
Expand Down
158 changes: 113 additions & 45 deletions apps/web/src/features/faucet/hooks/useClaim.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { useCallback, useState } from "react"
import { useCallback, useMemo, useRef, useState } from "react"
import { toast } from "sonner"
import { useQueryClient } from "@tanstack/react-query"
import { FAUCET_TOKENS } from "../data/tokens"
import { createFaucetClient } from "../lib/clients"
import { useWalletStore } from "@/features/wallet/store/wallet-store"
import { walletKit } from "@/features/wallet/lib/wallet-kit"
import { sendAndPoll } from "@/lib/tx-builder"
import { explorerTxUrl } from "@/app/config/network"
import { queryKeys } from "@/shared/lib/query-keys"
import { FAUCET_TOKENS } from "../data/tokens"
import { createFaucetClient } from "../lib/clients"
import { parseSorobanError } from "@/lib/contracts"

function isClaimTooSoonError(error: unknown): boolean {
Expand All @@ -24,53 +24,121 @@ export function useClaim() {
const address = useWalletStore((state) => state.address)
const isConnected = useWalletStore((state) => state.status === "connected")
const queryClient = useQueryClient()
const [isPending, setIsPending] = useState(false)
const [pendingTokenIds, setPendingTokenIds] = useState<Set<string>>(
() => new Set()
)
const pendingTokenIdsRef = useRef<Set<string>>(new Set())
const isBulkPendingRef = useRef(false)
const [isBulkPending, setIsBulkPending] = useState(false)

const setBulkPending = useCallback((value: boolean) => {
isBulkPendingRef.current = value
setIsBulkPending(value)
}, [])

const markTokensPending = useCallback((tokenIds: Array<string>) => {
setPendingTokenIds((current) => {
const next = new Set(current)
tokenIds.forEach((tokenId) => next.add(tokenId))
pendingTokenIdsRef.current = next
return next
})
}, [])

const claim = useCallback(async (tokenIds = FAUCET_TOKENS.map((token) => token.contractId)) => {
if (!address || !isConnected) return
const clearTokensPending = useCallback((tokenIds: Array<string>) => {
setPendingTokenIds((current) => {
const next = new Set(current)
tokenIds.forEach((tokenId) => next.delete(tokenId))
pendingTokenIdsRef.current = next
return next
})
}, [])

setIsPending(true)
const toastId = toast.loading(
tokenIds.length === 1 ? "Claiming test token…" : "Claiming test tokens…",
)
const claim = useCallback(
async (tokenIds = FAUCET_TOKENS.map((token) => token.contractId)) => {
if (!address || !isConnected) return

try {
const faucet = createFaucetClient(address)
const tx = await faucet.claim_many({
account: address,
tokens: tokenIds,
})
const isBulkClaim = tokenIds.length !== 1
const hasPendingToken = tokenIds.some((tokenId) =>
pendingTokenIdsRef.current.has(tokenId)
)
if (isBulkClaim ? isBulkPendingRef.current : hasPendingToken) return

const unsignedXdr = tx.toXDR()
const { signedTxXdr } = await walletKit.signTransaction(unsignedXdr)
const signedXdr = signedTxXdr
const { hash } = await sendAndPoll(signedXdr)
if (isBulkClaim) {
setBulkPending(true)
}
markTokensPending(tokenIds)
const toastId = toast.loading(
tokenIds.length === 1 ? "Claiming test token…" : "Claiming test tokens…"
)

// Refresh balances after a successful claim
await queryClient.invalidateQueries({ queryKey: queryKeys.faucet.data(address) })
try {
const faucet = createFaucetClient(address)
const tx = await faucet.claim_many({
account: address,
tokens: tokenIds,
})

toast.success("Test tokens claimed!", {
id: toastId,
description: (
<a
href={explorerTxUrl(hash)}
target="_blank"
rel="noreferrer"
className="text-xs text-primary hover:underline"
>
View transaction →
</a>
),
})
} catch (error) {
const message = isClaimTooSoonError(error)
? "Cooldown active — please wait before claiming again."
: parseSorobanError(error)
toast.error(message, { id: toastId })
} finally {
setIsPending(false)
}
}, [address, isConnected, queryClient])
const unsignedXdr = tx.toXDR()
const { signedTxXdr } = await walletKit.signTransaction(unsignedXdr)
const signedXdr = signedTxXdr
const { hash } = await sendAndPoll(signedXdr)

// Refresh balances after a successful claim
await queryClient.invalidateQueries({
queryKey: queryKeys.faucet.data(address),
})

toast.success("Test tokens claimed!", {
id: toastId,
description: (
<a
href={explorerTxUrl(hash)}
target="_blank"
rel="noreferrer"
className="text-xs text-primary hover:underline"
>
View transaction →
</a>
),
})
} catch (error) {
const message = isClaimTooSoonError(error)
? "Cooldown active — please wait before claiming again."
: parseSorobanError(error)
toast.error(message, { id: toastId })
} finally {
if (isBulkClaim) {
setBulkPending(false)
}
clearTokensPending(tokenIds)
}
},
[
address,
clearTokensPending,
isConnected,
markTokensPending,
queryClient,
setBulkPending,
]
)

const isPending = isBulkPending || pendingTokenIds.size > 0
const isTokenPending = useCallback(
(tokenId: string) => pendingTokenIds.has(tokenId),
[pendingTokenIds]
)
const pendingTokenIdList = useMemo(
() => Array.from(pendingTokenIds),
[pendingTokenIds]
)

return { claim, isPending }
return {
claim,
isPending,
isBulkPending,
isTokenPending,
pendingTokenIds: pendingTokenIdList,
}
}