forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusage-examples.ts
More file actions
329 lines (283 loc) · 7.92 KB
/
Copy pathusage-examples.ts
File metadata and controls
329 lines (283 loc) · 7.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
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
/**
* USAGE EXAMPLES: Stellar Module Integration
*
* This file demonstrates how to use the StellarModule in other parts of the application
*/
import { Injectable, Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import {
StellarService,
StellarValidator,
StellarAccountNotFoundException,
HorizonApiException,
} from "../stellar";
/**
* Example 1: Payment Watcher Service
* Monitors Stellar network for incoming payments
*/
@Injectable()
export class PaymentWatcherExample {
private readonly logger = new Logger(PaymentWatcherExample.name);
constructor(
private readonly stellarService: StellarService,
private readonly configService: ConfigService,
) {}
/**
* Start watching for payments to merchant account
*/
async startWatching(): Promise<void> {
const merchantKey = this.stellarService.getMerchantPublicKey();
if (!merchantKey) {
this.logger.warn("Merchant public key not configured");
return;
}
await this.stellarService.watchPayments((payment) => {
this.handlePayment(payment);
});
}
/**
* Handle incoming payment
*/
private handlePayment(payment: any): void {
this.logger.log(`Payment received: ${payment.amount}`);
// Extract invoice ID from memo
const invoiceId = this.stellarService.parseMemo(payment.memo);
if (invoiceId) {
this.logger.log(`Payment matched to invoice: ${invoiceId}`);
// TODO: Update invoice status
}
}
/**
* Verify if specific payment was received
*/
async verifyInvoicePayment(invoiceId: string): Promise<boolean> {
const memo = this.stellarService.generateMemo(invoiceId);
const result = await this.stellarService.verifyPayment(
memo,
this.stellarService.getMerchantPublicKey(),
);
return result.found;
}
}
/**
* Example 2: Balance Service
* Provides balance checking functionality
*/
@Injectable()
export class BalanceServiceExample {
constructor(private readonly stellarService: StellarService) {}
/**
* Get user's total balance in USD (simplified)
*/
async getUserBalance(publicKey: string): Promise<{
xlm: string | null;
usdc: string | null;
allBalances: any[];
}> {
try {
// Validate address first
this.stellarService.assertValidPublicKey(publicKey);
// Get XLM balance
const xlm = await this.stellarService.getXlmBalance(publicKey);
// Get USDC balance
const usdc = await this.stellarService.getUsdcBalance(publicKey);
// Get all balances
const allBalances =
await this.stellarService.getAccountBalance(publicKey);
return { xlm, usdc, allBalances };
} catch (error) {
if (error instanceof StellarAccountNotFoundException) {
// Account doesn't exist yet
return { xlm: "0", usdc: "0", allBalances: [] };
}
if (error instanceof HorizonApiException) {
// Handle Horizon API errors
throw error;
}
throw error;
}
}
/**
* Check if account has sufficient balance
*/
async hasMinimumBalance(
publicKey: string,
minimum: number,
): Promise<boolean> {
try {
const accountDetails =
await this.stellarService.getAccountDetails(publicKey);
const xlmBalance = accountDetails.balances.find((b) => b.asset === "XLM");
if (!xlmBalance) {
return false;
}
return parseFloat(xlmBalance.balance) >= minimum;
} catch (error) {
this.logger.error("Error checking balance:", error);
return false;
}
}
private readonly logger = new Logger(BalanceServiceExample.name);
}
/**
* Example 3: Invoice Service Integration
* Shows how invoices module can use Stellar
*/
@Injectable()
export class InvoiceServiceExample {
constructor(private readonly stellarService: StellarService) {}
/**
* Create payment instructions for an invoice
*/
createPaymentInstructions(
invoiceId: string,
amount: number,
): {
destination: string;
amount: string;
asset: string;
memo: string;
} {
const merchantKey = this.stellarService.getMerchantPublicKey();
const memo = this.stellarService.generateMemo(invoiceId);
return {
destination: merchantKey,
amount: amount.toString(),
asset: "USDC", // or XLM
memo,
};
}
/**
* Check if invoice has been paid
*/
async checkInvoicePaid(invoiceId: string): Promise<{
paid: boolean;
amount?: string;
asset?: string;
}> {
const memo = this.stellarService.generateMemo(invoiceId);
const verification = await this.stellarService.verifyPayment(
memo,
this.stellarService.getMerchantPublicKey(),
);
return {
paid: verification.found,
amount: verification.amount,
asset: verification.asset,
};
}
private readonly logger = new Logger(InvoiceServiceExample.name);
}
/**
* Example 4: User Registration with Key Generation
*/
@Injectable()
export class UserRegistrationExample {
constructor(private readonly stellarService: StellarService) {}
/**
* Generate new Stellar keypair for user
*/
generateUserKeypair(): {
publicKey: string;
secretKey: string;
isValid: boolean;
} {
const keypair = StellarValidator.generateKeypair();
return {
publicKey: keypair.publicKey,
secretKey: keypair.secretKey,
isValid: StellarValidator.isValidPublicKey(keypair.publicKey),
};
}
/**
* Validate user-provided public key
*/
validateUserPublicKey(publicKey: string): boolean {
return StellarValidator.isValidPublicKey(publicKey);
}
/**
* Derive public key from secret (for recovery)
*/
derivePublicKey(secretKey: string): string {
return StellarValidator.getPublicKeyFromSecret(secretKey);
}
private readonly logger = new Logger(UserRegistrationExample.name);
}
/**
* Example 5: Transaction Lookup Service
*/
@Injectable()
export class TransactionLookupExample {
constructor(private readonly stellarService: StellarService) {}
/**
* Get transaction details by hash
*/
async getTransaction(transactionHash: string): Promise<any> {
try {
return await this.stellarService.getTransactionByHash(transactionHash);
} catch (error) {
this.logger.error("Transaction not found:", transactionHash);
throw error;
}
}
/**
* Get full account information
*/
async getAccountInfo(publicKey: string): Promise<any> {
try {
return await this.stellarService.getAccountDetails(publicKey);
} catch (error) {
if (error instanceof StellarAccountNotFoundException) {
this.logger.warn("Account not found:", publicKey);
return null;
}
throw error;
}
}
private readonly logger = new Logger(TransactionLookupExample.name);
}
/**
* Example 6: Module Registration (app.module.ts)
*/
/*
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { StellarModule } from './stellar';
import { APP_FILTER } from '@nestjs/core';
import { StellarExceptionFilter } from './stellar/exceptions/stellar.exceptions';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: ['.env'],
}),
StellarModule, // Import StellarModule
],
providers: [
{
provide: APP_FILTER,
useClass: StellarExceptionFilter, // Global exception filter
},
],
})
export class AppModule {}
*/
/**
* Example 7: Controller Usage
*/
/*
import { Controller, Get, Param, UseFilters } from '@nestjs/common';
import { BalanceServiceExample } from './balance.service';
import { StellarExceptionFilter } from './stellar/exceptions/stellar.exceptions';
@Controller('balances')
@UseFilters(new StellarExceptionFilter()) // Apply filter to this controller
export class BalanceController {
constructor(
private readonly balanceService: BalanceServiceExample,
) {}
@Get(':publicKey')
async getBalance(@Param('publicKey') publicKey: string) {
return this.balanceService.getUserBalance(publicKey);
}
}
*/