Skip to content

Swaps API

Functions for token swaps using 0x Protocol.

Get an indicative price for a token swap.

getPrice(params: GetSwapPriceParams): Promise<SwapPrice>
ParameterTypeRequiredDescription
takerAddressAddressYesAddress that will execute the swap
chainIdnumberYesChain ID (1, 137, or 8453)
tokenInAddressYesInput token address
tokenOutAddressYesOutput token address
sellAmountbigintYesAmount to sell in wei
slippageBps?numberNoSlippage tolerance in basis points (default: 100)
platformFeeBps?numberNoPlatform fee in basis points

Promise<SwapPrice> - Indicative price information.

{
tokenIn: Address;
tokenOut: Address;
sellAmount: bigint;
buyAmount: bigint;
priceImpact: number;
fees: SwapFee[];
allowanceTarget: Address;
gasEstimate: bigint;
gasEstimateUsd: number;
}
import { getPrice } from "cooperative";
import { parseEther } from "viem";
const price = await getPrice({
takerAddress: "0x...",
chainId: 1,
tokenIn: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", // ETH
tokenOut: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC
sellAmount: parseEther("1"), // 1 ETH
slippageBps: 50, // 0.5% slippage
});
console.log(`Expected output: ${price.buyAmount} USDC`);
console.log(`Price impact: ${price.priceImpact}%`);
  • Error: Unsupported chain - Chain ID not in [1, 137, 8453]
  • Error: Invalid address - Invalid token or taker address
  • Error: Slippage outside allowed range - Slippage < 0 or > 1000 BPS

Get a firm quote with transaction data.

getQuote(params: GetSwapQuoteParams): Promise<QuotePrice>

Same as GetSwapPriceParams.

Promise<QuotePrice> - Firm quote with transaction data.

{
tokenIn: Address;
tokenOut: Address;
sellAmount: bigint;
buyAmount: bigint;
minBuyAmount: bigint;
priceImpact: number;
fees: SwapFee[];
allowanceTarget: Address;
transaction: {
to: Address;
data: Hex;
value: bigint;
gas: bigint;
gasPrice: bigint;
};
}
import { getQuote } from "cooperative";
const quote = await getQuote({
takerAddress: "0x...",
chainId: 1,
tokenIn: ETH_ADDRESS,
tokenOut: USDC_ADDRESS,
sellAmount: parseEther("1"),
});
console.log(`Transaction to: ${quote.transaction.to}`);
console.log(`Gas estimate: ${quote.transaction.gas}`);

Validate a quote against a price to ensure it’s still acceptable.

validateQuoteAgainstPrice(
price: SwapPrice,
quote: QuotePrice,
tolerance?: QuoteAcceptabilityTolerance
): QuoteAcceptabilityResult
ParameterTypeDefaultDescription
maxPriceDeviationBpsnumber50Max price deviation in BPS (0.5%)
maxSlippageDeviationBpsnumber100Max slippage deviation in BPS (1%)
maxTimeDeltaMsnumber30000Max time between price and quote (30s)

QuoteAcceptabilityResult - Validation result.

{
acceptable: boolean;
reasons: string[];
metrics: QuoteAcceptabilityMetrics;
}
import { getPrice, getQuote, validateQuoteAgainstPrice } from "cooperative";
// Get price first
const price = await getPrice(params);
// User takes some time...
await new Promise((resolve) => setTimeout(resolve, 10000));
// Get quote
const quote = await getQuote(params);
// Validate
const result = validateQuoteAgainstPrice(price, quote);
if (!result.acceptable) {
console.error("Quote no longer valid:", result.reasons);
return;
}
// Quote is valid, proceed

Submit a quote transaction to the blockchain.

submitQuoteTransaction(chainId: number, quote: QuotePrice): Promise<`0x${string}`>

Promise<0x${string}> - Transaction hash.

import { submitQuoteTransaction } from "cooperative";
const txHash = await submitQuoteTransaction(1, quote);
console.log(`Transaction submitted: ${txHash}`);
// Wait for receipt
import { waitReceipt } from "cooperative";
const receipt = await waitReceipt({ hash: txHash, chainId: 1 });
  • Error: SDK is not configured - Forgot to call configureSetup()
  • Error: User rejected transaction - User cancelled in wallet
  • Error: Insufficient funds - Not enough balance for gas + value
import {
getPrice,
getQuote,
validateQuoteAgainstPrice,
submitQuoteTransaction,
waitReceipt,
} from "cooperative";
import { parseEther } from "viem";
async function executeSwap(
takerAddress: Address,
chainId: number,
tokenIn: Address,
tokenOut: Address,
amount: string,
) {
try {
// 1. Get indicative price
const price = await getPrice({
takerAddress,
chainId,
tokenIn,
tokenOut,
sellAmount: parseEther(amount),
});
// 2. Get firm quote
const quote = await getQuote({
takerAddress,
chainId,
tokenIn,
tokenOut,
sellAmount: parseEther(amount),
});
// 3. Validate quote
const validation = validateQuoteAgainstPrice(price, quote);
if (!validation.acceptable) {
throw new Error(`Quote invalid: ${validation.reasons.join(", ")}`);
}
// 4. Submit transaction
const txHash = await submitQuoteTransaction(chainId, quote);
console.log(`Transaction submitted: ${txHash}`);
// 5. Wait for confirmation
const receipt = await waitReceipt({ hash: txHash, chainId });
console.log(`Transaction confirmed in block ${receipt.blockNumber}`);
return receipt;
} catch (error) {
console.error("Swap failed:", error);
throw error;
}
}