UNPKG

@b3dotfun/anyspend-sdk

Version:

React Hooks and UI Components for AnySpend by B3

287 lines (219 loc) 6.9 kB
# AnySpend SDK A React SDK for integrating with the Anyspend protocol, providing hooks and utilities for cross-chain swaps, NFT minting, and other blockchain operations. ## Installation ```bash npm install @b3dotfun/anyspend-sdk # or yarn add @b3dotfun/anyspend-sdk # or pnpm add @b3dotfun/anyspend-sdk ``` ## Requirements - React 19+ - TanStack Query (React Query) v5+ - Viem v2+ - Zod v3+ ## Setup The SDK uses TanStack Query for data fetching and caching. You need to wrap your application or the components using AnySpend hooks with the `AnyspendProvider`: ```tsx import { AnyspendProvider } from "@b3dotfun/anyspend-sdk"; // App-level setup (in your root layout) function App() { return ( <AnyspendProvider> <YourApp /> </AnyspendProvider> ); } // OR // Component-level setup (for specific pages/components) function YourComponent() { return ( <AnyspendProvider> <YourAnyspendFeature /> </AnyspendProvider> ); } ``` Important notes about the provider: - Must be mounted before any AnySpend hooks are used - Should be used on the client side (add 'use client' directive in Next.js) - Only one instance is needed in your component tree - When using with dynamic imports, ensure the provider wraps the dynamic component ## Available Hooks ### `useAnyspendCreateOrder` Creates a new order in the Anyspend protocol. Handles address formatting and payload structure. ```tsx import { useAnyspendCreateOrder } from "@b3dotfun/anyspend-sdk"; function CreateOrder() { const { createOrder, isCreatingOrder } = useAnyspendCreateOrder({ onSuccess: data => { console.log("Order created:", data); }, onError: (error: Error | AnyspendApiError) => { // Handle API errors with proper typing if ("statusCode" in error) { console.error("API Error:", error.message, "Status:", error.statusCode); } else { console.error("Client Error:", error.message); } } }); const handleCreateOrder = async () => { createOrder({ isMainnet, recipientAddress, orderType, srcChain, dstChain, srcToken, srcAmount, dstToken, expectedDstAmount, creatorAddress }); }; return ( <button onClick={handleCreateOrder} disabled={isCreatingOrder}> Create Order </button> ); } ``` The hook provides proper error typing through `AnyspendApiError` interface: ```typescript type AnyspendApiError = { message: string; // Error message from the API statusCode: number; // HTTP status code success: false; // Always false for errors data: null; // No data in error cases }; ``` Common API errors include: - 400: Invalid input parameters - 401: Unauthorized - 404: Resource not found - 500: Server error ### `useAnyspendTokenList` Fetches available tokens for a specific chain. ```tsx import { useAnyspendTokenList } from "@b3dotfun/anyspend-sdk"; function TokenList({ chainId }) { const { data: tokens, isLoading } = useAnyspendTokenList(isMainnet, chainId); // ... } ``` ### `useAnyspendOrderAndTransactions` Fetches and auto-refreshes order status and transaction details. ```tsx import { useAnyspendOrderAndTransactions } from "@b3dotfun/anyspend-sdk"; function OrderDetails({ orderId }) { const { orderAndTransactions, isLoadingOrderAndTransactions, getOrderAndTransactionsError, refetchOrderAndTransactions } = useAnyspendOrderAndTransactions(isMainnet, orderId); // ... } ``` ### `useAnyspendOrderHistory` Retrieves order history for order creator address. Orders are sorted by creation date (newest first). ```tsx import { useAnyspendOrderHistory } from "@b3dotfun/anyspend-sdk"; function OrderHistory({ creatorAddress }) { const { orderHistory, isLoadingOrderHistory, getOrderHistoryError, refetchOrderHistory } = useAnyspendOrderHistory( isMainnet, creatorAddress ); // ... } ``` ### `useAnyspendQuote` Fetches price/rate information for token swaps or other order types. ```tsx import { useAnyspendQuote, OrderType, GetQuoteRequest } from "@b3dotfun/anyspend-sdk"; function PriceQuoteComponent( { /* relevant props for your component */ } ) { // Example request, adjust according to your needs const quoteRequest: GetQuoteRequest = { srcChain: 1, // Example: Ethereum Mainnet dstChain: 137, // Example: Polygon Mainnet srcTokenAddress: "0x...", // Address of source token dstTokenAddress: "0x...", // Address of destination token type: OrderType.Swap, amount: "1000000000000000000" // Amount in smallest unit (e.g., wei for ETH) // Add other fields like 'price', 'fundAmount', or 'payload' as per OrderType }; const isMainnet = true; // or false for testnet const { anyspendQuote, isLoadingAnyspendQuote, getAnyspendQuoteError, refetchAnyspendQuote } = useAnyspendQuote( isMainnet, quoteRequest ); if (isLoadingAnyspendQuote) { return <p>Loading quote...</p>; } if (getAnyspendQuoteError) { return <p>Error fetching quote: {getAnyspendQuoteError.message}</p>; } // Use anyspendQuote data // ... } ``` ### `useCoinbaseOnrampOptions` Fetches available Coinbase onramp options based on user's location. ```tsx import { useCoinbaseOnrampOptions } from "@b3dotfun/anyspend-sdk"; function CoinbaseOnramp({ country }) { const { onrampOptions, isLoadingOnrampOptions, onrampOptionsError, refetchOnrampOptions } = useCoinbaseOnrampOptions( true, country, ); // ... } ``` ### `useStripeSupport` Checks if Stripe payment is supported for the user's location. ```tsx import { useStripeSupport } from "@b3dotfun/anyspend-sdk"; function StripePayment({ ipAddress }) { const { isStripeSupported, isLoadingStripeSupport, stripeSupportError, refetchStripeSupport } = useStripeSupport( true, ipAddress ); // ... } ``` ## Utilities ### `formatTokenAmount` Formats token amounts with proper decimal places. ```tsx import { formatTokenAmount } from "@b3dotfun/anyspend-sdk"; const formattedAmount = formatTokenAmount(amount, decimals); ``` ### Address and Chain Utilities The SDK provides various utilities for working with addresses and chains: ```tsx import { isValidEthereumAddress, isValidSolanaAddress, isEvmChain, isSolanaChain, chainIdToPublicClient } from "@b3dotfun/anyspend-sdk"; // Check address validity const isEthValid = isValidEthereumAddress(address); const isSolValid = isValidSolanaAddress(address); // Chain utilities const isEvm = isEvmChain(chainId); const isSol = isSolanaChain(chainId); // Get viem public client for EVM chain const publicClient = chainIdToPublicClient(chainId); ``` ## Environment Variables The SDK uses the following environment variables: - `NEXT_PUBLIC_ANYSPEND_MAINNET_BASE_URL`: Base URL for the Anyspend Mainnet API - `NEXT_PUBLIC_ANYSPEND_TESTNET_BASE_URL`: Base URL for the Anyspend Testnet API