forked from Lilly-Protocol/lily-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathidempotent-payment.ts
More file actions
109 lines (94 loc) · 3.93 KB
/
Copy pathidempotent-payment.ts
File metadata and controls
109 lines (94 loc) · 3.93 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
/**
* Idempotent Payment Execution with Retries
*
* Demonstrates the safe pattern for executing payments that may be retried
* on transient failures without risk of double-charging:
*
* 1. Generate a unique idempotency key per logical payment
* 2. Pass the same key on every retry attempt
* 3. The server deduplicates by key, so retries are safe
*
* Run: npx tsx examples/idempotent-payment.ts
*/
import { randomUUID } from 'node:crypto';
import { LilySdk } from '../src/sdk';
import { LilyApiError, LilyTransportError } from '../src/errors/sdk-error';
/** Maximum number of retry attempts for transient failures. */
const MAX_RETRIES = 3;
/** Base delay in ms between retries (exponential backoff). */
const BASE_RETRY_DELAY_MS = 500;
async function main(): Promise<void> {
const apiKey = process.env.LILY_API_KEY;
const authToken = process.env.LILY_AUTH_TOKEN;
const sdk = new LilySdk({
baseUrl: process.env.LILY_API_URL ?? 'https://api.lily.test',
...(apiKey ? { apiKey } : {}),
...(authToken ? { authToken } : {}),
timeoutMs: 10_000,
retry: {
retries: 0, // We handle retries manually to preserve the idempotency key
retryDelayMs: 0,
retryableStatusCodes: [],
},
});
// ── Step 1: Generate a unique key for THIS logical payment ──────────
// Use a UUID, a business-reference slug, or any value that is unique
// per distinct payment intent. Reuse the SAME key across retries.
const idempotencyKey = `pay-${randomUUID()}`;
console.log(`Idempotency key: ${idempotencyKey}`);
// ── Step 2: Execute with manual retry loop ─────────────────────────
let lastError: Error | undefined;
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
try {
if (attempt > 0) {
const delay = BASE_RETRY_DELAY_MS * Math.pow(2, attempt - 1);
console.log(` Retry ${attempt}/${MAX_RETRIES} after ${delay}ms...`);
await new Promise((resolve) => setTimeout(resolve, delay));
}
console.log(`Attempt ${attempt + 1}: executing payment...`);
const payment = await sdk.payments.execute({
fromWalletId: 'wallet-stellar-main',
toAddress: 'GABC...DESTINATION',
amount: { assetCode: 'USDC', amount: '25.00' },
memo: 'Invoice #INV-2026-0842',
idempotencyKey, // ← Same key on every attempt
});
console.log(`✅ Payment executed successfully!`);
console.log(` ID: ${payment.id}`);
console.log(` Status: ${payment.status}`);
return; // Success — exit the retry loop
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
if (error instanceof LilyApiError) {
// Server-side errors (5xx) are safe to retry with the same key.
// The server will return the original response if it already processed
// this idempotency key, preventing double-charges.
if ((error.statusCode ?? 0) >= 500) {
console.log(
` ⚠️ Server error ${error.statusCode}: ${error.message}`,
);
continue;
}
// Client errors (4xx except 429) are NOT retryable — fix the request.
console.error(`❌ Client error ${error.statusCode}: ${error.message}`);
throw error;
}
if (error instanceof LilyTransportError) {
// Network timeouts and connection errors are always safe to retry.
// The server either never received the request (safe to resend) or
// already processed it (will deduplicate by idempotency key).
console.log(` ⚠️ Transport error: ${error.message}`);
continue;
}
// Unexpected errors — do not retry.
throw error;
}
}
// All retries exhausted
console.error(`❌ Payment failed after ${MAX_RETRIES + 1} attempts.`);
throw lastError;
}
main().catch((error) => {
console.error('Fatal error:', error);
process.exit(1);
});