import axios from "axios"; import { Token } from "../Tokens"; import { ChainId, WALLET_SERVICE_URL } from "../constants"; import { tryParseTokenAmount } from "../utils"; import { isTokenSwap, isTokenTransfer, TokenSwapTransaction, TokenTransactionBase, TokenTransferTransaction, } from "./types"; /** * * Fetches transactions for a given wallet, and classifies them based by their type. When applicable, includes the equivalent * value of a transaction in local currency at the time of transaction. * * @param walletAddress Wallet to fetch transactions for * @param chain Chain Id to get transactions for * @param getToken Helper to turn an address into a Token * @param opts Optional paramter to set page, number of txns per page, and the local currency * @returns A list of transactions parsed into a useable format, alongside the equivalent value in the given local currency */ export const fetchTransactions = async ( walletAddress: string, chain: ChainId, getToken: (address: string) => Token, opts?: { page?: number; perPage?: number; localCurrencyCode?: string; } ): Promise<(TokenTransferTransaction | TokenSwapTransaction)[]> => { const resp = await axios.get( `${WALLET_SERVICE_URL}transactions`, { params: { account: walletAddress, chain, ...opts, }, } ); return resp.data .map((t) => { if (isTokenTransfer(t)) { const amount = t.amount as unknown as { token: string; amount?: string; decimalAdjustedAmount?: number; }; return { ...t, amount: tryParseTokenAmount( amount.decimalAdjustedAmount?.toString(), getToken(amount.token) ) ?? undefined, }; } else if (isTokenSwap(t)) { const inAmount = t.inAmount as unknown as { token: string; value?: string; valueInLocalCurrency?: number; decimalAdjustedValue?: number; }; const outAmount = t.outAmount as unknown as { token: string; value?: string; valueInLocalCurrency?: number; decimalAdjustedValue?: number; }; return { ...t, inAmount: { amount: tryParseTokenAmount( inAmount.value, getToken(inAmount.token) ), valueInLocalCurrency: inAmount.valueInLocalCurrency, }, outAmount: { amount: tryParseTokenAmount( outAmount.value, getToken(outAmount.token) ), valueInLocalCurrency: outAmount.valueInLocalCurrency, }, valueInLocalCurrency: inAmount.valueInLocalCurrency, }; } else { return undefined; } }) .filter((el) => !!el) as ( | TokenTransferTransaction | TokenSwapTransaction )[]; };