-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathStellarService.js
More file actions
419 lines (379 loc) · 12.8 KB
/
StellarService.js
File metadata and controls
419 lines (379 loc) · 12.8 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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/**
* Stellar Service - Blockchain Integration Layer
*
* RESPONSIBILITY: Direct integration with Stellar blockchain network via Stellar SDK
* OWNER: Blockchain Team
* DEPENDENCIES: Stellar SDK, Horizon API, stellar config
*
* Handles all blockchain operations including wallet creation, balance queries,
* transaction submission, and network communication with retry logic and error handling.
* Real Stellar Service - Handles actual blockchain interactions with Stellar network
*/
// External modules
const StellarSdk = require('stellar-sdk');
// Internal modules
const StellarServiceInterface = require('./interfaces/StellarServiceInterface');
const { STELLAR_NETWORKS, HORIZON_URLS } = require('../constants');
const StellarErrorHandler = require('../utils/stellarErrorHandler');
const log = require('../utils/log');
const { withTimeout, TIMEOUT_DEFAULTS, TimeoutError } = require('../utils/timeoutHandler');
class StellarService extends StellarServiceInterface {
/**
* Create a new StellarService instance
* @param {Object} [config={}] - Configuration options
* @param {string} [config.network='testnet'] - Stellar network ('testnet' or 'public')
* @param {string} [config.horizonUrl] - Horizon server URL
* @param {string} [config.serviceSecretKey] - Service account secret key
*/
constructor(config = {}) {
this.network = config.network || STELLAR_NETWORKS.TESTNET;
this.horizonUrl = config.horizonUrl || HORIZON_URLS.TESTNET;
this.serviceSecretKey = config.serviceSecretKey;
this.server = new StellarSdk.Horizon.Server(this.horizonUrl);
// Timeout configuration
this.timeouts = {
api: config.apiTimeout || TIMEOUT_DEFAULTS.STELLAR_API,
submit: config.submitTimeout || TIMEOUT_DEFAULTS.STELLAR_SUBMIT,
stream: config.streamTimeout || TIMEOUT_DEFAULTS.STELLAR_STREAM,
};
}
/**
* Check if an error is a transient network error that can be retried
* @private
* @param {Error} error - Error to check
* @returns {boolean} True if error is transient and retryable
*/
_isTransientNetworkError(error) {
// Timeout errors are retryable
if (error instanceof TimeoutError) {
return true;
}
const message = error && error.message ? error.message : '';
const code = error && error.code ? error.code : '';
const status = error && error.response && error.response.status ? error.response.status : null;
if (status === 503 || status === 504) {
return true;
}
const messageTokens = [
'ENOTFOUND',
'ECONNREFUSED',
'ETIMEDOUT',
'EHOSTUNREACH',
'ECONNRESET',
'socket hang up',
'Network Error',
'network timeout',
'timed out'
];
if (messageTokens.some(token => message.includes(token))) {
return true;
}
const codeTokens = [
'ENOTFOUND',
'ECONNREFUSED',
'ETIMEDOUT',
'EHOSTUNREACH',
'ECONNRESET'
];
return codeTokens.includes(code);
}
/**
* Calculate exponential backoff delay for retry attempts
* @private
* @param {number} attempt - Current attempt number (1-indexed)
* @returns {number} Delay in milliseconds
*/
_getBackoffDelay(attempt) {
const base = 200;
const max = 2000;
const delay = base * Math.pow(2, attempt - 1);
return Math.min(delay, max);
}
/**
* Execute an operation with automatic retry on transient errors and timeout
* @private
* @param {Function} operation - Async operation to execute
* @param {string} operationName - Name of operation for logging
* @param {number} [timeout] - Timeout in milliseconds (defaults to api timeout)
* @returns {Promise<*>} Result of the operation
* @throws {Error} If all retry attempts fail or error is not transient
*/
async _executeWithRetry(operation, operationName = 'stellar_operation', timeout = null) {
const maxAttempts = 3;
const timeoutMs = timeout || this.timeouts.api;
let lastError = null;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await withTimeout(operation(), timeoutMs, operationName);
} catch (error) {
lastError = error;
// Log timeout errors
if (error instanceof TimeoutError) {
log.warn('STELLAR_SERVICE', 'Operation timeout', {
operation: operationName,
attempt,
maxAttempts,
timeoutMs
});
}
if (!this._isTransientNetworkError(error) || attempt === maxAttempts) {
throw error;
}
const delay = this._getBackoffDelay(attempt);
log.debug('STELLAR_SERVICE', 'Retrying after transient error', {
operation: operationName,
attempt,
delay,
error: error.message
});
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw lastError;
}
/**
* Submit transaction with network safety checks and timeout
* Attempts to verify transaction was recorded even if submission fails
* @private
* @param {Object} builtTx - Built and signed Stellar transaction
* @returns {Promise<{hash: string, ledger: number}>} Transaction result
* @throws {Error} If transaction submission fails and cannot be verified
*/
async _submitTransactionWithNetworkSafety(builtTx) {
const txHash = builtTx.hash().toString('hex');
try {
const result = await withTimeout(
this.server.submitTransaction(builtTx),
this.timeouts.submit,
'submitTransaction'
);
return {
hash: result.hash,
ledger: result.ledger
};
} catch (error) {
if (this._isTransientNetworkError(error)) {
try {
const existingTx = await this._executeWithRetry(
() => this.server.transaction(txHash).call(),
'verifySubmittedTransaction'
);
if (existingTx && existingTx.hash === txHash) {
log.info('STELLAR_SERVICE', 'Transaction verified after submission timeout', {
txHash,
ledger: existingTx.ledger
});
return {
hash: existingTx.hash,
ledger: existingTx.ledger
};
}
} catch (checkError) {
log.debug('STELLAR_SERVICE', 'Could not verify transaction after submission error', {
txHash,
error: checkError.message
});
// Best-effort network safety check; original transient error will be thrown below.
}
}
throw error;
}
}
/**
* Create a new Stellar wallet
* @returns {Promise<{publicKey: string, secretKey: string}>}
*/
async createWallet() {
const pair = StellarSdk.Keypair.random();
return {
publicKey: pair.publicKey(),
secretKey: pair.secret(),
};
}
/**
* Get wallet balance
* @param {string} publicKey - Stellar public key
* @returns {Promise<{balance: string, asset: string}>}
*/
// eslint-disable-next-line no-unused-vars
async getBalance(publicKey) {
return StellarErrorHandler.wrap(async () => {
const account = await this._executeWithRetry(
() => this.server.loadAccount(publicKey),
'loadAccount'
);
const nativeBalance = account.balances.find(b => b.asset_type === 'native');
return {
balance: nativeBalance ? nativeBalance.balance : '0',
asset: 'XLM',
};
}, 'getBalance');
}
/**
* Fund a testnet wallet via Friendbot
* @param {string} publicKey - Stellar public key
* @returns {Promise<{balance: string}>}
*/
// eslint-disable-next-line no-unused-vars
async fundTestnetWallet(publicKey) {
return StellarErrorHandler.wrap(async () => {
await this._executeWithRetry(
() => this.server.friendbot(publicKey).call(),
'friendbot'
);
const balance = await this.getBalance(publicKey);
return balance;
}, 'fundTestnetWallet');
}
/**
* Check if an account is funded on Stellar
* @param {string} publicKey - Stellar public key
* @returns {Promise<{funded: boolean, balance: string, exists: boolean}>}
*/
// eslint-disable-next-line no-unused-vars
async isAccountFunded(publicKey) {
return StellarErrorHandler.wrap(async () => {
const balance = await this.getBalance(publicKey);
const funded = parseFloat(balance.balance) > 0;
return {
funded,
balance: balance.balance,
exists: true,
};
}, 'isAccountFunded');
}
/**
* Send a donation transaction
* @param {Object} params
* @param {string} params.sourceSecret - Source account secret key
* @param {string} params.destinationPublic - Destination public key
* @param {string} params.amount - Amount in XLM
* @param {string} [params.memo] - Optional transaction memo (max 28 bytes)
* @returns {Promise<{transactionId: string, ledger: number}>}
*/
async sendDonation({ sourceSecret, destinationPublic, amount, memo = '' }) {
return StellarErrorHandler.wrap(async () => {
const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecret);
const sourceAccount = await this._executeWithRetry(
() => this.server.loadAccount(sourceKeypair.publicKey()),
'loadAccountForDonation'
);
const transaction = new StellarSdk.TransactionBuilder(sourceAccount, {
fee: StellarSdk.BASE_FEE,
networkPassphrase: this.network === 'public' ? StellarSdk.Networks.PUBLIC : StellarSdk.Networks.TESTNET,
})
.addOperation(StellarSdk.Operation.payment({
destination: destinationPublic,
asset: StellarSdk.Asset.native(),
amount: amount.toString(),
}))
.setTimeout(30);
if (memo) {
transaction.addMemo(StellarSdk.Memo.text(memo));
}
const builtTx = transaction.build();
builtTx.sign(sourceKeypair);
const result = await this._submitTransactionWithNetworkSafety(builtTx);
return {
transactionId: result.hash,
ledger: result.ledger,
};
}, 'sendDonation');
}
/**
* Get transaction history for an account
* @param {string} publicKey - Stellar public key
* @param {number} limit - Number of transactions to retrieve
* @returns {Promise<Array>}
*/
// eslint-disable-next-line no-unused-vars
async getTransactionHistory(publicKey, limit = 10) {
return StellarErrorHandler.wrap(async () => {
const result = await this._executeWithRetry(
() => this.server.transactions()
.forAccount(publicKey)
.limit(limit)
.order('desc')
.call(),
'getTransactionHistory'
);
return result.records;
}, 'getTransactionHistory');
}
/**
* Stream transactions for an account
* @param {string} publicKey - Stellar public key
* @param {Function} onTransaction - Callback for each transaction
* @returns {Function} Unsubscribe function
*/
// eslint-disable-next-line no-unused-vars
streamTransactions(publicKey, onTransaction) {
const streamTimeout = this.timeouts.stream;
let lastMessageTime = Date.now();
let timeoutTimer = null;
const resetTimeout = () => {
if (timeoutTimer) {
clearTimeout(timeoutTimer);
}
timeoutTimer = setTimeout(() => {
const elapsed = Date.now() - lastMessageTime;
log.error('STELLAR_SERVICE', 'Transaction stream timeout', {
publicKey,
timeoutMs: streamTimeout,
elapsedMs: elapsed
});
if (closeStream) {
closeStream();
}
}, streamTimeout);
};
resetTimeout();
const closeStream = this.server.transactions()
.forAccount(publicKey)
.cursor('now')
.stream({
onmessage: (tx) => {
lastMessageTime = Date.now();
resetTimeout();
onTransaction(tx);
},
onerror: (error) => {
if (timeoutTimer) {
clearTimeout(timeoutTimer);
}
log.error('STELLAR_SERVICE', 'Transaction stream error', {
error: error.message,
publicKey
});
},
});
// Return enhanced close function that also clears timeout
return () => {
if (timeoutTimer) {
clearTimeout(timeoutTimer);
}
if (closeStream) {
closeStream();
}
};
}
/**
* Verify a donation transaction by hash
* @param {string} transactionHash - Transaction hash to verify
* @returns {Promise<{verified: boolean, transaction: Object}>}
*/
// eslint-disable-next-line no-unused-vars
async verifyTransaction(transactionHash) {
return StellarErrorHandler.wrap(async () => {
const tx = await this._executeWithRetry(
() => this.server.transaction(transactionHash).call(),
'verifyTransaction'
);
return {
verified: true,
transaction: tx,
};
}, 'verifyTransaction');
}
}
module.exports = StellarService;