> ## Documentation Index
> Fetch the complete documentation index at: https://docs.b3.fun/llms.txt
> Use this file to discover all available pages before exploring further.

# 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.

<CardGroup cols={3}>
  <Card title="Order Hooks" icon="plus-circle" href="#order-hooks">
    Create orders, get quotes, track payments
  </Card>

  <Card title="Payment Hooks" icon="wallet" href="#payment-hooks">
    Direct transfers, gas prices
  </Card>

  <Card title="Fiat & Onramp" icon="credit-card" href="#fiat--onramp-hooks">
    Stripe, Coinbase, geo-based options
  </Card>
</CardGroup>

***

## Order hooks

### `useAnyspendQuote`

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

```tsx title="Basic Usage" icon="chart-line" theme={null}
import { useAnyspendQuote } from "@b3dotfun/sdk/anyspend";

const {
  anyspendQuote,
  isLoadingAnyspendQuote,
  getAnyspendQuoteError,
  refetchAnyspendQuote
} = useAnyspendQuote(quoteRequest);
```

#### Parameters

<ParamField path="quoteRequest" type="QuoteRequest" required>
  Quote configuration object
</ParamField>

```typescript title="QuoteRequest" icon="code" theme={null}
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

<ResponseField name="anyspendQuote" type="QuoteResponse | null">
  Quote data with pricing, fees, and expected output
</ResponseField>

<ResponseField name="isLoadingAnyspendQuote" type="boolean">
  Loading state
</ResponseField>

<ResponseField name="getAnyspendQuoteError" type="Error | null">
  Error if quote request failed
</ResponseField>

<ResponseField name="refetchAnyspendQuote" type="() => void">
  Manually refresh the quote
</ResponseField>

#### Example

```tsx title="Swap Quote Preview" icon="exchange-alt" theme={null}
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 title="Basic Usage" icon="plus-circle" theme={null}
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

<ParamField path="options" type="UseAnyspendCreateOrderProps">
  Configuration with callback functions
</ParamField>

```typescript title="UseAnyspendCreateOrderProps" icon="code" theme={null}
interface UseAnyspendCreateOrderProps {
  onSuccess?: (data: CreateOrderResponse) => void;
  onError?: (error: Error) => void;
  onSettled?: () => void;
}
```

#### Returns

<ResponseField name="createOrder" type="(params: CreateOrderParams) => void">
  Function to create an order
</ResponseField>

<ResponseField name="isCreatingOrder" type="boolean">
  Loading state
</ResponseField>

```typescript title="CreateOrderParams" icon="code" theme={null}
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 title="Payment Form" icon="credit-card" theme={null}
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 title="Basic Usage" icon="credit-card" theme={null}
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 title="UseAnyspendCreateOnrampOrderProps" icon="code" theme={null}
interface UseAnyspendCreateOnrampOrderProps {
  onSuccess?: (data: CreateOrderResponse) => void;
  onError?: (error: Error) => void;
}
```

#### Returns

<ResponseField name="createOrder" type="(params: CreateOnrampOrderParams) => void">
  Function to create a fiat onramp order
</ResponseField>

<ResponseField name="isCreatingOrder" type="boolean">
  Loading state
</ResponseField>

```typescript title="CreateOnrampOrderParams" icon="code" theme={null}
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 title="Basic Usage" icon="eye" theme={null}
import { useAnyspendOrderAndTransactions } from "@b3dotfun/sdk/anyspend";

const {
  orderAndTransactions,
  isLoadingOrderAndTransactions,
  getOrderAndTransactionsError
} = useAnyspendOrderAndTransactions(orderId);
```

#### Parameters

<ParamField path="orderId" type="string" required>
  Order ID to track
</ParamField>

#### Returns

<ResponseField name="orderAndTransactions" type="OrderWithTransactions | null">
  Complete order data with transaction details
</ResponseField>

<ResponseField name="isLoadingOrderAndTransactions" type="boolean">
  Loading state
</ResponseField>

<ResponseField name="getOrderAndTransactionsError" type="Error | null">
  Error if fetch failed
</ResponseField>

```typescript title="OrderWithTransactions" icon="code" theme={null}
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 title="Order Tracker" icon="eye" theme={null}
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 title="Basic Usage" icon="clock-rotate-left" theme={null}
import { useAnyspendOrderHistory } from "@b3dotfun/sdk/anyspend";

const { orderHistory, isLoadingOrderHistory } =
  useAnyspendOrderHistory(creatorAddress, limit, offset);
```

#### Parameters

<ParamField path="creatorAddress" type="string" required>
  User wallet address
</ParamField>

<ParamField path="limit" type="number" required>
  Number of orders to fetch (max 100)
</ParamField>

<ParamField path="offset" type="number" required>
  Pagination offset
</ParamField>

***

## Token and chain hooks

### `useAnyspendTokens`

Fetch available tokens for a specific chain with optional search.

```tsx title="Basic Usage" icon="coins" theme={null}
import { useAnyspendTokens } from "@b3dotfun/sdk/anyspend";

const { tokens, isLoadingTokens } = useAnyspendTokens(chainId, searchQuery);
```

#### Parameters

<ParamField path="chainId" type="number" required>
  Chain ID to fetch tokens for
</ParamField>

<ParamField path="searchQuery" type="string">
  Optional search filter (token name or symbol)
</ParamField>

***

### `useGasPrice`

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

```tsx title="Basic Usage" icon="gas-pump" theme={null}
import { useGasPrice } from "@b3dotfun/sdk/anyspend";

const { gasPrice, isLoading, isSpike, refetch } = useGasPrice(chainId);
```

#### Parameters

<ParamField path="chainId" type="number">
  Chain ID to fetch gas price for
</ParamField>

<ParamField path="options" type="UseGasPriceOptions">
  Optional configuration
</ParamField>

```typescript title="UseGasPriceOptions" icon="code" theme={null}
interface UseGasPriceOptions {
  /** Refetch interval in ms (default: 10000) */
  refetchInterval?: number;
  /** Enable/disable the query (default: true if chainId is supported) */
  enabled?: boolean;
}
```

#### Returns

<ResponseField name="gasPrice" type="GasPriceData | undefined">
  Gas price data including fast, standard, and slow estimates
</ResponseField>

<ResponseField name="isLoading" type="boolean">
  Loading state
</ResponseField>

<ResponseField name="isSpike" type="boolean">
  Whether gas is currently spiking above normal levels
</ResponseField>

<ResponseField name="isError" type="boolean">
  Whether there's an error
</ResponseField>

<ResponseField name="error" type="Error | null">
  Error object
</ResponseField>

<ResponseField name="refetch" type="() => void">
  Manually refresh gas price
</ResponseField>

***

## Payment hooks

### `useDirectTransfer`

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

```tsx title="Basic Usage" icon="arrow-right" theme={null}
import { useDirectTransfer } from "@b3dotfun/sdk/anyspend";

const { executeDirectTransfer, isTransferring } = useDirectTransfer();
```

#### Returns

<ResponseField name="executeDirectTransfer" type="(params: DirectTransferParams) => Promise<string | undefined>">
  Execute a direct transfer. Returns the transaction hash on success.
</ResponseField>

<ResponseField name="isTransferring" type="boolean">
  Loading state
</ResponseField>

```typescript title="DirectTransferParams" icon="code" theme={null}
interface DirectTransferParams {
  chainId: number;
  tokenAddress: string;
  recipientAddress: string;
  amount: bigint;
  method: CryptoPaymentMethodType; // "CONNECT_WALLET" | "GLOBAL_WALLET"
}
```

#### Example

```tsx title="Direct Transfer" icon="arrow-right" theme={null}
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 title="Basic Usage" icon="globe" theme={null}
import { useGeoOnrampOptions } from "@b3dotfun/sdk/anyspend";

const {
  isOnrampSupported,
  coinbaseOnrampOptions,
  stripeOnrampSupport,
  stripeWeb2Support,
  isLoading,
} = useGeoOnrampOptions(fiatAmount);
```

#### Parameters

<ParamField path="srcFiatAmount" type="string" required>
  The fiat amount for the onramp (e.g., `"50"`)
</ParamField>

#### Returns

<ResponseField name="isOnrampSupported" type="boolean">
  Whether any fiat onramp is available for the user's location
</ResponseField>

<ResponseField name="coinbaseOnrampOptions" type="object">
  Coinbase Pay configuration and available payment methods
</ResponseField>

<ResponseField name="coinbaseAvailablePaymentMethods" type="array">
  Available Coinbase payment methods for the user's region
</ResponseField>

<ResponseField name="stripeOnrampSupport" type="boolean">
  Whether Stripe redirect flow is supported
</ResponseField>

<ResponseField name="stripeWeb2Support" type="object">
  Whether Stripe embedded form is supported (`{ isSupport: boolean }`)
</ResponseField>

<ResponseField name="isLoading" type="boolean">
  Combined loading state
</ResponseField>

<ResponseField name="geoData" type="object">
  User's detected geographic data (country, city, timezone)
</ResponseField>

***

### `useCoinbaseOnrampOptions`

Get Coinbase Pay onramp configuration for fiat payments.

```tsx title="Basic Usage" icon="credit-card" theme={null}
import { useCoinbaseOnrampOptions } from "@b3dotfun/sdk/anyspend";

const { coinbaseOptions, isLoadingCoinbaseOptions } = useCoinbaseOnrampOptions(country);
```

#### Parameters

<ParamField path="country" type="string">
  ISO country code (e.g., `"US"`)
</ParamField>

***

### `useStripeSupport`

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

```tsx title="Basic Usage" icon="stripe" theme={null}
import { useStripeSupport } from "@b3dotfun/sdk/anyspend";

const {
  stripeOnrampSupport,
  stripeWeb2Support,
  isLoadingStripeSupport,
} = useStripeSupport(usdAmount, visitorData, isLoadingVisitorData);
```

#### Parameters

<ParamField path="usdAmount" type="string">
  USD amount for the payment
</ParamField>

<ParamField path="visitorData" type="VisitorData">
  Fingerprint.js visitor data (optional, for fraud detection)
</ParamField>

<ParamField path="isLoadingVisitorData" type="boolean">
  Whether visitor data is still loading
</ParamField>

#### Returns

<ResponseField name="stripeOnrampSupport" type="boolean">
  Whether Stripe redirect flow is available
</ResponseField>

<ResponseField name="stripeWeb2Support" type="{ isSupport: boolean }">
  Whether Stripe embedded form is available
</ResponseField>

<ResponseField name="isLoadingStripeSupport" type="boolean">
  Loading state
</ResponseField>

***

### `useStripeClientSecret`

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

```tsx title="Basic Usage" icon="stripe" theme={null}
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 title="Basic Usage" icon="cart-shopping" theme={null}
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 title="Basic Usage" icon="eye" theme={null}
import { useCheckoutSession } from "@b3dotfun/sdk/anyspend";

const { data: session, isLoading } = useCheckoutSession(sessionId);
```

#### Parameters

<ParamField path="sessionId" type="string" required>
  Checkout session ID to track
</ParamField>

#### Returns

<ResponseField name="data" type="CheckoutSession">
  Session data including `status`, `order_id`, `metadata`
</ResponseField>

<ResponseField name="isLoading" type="boolean">
  Loading state
</ResponseField>

#### Example

```tsx title="Session Tracker" icon="eye" theme={null}
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 title="Error Handling Pattern" icon="shield-exclamation" theme={null}
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 title="Combined Loading States" icon="spinner" theme={null}
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

<CardGroup cols={3}>
  <Card title="Components" icon="puzzle-piece" href="/anyspend/components">
    Pre-built components using these hooks
  </Card>

  <Card title="Examples" icon="code" href="/anyspend/examples">
    Real-world implementation examples
  </Card>

  <Card title="Error Handling" icon="shield-exclamation" href="/anyspend/error-handling">
    Comprehensive error handling guide
  </Card>
</CardGroup>
