Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/api2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ export * as util from "./util";
export * as eth from "./eth";
export * as erc20 from "./erc20";
export * as abi from "./abi/abi2";
export * as config from "./general";
export * as config from "./general";
4 changes: 4 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ test("imports", async () => {
"writeCache": [Function],
"writeExpiringJsonCache": [Function],
},
"coins": {
"getMcaps": [Function],
"getPrices": [Function],
},
"elastic": {
"addDebugLog": [Function],
"addErrorLog": [Function],
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export * as indexer from "./util/indexer";
export * as types from "./types";
export * as tron from "./abi/tron";
export * as erc20 from "./erc20";
export * as coins from "./util/coinsApi";

export const log = debugLog
export const logTable = debugTable
Expand Down
18 changes: 18 additions & 0 deletions src/util/coinsApi.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { getPrices, getMcaps } from "./coinsApi";

test("coinsApi - mcaps", async () => {
const res = await getMcaps(["coingecko:tether"], "now");
expect(res["coingecko:tether"].mcap).toBeGreaterThan(100_000);
expect(res["coingecko:tether"].mcap).toBeLessThan(1_000_000_000_000);
expect(res["coingecko:tether"].timestamp).toBeGreaterThan(Math.floor(Date.now() / 1e3 - 3600));
expect(Object.keys(res).length).toBe(1);
})

test("coinsApi - prices", async () => {
const res = await getPrices(["coingecko:tether", "ethereum:0xdac17f958d2ee523a2206206994597c13d831ec7", "solana:So11111111111111111111111111111111111111112"], "now");
expect(res["coingecko:tether"].price).toBe(1);
expect(res["ethereum:0xdac17f958d2ee523a2206206994597c13d831ec7"].symbol).toBe("USDT");
expect(res["ethereum:0xdac17f958d2ee523a2206206994597c13d831ec7"].decimals).toBe(6);
expect(Object.keys(res).length).toBe(3);
expect(res["solana:So11111111111111111111111111111111111111112"].timestamp).toBeGreaterThan(Math.floor(Date.now() / 1e3 - 3600));
})
172 changes: 172 additions & 0 deletions src/util/coinsApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import axios from "axios";
import { getEnvValue } from "./env";
import runInPromisePool from "./promisePool";

type CoinsApiData = {
decimals: number;
price: number;
symbol: string;
timestamp: number;
PK?: string;
};

type McapsApiData = {
mcap: number;
timestamp: number;
};

const coinsApiKey = getEnvValue("COINS_API_KEY")
const bodySize = 2; // 100;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this was test code should have reverted back to 100


function getBodies(readKeys: string[], timestamp: number | "now") {
const bodies: string[] = [];
for (let i = 0; i < readKeys.length; i += bodySize) {
const body = {
coins: readKeys.slice(i, i + bodySize),
} as any;
if (timestamp !== "now") body.timestamp = timestamp;
bodies.push(JSON.stringify(body));
}

return bodies;
}

function sleep(ms: number) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this we already have defined sleep somewhere else?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I cant find a timeout/sleep anywhere else in the codebase

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so, there was sleep already here

return new Promise((resolve) => setTimeout(resolve, ms));
}

async function restCallWrapper(
request: () => Promise<any>,
retries: number = 3,
name: string = "-"
) {
while (retries > 0) {
try {
const res = await request();
return res;
} catch {
await sleep(5_000 + 10_000 * Math.random());
restCallWrapper(request, retries--, name);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing await, and why both recursive call and a while loop, should have been one or the other

}
}
throw new Error(`couldnt work ${name} call after retries!`);
}

const priceCache: { [PK: string]: any } = {
"coingecko:tether": {
price: 1,
symbol: "USDT",
timestamp: Math.floor(Date.now() / 1e3 + 3600), // an hour from script start time
},
};

export async function getPrices(
readKeys: string[],
timestamp: number | "now"
): Promise<{ [address: string]: CoinsApiData }> {
if (!readKeys.length) return {};

const aggregatedRes: { [address: string]: CoinsApiData } = {};

// read data from cache where possible
readKeys = readKeys.filter((PK: string) => {
if (timestamp !== "now") return true;
if (priceCache[PK]) {
aggregatedRes[PK] = { ...priceCache[PK], PK };
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you read from the cache, but there is no code that sets to the cache

return false;
}
return true;
});

const bodies = getBodies(readKeys, timestamp);
const tokenData: CoinsApiData[][] = [];
await runInPromisePool({
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lot of code duplication between /prices and /mcaps call

items: bodies,
concurrency: 10,
processor: async (body: string) => {
const res = await restCallWrapper(() =>
axios.post(
`https://coins.llama.fi/prices?source=internal${coinsApiKey ? `?apikey=${coinsApiKey}` : ""
}`,
body,
{
headers: { "Content-Type": "application/json" },
params: { source: "internal", apikey: coinsApiKey },
},
)
);

const data = (res.data.coins = Object.entries(res.data.coins).map(
([PK, value]) => ({
...(value as CoinsApiData),
PK,
})
));

tokenData.push(data);
},
});

const normalizedReadKeys = readKeys.map((k: string) => k.toLowerCase());
tokenData.map((batch: CoinsApiData[]) => {
batch.map((a: CoinsApiData) => {
if (!a.PK) return;
const i = normalizedReadKeys.indexOf(a.PK.toLowerCase());
aggregatedRes[readKeys[i]] = a;
});
});

return aggregatedRes;
}

const mcapCache: { [PK: string]: any } = {};

export async function getMcaps(
readKeys: string[],
timestamp: number | "now"
): Promise<{ [address: string]: McapsApiData }> {
if (!readKeys.length) return {};

const aggregatedRes: { [address: string]: McapsApiData } = {};

// read data from cache where possible
readKeys = readKeys.filter((PK: string) => {
if (timestamp !== "now") return true;
if (mcapCache[PK]) {
aggregatedRes[PK] = { ...mcapCache[PK], PK };
return false;
}
return true;
});

const bodies = getBodies(readKeys, timestamp);
const tokenData: { [key: string]: McapsApiData }[] = [];
await runInPromisePool({
items: bodies,
concurrency: 10,
processor: async (body: string) => {
const res = await restCallWrapper(() =>
axios.post(
`https://coins.llama.fi/mcaps${coinsApiKey ? `?apikey=${coinsApiKey}` : ""
}`,
body,
{
headers: { "Content-Type": "application/json" },
}
)
);
tokenData.push(res.data as any);
},
});

const normalizedReadKeys = readKeys.map((k: string) => k.toLowerCase());
tokenData.map((batch: { [key: string]: McapsApiData }) => {
Object.keys(batch).map((a: string) => {
if (!batch[a].mcap) return;
const i = normalizedReadKeys.indexOf(a.toLowerCase());
aggregatedRes[readKeys[i]] = batch[a];
});
});

return aggregatedRes;
}
29 changes: 6 additions & 23 deletions src/util/computeTVL.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { sliceIntoChunks } from ".";
import { fetchJson, postJson, sumSingleBalance } from "./common";
import { sumSingleBalance } from "../generalUtil";
import { Balances } from "../types";
import { ENV_CONSTANTS } from "./env";
import { getPrices } from "./coinsApi";

type PricesObject = {
// NOTE: the tokens queried might be case sensitive and can be in mixed case, but while storing them in the cache, we convert them to lowercase
Expand Down Expand Up @@ -84,27 +83,11 @@ async function updatePriceCache(keys: string[], timestamp?: number) {

const missingKeys = keys.filter(key => !pricesCache[key.toLowerCase()])

const chunks = sliceIntoChunks(missingKeys, 100)
for (const chunk of chunks) {
const coins = await getPrices(chunk)
for (const [token, data] of Object.entries(coins)) {
pricesCache[token.toLowerCase()] = data
}
chunk.map(i => i.toLowerCase()).filter(i => !pricesCache[i]).forEach(i => pricesCache[i] = {})
const coins = await getPrices(missingKeys, timestamp ?? "now")
for (const [token, data] of Object.entries(coins)) {
pricesCache[token.toLowerCase()] = data
}

async function getPrices(keys: string[]) {
if (!timestamp) {
const { coins } = await fetchJson(`https://coins.llama.fi/prices/current/${keys.join(',')}`)
return coins
}

// fetch post with timestamp in body
const coinsApiKey = ENV_CONSTANTS['COINS_API_KEY']
const { coins } = await postJson("https://coins.llama.fi/prices?source=internal&apikey=" + coinsApiKey, { coins: keys, timestamp })
return coins
}

missingKeys.map(i => i.toLowerCase()).filter(i => !pricesCache[i]).forEach(i => pricesCache[i] = {})
}

function getPriceCache(timestamp?: number) {
Expand Down