Swap tokens

Build a token swap using the OpenSea API and SDK.

Use the OpenSea API to swap tokens across chains, with no manual bridging required. This guide covers getting a quote, executing the swap, and discovering tokens.

Prerequisites

Security Warning: Do not use the SDK in client-side code, since your API key would be exposed. Use it on a backend server and return transaction data to your frontend.

Setup

npm install @opensea/sdk viem
import { createPublicClient, createWalletClient, http } from "viem";
import { base } from "viem/chains";
import { OpenSeaSDK, Chain } from "@opensea/sdk/viem";

const publicClient = createPublicClient({ chain: base, transport: http("https://your-rpc-url") });
const walletClient = createWalletClient({ chain: base, transport: http("https://your-rpc-url"), account: "0x..." });

const sdk = new OpenSeaSDK(
  { publicClient, walletClient },
  { chain: Chain.Base, apiKey: "YOUR_API_KEY" },
);

The examples below use viem. The SDK also supports ethers.js (v6+); see Buy and sell NFTs for the ethers setup. All SDK methods work the same with either library.

Step 1: Discover tokens

Before swapping, you can discover which tokens are available using the trending and top token endpoints.

SDK

// Get trending tokens (ranked by OpenSea's trending score)
const trending = await sdk.api.tokens.getTrendingTokens();
console.log(trending);

// Get top tokens by volume
const top = await sdk.api.tokens.getTopTokens();
console.log(top);

curl

# Trending tokens
curl -X GET "https://api.opensea.io/api/v2/tokens/trending" \
  -H "X-API-KEY: YOUR_API_KEY"

# Top tokens
curl -X GET "https://api.opensea.io/api/v2/tokens/top" \
  -H "X-API-KEY: YOUR_API_KEY"

Step 2: Check your balance

Confirm your wallet holds enough of the source token.

SDK

const balances = await sdk.api.accounts.getAccountTokens("0xYOUR_WALLET_ADDRESS");
console.log(balances);

curl

curl -X GET "https://api.opensea.io/api/v2/account/0xYOUR_WALLET_ADDRESS/tokens" \
  -H "X-API-KEY: YOUR_API_KEY"

Step 3: Get a swap quote

Request a quote to see raw token amounts, price and costs in USD, price impact, slippage settings, and the transaction data needed to execute the swap.

Parameters:

ParameterDescription
from_chainSource chain slug (e.g. base or solana)
from_addressToken contract address to sell (use 0x0000000000000000000000000000000000000000 for native ETH)
to_chainDestination chain slug (use a different chain for a cross-chain swap)
to_addressToken contract address to buy
quantityAmount to swap in the token's smallest unit, as an integer string (wei for ETH: 20000000000000000 is 0.02 ETH)
addressYour wallet address (the taker)
slippage(Optional) Slippage tolerance from 0.0 to 0.5. Defaults to 0.01
recipient(Optional) Address that receives the bought tokens. Defaults to address

Use Get supported chains to discover chain identifiers and swap support. Chain support does not guarantee a route for every token pair or amount.

For native SOL, set the chain to solana and the token address to 11111111111111111111111111111111. Use lamports for quantity: 10000000 is 0.01 SOL. Wrapped SOL uses its mint address, So11111111111111111111111111111111111111112, instead. SPL tokens use their mint addresses and smallest token units.

The SDK takes these parameters in camelCase (fromChain, fromAddress, toChain, toAddress). The raw REST endpoint shown in the curl example uses the snake_case names above.

SDK

const quote = await sdk.api.tokens.getSwapQuote({
  fromChain: "base",
  fromAddress: "0x0000000000000000000000000000000000000000", // native ETH
  toChain: "base",
  toAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base
  quantity: "20000000000000000", // 0.02 ETH in wei
  address: "0xYOUR_WALLET_ADDRESS",
});

console.log("Quote:", quote);
// quote.transactions contains the transaction(s) to execute

curl

curl -X GET "https://api.opensea.io/api/v2/swap/quote?\
from_chain=base&\
from_address=0x0000000000000000000000000000000000000000&\
to_chain=base&\
to_address=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913&\
quantity=20000000000000000&\
address=0xYOUR_WALLET_ADDRESS" \
  -H "X-API-KEY: YOUR_API_KEY"

The response includes a transactions array. Each transaction contains:

  • chain: the chain to submit the transaction on
  • to: the target contract address (null for Solana transactions, which carry their instructions in svm instead)
  • data: hex-encoded calldata for EVM transactions; use svm.instructions for Solana
  • value: native token value to send (if any)

Quote amounts and fees

quote.routes lists successful routes in execution order. Each route identifies its input and output with from_chain, from_address, to_chain and to_address. from_quantity and to_quantity are raw input and expected output amounts, encoded as decimal integer strings. Keep these values as strings or arbitrary-precision integers when parsing them. For routes with intermediate swaps, do not add intermediate outputs to the final amount received.

min_to_quantity is the provider-reported minimum output in raw token units, or null when unavailable. It is not independently decoded from the transaction and does not describe the net wallet change after separately charged fees. The slippage percentage and USD totals also do not establish an exact onchain minimum.

quote.costs separates marketplace, provider and other costs in USD. For Solana, svm.marketplace_fee_transfer reports the OpenSea fee transfer when available: its raw_amount, token_address, native_token, decimals, destination recipient, optional SPL recipient_owner, and settlement. Native SOL uses the same 11111111111111111111111111111111 address as the request. An SPL recipient is a token account; recipient_owner identifies its owner.

A separate_transfer settlement means a separate instruction transfers the fee. It does not say whether the funds came from the swap output. unknown means the server did not report a recognized settlement. Missing or null metadata means unreported, not zero fees, and this field excludes provider fees and total transaction costs. Provider fees can come from the swapped input or output. Keep enough SOL for network fees and separate transfers; sponsored flows can use a payment token.

REST execution options

Pass these optional fields as query parameters to Get swap quote, or as JSON body fields to Execute swap.

FieldBehavior
transaction_formatinstructions (default) returns raw Solana instructions. serialized also returns an unsigned v0 transaction with blockhash expiry metadata.
single_transaction_onlytrue rejects the selected route unless it is one direct same-chain transaction. Defaults to false.
swap_providerjupiter requires Jupiter for a swap with one Solana input and one Solana output. The request fails if Jupiter cannot provide an eligible route.
compute_unit_limitInteger from 1 to 1400000, subject to server limits. Sets the exact compute limit.
compute_unit_price_micro_lamportsNonnegative decimal integer string. Sets the exact compute price; "0" disables the priority fee.
jito_tip_lamportsNonnegative decimal integer string, subject to server tip limits. "0" requests no canonical Jito tip. A positive amount requires Jito bundle submission.

Compute and tip controls support self-funded, unsigned same-chain Solana v0 swaps. Unsupported transactions and budgets above server limits are rejected. Omitted compute components use existing defaults when available; unresolved budgets are rejected. Quoted network fees remain estimates, and route ranking is not recalculated after the final compute budget is applied.

An explicit tip requires one unsigned swap transaction. The API uses canonical Jito tip accounts and rejects routes with conflicting tips. A zero tip rejects routes that still require a tip or bundle. A positive tip is incompatible with single_transaction_only. If you are building for a user, get approval for the exact quote before signing or submitting. When svm.requires_jito_bundle is true, submit the signed transaction as a Jito bundle.

The single-transaction option checks the selected route; it does not retry other providers to find an eligible route. It rejects extra actions, relayer fulfillment, bundles and unsupported signing requirements with SINGLE_TRANSACTION_UNAVAILABLE. Never discard returned transactions to force a route into one transaction.

Jupiter selects its downstream venues and programs. Review the returned instructions and accounts before signing.

Step 4: Execute the swap

Use the transaction data from the quote response to submit the swap onchain. This example uses viem, so it submits EVM transactions only. A Solana transaction has to: null and carries its instructions in svm, which you submit with a Solana client instead.

import type { Address, Hex } from "viem";

for (const tx of quote.transactions) {
  if (!tx.to) {
    throw new Error(`Transaction on ${tx.chain} is not EVM: submit tx.svm with a Solana client`);
  }

  const hash = await walletClient.sendTransaction({
    to: tx.to as Address,
    data: tx.data as Hex,
    value: tx.value ? BigInt(tx.value) : 0n,
  });

  console.log("Transaction hash:", hash);
  const receipt = await publicClient.waitForTransactionReceipt({ hash });
  console.log("Confirmed in block:", receipt.blockNumber);
}

Solana transactions

Both the quote endpoint and execute endpoint return transaction data for your wallet to sign and submit. Calling the execute endpoint does not broadcast a signed transaction.

For each Solana entry in transactions, use its svm object. With transaction_format=serialized, svm.serialized_transaction is a base64-encoded unsigned v0 transaction. Deserialize and review it, then sign without rebuilding the message. svm.blockhash is the embedded recent blockhash, and svm.last_valid_block_height is its last valid block height, not a slot or timestamp. Request a fresh quote after expiry. Serialization supports unsigned wallet-funded transactions and rejects additional signer requirements.

With the default transaction_format=instructions, compile the transaction yourself:

  1. Convert svm.instructions into your Solana client's instruction type, preserving instruction and account order. Map program_id to the program public key and each account's pubkey, signer and writable fields to the corresponding account metadata. Instruction data is hex, optionally prefixed with 0x.
  2. Fetch the lookup table accounts listed in svm.address_lookup_tables. These are addresses, not the resolved table contents.
  3. Fetch a recent blockhash and its last valid block height from your Solana RPC. Compile a v0 message using svm.from as the fee payer, the returned instructions and the resolved lookup tables. A v0 compiler ignores svm.transaction_config, which is metadata for v1 compilation.
  4. Review the compiled transaction and sign it with the required signer accounts. Submit it as a Jito bundle when svm.requires_jito_bundle is true; otherwise use your Solana RPC. Track confirmation and blockhash expiry before retrying, so a delayed confirmation does not cause a duplicate trade.

Both formats retain the returned instructions. In addition to the provider swap, these can include compute-budget settings, token-account setup, an OpenSea attribution memo, separate marketplace-fee or Jito-tip transfers, and cleanup. Creating a token account can require a rent deposit. marketplace_fee_transfer identifies the reported OpenSea fee, not every transfer in the transaction. Verify each remaining instruction by its program, accounts and decoded data rather than treating an extra transfer as a fee by position.

Preserve all instructions when compiling. If a response contains several transactions, process them in order.

Provider programs

DFlow v4 uses program ID DF1ow4tspfHX9JwWJsAb9epbkA8hmpSEAtxXy1V27QBH; see the DFlow v4 program reference. Verify all programs and accounts in the returned instructions for the selected route. The swap_provider label, including RELAY, is not a program ID or a complete instruction allowlist.

Checking a program ID alone does not verify the recipient, token amounts or enforced minimum output. Use a decoder for the specific program version when checking instruction fields; this guide does not specify minimum-output byte offsets.

Cross-chain swaps

Cross-chain swaps work the same way. Specify a different toChain and the API handles bridging automatically.

const crossChainQuote = await sdk.api.tokens.getSwapQuote({
  fromChain: "ethereum",
  fromAddress: "0x0000000000000000000000000000000000000000",
  toChain: "base",
  toAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
  quantity: "100000000000000000", // 0.1 ETH in wei
  address: "0xYOUR_WALLET_ADDRESS",
});

Cross-chain swaps may return multiple transactions (e.g. an approval and a bridge transaction). Execute them in order.

CLI

The OpenSea CLI supports swap quotes directly. Unlike the API, it accepts a decimal --quantity and converts it to the token's smallest unit:

opensea swaps quote \
  --from-chain base \
  --from-address 0x0000000000000000000000000000000000000000 \
  --to-chain base \
  --to-address 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 \
  --quantity 0.02 \
  --address 0xYOUR_WALLET_ADDRESS

Rate limits and route failures

Use the X-RateLimit-* response headers to track your available request budget. On 429, wait for Retry-After before trying again. Limits depend on the API key category; self-serve swap requests may also share an IP-based budget across quote and execute. See API keys for limit and upgrade guidance.

A failed quote can include route_errors; inspect the returned error types before retrying. A token's presence in discovery results does not guarantee an executable route. DFlow lists Pump.fun among its liquidity venues, but that does not guarantee an OpenSea route for every new token. Request a quote for the exact mint, direction and amount you intend to trade.

Next steps