Quote With Fallback

We recommend using Paraswap SDK for better developer experience. You can find SDK example of the exact functionality of this code here.

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);
  }
}

Last updated