Skip to main content
The Swap component handles cross-chain token exchanges. It supports exact-input (user specifies how much to spend) and exact-output (user specifies how much to receive) modes, and automatically routes across bridges and DEXs for the best price.

Basic usage

import { Swap } from "0xtrails";

<Swap
  apiKey="YOUR_API_KEY"
  from={{
    token: "ETH",
    chain: "ethereum",
  }}
  to={{
    token: "USDC",
    chain: "polygon",
  }}
  onSwapSuccess={(result) => console.log("Swapped:", result)}
/>

Exact input vs. exact output

// Exact input: user spends a fixed amount, output varies
<Swap
  apiKey="YOUR_API_KEY"
  from={{ token: "ETH", chain: "ethereum", amount: "0.1" }}
  to={{ token: "USDC", chain: "polygon" }}
/>

// Exact output: user receives a fixed amount, input varies
<Swap
  apiKey="YOUR_API_KEY"
  from={{ token: "ETH", chain: "ethereum" }}
  to={{ token: "USDC", chain: "polygon", amount: "200" }}
/>

Headless with useQuote

To build your own UI and manage quote refresh yourself:
import { useQuote } from "0xtrails";

const { quote, loading, refetch } = useQuote({
  from: {
    chainId: 1,
    tokenAddress: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // WETH
    amount: "0.1",
  },
  to: {
    chainId: 137,
    tokenAddress: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", // USDC on Polygon
    recipient: "0xUSER_WALLET",
  },
  onStatusUpdate: (status) => console.log("Status:", status),
});

// Refresh quote every 30 seconds
useEffect(() => {
  const interval = setInterval(refetch, 30_000);
  return () => clearInterval(interval);
}, [refetch]);

Props reference

PropTypeRequiredDescription
apiKeystringYesYour API key
from.tokenstringNoSource ERC20 symbol or address
from.chainstring | numberNoSource chain
from.amountstringNoAmount to spend (exact input)
to.tokenstringNoDestination ERC20 symbol or address
to.chainstring | numberNoDestination chain
to.amountstringNoAmount to receive (exact output)
slippageTolerancestring | numberNoSlippage tolerance; default from provider config
swapProviderstringNoPreferred DEX provider
bridgeProviderstringNoPreferred bridge provider
paymentMethodstringNoPre-select funding method
onSwapStartfunctionNoCalled when the user begins
onSwapSuccessfunctionNoCalled on completion
onSwapErrorfunctionNoCalled on failure
For appearance and wallet options, see SDK configuration.