Token Swaps

Use Etherspot to fetch Exchange offers between pairs

Before we continue, please ensure that you have had a look at our Supported Ethereum Chains, followed the steps in Install Etherspot SDK and how to Bootstrap Etherspot SDK. We're assuming that you have completed these steps before going forward.

In this example, we're going to show you how to exchange tokens using the Etherspot Exchange. The Etherspot Exchange gives the ability for your users of your dApp or service to take advantage of swapping tokens and using different tokens as needed.

🛑 Before we continue...

Whilst the Etherspot Exchange service returns exchange offers on multiple chains, the service does not facilitate swaps from one chain to another. For that, you need to use an official "bridge" service.

We're going to be using one Etherspot SDK instance here:

  • A mainnet Etherspot SDK to receive our offers. For the purposes of this guide, we're going to assume the variable is called mainnetEtherspotSdk.

When using a different network for the SDK like Polygon or Binance Smart Chain - token swap offers will be returned for their respective chains.

We also need to ensure that we have the Ethers library installed and available to use:

import { utils as EthersUtils } from 'ethers';

Supported chains and exchanges

Currently, we support following chains and exchanges.

⛓️ Mainnet

  • 1inch

  • Synethetix

  • Uniswap

  • Sushiswap

⛓️ Polygon, formerly known as MATIC:

  • 1inch

  • Sushiswap

⛓️ Binance Smart Chain

  • 1inch

  • Sushiswap

⛓️ xDai

  • Sushiswap

Searching for swap offers

To start a search for token swap offers, we need to call the getExchangeOffers method with our desired token and amount parameters as illustrated below.

// DAI
const fromToken = {
  address: '0x6B175474E89094C44Da98b954EedeAC495271d0F',
  decimals: 18,
}

// USDC
const toToken = {
  address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
  decimals: 6,
}

// Amount requested to swap
const fromAmountEthers = EthersUtils
  .parseUnits(
    '1.5', // Amount in ethers
    fromToken.decimals
  );

// Returns an array of offers, if any.
const tokenSwapOffers = await mainnetEtherspotSdk
  .getExchangeOffers({
    fromTokenAddress: fromToken.address,
    toTokenAddress: toToken.address,
    fromAmount: fromAmountEthers
  });

When getExchangeOffers is executed, you will receive an array of 0 or more offers based on your swap request. For each item in the array, this data object is returned:

Property

Meaning

exchangeRate

The rate that is being returned by the exchange

provider

Who is providing this swap offer

receiveAmount

The total amount due to be received

transactions

An array of required transactions to execute this swap

You can now execute the Transactions in a chosen exchange offer to perform the desired Token Swap.

🎉 Finished!

Last updated