feat: add get latest prices

This commit is contained in:
Kyle Fang
2023-04-24 11:48:40 +08:00
parent c61ca39bae
commit c2aa23cb57
2 changed files with 46 additions and 0 deletions

View File

@@ -9,6 +9,7 @@ import {
defaultReadonlyCallExecutor,
ReadonlyCallExecutor,
} from './utils/readonlyCallExecutor';
import { fetchLatestPrices } from './utils/currencyPrice';
export class AlexSDK {
constructor(
@@ -64,4 +65,12 @@ export class AlexSDK {
getCurrencyFrom(address: string): Currency | undefined {
return findCurrencyByNativeAddress(address);
}
getLatestPrices(): Promise<
Partial<{
[currency in Currency]: number;
}>
> {
return fetchLatestPrices();
}
}

View File

@@ -0,0 +1,37 @@
import { Currency } from '../currency';
export async function fetchLatestPrices(): Promise<
Partial<{
[currency in Currency]: number;
}>
> {
const res = await fetch('https://gql.alexlab.co/v1/graphql', {
body: JSON.stringify({
query: `
query FetchLatestPrices {
laplace_current_token_price {
avg_price_usd
token
}
}
`,
}),
}).then((a) => a.json());
const result: Partial<{ [currency in Currency]: number }> = {};
for (const value of Object.values(Currency)) {
const external = res.data.laplace_current_token_price.find(
(a: any) => a.token === value + '-external' && a.avg_price_usd != null
);
if (external) {
result[value] = external.avg_price_usd!;
} else {
const nonExternal = res.data.laplace_current_token_price.find(
(a: any) => a.token === value && a.avg_price_usd != null
);
if (nonExternal) {
result[value] = nonExternal.avg_price_usd!;
}
}
}
return result;
}