Using ThirdFi Borrow and Lending API in a self-hosted backend

Using ThirdFi Borrow and Lending API in a self-hosted backend

Using ThirdFi Borrow and Lending API in a self-hosted backend

Wednesday, May 10, 2023

ThirdFi is providing a one-stop solution with an all-in-1 API integration to help bridge the gap between traditional finance and the Web3 finance ecosystem. In this article, we will explore the features integrated into ThirdFi’s Borrow & Lend API with top-tier non-custodial loan markets.Here is the complete guide to the Decentralised Borrow and Lending. Currently, ThirdFi provides support for Aave and Venus Protocol. Aave is a decentralized non-custodial liquidity protocol that allows users to participate as depositors or borrowers. On the other hand, Venus Protocol is an algorithmic-based money market system that enables users to supply collateral to the network and borrow over-collateralized cryptocurrencies.

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

Let’s Get the list of supported tokensBelow is the list of the supported chains by ThirdFi API

A normal GET request can be done to the below API to get the list of supported tokens on ThirdFi.Mainnet
https://api.thirdfi.org/api/v1/web3/get-lending-pools?chain={CHAIN_NAME}Testnet
https://sandbox.thirdfi.org/api/v1/web3/get-lending-pools?chain={CHAIN_NAME}For example, to get supported tokens on Avalanche testnet, we have to put the chain name as “Fuji”. We can request the below URL to get the supported token list on the “Fuji” chain. You also don’t need any API Key or SECRET to make a GET request to this.https://sandbox.thirdfi.org/api/v1/web3/get-lending-pools?chain=fuji


Let’s Test out the Borrow and Lending API(with code)

Let’s make an API call using NodeJS, you can try running the same after getting the API key from the ThirdFi dashboard.

import axios from “axios”;
import crypto from “crypto”
import moment from “moment”;
import dotenv from “dotenv”
dotenv.config()
let data = JSON.stringify({
“userEmail”: “abc@test.com”,
“successURL”: “https://thirdfi.org”,
“cancelURL”: “https://thirdfi.org”,
“version”: 3,
“chain”: “fuji”,
“supplyAsset”: “USDC”,
“supplyAmount”: 10,
“borrowAsset”: “WETH”,
“borrowAmount”: 0.001,
“borrowInterestRateMode”: 2
});
const URL = `https://sandbox.thirdfi.org/api/v1/sessions/supplyAndBorrow`
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’, {{SECRET_KEY}})
.update(baseString).digest(‘hex’);
let config = {
method: METHOD,
maxBodyLength: Infinity,
url: URL,
headers: {
‘x-sec-key’: {{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 supply and borrow assets at the same time. Check out the API reference here.

 {
        "userEmail": "abc@test.com",
        "successURL": "https://thirdfi.org",
        "cancelURL": "https://thirdfi.org",
        "version": 3,
        "chain": "fuji",
        "supplyAsset": "USDC",
        "supplyAmount": 10,
        "borrowAsset": "WETH",
        "borrowAmount": 0.001,
        "borrowInterestRateMode": 2
}

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. If you haven’t please check out this Getting Started guide to learn more about the authentication and API part.


Result(after calling the API)

To run the code, you should have NodeJs installed and to run you have to run the below commandnode path/to/the/code/file



The highlighted session URL can be used for lending and borrowing Assets at the same time. Let’s try out requesting the API from Postman too. Afterwards, we will see how the borrowing and lending session works.


Using Postman to Call Borrow and Lending API

There are a lot of different APIs to customize the user experience and developers can build any app using the same.  below are the listed APIs under borrowing and lending API.You can test out all of them from our Postman Workspace.



Below are the POST requests that require a post body that contains the request data.

  1. The User can get Withdraw Collateral and claim rewards only if they have supplied the same assets before with “Supply Asset” API.

  2. The users who have borrowed assets can repay the debt.

  3. And, the users who supplied and borrowed assets can Repay the assets and withdraw their collateral from the pool. 

Also, the users can easily “get their pool position”(in different protocols) and “get unclaimed rewards” data by simply making a GET request to the ThirdFi API. It only requires the user’s wallet address to do the same.

Calling Lending/Supply Asset API

Let’s try the “Lending Asset” API using Postman. You can change the body as per the need. Here we will be borrowing 10 USDC on “mumbai” chain.

After clicking on the Send button, you will get a response with a session URL. Open the URL in the new tab to do the transaction.

Connect your wallet after opening the session.

Complete the transaction by clicking on the “Confirm” button and you will have to approve the transaction on your wallet. You will get the below page after the transaction is completed. 

You can also check the transaction on the block explorer.

Getting User Position in the Pool

To get the user position in the pool, just put in the user’s wallet address in the query parameters and hit Send button.

The API can be found in the Postman Workspace in Session -> Borrow and Lending -> get user position.

This will give back a response with all the assets on the different chain that the user have provided with the wallet address in a JSON format.

Claiming Rewards from the Pool

To Claim rewards, you can simply make a post request with a body containing the chain name and version(this is the Aave protocol version, supported by the chain).

Hit the send button to receive a response with a session URL.

Click on the link and after connecting your wallet you can claim rewards. Click on confirm to receive the reward accumulated on your assets.

NOTE: Rewards are accumulated over time and it won’t show up on the same day as it was provided.

Withdrawing Assets from the Pool

To withdraw any asset, you have to provide the Chain name, asset and the amount you want to withdraw.

This API can be found here: Session -> Borrow and Lending -> Withdraw Assets

Hit the send button to get the session URL in the response.

Click on the Session URL and connect the wallet.

Click on confirm and you can see your Asset getting back to your wallet in the Explorer and wallet.

Webhook Event

If you have added the webhook event on the ThirdFi dashboard, you can also receive a webhook to customize the user experience further.
Here is the webhook received after lending USDC to the pool.

Similarly, as we withdraw the amount, we will receive a withdraw event on our webhook too.


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 Borrow and Lending API and check out its working.

 

Below are more APIs included in Borrow and Lending API.

  1. Create Supply Session This API is used to create a supply session to supply (lend) assets to the protocol.

  2. Create Supply and Borrow Session – This API is used to create a single-click supply and borrow session for Aave.

  3. Create Withdraw Session – This API is used to create withdraw session to withdraw (exit) collateral assets from the protocol.

  4. Create Borrow Session – This API is used to create borrow session to borrow asset based on collateral assets from the protocol.

  5. Create Repay Session – This API is used to create repay session to repay debts to the protocol.

  6. Create Repay and Withdraw Session – This API is used to create a single-click repay and withdraw session.

  7. Claim Rewards – This API is used to create claim reward sessions from the protocol.

  8. Swap Borrow Rate Session – This API is used to create swap borrow rate mode session for Aave.

Try out the APIs from our Postman Workspace here.


Feel free to reach out to us on our Socials
Website | Twitter | Discord | Youtube | Linkedin 

Read More

Supercharge web3 with ThirdFi infra⚡

Supercharge web3 with ThirdFi infra⚡

Supercharge web3 with ThirdFi infra⚡

©ThirdFi 2024. All Rights Reserved.

©ThirdFi 2024. All Rights Reserved.

©ThirdFi 2024. All Rights Reserved.