Skip to main content
All hooks and utilities are available from the 0xtrails package unless stated otherwise.

TrailsProvider

Required for Hooks: The TrailsProvider must wrap your application when using any Trails hooks. This provider configures the necessary context for all hook functionality.

Apps without wagmi

Since 0xtrails@0.16.0, Trails uses a built-in EVM runtime by default and no longer requires wagmi for the widget or the SDK hooks. See the 0.16 release notes for migration details.
The SDK still uses @tanstack/react-query internally. If your app does not already include a QueryClientProvider, add one above TrailsProvider:

Apps with wagmi

If your app already uses wagmi, wrap your app with WagmiProvider and use wagmi hooks (useAccount, useWalletClient, etc.) to supply wallet state to Trails hooks. For widget integrations that should share the same wagmi session, pass wagmiAdapter on the widget’s adapters prop — see Adapters.
For custom EIP-1193 wallets without wagmi, use the evmAdapter helper on widget components — see EIP-1193 adapter.

Configuration Options

Wallet adapters

Added in 0xtrails@0.16.0. Adapters are a widget-only feature — pass them on focused widget components (Pay, Fund, Swap, …), not on TrailsProvider. See the Adapters section for wagmi, EIP-1193, Solana, and thirdweb integrations.
Hooks-based integrations do not use adapters. Supply wallet state directly to hooks such as useQuote and useTrailsSendTransaction via walletClient and address from your own wallet stack (wagmi, viem, ethers, etc.).

Edge chains

Edge chains (non-EVM / alternative VMs — see Supported Chains) are supported at the quote and execution layer, not uniformly across every hook. Chain-family handling is transparent to the hooks that support it — pass an edge chain via ChainIdentifier (name or chain ID) the same way you pass an EVM chain.
Execution model. Paying from an edge chain (edge as origin) requires the matching edge wallet adapter registered on TrailsProvider plus a connected edge wallet — a viem walletClient cannot sign an edge-chain transaction. See Adapters (currently the Solana adapter). Paying to an edge chain (edge as destination) works with a standard EVM wallet and an edge recipient address — no adapter needed.

Chains

  • getSupportedChains(): Promise<Chain[]>
  • useSupportedChains(): { supportedChains: Chain[], isLoadingChains: boolean }

Utility Functions

Chain Type

Public Clients

Added in 0xtrails@0.16.0. Use these to get a viem PublicClient for any supported chain without configuring transports yourself — Trails resolves the RPC via the Sequence node gateway using your API key.
  • usePublicClient(chainId?: number): returns a viem PublicClient | null for the given chain.
  • usePublicClientGetter(): returns a (chainId: number, retryCount?: number) => PublicClient | null you can call inside event handlers or effects.

Tokens

  • useTokenList(): { tokens: Token[] | undefined, isLoadingTokens: boolean }
  • useSupportedTokens({ chainId?: number }): { supportedTokens: Token[], isLoadingTokens: boolean }
  • getSupportedTokens(): Promise<Token[]>

Additional Helpers

Token Type

The unified Token type is used throughout the Trails SDK:

Balances

Balance hooks and utilities:
  • useTokenBalances(address, options?): Returns sorted token balances enriched with USD price
  • useTokenBalancesForMultipleAccounts(addresses, options?): Returns token balances for multiple accounts
  • useAccountTotalBalanceUsd(address): Returns total USD balance across tokens
  • useHasSufficientBalanceUsd(address, targetUsd): Check if account has sufficient USD balance
  • useHasSufficientBalanceToken(address, tokenAddress, tokenAmount, chainId): Check token balance

Example Usage

useTokenBalances

Signature:
Return Type:
Token balances are returned as Token[] with balance fields populated. See the Token Type above for all available fields including balance, balanceFormatted, balanceDisplay, balanceUsd, etc.

useTokenBalancesForMultipleAccounts

Fetches token balances for multiple wallet addresses in a single API call. More efficient than calling useTokenBalances multiple times. Signature:
Return Type:
Example:

Quotes and Swapping

useQuote Hook

The useQuote hook provides real-time quotes for token swaps, cross-chain transfers and ability to pass in calldata for executions - enabling you to use Trails headlessly. from.amount and to.amount are human-readable decimal strings such as "1" or "0.25". Do not pass raw wei strings; the SDK scales amounts using the token decimals. Pass walletAddress to preview quotes before a wallet is connected. If a connected walletClient.account.address is available, it becomes the quote owner and takes precedence over walletAddress. Executing with send still requires a real wallet client.

Usage Example

Types

useTrailsSendTransaction Hook

useTrailsSendTransaction creates a button-driven transaction flow with the Trails modal. It accepts most useQuote options except from, to, walletClient, and selectedFeeOption; pass destination requirements when calling sendTransaction. tokenAmount and fromAmount are human-readable decimal strings. Native value remains a raw wei bigint, matching wagmi.

Types

Earn Markets and Providers

useEarnMarkets Hook

Fetch earn markets for lend and deposit actions. Use the returned market id as a marketId.

Types

useEarnProviders Hook

Fetch supported earn providers.

Types

useEarnBalances Hook

Fetch earn positions for a wallet. Use chain for one network or chains to batch multiple networks in one backend request.
Restrict the lookup to one market:

Types

useResolveActions Hook

Added in 0xtrails@0.16.0. Resolves an array of composable actions (lend, deposit, swap, assertCondition, custom) into the concrete Call[] you can pass to useTrailsSendTransaction or sign directly.

Types

Fiat & Exchange Rates

Added in 0xtrails@0.16.0. Use these to drive fiat-aware UI (currency selectors, USD-to-local-currency displays) without rolling your own pricing source.

useFiatCurrencyList

Returns the list of fiat currencies the Trails API supports for the fiat on-ramp flow. Backed by @tanstack/react-query.

useExchangeRate

Fetch the exchange rate between two currencies. Handles same-currency (returns 1) and direction inversion (e.g. EUR → USD inverts the USD → EUR rate).

Options

Onramp Providers

Added in 0xtrails@0.16.0. Use these to drive your own fiat on-ramp UI (e.g. payment method picker, exchange selector) outside the Trails widget. Backed by Mesh.

useMeldPaymentMethods

List the payment methods available for a given fiat currency (e.g. CREDIT_DEBIT_CARD, APPLE_PAY, GOOGLE_PAY, SEPA, PAYPAL).

useMeldServiceProviders

List the on-ramp service providers available, optionally filtered.

Constants

TRAILS_ROUTER_PLACEHOLDER_AMOUNT

This constant provides a placeholder value for amounts when encoding calldata in fund mode. It’s used to replace dynamic output amounts during contract execution. Use Case: When creating calldata for fund mode transactions where the final amount isn’t known until execution time, use this placeholder in your encoded function calls. The Trails system will replace it with the actual dynamic amount during contract execution. Example:
This pattern is essential for fund mode transactions where users choose their input amount, but the contract needs to receive the exact output amount after any swaps or bridging operations.

Transaction History

getAccountTransactionHistory

Gets transaction history for a wallet address interacting with Trails. Signature:
Usage:

useAccountTransactionHistory

Hook for fetching transaction history from a user’s wallet address for a specific chain.

Usage

Types

useIntentTransactionHistory

React hook for fetching transaction history for a specific intent address. Usage:

getTxTimeDiff

Gets the time difference for a transaction in human-readable format. Signature: (timestamp: string | number) => string Usage:

SDK Utilities

  • SDK_VERSION: Current SDK version string
  • getVersion(): Returns the current SDK version at runtime

FundMethod Type

FundMethod is exported as a strict union: "wallet" | "direct-transfer" | "onramp-mesh" | "onramp-meld".

Encoders

getERC20TransferData

Encodes ERC20 transfer calldata for token transfers. Signature: (params: { recipient: string, amount: bigint }) => string Usage:

Error Handling

Error Classes

InsufficientBalanceError

Error thrown when a user has insufficient balance to complete a transaction.

UserRejectionError

Error thrown when a user rejects a transaction in their wallet.

Error Detection Utilities

All error detection functions have the same signature: (error: unknown) => boolean

getPrettifiedErrorMessage

Converts any error into a user-friendly message string. Signature: (error: unknown) => string

Example: Comprehensive Error Handling

useGetIntent

Hook to fetch intent data from the Trails API.

Usage

Types

useIntentRecover

Hook for recovering funds from stuck or failed intent transactions. Trails automatically refunds upon reverting, but this hook handles situations where funds are stuck without an explicit revert. It automatically selects the intent address (origin or destination) with the highest balance for recovery.

Usage

Types

useIntentRecoverWithAddress

Recovery hook designed for apps that handle signing externally (e.g., embedded wallets, or custodial solutions). Unlike useIntentRecover which requires a walletClient, this hook accepts a plain walletAddress and exposes getDataToSign so you can sign the EIP-712 typed data with any signing method. Like useIntentRecover, it automatically selects the intent address (origin or destination) with the highest balance for recovery.

Usage

Types

Comparison with useIntentRecover

useCommitIntent / useExecuteIntent

Mutation hooks for committing and executing intents. These are lower-level hooks for advanced users who need direct control over the intent lifecycle.

useCommitIntent

useExecuteIntent

TrailsClient

For advanced use cases, you can access the underlying Trails API client directly.

useTrailsClient Hook

getTrailsClient Function

For non-React contexts:

Advanced: Intent Functions

These are advanced functions for direct intent management. Most developers should use the focused components or useQuote hook instead.

Types

calculateOriginAndDestinationIntentAddresses

Calculates both origin and destination intent addresses. Signature:
Usage:

commitIntent

Commits an intent to the blockchain. Signature: (params: CommitIntentParams) => Promise<CommitIntentResult> Usage:

sendOriginTransaction

Sends the origin transaction for an intent. Signature: (params: SendOriginTxParams) => Promise<string> Usage: