import { getCsrfToken } from '@shared/api/csrf' import { tokenStore, refreshAccessToken } from '@shared/api/tokenStore' const WALLET_API_URL = 'https://app.cryptowallet.elcsa.ru' export type Chain = 'ETH' | 'BSC' | 'BTC' | 'TRX' | 'SOL' export interface FormattedAmount { raw: string formatted: string decimals: number usdPrice: number usdValue: number } export interface WalletBalanceData { chain: Chain address: string native: FormattedAmount tokens: Record } export interface PriceEntry { usd: number } export const CHAINS: Chain[] = ['ETH', 'BSC', 'BTC', 'TRX', 'SOL'] async function walletGet(path: string, allowRetry: boolean = true): Promise { const csrf = await getCsrfToken() const bearer = tokenStore.get() const res = await fetch(`${WALLET_API_URL}${path}`, { credentials: 'include', headers: { 'X-CSRF-Token': csrf, ...(bearer ? { Authorization: `Bearer ${bearer}` } : {}), }, }) if (res.status === 401 && allowRetry) { try { await refreshAccessToken() return walletGet(path, false) } catch { tokenStore.clear() throw new Error('Unauthorized') } } const data = await res.json() if (!res.ok) throw data return data as T } export async function getWalletBalance(chain: Chain): Promise { const res = await walletGet<{ success: boolean; data: WalletBalanceData }>(`/api/wallets/${chain}/balance`) return res.data } export async function getPrices(symbols: string[]): Promise> { const res = await walletGet<{ success: boolean; data: Record }>( `/api/prices?symbols=${symbols.join(',')}` ) return res.data }