forked from Disciplr-Org/Disciplr-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhorizon.ts
More file actions
129 lines (105 loc) · 4.21 KB
/
Copy pathhorizon.ts
File metadata and controls
129 lines (105 loc) · 4.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import type { WalletNetwork } from '../context/WalletContext';
import { EXPLORER_BASE_URLS, explorerBaseUrl } from './explorer';
export { EXPLORER_BASE_URLS, explorerBaseUrl };
export const HORIZON_URLS: Record<WalletNetwork, string> = {
TESTNET: 'https://horizon-testnet.stellar.org',
PUBLIC: 'https://horizon.stellar.org',
};
export const USDC_ISSUERS: Record<WalletNetwork, string> = {
TESTNET: 'GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5',
PUBLIC: 'GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN',
};
/** Maximum number of balance lines to accept from a Horizon account response.
* If the response contains more than this many lines the fetch is rejected
* with an INVALID_RESPONSE error, preventing excessive memory use. */
export const MAX_HORIZON_BALANCES = 100;
export type HorizonBalanceErrorCode = 'ACCOUNT_NOT_FOUND' | 'REQUEST_FAILED' | 'INVALID_RESPONSE';
export class HorizonBalanceError extends Error {
code: HorizonBalanceErrorCode;
constructor(code: HorizonBalanceErrorCode, message: string) {
super(message);
this.name = 'HorizonBalanceError';
this.code = code;
}
}
interface HorizonBalanceLine {
asset_type: string;
asset_code?: string;
asset_issuer?: string;
balance?: unknown;
}
interface HorizonAccountResponse {
balances?: HorizonBalanceLine[];
}
export interface UsdcBalanceResult {
balance: string;
hasTrustline: boolean;
issuer: string;
network: WalletNetwork;
}
export function horizonUrl(network: WalletNetwork) {
return HORIZON_URLS[network];
}
function isFiniteNumericString(value: unknown): value is string {
if (typeof value !== 'string' || value.length === 0) {
return false;
}
return /^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(value) && Number.isFinite(Number(value));
}
export async function fetchUsdcBalance(
address: string,
network: WalletNetwork,
fetcher: typeof fetch = fetch,
{ signal, timeoutMs = 10000 }: { signal?: AbortSignal; timeoutMs?: number } = {},
): Promise<UsdcBalanceResult> {
const issuer = USDC_ISSUERS[network];
const controller = new AbortController();
const combinedSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetcher(`${horizonUrl(network)}/accounts/${encodeURIComponent(address)}`, {
signal: combinedSignal,
});
if (response.status === 404) {
throw new HorizonBalanceError('ACCOUNT_NOT_FOUND', 'Stellar account was not found on Horizon.');
}
if (!response.ok) {
throw new HorizonBalanceError(
'REQUEST_FAILED',
`Horizon balance request failed with status ${response.status}.`,
);
}
const account = (await response.json()) as HorizonAccountResponse;
if (!Array.isArray(account.balances)) {
throw new HorizonBalanceError('INVALID_RESPONSE', 'Horizon account response did not include balances.');
}
if (account.balances.length > MAX_HORIZON_BALANCES) {
throw new HorizonBalanceError('INVALID_RESPONSE', 'Horizon account response included too many balances.');
}
const usdcBalance = account.balances.find(
(balanceLine) =>
balanceLine.asset_type !== 'native' &&
balanceLine.asset_code === 'USDC' &&
balanceLine.asset_issuer === issuer,
);
if (usdcBalance && !isFiniteNumericString(usdcBalance.balance)) {
throw new HorizonBalanceError(
'INVALID_RESPONSE',
'Horizon USDC balance was missing or not a finite numeric string.',
);
}
return {
balance: usdcBalance?.balance ?? '0.00',
hasTrustline: Boolean(usdcBalance),
issuer,
network,
};
} catch (err) {
if (err instanceof Error && err.name === 'AbortError') {
throw new HorizonBalanceError('REQUEST_FAILED', 'Horizon balance request was aborted or timed out.');
}
throw err;
} finally {
clearTimeout(timeoutId);
}
}