forked from Emmy123222/Stellar-MicroPay
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstellarService.js
More file actions
286 lines (245 loc) · 8.16 KB
/
Copy pathstellarService.js
File metadata and controls
286 lines (245 loc) · 8.16 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
/**
* src/services/stellarService.js
* Business logic for interacting with the Stellar Horizon API.
* All blockchain reads happen here — this is the single source of truth.
*/
"use strict";
const { server } = require("../config/stellar");
const logger = require("../utils/logger");
// ─── In-memory LRU cache for getAccount (5 s TTL) ────────────────────────────
const ACCOUNT_CACHE_TTL_MS = 5_000;
const ACCOUNT_CACHE_MAX = 256;
// ─── Timeout + retry ──────────────────────────────────────────────────────────
const DEFAULT_TIMEOUT_MS = 10_000;
const MAX_RETRIES = 3;
const PAYMENT_TYPES = new Set([
"payment",
"path_payment_strict_send",
"path_payment_strict_receive",
]);
function isTransientError(err) {
if (!err) return false;
const status = err?.response?.status ?? err?.status;
if (status === 404) return false; // definitive — don't retry
if (status >= 500) return true;
const msg = err?.message || "";
return (
msg.includes("ECONNRESET") ||
msg.includes("ETIMEDOUT") ||
msg.includes("ENOTFOUND") ||
msg.includes("network") ||
err.name === "AbortError"
);
}
/**
* Run `fn` with a hard timeout and retry up to MAX_RETRIES times on
* transient errors, using exponential back-off (100 ms × 2^attempt).
*/
async function withTimeoutAndRetry(fn, timeoutMs = DEFAULT_TIMEOUT_MS) {
let lastErr;
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const result = await Promise.race([
fn(controller.signal),
new Promise((_, reject) =>
controller.signal.addEventListener("abort", () =>
reject(Object.assign(new Error("Horizon request timed out"), { name: "AbortError" }))
)
),
]);
clearTimeout(timer);
return result;
} catch (err) {
clearTimeout(timer);
lastErr = err;
if (!isTransientError(err) || attempt === MAX_RETRIES) throw err;
// Exponential back-off: 100 ms, 200 ms, 400 ms …
await new Promise((resolve) => setTimeout(resolve, 100 * 2 ** attempt));
}
}
throw lastErr;
}
/** @type {Map<string, { value: object, expiresAt: number }>} */
const accountCache = new Map();
function cacheGet(key) {
const entry = accountCache.get(key);
if (!entry) return null;
if (Date.now() > entry.expiresAt) {
accountCache.delete(key);
return null;
}
// LRU: re-insert to move to end
accountCache.delete(key);
accountCache.set(key, entry);
return entry.value;
}
function cacheSet(key, value) {
if (accountCache.size >= ACCOUNT_CACHE_MAX) {
// Evict the oldest entry (first key in insertion order)
accountCache.delete(accountCache.keys().next().value);
}
accountCache.set(key, { value, expiresAt: Date.now() + ACCOUNT_CACHE_TTL_MS });
}
function clearAccountCache() {
accountCache.clear();
}
// ─── Account ──────────────────────────────────────────────────────────────────
/**
* Load a Stellar account and return its balances.
*/
async function getAccount(publicKey) {
validatePublicKey(publicKey);
const cached = cacheGet(publicKey);
if (cached) return cached;
try {
const account = await withTimeoutAndRetry(() => server.loadAccount(publicKey));
const balances = account.balances.map((b) => {
if (b.asset_type === "native") {
return { assetCode: "XLM", balance: b.balance, asset_type: "native" };
}
return {
assetCode: b.asset_code,
balance: b.balance,
assetIssuer: b.asset_issuer,
asset_type: b.asset_type,
};
});
const result = {
publicKey,
sequence: account.sequence,
balances,
subentryCount: account.subentry_count,
};
cacheSet(publicKey, result);
return result;
} catch (err) {
if (err?.response?.status === 404) {
const error = new Error(
"Account not found. It may not be funded yet. Use Friendbot on testnet."
);
error.status = 404;
logger.error({ err: error, publicKey: publicKey.replace(/[\r\n]/g, "") }, "Account not found");
throw error;
}
logger.error({ err, publicKey: publicKey.replace(/[\r\n]/g, "") }, "Error loading account from Horizon");
throw err;
}
}
/**
* Get only the native XLM balance.
*/
async function getXLMBalance(publicKey) {
const { balances } = await getAccount(publicKey);
const xlm = balances.find((b) => b.assetCode === "XLM");
return xlm ? xlm.balance : "0";
}
// ─── Payments ─────────────────────────────────────────────────────────────────
/**
* Fetch payment history for an account from Horizon.
*
* @param {string} publicKey
* @param {{ limit?: number, cursor?: string }} options
*/
async function getPayments(publicKey, { limit = 20, cursor } = {}) {
validatePublicKey(publicKey);
let query = server.payments().forAccount(publicKey).limit(limit).order("desc");
if (cursor) {
query = query.cursor(cursor);
}
const result = await withTimeoutAndRetry(() => query.call());
const payments = [];
for (const op of result.records) {
if (!PAYMENT_TYPES.has(op.type)) continue;
const payment = await normalizePaymentOperation(op, publicKey);
let memo;
try {
const tx = await withTimeoutAndRetry(() => op.transaction());
if (tx.memo_type === "text" && tx.memo) {
memo = tx.memo;
}
} catch (err) {
logger.error({ err, transactionHash: op.transaction_hash }, "Failed to fetch memo for transaction");
// memo is optional
}
payments.push({ ...payment, memo });
}
return payments;
}
/**
* Stream new payment operations for a public key.
*
* Horizon handles reconnection internally. The caller receives normalized
* payment records for both payment and path-payment operations.
*/
function streamPaymentEvents(publicKey, { onPayment, onError } = {}) {
validatePublicKey(publicKey);
const close = server
.payments()
.forAccount(publicKey)
.order("asc")
.cursor("now")
.stream({
onmessage: async (op) => {
if (!PAYMENT_TYPES.has(op.type)) return;
try {
const payment = await normalizePaymentOperation(op, publicKey);
onPayment?.(payment);
} catch (error) {
onError?.(error);
}
},
onerror: (error) => {
logger.error({ err: error, publicKey }, "Payment stream error");
onError?.(error);
},
});
return () => {
try {
close?.();
} catch {
// swallow errors on close
}
};
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
async function normalizePaymentOperation(op, publicKey) {
const isPathPayment = op.type !== "payment";
const isSent = op.from === publicKey;
let assetCode;
if (isPathPayment && !isSent) {
assetCode =
op.dest_asset_type === "native" ? "XLM" : op.dest_asset_code || "UNKNOWN";
} else {
assetCode =
op.asset_type === "native" ? "XLM" : op.asset_code || "UNKNOWN";
}
const amount = isPathPayment && !isSent ? op.dest_amount : op.amount;
return {
id: op.id,
type: isSent ? "sent" : "received",
amount,
asset: assetCode,
from: op.from,
to: op.to,
createdAt: op.created_at,
transactionHash: op.transaction_hash,
pagingToken: op.paging_token,
};
}
function validatePublicKey(publicKey) {
if (!publicKey || !/^G[A-Z0-9]{55}$/.test(publicKey)) {
const err = new Error("Invalid Stellar public key format");
err.status = 400;
throw err;
}
}
module.exports = {
getAccount,
getXLMBalance,
getPayments,
streamPaymentEvents,
validatePublicKey,
clearAccountCache,
};