Skip to content

JavaScript API

Reference for the TokenFlightWidget class. For the declarative (custom-element) API, see HTML Attributes.

TokenFlightWidget

The only supported public component. One class and one HTML tag cover swap and receive.

Constructor

js
const widget = new TokenFlightWidget({
  container: '#widget',
  config: {
    toToken: { chainId: 8453, address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' },
    tradeType: 'EXACT_OUTPUT',
    amount: '100',
    theme: 'dark',
  },
  walletAdapter: myAdapter,
  callbacks: {},
});

Config Properties

PropertyTypeDefaultDescription
toTokenTokenIdentifier | TokenIdentifier[]Destination token or token list
fromTokenTokenIdentifierOptional source token
tradeType'EXACT_INPUT' | 'EXACT_OUTPUT''EXACT_INPUT'Swap vs fixed-output receive
amountstringAmount value in human-readable units
theme'dark' | 'light' | 'auto''light'Widget color theme
localestring'en-US'Display locale
apiEndpointstring'https://api.hyperstream.dev'API endpoint
fiatApiEndpointstring'https://fiat.hyperstream.dev' when omittedFiat API endpoint
recipientstringCustom recipient address
recipientEditablebooleanfalseAllow the user to edit a preset recipient address
refundTostringAddress the filler should refund to if the fill fails
iconstringCustom icon URL for the target token
fromTokensTokenIdentifier[]Source token allowlist
toTokensTokenIdentifier[]Destination token allowlist
methodsArray<'crypto' | 'card'>['crypto']Payment methods to offer
defaultPayMethod'crypto' | 'card'In EXACT_INPUT swap mode, skip the method picker and open this tab first
lockFromTokenbooleanfalseLock the source token selector
lockToTokenbooleanfalseLock the destination token selector
quoteCard'hidden' | 'visible''hidden' in EXACT_INPUT, otherwise visibleControls the inline quote card in swap mode
rpcOverridesRecord<string, string>Decimal chain ID to RPC URL overrides
customColorsRecord<string, string>CSS color variable overrides
titleTextstringCustom widget title text
titleImageUrlstringCustom widget title image URL
hideTitlebooleanfalseHide the top title/header area
hidePoweredBybooleanfalseHide the footer
hideProviderbooleanfalseHide the provider name in order tracking
noBackgroundbooleanfalseRemove container background
noBorderbooleanfalseRemove container border and shadow
referrerstringReferrer address for fee attribution
referrerFeeBpsnumberReferrer fee in basis points

HTML Attributes

html
<tokenflight-widget
  theme="dark"
  locale="en-US"
  to-token="eip155:8453:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
  trade-type="EXACT_OUTPUT"
  amount="100"
  from-token="eip155:1:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
  csp-nonce="abc123"
></tokenflight-widget>
AttributeDescription
to-tokenDestination token in CAIP-10 or JSON format
trade-typeEXACT_INPUT or EXACT_OUTPUT
amountAmount value in human-readable units
theme'light', 'dark', or 'auto'
localeDisplay locale
from-tokenSource token in CAIP-10 or JSON format
api-endpointCustom Hyperstream API endpoint URL
fiat-api-endpointCustom fiat API endpoint URL
csp-nonceNonce for CSP-restricted environments

Instance Methods

MethodDescription
initialize()Mount and render the widget into the container
destroy()Unmount the widget and clean up widget DOM/resources. Destroy your wallet adapter separately if it exposes destroy()
setTheme(theme)Switch theme at runtime ('light', 'dark', 'auto')
setCustomColors(colors)Apply custom CSS color overrides at runtime
js
widget.initialize();
widget.setTheme('light');
widget.setCustomColors({ '--tf-primary': '#FF6B00', '--tf-bg': '#1A1A2E' });
widget.destroy();

Callbacks

Pass callbacks to widget lifecycle events:

js
const widget = new TokenFlightWidget({
  container: '#widget',
  config: {
    toToken: { chainId: 8453, address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' },
    tradeType: 'EXACT_OUTPUT',
    amount: '100',
    theme: 'dark',
  },
  callbacks: {
    onDepositSuccess: (data) => console.log('Success:', data),
    onDepositError: (data) => console.log('Error:', data),
    onQuoteReceived: (quote) => console.log('Quote:', quote),
    onAmountChanged: (data) => console.log('Amount:', data),
    onWalletConnected: (data) => console.log('Wallet:', data),
    onConnectWallet: () => openMyWalletModal(),
    onAccountModal: () => openMyAccountModal(),
    onFiatOrderCreated: (data) => console.log('Card order:', data.orderId),
    onFiatOrderCompleted: (data) => console.log('Card status:', data.status),
  },
});
CallbackPayloadDescription
onSwapSuccessSwapSuccessDataFired after a successful EXACT_INPUT swap
onSwapErrorSwapErrorDataFired when an EXACT_INPUT swap fails
onDepositSuccessSwapSuccessDataFired after a successful EXACT_OUTPUT receive or deposit
onDepositErrorSwapErrorDataFired when an EXACT_OUTPUT receive or deposit fails
onQuoteReceivedQuoteResponseFired when a new price quote is fetched
onAmountChangedAmountChangedDataFired when the user changes an editable amount
onWalletConnectedWalletConnectedDataFired when a wallet connects
onConnectWalletCalled when the user clicks "Connect Wallet" and no walletAdapter is provided
onAccountModalFallback when the user clicks the connected wallet address and the adapter has no openAccountModal()
onFiatOrderCreated{ orderId, widgetUrl }Fired when the fiat provider widget URL is ready
onFiatOrderCompleted{ orderId, status, txHash? }Fired when a fiat order reaches a terminal status

Callback Payload Types

ts
interface SwapSuccessData {
  orderId: string;
  fromToken: string;
  toToken: string;
  fromAmount: string;
  toAmount: string;
  txHash: string;
}

interface SwapErrorData {
  code: string;
  message: string;
  details?: unknown;
}

interface WalletConnectedData {
  address: string;
  chainType: string;
}

interface AmountChangedData {
  amount: string;
  direction: 'from' | 'to';
}

interface FiatOrderCreatedData {
  orderId: string;
  widgetUrl: string;
}

interface FiatOrderCompletedData {
  orderId: string;
  status: string;
  txHash?: string;
}

Custom Colors

Override any theme color via config or at runtime. Keys must be CSS variable names (--tf-*):

ts
widget.setCustomColors({
  '--tf-primary': '#FF6B00',
  '--tf-bg': '#1A1A2E',
  '--tf-text': '#FFFFFF',
});

The exported CustomColors type from @tokenflight/swap provides autocomplete for supported variables while still allowing custom --tf-* overrides. See Theming & Custom Colors for the common variables and full examples.


Token Identifiers

Three formats are accepted anywhere a TokenIdentifier is expected:

FormatExample
Object literal{ chainId: 1, address: '0xA0b8...' }
CAIP-10 string'eip155:1:0xA0b8...'
JSON string'{"chainId":1,"address":"0xA0b8..."}'

Use the zero address for native tokens:

  • EVM: 0x0000000000000000000000000000000000000000
  • Solana: 11111111111111111111111111111111

See Token Preselection for full details on supported chains and examples.