forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstellar.service.ts
More file actions
376 lines (326 loc) · 10.7 KB
/
Copy pathstellar.service.ts
File metadata and controls
376 lines (326 loc) · 10.7 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import { Injectable, Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import * as StellarSdk from "@stellar/stellar-sdk";
import {
StellarException,
StellarAccountNotFoundException,
StellarPaymentNotFoundException,
HorizonApiException,
StellarNetworkConfigException,
StellarAddressInvalidException,
} from "./exceptions/stellar.exceptions";
import {
AccountDetailsDto,
AccountBalanceDto,
PaymentVerificationDto,
TransactionDto,
} from "./dto/stellar.dto";
import { StellarValidator } from "./utils/stellar.validator";
/**
* Stellar service for Horizon API interactions
*
* Provides comprehensive Stellar blockchain integration including:
* - Account management and balance queries
* - Payment verification and monitoring
* - Address and contract validation
* - Error handling with custom exceptions
*/
@Injectable()
export class StellarService {
private readonly logger = new Logger(StellarService.name);
private server: StellarSdk.Horizon.Server | null = null;
constructor(private readonly configService: ConfigService) {
this.initializeServer();
}
/**
* Initialize Stellar SDK Server with configured Horizon URL
*/
private initializeServer() {
try {
const horizonUrl = this.getHorizonUrl();
this.server = new StellarSdk.Horizon.Server(horizonUrl, {
allowHttp: false,
});
this.logger.log(
`Stellar server initialized with Horizon URL: ${horizonUrl}`,
);
} catch (error) {
this.logger.error("Failed to initialize Stellar server", error);
throw new StellarNetworkConfigException(
`Failed to initialize Stellar server: ${error.message}`,
);
}
}
getConfig() {
return this.configService.get("stellar");
}
getHorizonUrl(): string {
const config = this.getConfig();
return config?.horizonUrl || "https://horizon-testnet.stellar.org";
}
getMerchantPublicKey(): string {
const config = this.getConfig();
return config?.merchantPublicKey || "";
}
getNetworkPassphrase(): string {
const config = this.getConfig();
return config?.networkPassphrase || "Test SDF Network ; September 2015";
}
isTestnet(): boolean {
return this.getNetworkPassphrase().includes("Test");
}
getServer(): StellarSdk.Horizon.Server {
if (!this.server) {
throw new StellarNetworkConfigException(
"Stellar server not initialized. Check your Horizon URL configuration.",
);
}
return this.server;
}
isValidPublicKey(publicKey: string): boolean {
return StellarValidator.isValidPublicKey(publicKey);
}
isValidContractAddress(contractAddress: string): boolean {
return StellarValidator.isValidContractAddress(contractAddress);
}
assertValidPublicKey(publicKey: string): void {
if (!StellarValidator.isValidPublicKey(publicKey)) {
throw new StellarAddressInvalidException(publicKey, "account");
}
}
assertValidContractAddress(contractAddress: string): void {
if (!StellarValidator.isValidContractAddress(contractAddress)) {
throw new StellarAddressInvalidException(contractAddress, "contract");
}
}
async getAccountDetails(publicKey: string): Promise<AccountDetailsDto> {
this.assertValidPublicKey(publicKey);
try {
const server = this.getServer();
const accountResponse = await server.loadAccount(publicKey);
const balances: AccountBalanceDto[] = accountResponse.balances.map(
(balance: any) => ({
asset: this.formatAsset(balance.asset_code, balance.asset_issuer),
balance: balance.balance,
}),
);
// Calculate minimum balance based on subentries
const baseReserve = 0.5; // 0.5 XLM per base reserve
const subentryCount = parseInt(
String(accountResponse.subentry_count),
10,
);
const minimumBalance = (baseReserve * (2 + subentryCount)).toString();
return {
id: accountResponse.id,
publicKey:
(accountResponse as any).public_key ||
(accountResponse as any).account_id,
sequence: accountResponse.sequence,
subentryCount: String(accountResponse.subentry_count),
balances,
minimumBalance,
};
} catch (error) {
if (error.isAxiosError && error.response?.status === 404) {
throw new StellarAccountNotFoundException(publicKey);
}
if (error.isAxiosError) {
throw new HorizonApiException(
`Horizon API error fetching account: ${error.message}`,
error.response?.status || 500,
error,
);
}
throw new StellarException(
`Failed to fetch account details: ${error.message}`,
"STELLAR_ACCOUNT_FETCH_ERROR",
);
}
}
async getAccountBalance(publicKey: string): Promise<AccountBalanceDto[]> {
const accountDetails = await this.getAccountDetails(publicKey);
return accountDetails.balances;
}
async verifyPayment(
memo: string,
destinationAccount?: string,
): Promise<PaymentVerificationDto> {
try {
const server = this.getServer();
// Build query to search for payments with this memo
// @ts-expect-error - memo filter not in types but available in API
const callBuilder = server.payments().memo(memo).order("desc").limit(1);
// Filter by destination if provided
if (destinationAccount) {
callBuilder.destination(destinationAccount);
}
const payments = await callBuilder.call();
if (payments.records.length === 0) {
return { found: false };
}
const payment = payments.records[0];
return {
found: true,
amount: payment.amount,
asset: this.formatAsset(payment.asset_code, payment.asset_issuer),
transactionHash: payment.transaction_hash,
memo,
};
} catch (error) {
if (error.isAxiosError) {
throw new HorizonApiException(
`Horizon API error verifying payment: ${error.message}`,
error.response?.status || 500,
error,
);
}
throw new StellarException(
`Failed to verify payment: ${error.message}`,
"STELLAR_PAYMENT_VERIFICATION_ERROR",
);
}
}
async watchPayments(
callback: (payment: any) => void,
memo?: string,
): Promise<void> {
const merchantPublicKey = this.getMerchantPublicKey();
if (!merchantPublicKey) {
this.logger.warn(
"Cannot start payment watch: MERCHANT_PUBLIC_KEY not configured",
);
return;
}
try {
const server = this.getServer();
let callBuilder = server
.payments()
.forAccount(merchantPublicKey)
.cursor("now");
if (memo) {
// @ts-expect-error - memo filter not in types but available in API
callBuilder = callBuilder.memo(memo);
}
callBuilder.stream({
onmessage: (paymentRecord: any) => {
this.logger.log(
`Payment received: ${paymentRecord.amount} ${paymentRecord.asset_code || "XLM"}`,
);
callback(paymentRecord);
},
onerror: (error: any) => {
this.logger.error("Payment stream error:", error);
if (error.isAxiosError) {
throw new HorizonApiException(
`Payment stream error: ${error.message}`,
error.status,
error,
);
}
},
});
this.logger.log("Payment watch started");
} catch (error) {
this.logger.error("Failed to start payment watch:", error);
throw error;
}
}
async getTransactionByHash(transactionHash: string): Promise<TransactionDto> {
try {
const server = this.getServer();
const transaction = await server
.transactions()
.transaction(transactionHash)
.call();
return {
id: transaction.id,
hash: transaction.hash,
ledger: String((transaction as any).ledger_attr),
createdAt: transaction.created_at,
sourceAccount: transaction.source_account,
feeCharged: String(transaction.fee_charged),
operationCount: Number(transaction.operation_count),
memo: transaction.memo || undefined,
};
} catch (error) {
if (error.isAxiosError && error.response?.status === 404) {
throw new StellarPaymentNotFoundException(undefined, transactionHash);
}
if (error.isAxiosError) {
throw new HorizonApiException(
`Horizon API error fetching transaction: ${error.message}`,
error.response?.status || 500,
error,
);
}
throw new StellarException(
`Failed to fetch transaction: ${error.message}`,
"STELLAR_TRANSACTION_FETCH_ERROR",
);
}
}
generateMemo(invoiceId: string): string {
const config = this.getConfig();
const prefix = config?.memoPrefix || "invoisio-";
return `${prefix}${invoiceId}`;
}
parseMemo(memo: string): string | null {
const config = this.getConfig();
const prefix = config?.memoPrefix || "invoisio-";
if (memo.startsWith(prefix)) {
return memo.slice(prefix.length);
}
return null;
}
private formatAsset(assetCode?: string, issuer?: string): string {
if (!assetCode) {
return "XLM";
}
if (issuer) {
return `${assetCode}:${issuer}`;
}
return assetCode;
}
async getXlmBalance(publicKey: string): Promise<string | null> {
const balances = await this.getAccountBalance(publicKey);
const xlmBalance = balances.find((b) => b.asset === "XLM");
return xlmBalance?.balance || null;
}
async getUsdcBalance(publicKey: string): Promise<string | null> {
const balances = await this.getAccountBalance(publicKey);
const usdcIssuer = this.getConfig()?.usdcIssuer;
const usdcAssetCode = this.getConfig()?.usdcAssetCode || "USDC";
const usdcBalance = balances.find(
(b) => b.asset === `${usdcAssetCode}:${usdcIssuer}`,
);
return usdcBalance?.balance || null;
}
/**
* Lightweight Horizon reachability probe.
* Fetches the root endpoint with a 5 s timeout to verify the server is
* reachable without issuing a full account/transaction query.
* @returns `{ reachable: true }` or `{ reachable: false, error }` on failure.
*/
async pingHorizon(): Promise<{
reachable: boolean;
latencyMs: number;
error?: string;
}> {
const start = Date.now();
try {
const server = this.getServer();
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5_000);
await server.root();
clearTimeout(timeout);
return { reachable: true, latencyMs: Date.now() - start };
} catch (err) {
return {
reachable: false,
latencyMs: Date.now() - start,
error: err instanceof Error ? err.message : String(err),
};
}
}
}