Skip to content

Data & Utility Hooks

The SilentSwap SDK provides several hooks to access protocol data, user balances, and asset prices. These hooks are automatically available within the SilentSwapProvider.

Balances Hook

The useBalancesContext hook provides access to the user's cross-chain balances across all supported EVM and Solana chains.

import { useBalancesContext, formatBalance } from '@silentswap/react';
 
function BalanceDisplay() {
  const { balances, loading, totalUsdValue, refetch } = useBalancesContext();
 
  if (loading) return <div>Loading balances...</div>;
 
  return (
    <div>
      <h3>Total Portfolio: ${totalUsdValue.toFixed(2)}</h3>
      <ul>
        {Object.values(balances).map((info) => (
          <li key={info.asset.caip19}>
            {info.asset.symbol}: {formatBalance(info.balance, info.asset)} (${info.usdValue.toFixed(2)})
          </li>
        ))}
      </ul>
      <button onClick={refetch}>Refresh</button>
    </div>
  );
}

Return Values

  • balances: Record of UserBalance indexed by CAIP-19 ID
  • loading: Boolean indicating if balances are being fetched
  • totalUsdValue: The total value of all tracked assets in USD
  • errors: Record mapping chain ID (number) or 'solana' to error messages
  • refetch: Function to manually trigger a balance update for all chains
  • refetchChains: Function to refetch balances for specific chains: (chainIds: (number | 'solana')[]) => Promise<void>

Prices Hook

The usePricesContext hook provides access to real-time asset prices and caching logic.

import { usePricesContext } from '@silentswap/react';
 
function PriceInfo({ asset }) {
  const { getPrice, prices, loadingPrices } = usePricesContext();
  const price = getPrice(asset);
 
  return (
    <div>
      <p>Current Price: {price ? `${price.toFixed(2)}` : 'Loading...'}</p>
    </div>
  );
}

Return Values

  • prices: Record of cached prices indexed by CAIP-19
  • getPrice(asset): Function that returns the price for an asset (triggers fetch if not cached)
  • loadingPrices: Boolean indicating if any price requests are in flight

Orders Hook

The useOrdersContext hook manages the history of Silent Swap orders and provides methods to track them.

import { useOrdersContext, type OrdersContextOrder } from '@silentswap/react';
 
function RecentOrders() {
  const { orders, loading, refreshOrders } = useOrdersContext();
 
  return (
    <div>
      <h2>Your Swap History</h2>
      {orders.map((order: OrdersContextOrder) => (
        <div key={order.orderId}>
          <span>Order: {order.orderId}</span>
          <span>Status: {order.status}</span>
        </div>
      ))}
    </div>
  );
}

Return Values

  • orders: Array of recent swap orders
  • loading: Boolean indicating if orders are being loaded
  • facilitatorGroups: Array of facilitator groups used for order viewing
  • orderIdToViewingAuth: Record mapping order IDs to viewing auth tokens
  • orderIdToDefaultPublicKey: Record mapping order IDs to default public keys
  • refreshOrders(): Manually refresh the order history
  • addFacilitatorGroup(group): Add a facilitator group for order viewing
  • setFacilitatorGroups(groups): Replace all facilitator groups
  • clearFacilitatorGroups(): Clear all facilitator groups and orders
  • setOrderDefaultPublicKey(orderId, publicKey): Set default public key for an order
  • getOrderAgeText(modified?): Get human-readable order age (e.g., "5 min ago")
  • getStatusInfo(status, refundEligibility?): Get status display info with text, color, and pulsing state

Swap State Hook

The useSwap hook provides access to the global swap form state, which is shared across the SilentSwapProvider.

import { useSwap } from '@silentswap/react';
 
function AssetSelector() {
  const { tokenIn, setTokenIn } = useSwap();
  
  // Update tokenIn will automatically trigger re-quoting
  // in the SilentSwapProvider
  return (
    <select onChange={(e) => setTokenIn(e.target.value)}>
      {/* ... options */}
    </select>
  );
}

Key State Properties

  • tokenIn: Currently selected input asset (AssetInfo | null)
  • inputAmount: Amount of input asset to swap (string)
  • destinations: Array of swap outputs (recipients and amounts)
  • splits: Array of split percentages for multi-output swaps (number[])
  • slippage: Allowed slippage percentage (number)
  • isAutoSlippage: Whether auto-slippage is enabled (boolean)
  • privacyEnabled: Whether private swap features are active (boolean)
  • usdInputMode: Whether input mode is in USD (boolean)

Key Methods

  • setTokenIn(token): Set the input asset
  • setInputAmount(amount): Set the input amount
  • setDestinations(updater): Update destinations (accepts array or function)
  • setSplits(updater): Update splits array (accepts array or function)
  • setSlippage(value): Set slippage percentage
  • setIsAutoSlippage(value): Enable/disable auto-slippage
  • updateDestinationAsset(index, asset): Update asset for a destination
  • updateDestinationContact(index, contact): Update contact/address for a destination
  • updateDestinationAmount(index, amount): Update amount for a destination
  • handleAddOutput(caip19Asset?, defaultAddress?): Add a new output destination
  • handleDeleteOutput(index): Delete an output destination
  • toggleUsdInputMode(): Toggle between token and USD input mode
  • getCanAddOutput(): Check if more outputs can be added (max 5)
  • getHasMultipleOutputs(): Check if there are multiple outputs

Order tracking hook

The useOrderTracking hook connects to the SilentSwap WebSocket and keeps live order status (deposit, output stages) in sync. Use it on an order detail page so users see progress until all outputs are FINALIZED.

import { useOrderTracking, useSilentSwap } from '@silentswap/react';
 
function OrderDetail({ orderId, viewingAuth }: { orderId: string; viewingAuth: string | undefined }) {
  const { client } = useSilentSwap();
 
  const { orderStatus, deposit, outputs, isComplete, error } = useOrderTracking({
    client,
    orderId,
    viewingAuth,
    onStatusUpdate: (s) => console.log(s),
    onComplete: () => console.log('Done'),
  });
 
  if (error) return <div>Error: {error.message}</div>;
  return (
    <div>
      <p>Deposit: {deposit?.amount}</p>
      {outputs.map((o, i) => <p key={i}>{o?.stage}{o?.recipient}</p>)}
      {isComplete && <p>Complete</p>}
    </div>
  );
}

Viewing auth can come from useOrdersContext().orderIdToViewingAuth[orderId], from the order object (order.auth), or from URL params (?orderId=...&auth=...). See Order tracking, refund & recovery for full usage and integration with the example app.

Return values

  • orderStatus – Full order status (signer, deposit, outputs)
  • deposit{ amount, timestamp, duration, orderId, tx }
  • outputs – Array of output status (stage, recipient, asset, value, txs)
  • statusTexts – Human-readable status strings
  • isComplete – True when all outputs are FINALIZED
  • error – Connection or protocol error

Refund hook

The useRefund hook checks refund eligibility and executes refunds for expired, unclaimed deposits. Only the refundee (the signer that placed the order) can call the refund on the Avalanche gateway.

import { useRefund } from '@silentswap/react';
import { createPublicClient, http } from 'viem';
import { avalanche } from 'viem/chains';
 
const publicClient = createPublicClient({ chain: avalanche, transport: http() });
 
const { checkRefund, refund, refundEligibility, checkRecovery, isRecoveryEligible } = useRefund({
  orderId,
  publicClient,
  walletClient,
  s0xGatewayAddress: client.s0xGatewayAddress,
  onSuccess: (txHash) => toast.success(`Refund: ${txHash}`),
  onError: (e) => toast.error(e.message),
});
 
// Check eligibility (OPEN + expired), then execute on Avalanche
await checkRefund(orderId, client.s0xGatewayAddress);
if (refundEligibility?.refundable) {
  await ensureChain(NI_CHAIN_ID_AVALANCHE, walletClient, connector);
  await refund(orderId, client.s0xGatewayAddress);
}

Recovery (for completed orders): use checkRecovery(orderId, depositTimestamp) to set isRecoveryEligible (e.g. 20 minutes after deposit). The example app uses this plus mnemonic export for manual recovery. Full details: Order tracking, refund & recovery.