Example: Quote With Fallback

This example shows an implementation for token swapping using the ParaSwap API, particularly focusing on getting a quote for a token swap and handling both Delta pricing and a fallback to market pricing when Delta fails.

Example:

import axios from 'axios';
import { ethers } from 'ethers';

const API_URL = "https://api.paraswap.io";

const chainId = 1; // Mainnet
const DAI_TOKEN = '0x6b175474e89094c44da98b954eedeac495271d0f';
const PSP_TOKEN = '0xcafe001067cdef266afb7eb5a286dcfd277f3de5';

async function quoteWithFallback() {
  // @ts-expect-error assume window.ethereum is available
  const ethersProvider = new ethers.providers.Web3Provider(window.ethereum);

  const accounts = await ethersProvider.listAccounts();
  const account = accounts[0]!;
  const signer = ethersProvider.getSigner(account);

  const amount = '100000000000000000000'; // 100 DAI

  const { data: quote } = await axios.get(`${API_URL}/quote`, {
    params: {
      chainId,
      srcToken: DAI_TOKEN,
      destToken: PSP_TOKEN,
      amount,
      userAddress: account,
      srcDecimals: 18,
      destDecimals: 18,
      mode: 'all', // Delta quote if possible, with fallback to Market price
      side: 'SELL',
    },
  });

  if ('delta' in quote) {
    // Delta pricing is available - we can build and submit a order
    const price = quote.delta;
    
    // build order
    const { data: builtOrder } = await axios.post(`${API_URL}/orders/build`, {
      price,
      chainId,
      owner: account,
    });
    
    // sign the order
    const signature = signer.signTypedData(
      builtOrder.domain,
      builtOrder.types,
      builtOrder.value,
    );
    
    // compact the signature
    const compactSignature = ethers.Signature.from(signature).compactSerialized;

    // submit the order
    const { data: deltaAuction } = await axios.post(`${API_URL}/orders`, {
      order: builtOrder.value,
      signature: compactSignature,
      // partner: '...' // if available
    });

    // poll if necessary
    const { data: auction } = await axios.get(`${API_URL}/orders/${deltaAuction.id}`);
    if (auction?.status === 'EXECUTED') {
      console.log('Auction was executed');
    }
  } else {
    // Delta pricing failed - falling back to market
    console.log(
      `Delta Quote failed: ${quote.fallbackReason.errorType} - ${quote.fallbackReason.details}`
    );
    const priceRoute = quote.market;

    // build transaction params
    const { data: txParams } = await axios.post(`${API_URL}/transactions/${chainId}`, {
      srcToken: DAI_TOKEN,
      destToken: PSP_TOKEN,
      srcAmount: amount,
      slippage: 100, // 1%
      priceRoute,
      userAddress: account,
      // partner: '...' // if available
    });

    // submit the transaction
    const swapTx = await signer.sendTransaction(txParams);
  }
}

Expected Behavior for Integrators:

When executed, this script:

  1. Connects to an Ethereum wallet.

  2. Retrieves the user's wallet address and prepares to swap 100 DAI for PSP tokens on Ethereum Mainnet (Chain ID: 1).

  3. Requests a quote from ParaSwap with the mode: "all", meaning it will prioritize Delta pricing but fall back to market pricing if Delta is unavailable.

  4. If Delta pricing is available, the script:

    • Builds an order for execution.

    • Signs the order using EIP-712 structured signing.

    • Submits the order for execution through the Delta auction system.

    • Polls the order status to confirm whether it was executed.

  5. If Delta pricing is not available, the script:

    • Logs the reason for the fallback.

    • Retrieves a market price route instead.

    • Builds a transaction using the market price.

    • Submits the transaction directly to the Ethereum network using the user's wallet.

This example ensures the swap execution is optimized for efficiency while providing a fail-safe fallback in case Delta pricing is unavailable. As a developer, you should expect a seamless experience for token swaps with automatic routing adjustments.

Last updated