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 ofUserBalanceindexed by CAIP-19 IDloading: Boolean indicating if balances are being fetchedtotalUsdValue: The total value of all tracked assets in USDerrors: Record mapping chain ID (number) or 'solana' to error messagesrefetch: Function to manually trigger a balance update for all chainsrefetchChains: 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-19getPrice(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 ordersloading: Boolean indicating if orders are being loadedfacilitatorGroups: Array of facilitator groups used for order viewingorderIdToViewingAuth: Record mapping order IDs to viewing auth tokensorderIdToDefaultPublicKey: Record mapping order IDs to default public keysrefreshOrders(): Manually refresh the order historyaddFacilitatorGroup(group): Add a facilitator group for order viewingsetFacilitatorGroups(groups): Replace all facilitator groupsclearFacilitatorGroups(): Clear all facilitator groups and orderssetOrderDefaultPublicKey(orderId, publicKey): Set default public key for an ordergetOrderAgeText(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 assetsetInputAmount(amount): Set the input amountsetDestinations(updater): Update destinations (accepts array or function)setSplits(updater): Update splits array (accepts array or function)setSlippage(value): Set slippage percentagesetIsAutoSlippage(value): Enable/disable auto-slippageupdateDestinationAsset(index, asset): Update asset for a destinationupdateDestinationContact(index, contact): Update contact/address for a destinationupdateDestinationAmount(index, amount): Update amount for a destinationhandleAddOutput(caip19Asset?, defaultAddress?): Add a new output destinationhandleDeleteOutput(index): Delete an output destinationtoggleUsdInputMode(): Toggle between token and USD input modegetCanAddOutput(): 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 stringsisComplete– True when all outputs are FINALIZEDerror– 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.