Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TW-1416: BTC exchange rate #168

Merged
merged 3 commits into from
Aug 1, 2024
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
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@
import { getAliceBobOrderInfo } from './utils/alice-bob/get-alice-bob-order-info';
import { getAliceBobPairInfo } from './utils/alice-bob/get-alice-bob-pair-info';
import { getAliceBobPairsInfo } from './utils/alice-bob/get-alice-bob-pairs-info';
import { btcExchangeRateProvider, tezExchangeRateProvider } from './utils/coingecko';
import { CodedError } from './utils/errors';
import { coinGeckoTokens } from './utils/gecko-tokens';
import { getExternalApiErrorPayload, isDefined, isNonEmptyString } from './utils/helpers';
import logger from './utils/logger';
import { getSignedMoonPayUrl } from './utils/moonpay/get-signed-moonpay-url';
import { getSigningNonce } from './utils/signing-nonce';
import SingleQueryDataProvider from './utils/SingleQueryDataProvider';
import { tezExchangeRateProvider } from './utils/tezos';
import { getExchangeRates } from './utils/tokens';

const PINO_LOGGER = {
Expand Down Expand Up @@ -156,7 +156,7 @@
await redisClient.lpush('notifications', JSON.stringify(newNotification));

res.status(200).send({ message: 'Notification added successfully', notification: newNotification });
} catch (error: any) {

Check warning on line 159 in src/index.ts

View workflow job for this annotation

GitHub Actions / Checks if ts and lint works

Unexpected any. Specify a different type
res.status(500).send({ error: error.message });
}
});
Expand All @@ -175,6 +175,7 @@
});

app.get('/api/exchange-rates/tez', makeProviderDataRequestHandler(tezExchangeRateProvider));
app.get('/api/exchange-rates/btc', makeProviderDataRequestHandler(btcExchangeRateProvider));

app.get('/api/exchange-rates', async (_req, res) => {
const tokensExchangeRates = await getExchangeRates();
Expand Down Expand Up @@ -342,7 +343,7 @@
await startMagicSquareQuest(req.body);

res.status(200).send({ message: 'Quest successfully started' });
} catch (error: any) {

Check warning on line 346 in src/index.ts

View workflow job for this annotation

GitHub Actions / Checks if ts and lint works

Unexpected any. Specify a different type
console.error(error);

if (error instanceof CodedError) {
Expand All @@ -356,7 +357,7 @@
app.get('/api/magic-square-quest/participants', basicAuth, async (req, res) => {
try {
res.status(200).send(await getMagicSquareQuestParticipants());
} catch (error: any) {

Check warning on line 360 in src/index.ts

View workflow job for this annotation

GitHub Actions / Checks if ts and lint works

Unexpected any. Specify a different type
console.error(error);

if (error instanceof CodedError) {
Expand All @@ -370,10 +371,10 @@
app.get('/api/signing-nonce', (req, res) => {
try {
const pkh = req.query.pkh;
if (!pkh || typeof pkh !== 'string') throw new Error('PKH is not a string');

Check warning on line 374 in src/index.ts

View workflow job for this annotation

GitHub Actions / Checks if ts and lint works

Unexpected value in conditional. A boolean expression is required

res.status(200).send(getSigningNonce(pkh));
} catch (error: any) {

Check warning on line 377 in src/index.ts

View workflow job for this annotation

GitHub Actions / Checks if ts and lint works

Unexpected any. Specify a different type
console.error(error);

if (error instanceof CodedError) {
Expand Down
31 changes: 30 additions & 1 deletion src/utils/coingecko.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { range } from './helpers';
import { AxiosError } from 'axios';

import { isDefined, range } from './helpers';
import logger from './logger';
import { makeBuildQueryFn } from './makeBuildQueryFn';
import SingleQueryDataProvider from './SingleQueryDataProvider';

Expand Down Expand Up @@ -89,3 +92,29 @@ export const getMarketsBySymbols = async (symbols: string[]) => {

return chunks.flat();
};

const createCoingeckoExchangeRateProvider = (tokenSymbol: string) =>
new SingleQueryDataProvider(60000, async () => {
try {
const [market] = await getMarketsBySymbols([tokenSymbol]);

return market.current_price;
} catch (e) {
if (!(e instanceof AxiosError)) {
logger.error(`Request for ${tokenSymbol} exchange rate failed with unknown error`);
} else if (isDefined(e.response) && isDefined(e.response.data)) {
logger.error(
`Request for ${tokenSymbol} exchange rate failed with status ${e.response.status} and message ${e.response.data}`
);
} else if (isDefined(e.response) && isDefined(e.response.status)) {
logger.error(`Request for ${tokenSymbol} exchange rate failed with status ${e.response.status}`);
} else {
logger.error(`Request for ${tokenSymbol} exchange rate failed without response`);
}

throw e;
}
});

export const tezExchangeRateProvider = createCoingeckoExchangeRateProvider('xtz');
export const btcExchangeRateProvider = createCoingeckoExchangeRateProvider('btc');
29 changes: 0 additions & 29 deletions src/utils/tezos.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
import { compose, MichelCodecPacker, Signer, TezosToolkit } from '@taquito/taquito';
import { tzip12 } from '@taquito/tzip12';
import { tzip16 } from '@taquito/tzip16';
import { AxiosError } from 'axios';
import memoizee from 'memoizee';

import { getMarketsBySymbols } from './coingecko';
import { isDefined } from './helpers';
import logger from './logger';
import SingleQueryDataProvider from './SingleQueryDataProvider';
import { BcdTokenData } from './tzkt';

const RPC_URL = process.env.RPC_URL ?? 'https://mainnet-node.madfish.solutions';
Expand Down Expand Up @@ -54,30 +49,6 @@ export const getStorage = memoizee(
{ promise: true, maxAge: 30000 }
);

const getTezExchangeRate = async () => {
try {
const [xtzMarket] = await getMarketsBySymbols(['xtz']);

return xtzMarket.current_price;
} catch (e) {
if (!(e instanceof AxiosError)) {
logger.error('Request for TEZ exchange rate failed with unknown error');
} else if (isDefined(e.response) && isDefined(e.response.data)) {
logger.error(
`Request for TEZ exchange rate failed with status ${e.response.status} and message ${e.response.data}`
);
} else if (isDefined(e.response) && isDefined(e.response.status)) {
logger.error(`Request for TEZ exchange rate failed with status ${e.response.status}`);
} else {
logger.error('Request for TEZ exchange rate failed without response');
}

throw e;
}
};

export const tezExchangeRateProvider = new SingleQueryDataProvider(60000, getTezExchangeRate);

export class MetadataParseError extends Error {}

export const getTokenMetadata = memoizee(
Expand Down
2 changes: 1 addition & 1 deletion src/utils/tokens.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { BigNumber } from 'bignumber.js';

import { redisClient } from '../redis';
import { tezExchangeRateProvider } from './coingecko';
import { isDefined } from './helpers';
import logger from './logger';
import SingleQueryDataProvider, { SingleQueryDataProviderState } from './SingleQueryDataProvider';
import { tezExchangeRateProvider } from './tezos';
import {
getThreeRouteExchangeRates,
getThreeRouteTokens,
Expand Down Expand Up @@ -40,14 +40,14 @@
}

const exchangeRatesWithHoles = await Promise.all(
tokens!

Check warning on line 43 in src/utils/tokens.ts

View workflow job for this annotation

GitHub Actions / Checks if ts and lint works

Forbidden non-null assertion
.filter(
(token): token is ThreeRouteFa12Token | ThreeRouteFa2Token => token.standard !== ThreeRouteStandardEnum.xtz
)
.map(async (token): Promise<TokenExchangeRateEntry | undefined> => {
const { contract, tokenId: rawTokenId, symbol } = token;
const tokenId = isDefined(rawTokenId) ? Number(rawTokenId) : undefined;
const { ask, bid } = exchangeRatesInputs![symbol] ?? { ask: 0, bid: 0 };

Check warning on line 50 in src/utils/tokens.ts

View workflow job for this annotation

GitHub Actions / Checks if ts and lint works

Forbidden non-null assertion

if (ask === 0 && bid === 0) {
logger.error(`Failed to get exchange rate for token ${token.symbol}`);
Expand Down
Loading