Hooks

React hooks for quotes, orders, transfers, onramp, and checkout sessions

Use these hooks when the pre-built components don't fit your UI. They give you direct access to quoting, order creation, status tracking, and fiat onramp logic.

Order Hooks

Create orders, get quotes, track payments

Learn More
Payment Hooks

Direct transfers, gas prices

Learn More
Fiat & Onramp

Stripe, Coinbase, geo-based options

Learn More

Order hooks

useAnyspendQuote

Get real-time pricing for token swaps and cross-chain transactions. Quotes auto-refresh every 10 seconds.

tsx
import { useAnyspendQuote } from "@b3dotfun/sdk/anyspend"; const { anyspendQuote, isLoadingAnyspendQuote, getAnyspendQuoteError, refetchAnyspendQuote } = useAnyspendQuote(quoteRequest);

Parameters

quoteRequest QuoteRequest required

Quote configuration object

typescript
interface QuoteRequest { srcChain: number; // Source chain ID dstChain: number; // Destination chain ID srcTokenAddress: string; // Source token contract address dstTokenAddress: string; // Destination token contract address type: "swap" | "custom"; // Order type tradeType: "EXACT_INPUT" | "EXACT_OUTPUT"; amount: string; // Amount in smallest unit (wei) }

Returns

anyspendQuote QuoteResponse | null

Quote data with pricing, fees, and expected output

Loading state

Error if quote request failed

Manually refresh the quote

Example

tsx
function SwapQuote() { const quoteRequest = { srcChain: 1, dstChain: 8453, srcTokenAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC on Ethereum dstTokenAddress: "0x0000000000000000000000000000000000000000", // ETH type: "swap" as const, tradeType: "EXACT_INPUT" as const, amount: "1000000", // 1 USDC }; const { anyspendQuote, isLoadingAnyspendQuote, getAnyspendQuoteError } = useAnyspendQuote(quoteRequest); if (isLoadingAnyspendQuote) return <div>Getting best price...</div>; if (getAnyspendQuoteError) return <div>Failed to get quote</div>; return ( <div> <p>You'll receive: {anyspendQuote?.expectedOutput} ETH</p> <p>Network fee: ${anyspendQuote?.networkFeeUsd}</p> <p>Service fee: ${anyspendQuote?.serviceFeeUsd}</p> </div> ); }

useAnyspendCreateOrder

Create and execute AnySpend orders for crypto payments.

tsx
import { useAnyspendCreateOrder } from "@b3dotfun/sdk/anyspend"; const { createOrder, isCreatingOrder } = useAnyspendCreateOrder({ onSuccess: (data) => console.log("Order created:", data.data.id), onError: (error) => console.error("Failed:", error.message), });

Parameters

options UseAnyspendCreateOrderProps

Configuration with callback functions

typescript
interface UseAnyspendCreateOrderProps { onSuccess?: (data: CreateOrderResponse) => void; onError?: (error: Error) => void; onSettled?: () => void; }

Returns

createOrder (params: CreateOrderParams) => void

Function to create an order

Loading state

typescript
interface CreateOrderParams { recipientAddress: string; orderType: string; // "swap", "hype_duel", "custom_exact_in", etc. srcChain: number; dstChain: number; srcToken: Token; dstToken: Token; srcAmount: string; expectedDstAmount?: string; creatorAddress?: string; metadata?: Record<string, unknown>; callbackMetadata?: Record<string, unknown>; nft?: NFT & { price: string }; tournament?: Tournament & { contractAddress: string; entryPriceOrFundAmount: string }; payload?: any; }

Example

tsx
function PaymentForm() { const { createOrder, isCreatingOrder } = useAnyspendCreateOrder({ onSuccess: (data) => { router.push(`/payment/${data.data.id}`); }, onError: (error) => { toast.error("Payment failed. Please try again."); }, }); const handlePayment = () => { createOrder({ recipientAddress: merchantAddress, orderType: "swap", srcChain: 1, dstChain: 8453, srcToken: { chainId: 1, address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", name: "USD Coin", symbol: "USDC", decimals: 6 }, dstToken: { chainId: 8453, address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", name: "USD Coin", symbol: "USDC", decimals: 6 }, srcAmount: "10000000", creatorAddress: userAddress, }); }; return ( <button onClick={handlePayment} disabled={isCreatingOrder}> {isCreatingOrder ? "Processing..." : "Pay 10 USDC"} </button> ); }

useAnyspendCreateOnrampOrder

Create orders for fiat onramp payments (Stripe, Coinbase Pay).

tsx
import { useAnyspendCreateOnrampOrder } from "@b3dotfun/sdk/anyspend"; const { createOrder, isCreatingOrder } = useAnyspendCreateOnrampOrder({ onSuccess: (data) => { // Redirect user to onramp provider window.location.href = data.data.oneClickBuyUrl; }, });

Parameters

typescript
interface UseAnyspendCreateOnrampOrderProps { onSuccess?: (data: CreateOrderResponse) => void; onError?: (error: Error) => void; }

Returns

createOrder (params: CreateOnrampOrderParams) => void

Function to create a fiat onramp order

Loading state

typescript
type CreateOnrampOrderParams = { recipientAddress: string; orderType: string; dstChain: number; dstToken: Token; expectedDstAmount?: string; srcFiatAmount: string; // Fiat amount (e.g., "10.00") onramp: { vendor: "coinbase" | "stripe"; paymentMethod: string; // e.g., "card" country: string; // ISO country code redirectUrl: string; // URL to redirect after payment }; };

Order tracking hooks

useAnyspendOrderAndTransactions

Monitor order status and track associated blockchain transactions in real-time.

tsx
import { useAnyspendOrderAndTransactions } from "@b3dotfun/sdk/anyspend"; const { orderAndTransactions, isLoadingOrderAndTransactions, getOrderAndTransactionsError } = useAnyspendOrderAndTransactions(orderId);

Parameters

orderId string required

Order ID to track

Returns

orderAndTransactions OrderWithTransactions | null

Complete order data with transaction details

Loading state

Error if fetch failed

typescript
interface OrderWithTransactions { data: { order: Order; // Order details and status depositTxs: Transaction[]; // User deposit transactions relayTx?: Transaction; // Cross-chain relay transaction executeTx?: Transaction; // Final execution transaction refundTxs: Transaction[]; // Refund transactions (if any) }; }

Example

tsx
function OrderTracker({ orderId }: { orderId: string }) { const { orderAndTransactions, isLoadingOrderAndTransactions } = useAnyspendOrderAndTransactions(orderId); if (isLoadingOrderAndTransactions) return <div>Loading...</div>; const { order, depositTxs, executeTx } = orderAndTransactions!.data; return ( <div> <h2>Order #{orderId.slice(0, 8)}</h2> <p>Status: {order.status}</p> {executeTx && ( <a href={`https://basescan.org/tx/${executeTx.txHash}`}> View Transaction </a> )} </div> ); }

useAnyspendOrderHistory

Retrieve paginated order history for a user address.

tsx
import { useAnyspendOrderHistory } from "@b3dotfun/sdk/anyspend"; const { orderHistory, isLoadingOrderHistory } = useAnyspendOrderHistory(creatorAddress, limit, offset);

Parameters

creatorAddress string required

User wallet address

limit number required

Number of orders to fetch (max 100)

offset number required

Pagination offset


Token and chain hooks

useAnyspendTokens

Fetch available tokens for a specific chain with optional search.

tsx
import { useAnyspendTokens } from "@b3dotfun/sdk/anyspend"; const { tokens, isLoadingTokens } = useAnyspendTokens(chainId, searchQuery);

Parameters

chainId number required

Chain ID to fetch tokens for

Optional search filter (token name or symbol)


useGasPrice

Fetch real-time gas prices for a chain with spike detection.

tsx
import { useGasPrice } from "@b3dotfun/sdk/anyspend"; const { gasPrice, isLoading, isSpike, refetch } = useGasPrice(chainId);

Parameters

chainId number

Chain ID to fetch gas price for

options UseGasPriceOptions

Optional configuration

typescript
interface UseGasPriceOptions { /** Refetch interval in ms (default: 10000) */ refetchInterval?: number; /** Enable/disable the query (default: true if chainId is supported) */ enabled?: boolean; }

Returns

gasPrice GasPriceData | undefined

Gas price data including fast, standard, and slow estimates

isLoading boolean

Loading state

isSpike boolean

Whether gas is currently spiking above normal levels

isError boolean

Whether there's an error

error Error | null

Error object

refetch () => void

Manually refresh gas price


Payment hooks

useDirectTransfer

Execute direct transfers when source and destination token/chain match, bypassing the swap backend for faster, cheaper transactions.

tsx
import { useDirectTransfer } from "@b3dotfun/sdk/anyspend"; const { executeDirectTransfer, isTransferring } = useDirectTransfer();

Returns

executeDirectTransfer (params: DirectTransferParams) => Promise<string | undefined>

Execute a direct transfer. Returns the transaction hash on success.

Loading state

typescript
interface DirectTransferParams { chainId: number; tokenAddress: string; recipientAddress: string; amount: bigint; method: CryptoPaymentMethodType; // "CONNECT_WALLET" | "GLOBAL_WALLET" }

Example

tsx
function DirectTransferButton({ token, recipient, amount }) { const { executeDirectTransfer, isTransferring } = useDirectTransfer(); const handleTransfer = async () => { const txHash = await executeDirectTransfer({ chainId: token.chainId, tokenAddress: token.address, recipientAddress: recipient, amount: BigInt(amount), method: CryptoPaymentMethodType.CONNECT_WALLET, }); if (txHash) { toast.success("Transfer complete!"); } }; return ( <button onClick={handleTransfer} disabled={isTransferring}> {isTransferring ? "Transferring..." : "Send Tokens"} </button> ); }

Fiat and onramp hooks

useGeoOnrampOptions

Get all available onramp options based on the user's geographic location. Combines geo detection, Coinbase availability, and Stripe support.

tsx
import { useGeoOnrampOptions } from "@b3dotfun/sdk/anyspend"; const { isOnrampSupported, coinbaseOnrampOptions, stripeOnrampSupport, stripeWeb2Support, isLoading, } = useGeoOnrampOptions(fiatAmount);

Parameters

srcFiatAmount string required

The fiat amount for the onramp (e.g., "50")

Returns

Whether any fiat onramp is available for the user's location

Coinbase Pay configuration and available payment methods

Available Coinbase payment methods for the user's region

Whether Stripe redirect flow is supported

Whether Stripe embedded form is supported ({ isSupport: boolean })

isLoading boolean

Combined loading state

geoData object

User's detected geographic data (country, city, timezone)


useCoinbaseOnrampOptions

Get Coinbase Pay onramp configuration for fiat payments.

tsx
import { useCoinbaseOnrampOptions } from "@b3dotfun/sdk/anyspend"; const { coinbaseOptions, isLoadingCoinbaseOptions } = useCoinbaseOnrampOptions(country);

Parameters

country string

ISO country code (e.g., "US")


useStripeSupport

Check Stripe payment availability based on the user's location and payment amount.

tsx
import { useStripeSupport } from "@b3dotfun/sdk/anyspend"; const { stripeOnrampSupport, stripeWeb2Support, isLoadingStripeSupport, } = useStripeSupport(usdAmount, visitorData, isLoadingVisitorData);

Parameters

usdAmount string

USD amount for the payment

visitorData VisitorData

Fingerprint.js visitor data (optional, for fraud detection)

Whether visitor data is still loading

Returns

Whether Stripe redirect flow is available

stripeWeb2Support { isSupport: boolean }

Whether Stripe embedded form is available

Loading state


useStripeClientSecret

Get a Stripe client secret for initializing the embedded Stripe payment form.

tsx
import { useStripeClientSecret } from "@b3dotfun/sdk/anyspend"; const { clientSecret, isLoadingClientSecret } = useStripeClientSecret(paymentIntentId);

Checkout session hooks

useCreateCheckoutSession

Create a checkout session for backend-tracked payment flows.

tsx
import { useCreateCheckoutSession } from "@b3dotfun/sdk/anyspend"; const { mutate: createSession, data, isPending } = useCreateCheckoutSession(); createSession({ success_url: "https://mysite.com/success/{SESSION_ID}", metadata: { sku: "widget-1" }, });

useCheckoutSession

Query a checkout session with automatic polling. Stops polling when status reaches complete or expired.

tsx
import { useCheckoutSession } from "@b3dotfun/sdk/anyspend"; const { data: session, isLoading } = useCheckoutSession(sessionId);

Parameters

sessionId string required

Checkout session ID to track

Returns

data CheckoutSession

Session data including status, order_id, metadata

isLoading boolean

Loading state

Example

tsx
function CheckoutSessionTracker({ sessionId }) { const { data: session, isLoading } = useCheckoutSession(sessionId); if (isLoading) return <div>Loading...</div>; switch (session?.data.status) { case "open": return <div>Waiting for payment...</div>; case "processing": return <div>Payment received, processing order...</div>; case "complete": return <div>Order complete! Order ID: {session.data.order_id}</div>; case "expired": return <div>Session expired. Please create a new checkout.</div>; } }

Hook patterns

Error handling

tsx
function PaymentComponent() { const { createOrder, isCreatingOrder } = useAnyspendCreateOrder({ onError: (error) => { switch (error.message) { case "INSUFFICIENT_BALANCE": toast.error("Insufficient balance. Please add funds."); break; case "SLIPPAGE": toast.error("Price moved unfavorably. Please try again."); break; case "QUOTE_EXPIRED": toast.info("Getting fresh quote..."); break; default: toast.error("Payment failed. Please try again."); } }, }); // ... }

Composing loading states

tsx
function SwapInterface() { const { anyspendQuote, isLoadingAnyspendQuote } = useAnyspendQuote(quoteRequest); const { createOrder, isCreatingOrder } = useAnyspendCreateOrder(); const isLoading = isLoadingAnyspendQuote || isCreatingOrder; return ( <div> {isLoading && <LoadingSpinner />} {/* Rest of component */} </div> ); }

Next steps

Components

Pre-built components using these hooks

Learn More
Examples

Real-world implementation examples

Learn More
Error Handling

Comprehensive error handling guide

Learn More
Ask a question... ⌘I