Using ThirdFi Index Funds API in a self-hosted backend

#BuidlWithThirdFi, Learn

Written by Ankit Singh

ThirdFi presents Invest API with DeFi Index Funds with top cryptocurrencies in decentralized finance. These funds employ an indexing investment approach carefully designed to track the performance of the major cryptocurrencies with respective themes.ThirdFi presents Invest API with DeFi Index Funds with top cryptocurrencies in decentralized finance. These funds employ an indexing investment approach carefully designed to track the performance of the major cryptocurrencies with respective themes.

If you are new to building with ThirdFi API, check out the ThirdFi Developer Guide and get your API keys from the Developer Dashboard.

How to get ThirdFi’s API Key

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.

 
 

Setting up Webhook

Let’s set up a webhook to listen to any transaction event and get updates on the user transactions. The Webhook setup page can be found at ThirdFi Dashboard -> Settings -> Webhooks. Make sure to tick the Sandbox option if you want to receive it for the sandbox transaction.

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.

 

Now, let’s try out the Index Fund API. Head over to the docs here to know more. Also, check out the API reference to know how to get started.

Let’s Test out the Index Funds API

Let’s make an API call using NodeJS, you can try running the same after getting the API key from the ThirdFi dashboard. Let’s start by getting the list of Index funds Products using ThirdFi’s API. 

Developers can fetch the supported Index Funds by making a GET request to this URL – https://api.thirdfi.org/api/v1/product/get-product.

There are three API headers that are used in ThirdFi API requests and all of them are required to successfully make an API request. 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. If you haven’t please check out this Getting Started guide to learn more about the authentication and API part.

Let’s try getting the Index Fund Products using the get-product API
 
 
import axios from “axios”;
import crypto from “crypto”
import moment from “moment”;
import dotenv from “dotenv”
dotenv.config()
 
 
const URL = `https://sandbox.thirdfi.org/api/v1/product/get-products`
const METHOD = ‘GET’
const timestamp = moment().unix()
 
// baseString updates with timestamp
let baseString = `${URL}&method=${METHOD}&timestamp=${timestamp}`
 
// Create hash based on baseString
const hash = crypto.createHmac(‘sha256’, process.env.SECRET)
.update(baseString).digest(‘hex’);
 
// API Call using axios
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);
});
 
 
The code can be run using NodeJS from the terminal. You can try running the below code after installing NodeJS on your computer system.
node /path/to/file
You will receive a JSON response containing the details of all the Index Fund Products provided by ThirdFi. Below is the response for the same.
 
 
There are two products provided by Index Fund API – MWI(Market Weighted Index) and LCI(Low-Risk Crypto Index). MWI and LCI are best for long-term investment but both have different token distributions.
 
You can also try getting the Pool Value and Price of the funds by changing the Base URL.
 
MWI Token Distribution(on Avalance network)
 
LCI Token Distribution(on Binance Network)

But before we can create a Index Fund session we have to create a customer using our API credentials. Creating a customer is easy, we can make a POST request to the Customer’s API with just a valid email address. Below is the NodeJS code for the same, it will create a new customer with “abc@gmail.com”. The user account will also be visible to the developer on the ThirdFi developer dashboard under the Customer section.

 
import axios from “axios”;
import crypto from “crypto”
import moment from “moment”;
import dotenv from “dotenv”
dotenv.config()
 
// bodyData is required for POST request
let data = JSON.stringify({
“emailAddress”: abc@gmailcom,
});
 
const URL = `https://sandbox.thirdfi.org/api/v1/customers`
const METHOD = ‘POST’
const timestamp = moment().unix()
 
// baseString updates with timestamp
let baseString = `${URL}&method=${METHOD}&timestamp=${timestamp}
&body=${JSON.stringify(JSON.parse(data))}`
 
// Create hash based on baseString
const hash = crypto.createHmac(‘sha256’, process.env.SECRET)
.update(baseString).digest(‘hex’);
 
// API Call using axios
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);
});
 
 

The Customer will be created once you run the above code using nodeJS

 

Now, let’s try creating an index fund session by making a POST request to this URL – https://sandbox.thirdfi.org/api/v1/sessions. We will need a product(MWI or LCI), type(deposit or withdraw), amount and User Mail address. "successfulURL" and "cancelURL" can be used to redirect users after the transaction and it’s optional.

 
import axios from “axios”;
import crypto from “crypto”
import moment from “moment”;
import dotenv from “dotenv”
dotenv.config()
 
// bodyData is required for POST request
let data = JSON.stringify({
“product”: “MWI”,
“type”: “deposit”,
“amount”: 10,
“userEmail”: USER_MAIL,
“successURL”: “https://app.thirdfi.org/”,
“cancelURL”: “https://app.thirdfi.org/”
});
 
const URL = `https://sandbox.thirdfi.org/api/v1/sessions`
const METHOD = ‘POST’
const timestamp = moment().unix()
 
// baseString updates with timestamp
let baseString = `${URL}&method=${METHOD}&timestamp=${timestamp}
&body=${JSON.stringify(JSON.parse(data))}`
 
// Create hash based on baseString
const hash = crypto.createHmac(‘sha256’, process.env.SECRET)
.update(baseString).digest(‘hex’);
 
// API Call using axios
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);
});
 
 
Below is the body used for making a POST request to create an Index Fund session to invest in a specific index fund pool. Check out the API reference here.
 
    {
        "product": "MWI",
        "type": "deposit",
        "amount": 10,
        "userEmail": USER_MAIL,
        "successURL": "https://app.thirdfi.org/",
        "cancelURL": "https://app.thirdfi.org/"
    }

Result(after calling the Index Funds 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

Click on the session URL and connect your wallet on the webview session.

After connecting the wallet, you can do the transaction by clicking on the Confirm button. The wallet will pop up for confirming the transaction(here for 10 USDT).

The completed page will be shown once the transaction is done.

You can also check your transaction on the Block Explorer. MWI takes USDT and in return, it will provide MWI tokens to the user. The MWI tokens can be withdrawn back by the user and they can get back the token benefits.

Using Postman to Call Index Funds API’s

There are a lot of different APIs to customize the user experience and developers can build any app using the same. We have provided the APIs in the Postman Workspace so that developers can test out the same without even coding.

For testing, add the API key and Secret key as environment variables in the forked Postman workspace.

You can test out all of them from our Postman Workspace. Below are the listed APIs under Index API.

Webhook Event

Remember we have added the webhook event on the ThirdFi dashboard, developers can receive a webhook so that developers can customize the user experience further. Here is how you can set up webhook on the dashboard.

Here is the webhook received for `Depositing 10 USDT with MWI using ThirdFi API.

Hope you find the blog useful. Check out our docs here to know more. Also, here is the API reference to learn more about the Index Funds API and check out its working.

Try out the APIs from our Postman Workspace here.

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