-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathhorizon.ts
More file actions
125 lines (103 loc) · 3.92 KB
/
Copy pathhorizon.ts
File metadata and controls
125 lines (103 loc) · 3.92 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
import type { WalletNetwork } from '../context/WalletContext';
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',
};
export const EXPLORER_BASE_URLS: Record<WalletNetwork, string> = {
TESTNET: 'https://stellar.expert/explorer/testnet',
PUBLIC: 'https://stellar.expert/explorer/public',
};
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];
}
export function explorerBaseUrl(network: WalletNetwork) {
return EXPLORER_BASE_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.');
}
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);
}
}