How to use ThirdFi SWAP API in self-hosted backend

#BuidlWithThirdFi, Learn

Written by Ankit Singh

Swapping is the process of exchanging one token for another on a decentralized exchange (DEX). Swaps are facilitated by liquidity pools, which hold the tokens being traded. When a user wants to swap one token for another, they send the first token to the liquidity pool and receive the second token in return. The swap price is determined by the ratio of tokens in the liquidity pool, which changes as tokens are added or removed from the pool. The swap price is always based on the current market price of the tokens, and the user is charged a fee for the trade.

ThirdFi provides Swap API that creates a swap session where a user can swap their tokens by connecting their wallet. We currently support Metamask Wallet, WalletConnect, Crypto.com, OKX Wallet, KuCoin Wallet and Fluent Wallet.

 

How to use ThirdFi’s Swap API

  1. Create an account on https://app.thirdfi.org/ and you will be redirected to the dashboard like this below.
thirdfi dashboard

2. From the setting menu, select sandbox environment for testing purposes. You can do the same with ‘API setup’ instead of selecting ‘Sandbox’ environment.

creating API key sandbox environment

3. From the dashboard, click on ‘Create New Sandbox Key’ to get an API Key and the Secret. Save these keys and keep them secret as these will be used to make API calls.

 

4. Also, let’s setup a webhook to listen to any transaction event and get updates of the user transactions.
You can https://webhook.site to get a custom link to receive a webhook. You can also use your own site for the same and listen to the events.

ThirdFi will make a POST request to the link whenever a transaction is done.

5. Let’s try out the Swap API. Head over to the docs here to know more. Also, check out the API reference to know how to get started.

To create a swap session, we need to do a POST request to this API – https://sandbox.thirdfi.org/api/v1/sessions/swap with a required “body” in the request.

Below is the body for the same, here userEmail, tokenIn, tokenOut, amount and chain are the required fields and others are optional

{
    "tokenIn" :"USDC",
    "tokenOut": "WBTC",
    "amount": "10",
    "chain":"mumbai",
    "isNative": false,
    "slippagePercentage": "5",
    "exactIn": true,
    "userEmail": "USER_MAIL",
    "successURL": "https://app.thirdfi.org/",
    "cancelURL": "https://app.thirdfi.org/"
}

Let’s make an API call using NodeJS, you can find the code here.

 
import axios from “axios”;
import crypto from “crypto”
import moment from “moment”;
import dotenv from “dotenv”
dotenv.config()
let data = JSON.stringify({
“tokenIn” :“USDC”,
“tokenOut”: “WBTC”,
“amount”: “10”,
“chain”:“mumbai”,
“isNative”: false,
“slippagePercentage”: “5”,
“exactIn”: true,
“userEmail”: “USER_MAIL”,
“successURL”: “https://app.thirdfi.org/”,
“cancelURL”: “https://app.thirdfi.org/”
});
const URL = `https://sandbox.thirdfi.org/api/v1/sessions/swap`
const METHOD = ‘POST’
const timestamp = moment().unix()
let baseString = `${URL}&method=${METHOD}&timestamp=${timestamp}
&body=${JSON.stringify(JSON.parse(data))}`
const hash = crypto.createHmac(‘sha256’, process.env.SECRET)
.update(baseString).digest(‘hex’);
let config = {
method: METHOD,
maxBodyLength: Infinity,
url: URL,
headers: {
‘x-sec-key’: process.env.API_KEY,
‘x-sec-ts’: timestamp,
‘x-sec-sign’: hash,
‘Content-Type’: ‘application/json’
},
data: data
};
axios.request(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
 
 
To know about the API headers and library used, head over to this ThirdFi Getting Started Blog.
 

There are three API headers that are used in ThirdFi API requests and all of them are required to successfully make an API request. In Postman, we have already added a pre-script to load the API headers but we need to calculate them programmatically. The headers are:

  1. x-sec-key  : ‘API KEY’
  2. x-sec-ts     : ‘Timestamp’
  3. x-sec-sign : ‘Hash Value’

The Hash value is calculated using the HMAC-SHA-256 function which takes two inputs, one is the base string and the other is the SECRET key.

Result(after calling the API)

To run the code, you should have NodeJs installed and to run you have to run the below command

node path/to/the/code/file

result output of swap api

The highlighted session URL can be used for swapping, let’s try out requesting the API from Postman too. Afterwards, we will see how the swap session actually works.

 

Using Postman to Call Swap API

  1. Fork this Postman Workspace and add your API key and Secret to the ThirdFi environment. You have to fork it before making any request.

swap api postman 

2. If you have already forked and added the API keys, let’s make an API request now.

send request(swap api postman)

3. Check out the Response for the “URL” part.

response(swap api postman)

 

Testing out Swap session

  1. Open the link in the browser window.

wallet connect page

 

2. Connect your wallet on the page.

swap transaction page

 

3. Click on confirm the transaction and sign the transaction popped up on the wallet.

swap transaction confirmation page

 

4. Here is the transaction on the explorer.

swap transaction page - explorer

 

5. Developers can check about the transaction on their API dashboard too.

logged swap api

logged swap api

 

6. Remember, we have added a webhook on the dashboard at the start. ThirdFi must have triggered a POST event to the webhook URL.

Below is the https://webhook.site page that received the event. 

webhook site - swap

 

7. The triggered events on the webhook can also be tracked in the ThirdFi dashboard in the webhook logs.

 

All webhook events have an “eventType” in the JSON object. The event type can help the developers to know what transaction triggered the event. Also, the webhook event contains all these important details about transactions in the “data” field. Most importantly, the developers can make an update to the User based on the transaction data such as transactionHash, status and crypto amounts transferred.

Feel free to reach out to us on our Socials

Website | Twitter | Discord | Youtube | Linkedin 

Supercharge DeFi with ThirdFi⚡
Code, deploy & profit with ThirdFi

© ThirdFi 2023. All Rights Reserved.

Quick Links

Doc