Repository navigation
Expand file tree
/
Copy pathstellar.js
More file actions
1592 lines (1448 loc) · 56 KB
/
Copy pathstellar.js
File metadata and controls
1592 lines (1448 loc) · 56 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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as StellarSDK from '@stellar/stellar-sdk';
import { randomUUID } from 'crypto';
import { eventMonitor } from '../eventSourcing/index.js';
import { getConfig } from '../config/env.js';
import { getIssuer } from '../config/assets.js';
import logger, { withContext } from '../config/logger.js';
import prisma from '../db/client.js';
import { createCircuitBreaker } from './circuitBreaker.js';
import { getCachedBalance, invalidateBalanceCache } from '../cache/balanceCache.js';
import { recordHorizonCall } from '../monitoring/horizonAlerter.js';
import { withSpan } from '../config/otel.js';
import { recordFeeSample, getSevenDayAverageFee, detectFeeSurge } from './feeSurge.js';
import { sequenceManager } from './sequenceManager.js';
const stellarInteractiveBreaker = createCircuitBreaker('Horizon-Interactive');
/**
* Retrieve aggregate fee-bump statistics from the database.
* @returns {Promise<{total: number, totalFeeStroops: number, uniqueAccounts: number}>}
*/
export async function getFeeBumpStats() {
const [summaryAgg, uniqueAccounts] = await Promise.all([
prisma.feeBumpSummary.aggregate({
_sum: {
total: true,
totalFeeStroops: true,
},
}),
prisma.feeBumpAccount.count(),
]);
return {
total: Number(summaryAgg?._sum?.total ?? 0),
totalFeeStroops: Number(summaryAgg?._sum?.totalFeeStroops ?? 0),
uniqueAccounts,
};
}
async function incrementFeeBumpStats(sourcePublicKey, feeStroops) {
try {
const today = new Date();
today.setUTCHours(0, 0, 0, 0);
// Account insert is contention-free via ON CONFLICT DO NOTHING.
// Daily summary update keeps counters bounded by date instead of one singleton row.
await Promise.all([
prisma.$executeRaw`
INSERT INTO "FeeBumpAccount" ("publicKey", "firstUsedAt")
VALUES (${sourcePublicKey}, NOW())
ON CONFLICT ("publicKey") DO NOTHING
`,
prisma.$executeRaw`
INSERT INTO "FeeBumpSummary" ("date", "total", "totalFeeStroops", "createdAt", "updatedAt")
VALUES (${today}, 1, ${feeStroops}, NOW(), NOW())
ON CONFLICT ("date")
DO UPDATE SET
"total" = "FeeBumpSummary"."total" + 1,
"totalFeeStroops" = "FeeBumpSummary"."totalFeeStroops" + ${feeStroops},
"updatedAt" = NOW()
`,
]);
} catch (err) {
logger.warn('stellar.feeBumpStats.persist.failed', { error: err.message });
}
}
function isBadSequenceError(err) {
const txCode =
err?.response?.data?.extras?.result_codes?.transaction ??
err?.data?.extras?.result_codes?.transaction;
if (txCode === 'tx_bad_seq') return true;
return String(err?.message ?? '').includes('tx_bad_seq');
}
/**
* Fee Bump Transaction
* A fee bump allows a third-party sponsor (e.g. the platform account) to pay the
* transaction fee on behalf of the source account. This is useful when users have
* low XLM balances and cannot cover fees themselves — the inner transaction is
* signed by the original sender, then wrapped so the sponsor covers the fee.
* @see https://developers.stellar.org/docs/learn/fundamentals/transactions/fee-bumps
*
* Wrap an inner transaction with a FeeBumpTransaction so the platform account
* pays the fee instead of the buyer. Fee multiplier is read from FEE_BUMP_MULTIPLIER
* (default 10×).
* @param {import('@stellar/stellar-sdk').Transaction} innerTx - Signed inner transaction to wrap
* @param {string} feeAccountSecret - Secret key of the fee-sponsoring platform account
* @returns {import('@stellar/stellar-sdk').FeeBumpTransaction} Signed fee-bump transaction ready to submit
*/
export function wrapWithFeeBump(innerTx, feeAccountSecret) {
const feeKeypair = StellarSDK.Keypair.fromSecret(feeAccountSecret);
const networkPassphrase = getNetworkPassphrase();
const multiplier = parseInt(process.env.FEE_BUMP_MULTIPLIER ?? '10', 10);
const minFee = parseInt(process.env.MIN_FEE_STROOPS ?? String(StellarSDK.BASE_FEE), 10);
const maxFee = parseInt(process.env.MAX_FEE_BUMP_STROOPS ?? process.env.MAX_FEE_STROOPS ?? '100000', 10);
let surgeFee = 0;
try {
const avgFee = getSevenDayAverageFee();
const surgeInfo = detectFeeSurge(StellarSDK.BASE_FEE * multiplier, avgFee);
if (surgeInfo?.surge && avgFee) {
surgeFee = Math.round(avgFee * surgeInfo.ratio);
}
} catch (err) {
logger.warn('stellar.wrapWithFeeBump.feeSurgeCheck.failed', { error: err.message });
}
const baseConfiguredFee = StellarSDK.BASE_FEE * multiplier;
const calculatedFee = Math.max(surgeFee, baseConfiguredFee, minFee);
const finalFee = Math.min(calculatedFee, maxFee);
logger.info('stellar.wrapWithFeeBump.feeDetermined', {
multiplier,
baseConfiguredFee,
surgeFee,
minFee,
maxFee,
finalFee,
});
const feeBumpTx = StellarSDK.TransactionBuilder.buildFeeBumpTransaction(
feeKeypair,
finalFee,
innerTx,
networkPassphrase,
);
feeBumpTx.sign(feeKeypair);
return feeBumpTx;
}
let horizonServerUrl;
let horizonServer;
const STELLAR_MEMO_ID_MAX = 18446744073709551615n;
const DEFAULT_FUTURENET_PASSPHRASE = 'Test SDF Future Network ; October 2022';
/**
* Return a cached Stellar Horizon server instance, re-creating it if the URL has changed.
* @returns {import('@stellar/stellar-sdk').Horizon.Server}
*/
export function getHorizonServer() {
const { horizonUrl } = getConfig().stellar;
if (!horizonServer || horizonUrl !== horizonServerUrl) {
horizonServerUrl = horizonUrl;
horizonServer = new StellarSDK.Horizon.Server(horizonUrl);
}
return horizonServer;
}
/** Timeout (ms) for Horizon calls. Reads HORIZON_TIMEOUT_MS env var, default 10 000. */
export function getHorizonTimeout() {
return parseInt(process.env.HORIZON_TIMEOUT_MS ?? '10000', 10);
}
/**
* Run a Horizon call with a timeout and circuit breaker. Throws a 504-tagged
* error on timeout, or a 503-tagged error when the circuit is open.
* @template T
* @param {() => Promise<T>} fn
* @returns {Promise<T>}
*/
export async function withHorizonTimeout(fn) {
const ms = getHorizonTimeout();
return stellarInteractiveBreaker.call(() => {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => {
const err = new Error('Horizon request timed out');
err.isTimeout = true;
reject(err);
}, ms);
});
return Promise.race([fn(), timeout]).finally(() => clearTimeout(timer));
});
}
const HORIZON_RETRY_BACKOFFS = [500, 1000, 2000];
function isTransientHorizonError(err) {
const status = err?.response?.status ?? err?.status;
if (status === 400 || status === 401 || status === 403 || status === 404 || status === 409) return false;
if (status === 429 || status === 502 || status === 503 || status === 504 || status === 520 || (status >= 500 && status < 600)) return true;
if (err.isTimeout) return true;
const code = err?.code;
if (
code === 'ECONNREFUSED' ||
code === 'ENOTFOUND' ||
code === 'ETIMEDOUT' ||
code === 'ECONNRESET'
)
return true;
return false;
}
/**
* Run a Horizon call with timeout, circuit breaker, and exponential backoff retry.
* Retries on 429, 503, and network timeouts (max 3 attempts: 500ms, 1s, 2s backoff).
* Does NOT retry on 400, 404, or 409.
* @template T
* @param {() => Promise<T>} fn
* @returns {Promise<T>}
*/
export async function withHorizonRetry(fn, txHash = null) {
let lastErr;
for (let attempt = 0; attempt <= HORIZON_RETRY_BACKOFFS.length; attempt++) {
try {
const result = await withHorizonTimeout(fn);
recordHorizonCall(false);
return result;
} catch (err) {
lastErr = err;
if (!isTransientHorizonError(err) || attempt === HORIZON_RETRY_BACKOFFS.length) {
recordHorizonCall(true);
throw err;
}
// If we have a transaction hash and encountered a timeout or network drop,
// verify if the transaction was already committed on-chain to avoid double submission.
if (txHash) {
try {
const confirmedTx = await getHorizonServer().transactions().transaction(txHash).call();
if (confirmedTx && (confirmedTx.successful !== undefined || confirmedTx.id || confirmedTx.hash)) {
logger.info('stellar.horizon.retry.alreadyCommitted', { txHash, ledger: confirmedTx.ledger_attr ?? confirmedTx.ledger });
recordHorizonCall(false);
return {
...confirmedTx,
hash: confirmedTx.hash || txHash,
ledger: confirmedTx.ledger_attr ?? confirmedTx.ledger,
successful: confirmedTx.successful ?? true,
};
}
} catch (checkErr) {
// If 404, tx is not on-chain yet; proceed with retry. Otherwise log warning and proceed.
if (checkErr?.response?.status !== 404) {
logger.warn('stellar.horizon.retry.hashCheckFailed', { txHash, error: checkErr.message });
}
}
}
const delay = HORIZON_RETRY_BACKOFFS[attempt];
logger.warn('stellar.horizon.retry', { attempt: attempt + 1, delay, error: err.message });
await new Promise((r) => setTimeout(r, delay));
}
}
recordHorizonCall(true);
throw lastErr;
}
/**
* Check whether the configured Stellar network is testnet.
* @returns {boolean}
*/
export function isTestnet() {
return getConfig().stellar.network === 'testnet';
}
/**
* Return network passphrase for the configured Stellar network.
* Supports testnet, mainnet, and futurenet.
* @returns {string}
*/
export function getNetworkPassphrase() {
const network = getConfig().stellar.network;
if (network === 'testnet') return StellarSDK.Networks.TESTNET;
if (network === 'mainnet') return StellarSDK.Networks.PUBLIC;
if (network === 'futurenet') return StellarSDK.Networks.FUTURENET ?? DEFAULT_FUTURENET_PASSPHRASE;
throw new Error(`Unsupported STELLAR_NETWORK value: ${network}`);
}
/**
* Error used when request payload data is semantically invalid.
*/
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
this.status = 400;
this.statusCode = 400;
}
}
/**
* Validate memo value against Stellar memo type constraints.
* @param {string|number|null} memo
* @param {'text'|'id'|'hash'|'return'} memoType
* @returns {void}
* @throws {ValidationError}
*/
export function validateMemo(memo, memoType = 'text') {
if (memo === null || memo === undefined || memo === '') return;
const memoString = String(memo);
switch (memoType) {
case 'id': {
if (!/^\d+$/.test(memoString)) {
throw new ValidationError('MEMO_ID must be an unsigned 64-bit integer');
}
const value = BigInt(memoString);
if (value < 0n || value > STELLAR_MEMO_ID_MAX) {
throw new ValidationError('MEMO_ID must be between 0 and 18446744073709551615');
}
return;
}
case 'hash':
case 'return':
if (!/^[0-9a-fA-F]{64}$/.test(memoString)) {
throw new ValidationError(`MEMO_${memoType.toUpperCase()} must be a 32-byte hex string`);
}
return;
case 'text':
default: {
const memoBytes = Buffer.byteLength(memoString, 'utf8');
if (memoBytes > 28) {
throw new ValidationError('MEMO_TEXT exceeds 28 bytes limit');
}
}
}
}
/**
* Validate Horizon network passphrase matches configured network.
* @returns {Promise<{expectedPassphrase: string, actualPassphrase: string}>}
*/
export async function verifyHorizonNetworkPassphrase() {
const expectedPassphrase = getNetworkPassphrase();
const root = await withHorizonRetry(() => getHorizonServer().root());
const actualPassphrase = root?.network_passphrase;
if (actualPassphrase !== expectedPassphrase) {
const err = new Error(
`Horizon passphrase mismatch: expected "${expectedPassphrase}" but received "${actualPassphrase}"`,
);
err.status = 500;
err.statusCode = 500;
throw err;
}
return { expectedPassphrase, actualPassphrase };
}
/**
* Fund a testnet account via Friendbot (testnet only).
* @param {string} publicKey - Stellar public key of the account to fund
* @returns {Promise<{funded: boolean, publicKey: string}>}
* @throws {Error} If called on mainnet or if Friendbot returns a non-OK response
*/
export async function fundAccount(publicKey) {
if (!isTestnet()) throw new Error('Only available on testnet');
const res = await fetch(`https://friendbot.stellar.org?addr=${publicKey}`);
if (!res.ok) throw new Error(`Friendbot funding failed: ${res.status} ${res.statusText}`);
logger.debug('stellar.friendbotFunded', { publicKey });
return { funded: true, publicKey };
}
/**
* Generate a new Stellar keypair, fund it via Friendbot on testnet, and persist the user record.
* @param {string|null} [correlationId] - Optional correlation ID for request tracing
* @returns {Promise<{publicKey: string, secretKey: string}>} The newly created key pair
* @throws {Error} If Friendbot funding fails
* @example
* const { publicKey, secretKey } = await createAccount('req-abc-123');
*/
export async function createAccount(correlationId = null) {
return withSpan('stellar-service', 'stellar.createAccount', async (span) => {
const pair = StellarSDK.Keypair.random();
const publicKey = pair.publicKey();
span.setAttribute('stellar.publicKey', publicKey);
withContext(logger, { action: 'createAccount', correlationId }).info('stellar.createAccount', {
publicKey,
});
let stellarAccountStatus = 'ACTIVE';
if (isTestnet()) {
const friendbotRes = await fetch(`https://friendbot.stellar.org?addr=${publicKey}`);
if (!friendbotRes.ok) {
throw new Error(
`Friendbot funding failed: ${friendbotRes.status} ${friendbotRes.statusText}`,
);
}
logger.debug('stellar.friendbotFunded', { publicKey, correlationId });
await eventMonitor.publishEvent(publicKey, {
type: 'AccountFunded',
data: { publicKey, correlationId },
version: 1,
});
} else {
const sponsorSecret = process.env.PLATFORM_FUNDING_SECRET || process.env.PLATFORM_FEE_ACCOUNT_SECRET;
if (sponsorSecret) {
const sponsorKeypair = StellarSDK.Keypair.fromSecret(sponsorSecret);
const sponsorAccount = await withHorizonRetry(() =>
getHorizonServer().loadAccount(sponsorKeypair.publicKey()),
);
const startingBalance = process.env.STELLAR_MIN_ACCOUNT_RESERVE_XLM || '1';
const tx = new StellarSDK.TransactionBuilder(sponsorAccount, {
fee: StellarSDK.BASE_FEE,
networkPassphrase: getNetworkPassphrase(),
})
.addOperation(
StellarSDK.Operation.createAccount({
destination: publicKey,
startingBalance: String(startingBalance),
}),
)
.setTimeout(30)
.build();
tx.sign(sponsorKeypair);
await withHorizonRetry(() => getHorizonServer().submitTransaction(tx));
await eventMonitor.publishEvent(publicKey, {
type: 'AccountFunded',
data: { publicKey, correlationId, sponsor: sponsorKeypair.publicKey() },
version: 1,
});
} else {
stellarAccountStatus = 'PENDING_ACTIVATION';
logger.warn('stellar.createAccount.pendingActivation', {
publicKey,
correlationId,
network: getConfig().stellar.network,
});
}
}
await eventMonitor.publishEvent(publicKey, {
type: 'AccountCreated',
data: { publicKey, correlationId },
version: 1,
});
await prisma.user
.upsert({
where: { publicKey },
update: { stellarAccountStatus },
create: { publicKey, stellarAccountStatus },
})
.catch((err) => logger.warn('db.user.upsert.failed', { error: err.message, correlationId }));
return {
publicKey,
secretKey: pair.secret(),
status: stellarAccountStatus,
};
});
}
/**
* Fetch all asset balances for a Stellar account from Horizon.
* @param {string} publicKey - Stellar public key of the account
* @param {string|null} [correlationId] - Optional correlation ID for request tracing
* @returns {Promise<{publicKey: string, balances: Array<{asset: string, balance: string}>}>}
* @throws {Error} If the account does not exist on the network
*/
export async function getBalance(publicKey, correlationId = null) {
return withSpan('stellar-service', 'stellar.getBalance', async (span) => {
span.setAttribute('stellar.publicKey', publicKey);
logger.debug('stellar.getBalance', { publicKey, correlationId });
return getCachedBalance(publicKey, async () => {
const account = await withHorizonRetry(() => getHorizonServer().loadAccount(publicKey));
const balances = account.balances.map((b) => ({
asset: b.asset_type === 'native' ? 'XLM' : `${b.asset_code}:${b.asset_issuer}`,
balance: b.balance,
}));
logger.info('stellar.balanceFetched', { publicKey, balances, correlationId });
return { publicKey, balances };
});
});
}
/**
* Send a payment on the Stellar network. Automatically wraps in a fee-bump when the
* sender's XLM balance is below FEE_BUMP_THRESHOLD_XLM and PLATFORM_FEE_ACCOUNT_SECRET is set.
* Persists the transaction to the database and emits a PaymentSent event.
* @param {string} sourceSecret - Secret key of the sending account
* @param {string} destination - Stellar public key of the recipient
* @param {string|number} amount - Amount to send (in asset units)
* @param {string} [assetCode='XLM'] - Asset code (e.g. 'XLM', 'USDC')
* @param {string|null} [memo] - Optional transaction memo value
* @param {'text'|'id'|'hash'|'return'} [memoType='text'] - Stellar memo type
* @param {string|null} [correlationId] - Optional correlation ID for request tracing
* @returns {Promise<{hash: string, ledger: number, success: boolean, feeBump: boolean}>}
* @throws {Error} If ASSET_ISSUER is missing for non-XLM assets, or if Horizon submission fails
* @example
* const result = await sendPayment(secret, 'GDEST...', '10', 'USDC', 'invoice-42');
*/
export async function sendPayment(
sourceSecret,
destination,
amount,
assetCode = 'XLM',
memo = null,
memoType = 'text',
correlationId = null,
) {
// Auto-generate a UUID correlation ID if the caller didn't supply one.
// This ID is stamped on every log line for this transaction attempt so
// engineers can filter the full lifecycle with a single query.
const txCorrelationId = correlationId ?? randomUUID();
const sourceKeypair = StellarSDK.Keypair.fromSecret(sourceSecret);
validateMemo(memo, memoType);
const sourcePublicKey = sourceKeypair.publicKey();
logger.info('stellar.sendPayment.start', {
source: sourcePublicKey,
destination,
amount,
assetCode,
memo,
memoType,
correlationId: txCorrelationId,
});
if (assetCode !== 'XLM' && !getIssuer(assetCode)) {
throw new Error('ASSET_ISSUER is required for non-XLM payments');
}
const asset =
assetCode === 'XLM'
? StellarSDK.Asset.native()
: new StellarSDK.Asset(assetCode, getIssuer(assetCode));
const txBuilder = new StellarSDK.TransactionBuilder(sourceAccount, {
fee: StellarSDK.BASE_FEE,
networkPassphrase: getNetworkPassphrase(),
}).addOperation(
StellarSDK.Operation.payment({
destination,
asset,
amount: amount.toString(),
}),
);
if (memo) {
let stellarMemo;
switch (memoType) {
case 'id':
stellarMemo = StellarSDK.Memo.id(memo);
break;
case 'hash':
stellarMemo = StellarSDK.Memo.hash(memo);
break;
case 'return':
stellarMemo = StellarSDK.Memo.return(memo);
break;
case 'text':
default:
stellarMemo = StellarSDK.Memo.text(memo);
break;
}
txBuilder.addMemo(stellarMemo);
}
const transaction = txBuilder.setTimeout(30).build();
transaction.sign(sourceKeypair);
// Fee bump: wrap if buyer XLM balance is below threshold and platform key is configured
const platformFeeSecret = process.env.PLATFORM_FEE_ACCOUNT_SECRET;
const feeBumpThreshold = parseFloat(process.env.FEE_BUMP_THRESHOLD_XLM ?? '2');
let result;
let usedFeeBump = false;
for (let attempt = 0; attempt < 2; attempt++) {
try {
const sequenceResult = await sequenceManager.withLock(sourcePublicKey, async () => {
const { account: sourceAccount, balances: sourceBalances } =
await sequenceManager.getAccountForBuild(sourcePublicKey, () =>
withHorizonRetry(() => getHorizonServer().loadAccount(sourcePublicKey)),
);
const txBuilder = new StellarSDK.TransactionBuilder(sourceAccount, {
fee: StellarSDK.BASE_FEE,
networkPassphrase: isTestnet() ? StellarSDK.Networks.TESTNET : StellarSDK.Networks.PUBLIC,
}).addOperation(
StellarSDK.Operation.payment({
destination,
asset,
amount: amount.toString(),
}),
);
if (memo) {
let stellarMemo;
switch (memoType) {
case 'id':
stellarMemo = StellarSDK.Memo.id(memo);
break;
case 'hash':
stellarMemo = StellarSDK.Memo.hash(memo);
break;
case 'return':
stellarMemo = StellarSDK.Memo.return(memo);
break;
case 'text':
default:
stellarMemo = StellarSDK.Memo.text(memo);
break;
}
txBuilder.addMemo(stellarMemo);
}
const transaction = txBuilder.setTimeout(30).build();
sequenceManager.markBuilt(sourcePublicKey, sourceAccount, sourceBalances);
transaction.sign(sourceKeypair);
let txToSubmit = transaction;
let feeBumpApplied = false;
if (platformFeeSecret) {
const xlmBalance = sourceBalances.find((b) => b.asset_type === 'native');
const xlmAmount = parseFloat(xlmBalance?.balance ?? '0');
if (xlmAmount < feeBumpThreshold) {
txToSubmit = wrapWithFeeBump(transaction, platformFeeSecret);
feeBumpApplied = true;
logger.info('stellar.feeBump.applied', {
source: sourcePublicKey,
xlmBalance: xlmAmount,
threshold: feeBumpThreshold,
correlationId: txCorrelationId,
});
await incrementFeeBumpStats(
sourcePublicKey,
StellarSDK.BASE_FEE * parseInt(process.env.FEE_BUMP_MULTIPLIER ?? '10', 10),
);
}
}
try {
const submissionResult = await withHorizonRetry(() =>
getHorizonServer().submitTransaction(txToSubmit),
);
return { submissionResult, feeBumpApplied };
} catch (submitErr) {
sequenceManager.clear(sourcePublicKey);
throw submitErr;
}
});
result = sequenceResult.submissionResult;
usedFeeBump = sequenceResult.feeBumpApplied;
break;
} catch (err) {
if (attempt === 0 && isBadSequenceError(err)) {
sequenceManager.clear(sourcePublicKey);
logger.warn('stellar.sendPayment.badSequenceResync', {
source: sourcePublicKey,
correlationId: txCorrelationId,
error: err.message,
});
continue;
}
logger.error('stellar.sendPayment.failed', {
source: sourcePublicKey,
destination,
amount,
assetCode,
error: err.message,
correlationId: txCorrelationId,
});
throw err;
}
}
const txHash = typeof txToSubmit?.hash === 'function' ? txToSubmit.hash().toString('hex') : null;
try {
result = await withHorizonRetry(() => getHorizonServer().submitTransaction(txToSubmit), txHash);
} catch (err) {
logger.error('stellar.sendPayment.failed', {
source: sourcePublicKey,
destination,
amount,
assetCode,
error: err.message,
correlationId: txCorrelationId,
});
throw err;
}
logger.info('stellar.sendPayment.success', {
source: sourcePublicKey,
destination,
amount,
assetCode,
hash: result.hash,
ledger: result.ledger,
feeBump: usedFeeBump,
memo,
memoType,
correlationId: txCorrelationId,
});
await Promise.all([
invalidateBalanceCache(sourcePublicKey),
invalidateBalanceCache(destination),
]);
try {
const { broadcastToAccount } = await import('./websocket.js');
broadcastToAccount(destination, {
type: 'balance_update',
action: 'payment_received',
source: sourcePublicKey,
destination,
amount,
assetCode: assetCode || 'XLM',
hash: result.hash,
});
} catch (wsErr) {
logger.warn('stellar.sendPayment.wsNotification.failed', { destination, error: wsErr.message });
}
await eventMonitor.publishEvent(sourcePublicKey, {
type: 'PaymentSent',
data: {
destination,
amount,
asset: assetCode || 'XLM',
hash: result.hash,
feeBump: usedFeeBump,
memo,
memoType,
correlationId: txCorrelationId,
},
version: 1,
});
await prisma
.$transaction(async (tx) => {
const [sender, recipient] = await Promise.all([
tx.user.upsert({
where: { publicKey: sourcePublicKey },
update: {},
create: { publicKey: sourcePublicKey },
}),
tx.user.upsert({
where: { publicKey: destination },
update: {},
create: { publicKey: destination },
}),
]);
await tx.transaction.create({
data: {
hash: result.hash,
assetCode: assetCode || 'XLM',
amount,
ledger: result.ledger ?? null,
successful: result.successful,
senderId: sender.id,
recipientId: recipient.id,
memo: memo ?? null,
memoType: memo ? memoType || 'text' : null,
},
});
})
.catch((err) =>
logger.warn('db.transaction.save.failed', { error: err.message, correlationId: txCorrelationId }),
);
return {
hash: result.hash,
ledger: result.ledger,
success: result.successful,
feeBump: usedFeeBump,
};
}
/**
* Trustlines
* A trustline is an explicit opt-in by an account to hold, send, or receive a
* specific non-native asset (e.g. USDC). Without a trustline, an account cannot
* receive that asset. This protects users from receiving unwanted or spam tokens
* without their consent. The Operation.changeTrust call below creates or updates
* the trustline; setting limit to '0' removes it.
* @see https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/accounts#trustlines
*
* Create a trustline for a non-XLM asset on an account. No-ops if the trustline already exists.
* @param {string} sourceSecret - Secret key of the account adding the trustline
* @param {string} assetCode - Asset code to trust (e.g. 'USDC')
* @param {string} [assetIssuer] - Optional issuer override; falls back to config/assets.js registry
* @param {string|number} [limit] - Optional trust limit; defaults to maximum if omitted
* @returns {Promise<{hash?: string, assetCode: string, issuer: string, alreadyExists?: boolean}>}
* @throws {Error} If the asset issuer is unknown or Horizon submission fails
*/
export async function createTrustline(sourceSecret, assetCode, assetIssuer, limit) {
const issuer = assetIssuer || getIssuer(assetCode);
if (!issuer) throw new Error(`Unknown asset or missing issuer for ${assetCode}`);
const sourceKeypair = StellarSDK.Keypair.fromSecret(sourceSecret);
const sourcePublicKey = sourceKeypair.publicKey();
const correlationId = randomUUID();
logger.info('stellar.createTrustline', { publicKey: sourcePublicKey, assetCode, correlationId });
const sourceAccount = await withHorizonRetry(() =>
getHorizonServer().loadAccount(sourcePublicKey),
);
const alreadyTrusted = sourceAccount.balances.some(
(b) => b.asset_code === assetCode && b.asset_issuer === issuer,
);
if (alreadyTrusted) {
logger.info('stellar.createTrustline.exists', { publicKey: sourcePublicKey, assetCode, correlationId });
return { alreadyExists: true, assetCode, issuer };
}
const asset = new StellarSDK.Asset(assetCode, issuer);
const changeTrustOpts = { asset };
if (limit !== undefined && limit !== null) changeTrustOpts.limit = limit.toString();
const transaction = new StellarSDK.TransactionBuilder(sourceAccount, {
fee: StellarSDK.BASE_FEE,
networkPassphrase: getNetworkPassphrase(),
})
.addOperation(StellarSDK.Operation.changeTrust(changeTrustOpts))
.setTimeout(30)
.build();
transaction.sign(sourceKeypair);
let result;
try {
result = await withHorizonRetry(() => getHorizonServer().submitTransaction(transaction));
} catch (err) {
logger.error('stellar.createTrustline.failed', {
publicKey: sourcePublicKey,
assetCode,
correlationId,
error: err.message,
});
throw err;
}
logger.info('stellar.createTrustline.success', {
publicKey: sourcePublicKey,
assetCode,
correlationId,
hash: result.hash,
});
await eventMonitor.publishEvent(sourcePublicKey, {
type: 'TrustlineCreated',
data: { assetCode, issuer, hash: result.hash },
version: 1,
});
return { hash: result.hash, assetCode, issuer };
}
/**
* Remove an existing trustline from an account. The asset balance must be zero.
* @param {string} sourceSecret - Secret key of the account removing the trustline
* @param {string} assetCode - Asset code of the trustline to remove
* @returns {Promise<{hash: string, assetCode: string, issuer: string}>}
* @throws {Error} If the trustline doesn't exist, the balance is non-zero, or submission fails
*/
export async function removeTrustline(sourceSecret, assetCode) {
const issuer = getIssuer(assetCode);
if (!issuer) throw new Error(`Unknown asset or missing issuer for ${assetCode}`);
const sourceKeypair = StellarSDK.Keypair.fromSecret(sourceSecret);
const sourcePublicKey = sourceKeypair.publicKey();
const correlationId = randomUUID();
logger.info('stellar.removeTrustline', { publicKey: sourcePublicKey, assetCode, correlationId });
const sourceAccount = await withHorizonRetry(() =>
getHorizonServer().loadAccount(sourcePublicKey),
);
const balance = sourceAccount.balances.find(
(b) => b.asset_code === assetCode && b.asset_issuer === issuer,
);
if (!balance) {
throw new Error(`No trustline found for ${assetCode}`);
}
if (parseFloat(balance.balance) !== 0) {
throw new Error(
`Cannot remove trustline: balance is non-zero (${balance.balance} ${assetCode})`,
);
}
const asset = new StellarSDK.Asset(assetCode, issuer);
const transaction = new StellarSDK.TransactionBuilder(sourceAccount, {
fee: StellarSDK.BASE_FEE,
networkPassphrase: getNetworkPassphrase(),
})
.addOperation(StellarSDK.Operation.changeTrust({ asset, limit: '0' }))
.setTimeout(30)
.build();
transaction.sign(sourceKeypair);
let result;
try {
result = await withHorizonRetry(() => getHorizonServer().submitTransaction(transaction));
} catch (err) {
logger.error('stellar.removeTrustline.failed', {
publicKey: sourcePublicKey,
assetCode,
correlationId,
error: err.message,
});
throw err;
}
logger.info('stellar.removeTrustline.success', {
publicKey: sourcePublicKey,
assetCode,
correlationId,
hash: result.hash,
});
await eventMonitor.publishEvent(sourcePublicKey, {
type: 'TrustlineRemoved',
data: { assetCode, issuer, hash: result.hash },
version: 1,
});
return { hash: result.hash, assetCode, issuer };
}
/**
* Path Payments
* A path payment lets the sender specify one asset to send while the recipient
* receives a different asset. The Stellar network automatically routes the
* conversion through on-chain order books or AMM liquidity pools to find the
* best available exchange rate — no manual swap step required. This is ideal
* for cross-currency remittances (e.g. send USDC, recipient receives EUR stablecoin).
* Two variants exist: strict-send (fix the send amount, maximise what arrives)
* and strict-receive (fix what the recipient gets, minimise what is sent).
* Path payment logic for this platform lives in pathPayment.js (sendPathPayment,
* findPaths, findPathsStrictReceive).
* @see https://developers.stellar.org/docs/learn/fundamentals/transactions/operations-list#path-payment-strict-send
*/
/**
* Map a raw Horizon transaction record into the shape returned to API
* consumers. Shared by {@link getTransactions} (paginated listing) and
* {@link getTransactionRecordByHash} (direct hash lookup), so both code
* paths always return an identically-shaped record.
* @param {import('@stellar/stellar-sdk').Horizon.ServerApi.TransactionRecord} tx
* @param {string} publicKey - Account the record is being rendered for (used to derive direction/counterparty)
*/
async function formatTransactionRecord(tx, publicKey) {
const ops = await tx.operations();
const op = ops.records[0];
const opType = op?.type ?? 'unknown';
const amount = op?.amount ?? null;
const asset = op?.asset_type === 'native' ? 'XLM' : op?.asset_code ? `${op.asset_code}` : null;
const counterparty = opType === 'payment' ? (op.from === publicKey ? op.to : op.from) : null;
const direction = opType === 'payment' ? (op.from === publicKey ? 'sent' : 'received') : null;
return {
id: tx.id,
hash: tx.hash,
type: opType,
direction,
amount,
asset,
counterparty,
date: tx.created_at,
fee: tx.fee_charged,
successful: tx.successful,
memo: tx.memo ?? null,
cursor: tx.paging_token,
ledger: tx.ledger_attr,
envelopeXdr: tx.envelope_xdr,
};
}
/**
* Fetch paginated transaction history for an account from Stellar Horizon.
* @param {string} publicKey - Stellar public key of the account
* @param {object} [options={}]
* @param {string} [options.cursor] - Paging token for cursor-based pagination
* @param {number} [options.limit=10] - Maximum records per page (max 200)
* @param {string} [options.type] - Filter by operation type (e.g. 'payment')
* @param {string} [options.dateFrom] - ISO date string; exclude transactions before this date
* @param {string} [options.dateTo] - ISO date string; exclude transactions after this date
* @returns {Promise<{records: object[], nextCursor: string|null, hasMore: boolean}>}
* @throws {Error} If the Horizon API call fails
*/
export async function getTransactions(
publicKey,
{ cursor, limit = 10, type, dateFrom, dateTo } = {},
) {
let builder = getHorizonServer().transactions().forAccount(publicKey).order('desc').limit(limit);
if (cursor) builder = builder.cursor(cursor);
const page = await withHorizonRetry(() => builder.call());
let records = await Promise.all(page.records.map((tx) => formatTransactionRecord(tx, publicKey)));
if (type) records = records.filter((r) => r.type === type);
if (dateFrom) records = records.filter((r) => new Date(r.date) >= new Date(dateFrom));
if (dateTo) records = records.filter((r) => new Date(r.date) <= new Date(dateTo));
return {
records,
nextCursor:
page.records.length === limit ? page.records[page.records.length - 1].paging_token : null,
hasMore: page.records.length === limit,
};
}