Skip to content

Commit

Permalink
feat: first cut at adding loan tvl endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
bvotteler committed Nov 29, 2023
1 parent 6ad7b83 commit cf7de3f
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
59 changes: 59 additions & 0 deletions api/tvl_loans.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { createInterBtcApi } from "@interlay/interbtc-api";
import { getCoingeckoId, getCoingeckoQueryUrl, getUsdMonetaryAmount } from "./currency-utils";

const tvlLoans = async (request, response) => {
if (request.method === 'GET') {
const interbtcApi = await createInterBtcApi(
process.env.REACT_APP_PARACHAIN_URL,
process.env.REACT_APP_BITCOIN_NETWORK,
undefined,
3
);

const loanAssets = await interbtcApi.loans.getLoanAssets();
const liquidityAmounts = Object.values(loanAssets).map((loanAsset) => loanAsset.totalLiquidity);

// dedupe ids
const coingeckoIds = new Set(
liquidityAmounts.map((monetaryAmount) => monetaryAmount.currency)
);
// base: usd, get price for all coingeckoIds
const queryUrl = getCoingeckoQueryUrl("usd", Array.from(coingeckoIds));
// return format: { <coingeckoId> : { <vs_id>: <price_as_number> }, ... }
// eg. {"bitcoin":{"usd":36478},"interlay":{"usd":0.0240072}}
const cgResponse = await fetch(queryUrl, { headers: { "accept": "application/json" } });
const cgData = await cgResponse.json();

const amounts = liquidityAmounts.map((monetaryAmount) => {
const atomicAmount = monetaryAmount.toString(true);
const amount = monetaryAmount.toString();

const cgId = getCoingeckoId(monetaryAmount.currency);
const usdPrice = (cgId != undefined && cgData[cgId] != undefined && cgData[cgId]["usd"] != undefined)
? cgData[cgId]["usd"]
: undefined;

const monetaryAmountUsd = usdPrice ? getUsdMonetaryAmount(monetaryAmount, usdPrice) : undefined;
const amountUsd = monetaryAmountUsd?.toString();
return {
currency: monetaryAmount.currency,
coingeckoId: cgId,
atomicAmount,
amount,
amountUsd
}
});

return response.status(200)
.setHeader("content-type", "application/json")
.setHeader("cache-control", "public, maxage=0, s-maxage=300")
.json(amounts);
} else {
return response.status(400).send('Bad Request');
}
}

export default async function (request, response) {
return tvlLoans(request, response);
}

8 changes: 8 additions & 0 deletions vercel.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
"api/tvl_dex.js": {
"memory": 256,
"maxDuration": 30
},
"api/tvl_loans.js": {
"memory": 256,
"maxDuration": 30
}
},
"rewrites": [
Expand All @@ -41,6 +45,10 @@
{
"source": "/tvl_dex",
"destination": "/api/tvl_dex.js"
},
{
"source": "/tvl_loans",
"destination": "/api/tvl_loans.js"
}
],
"headers": [
Expand Down

0 comments on commit cf7de3f

Please sign in to comment.