forked from karagozemin/OverSync
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
3767 lines (3222 loc) · 152 KB
/
Copy pathindex.ts
File metadata and controls
3767 lines (3222 loc) · 152 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
/**
* @fileoverview Relayer service for FusionBridge cross-chain operations
* @description Monitors Ethereum events and coordinates Stellar transactions
*/
import { config } from 'dotenv';
import { resolve } from 'path';
import express from 'express';
import cors from 'cors';
import { existsSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { ethers } from 'ethers';
import { startRefundWatchdog } from './refund-watchdog.js';
import { startContractEventPoller, type ContractEventBinding, type ContractEventPollerHandle } from './contract-event-poller.js';
import { startAdaptivePoll, type AdaptivePollHandle } from './adaptive-poll.js';
import { fetchIncomingEthPayments } from './eth-incoming-monitor.js';
import {
expireAbandonedOrders,
hasAwaitingXlmPayment,
hasPendingRelayerEscrow,
needsChainMonitoring,
} from './order-poll-utils.js';
import {
configureSitePresence,
hasRecentVisitor,
markVisitorPresent,
} from './site-presence.js';
import { resolveEthereumRpcUrl } from './ethereum-rpc-url.js';
// Load environment variables from root directory
config({ path: resolve(process.cwd(), '../.env') });
// ✅ NETWORK-AWARE Dynamic Safety Deposit Helper Function
function calculateDynamicSafetyDeposit(amountInWei: string | bigint, networkMode?: string): bigint {
const ETH_USD_PRICE = 3500; // $3500 per ETH
const amountInEth = parseFloat(ethers.formatEther(amountInWei.toString()));
const amountInUsd = amountInEth * ETH_USD_PRICE;
// ✅ Your preferred dynamic calculation
let safetyDepositInEth: number;
if (amountInUsd <= 50) {
safetyDepositInEth = 0.00005; // min
} else if (amountInUsd <= 100) {
safetyDepositInEth = 0.0001;
} else if (amountInUsd <= 500) {
safetyDepositInEth = 0.0002;
} else if (amountInUsd <= 1000) {
safetyDepositInEth = 0.0005;
} else {
safetyDepositInEth = Math.min(0.002, amountInEth * 0.01); // max cap
}
const originalSafetyDeposit = safetyDepositInEth;
// ✅ NETWORK-AWARE CONTRACT MINIMUMS
const isTestnet = networkMode === 'testnet' || DEFAULT_NETWORK_MODE === 'testnet';
if (isTestnet) {
// TESTNET: Enforce 0.01 ETH minimum (EscrowFactory.sol requirement)
const TESTNET_MIN_SAFETY_DEPOSIT = 0.01;
safetyDepositInEth = Math.max(safetyDepositInEth, TESTNET_MIN_SAFETY_DEPOSIT);
console.log(`🛡️ TESTNET SAFETY DEPOSIT:
📊 Amount: ${amountInEth} ETH (~$${amountInUsd.toFixed(2)})
💡 Dynamic calculation: ${originalSafetyDeposit} ETH
✅ Testnet minimum applied: ${safetyDepositInEth} ETH
📋 Testnet requires minimum: ${TESTNET_MIN_SAFETY_DEPOSIT} ETH`);
} else {
// MAINNET: Use pure dynamic calculation (no forced minimum)
console.log(`🛡️ MAINNET SAFETY DEPOSIT:
📊 Amount: ${amountInEth} ETH (~$${amountInUsd.toFixed(2)})
💡 Dynamic calculation: ${originalSafetyDeposit} ETH
✅ Final amount (no forced minimum): ${safetyDepositInEth} ETH
🎯 Mainnet uses dynamic tiers only`);
}
return ethers.parseEther(safetyDepositInEth.toString());
}
// Network Configuration
const NETWORK_CONFIG = {
testnet: {
ethereum: {
chainId: 11155111, // Sepolia
escrowFactory: '0x0ABa862Da2F004bCa6ce2990EbC0f77184B6d3a8', // NEW: Fresh EscrowFactory
htlcBridge: '0x3f42E2F5D4C896a9CB62D0128175180a288de38A', // NEW: Fresh HTLCBridge
},
stellar: {
networkPassphrase: 'Test SDF Network ; September 2015',
horizonUrl: 'https://horizon-testnet.stellar.org',
}
},
mainnet: {
ethereum: {
chainId: 1, // Ethereum Mainnet
escrowFactory: '0xa7bcb4eac8964306f9e3764f67db6a7af6ddf99a', // 1inch Factory
htlcBridge: '0x87372d4bba85acf7c2374b4719a1020e507ab73e', // MainnetHTLC (DEPLOYED!)
},
stellar: {
networkPassphrase: 'Public Global Stellar Network ; September 2015',
horizonUrl: 'https://horizon.stellar.org',
}
}
};
// Determine current network from environment (default)
const DEFAULT_NETWORK_MODE = process.env.NETWORK_MODE || 'mainnet'; // Read from .env
// Dynamic network config getter
function getNetworkConfig(networkMode?: string): any {
const selectedNetwork = networkMode || DEFAULT_NETWORK_MODE;
return NETWORK_CONFIG[selectedNetwork] || NETWORK_CONFIG[DEFAULT_NETWORK_MODE];
}
console.log(`🌐 Default Network Mode: ${DEFAULT_NETWORK_MODE.toUpperCase()}`);
console.log(`🏭 Default Escrow Factory: ${getNetworkConfig().ethereum.escrowFactory}`);
// Real HTLC Bridge Contract ABI
const HTLC_BRIDGE_ABI = [
"function createOrder(address token, uint256 amount, bytes32 hashLock, uint256 timelock, uint256 feeRate, address beneficiary, address refundAddress, uint256 destinationChainId, bytes32 stellarTxHash, bool partialFillEnabled) external payable returns (uint256 orderId)"
];
// MAINNET: GERÇEK 1inch EscrowFactory ABI (verdiğin ABI'dan)
const MAINNET_ESCROW_FACTORY_ABI = [
`function createDstEscrow(
(bytes32 orderHash, bytes32 hashlock, uint256 maker, uint256 taker, uint256 token, uint256 amount, uint256 safetyDeposit, uint256 timelocks) dstImmutables,
uint256 srcCancellationTimestamp
) external payable`,
"function addressOfEscrowSrc((bytes32 orderHash, bytes32 hashlock, uint256 maker, uint256 taker, uint256 token, uint256 amount, uint256 safetyDeposit, uint256 timelocks) immutables) external view returns (address)",
"function addressOfEscrowDst((bytes32 orderHash, bytes32 hashlock, uint256 maker, uint256 taker, uint256 token, uint256 amount, uint256 safetyDeposit, uint256 timelocks) immutables) external view returns (address)",
"function ESCROW_SRC_IMPLEMENTATION() external view returns (address)",
"function ESCROW_DST_IMPLEMENTATION() external view returns (address)",
"function availableCredit(address account) external view returns (uint256)",
"function increaseAvailableCredit(address account, uint256 amount) external returns (uint256 allowance)",
"function decreaseAvailableCredit(address account, uint256 amount) external returns (uint256 allowance)",
// Events
"event DstEscrowCreated(address escrow, bytes32 hashlock, uint256 taker)",
"event SrcEscrowCreated((bytes32 orderHash, bytes32 hashlock, uint256 maker, uint256 taker, uint256 token, uint256 amount, uint256 safetyDeposit, uint256 timelocks) srcImmutables, (uint256 maker, uint256 amount, uint256 token, uint256 safetyDeposit, uint256 chainId) dstImmutablesComplement)"
];
// TESTNET: Bizim custom EscrowFactory ABI (eski hali)
const TESTNET_ESCROW_FACTORY_ABI = [
"function createEscrow((address token, uint256 amount, bytes32 hashLock, uint256 timelock, address beneficiary, address refundAddress, uint256 safetyDeposit, uint256 chainId, bytes32 stellarTxHash, bool isPartialFillEnabled) config) external payable returns (uint256 escrowId)",
"function fundEscrow(uint256 escrowId) external",
"function claimEscrow(uint256 escrowId, bytes32 preimage) external",
"function refundEscrow(uint256 escrowId) external",
"function getEscrow(uint256 escrowId) external view returns (tuple(address escrowAddress, tuple(address token, uint256 amount, bytes32 hashLock, uint256 timelock, address beneficiary, address refundAddress, uint256 safetyDeposit, uint256 chainId, bytes32 stellarTxHash, bool isPartialFillEnabled) config, uint8 status, uint256 createdAt, uint256 filledAmount, uint256 safetyDepositPaid, address resolver, bool isActive))",
"function authorizeResolver(address resolver) external",
"function authorizedResolvers(address resolver) external view returns (bool)",
"function totalEscrows() external view returns (uint256)",
"function MIN_SAFETY_DEPOSIT() external view returns (uint256)",
"function MAX_SAFETY_DEPOSIT() external view returns (uint256)",
// Events
"event EscrowCreated(uint256 indexed escrowId, address indexed escrowAddress, address indexed resolver, address token, uint256 amount, bytes32 hashLock, uint256 timelock, uint256 safetyDeposit, uint256 chainId)",
"event EscrowFunded(uint256 indexed escrowId, address indexed funder, uint256 amount, uint256 safetyDeposit)",
"event EscrowClaimed(uint256 indexed escrowId, address indexed claimer, uint256 amount, bytes32 preimage)",
"event EscrowRefunded(uint256 indexed escrowId, address indexed refundee, uint256 amount, uint256 safetyDeposit)"
];
// Dinamik ABI seçici
function getEscrowFactoryABI(isMainnet: boolean) {
return isMainnet ? MAINNET_ESCROW_FACTORY_ABI : TESTNET_ESCROW_FACTORY_ABI;
}
import { ethereumListener } from './ethereum-listener.js';
import { quoterService } from './quoter-service.js';
import { ordersService } from './orders.js';
import { gasPriceTracker } from './gas-tracker.js';
import { presetManager } from './preset-manager.js';
import { validateQuoteRequest, createErrorResponse, createSuccessResponse, getErrorMessage } from './utils.js';
import { QuoteRequest, SignedOrderInput, SecretInput } from './types.js';
// Phase 4: Event System imports
import FusionEventManager, { EventType } from './event-handlers.js';
import FusionRpcHandler from './rpc-methods.js';
import EventHistoryManager from './event-history.js';
import ClientSubscriptionManager from './client-subscriptions.js';
// Phase 5: Recovery System imports
import RecoveryService, { RecoveryConfig, RecoveryType, RecoveryStatus } from './recovery-service.js';
// Stellar SDK will be imported dynamically when needed
// Phase 8: Monitoring System imports
import { getMonitor } from './monitoring.js';
// Contract addresses
const ETH_TO_XLM_RATE = 10000; // 1 ETH = 10,000 XLM (LEGACY - now using real-time prices)
// Network-aware contract addresses
const HTLC_CONTRACT_ADDRESS = getHtlcBridgeAddress(); // Dynamic: testnet/mainnet
// Real-time price fetching with two-tier in-memory cache.
//
// CoinGecko's free public API is aggressive about rate limits (~10-30 calls/min
// per IP), so we cannot hit it on every quote. But a flat 60s cache feels
// stale in a crypto UX — most DEX aggregators refresh visible prices every
// 10-20s. We split the difference with a stale-while-revalidate (SWR) cache:
//
// - Within FRESH_MS (15s): serve cached data, no upstream call.
// - Within STALE_MS (60s): serve cached data immediately AND kick off a
// background refresh so the next caller gets a fresher snapshot.
// - Past STALE_MS: callers wait for a fresh fetch (de-duped via inflight
// promise so a burst of swaps doesn't fan out to multiple CoinGecko calls).
//
// Net effect: the UI feels live (refreshes within ~15s of any user activity)
// while CoinGecko calls stay bounded to at most one every ~15s under load.
// Crucially, both the frontend quote and the relayer's settlement use this
// same cache, so the price a user is quoted matches the price they settle at
// for the duration of a single cache window.
interface PriceSnapshot {
xlmUsdPrice: number;
ethUsdPrice: number;
ethToXlmRate: number;
fetchedAt: number;
source: 'coingecko' | 'fallback' | 'cache';
}
const PRICE_CACHE_FRESH_MS = 15_000;
const PRICE_CACHE_STALE_MS = 60_000;
let cachedPrices: PriceSnapshot | null = null;
let inflightPriceFetch: Promise<PriceSnapshot> | null = null;
async function fetchPricesFromCoinGecko(): Promise<PriceSnapshot> {
const fallback: PriceSnapshot = {
xlmUsdPrice: 0.12,
ethUsdPrice: 3500,
ethToXlmRate: 3500 / 0.12,
fetchedAt: Date.now(),
source: 'fallback',
};
try {
const priceResponse = await fetch(
'https://api.coingecko.com/api/v3/simple/price?ids=stellar,ethereum&vs_currencies=usd'
);
if (!priceResponse.ok) {
console.warn('⚠️ CoinGecko API non-OK:', priceResponse.status);
return fallback;
}
const priceData = await priceResponse.json() as any;
const xlmUsdPrice = priceData.stellar?.usd;
const ethUsdPrice = priceData.ethereum?.usd;
if (typeof xlmUsdPrice !== 'number' || typeof ethUsdPrice !== 'number' || xlmUsdPrice <= 0 || ethUsdPrice <= 0) {
console.warn('⚠️ CoinGecko returned malformed prices, using fallback');
return fallback;
}
console.log('📊 Real-time prices fetched from CoinGecko:', { xlmUsdPrice, ethUsdPrice });
return {
xlmUsdPrice,
ethUsdPrice,
ethToXlmRate: ethUsdPrice / xlmUsdPrice,
fetchedAt: Date.now(),
source: 'coingecko',
};
} catch (priceError: any) {
console.warn('⚠️ Price fetch failed, using fallback prices:', priceError?.message);
return fallback;
}
}
function triggerBackgroundRefresh(): void {
if (inflightPriceFetch) return;
inflightPriceFetch = fetchPricesFromCoinGecko()
.then((snapshot) => {
cachedPrices = snapshot;
return snapshot;
})
.catch((err) => {
// SWR background refresh; keep the stale entry. We log so an outage is
// visible but never propagate the error to the caller serving stale.
console.warn('⚠️ Background price refresh failed; keeping stale entry:', err?.message ?? err);
return cachedPrices ?? {
xlmUsdPrice: 0.12,
ethUsdPrice: 3500,
ethToXlmRate: 3500 / 0.12,
fetchedAt: Date.now(),
source: 'fallback' as const,
};
})
.finally(() => {
inflightPriceFetch = null;
});
}
async function getPriceSnapshot(): Promise<PriceSnapshot> {
const now = Date.now();
if (cachedPrices) {
const age = now - cachedPrices.fetchedAt;
if (age < PRICE_CACHE_FRESH_MS) {
// Fully fresh — serve cached, do nothing else.
return { ...cachedPrices, source: 'cache' };
}
if (age < PRICE_CACHE_STALE_MS) {
// Stale-but-acceptable — serve cached, refresh in background so the
// next caller sees fresher data without blocking this one.
triggerBackgroundRefresh();
return { ...cachedPrices, source: 'cache' };
}
}
// No cache or beyond STALE — must block on a fresh fetch. De-dupe concurrent
// callers so a burst of swap requests collapses into a single CoinGecko hit.
if (!inflightPriceFetch) {
inflightPriceFetch = fetchPricesFromCoinGecko()
.then((snapshot) => {
cachedPrices = snapshot;
return snapshot;
})
.finally(() => {
inflightPriceFetch = null;
});
}
return inflightPriceFetch;
}
async function getRealTimePrices(): Promise<{xlmUsdPrice: number, ethUsdPrice: number, ethToXlmRate: number}> {
const snapshot = await getPriceSnapshot();
return {
xlmUsdPrice: snapshot.xlmUsdPrice,
ethUsdPrice: snapshot.ethUsdPrice,
ethToXlmRate: snapshot.ethToXlmRate,
};
}
// Dynamic contract address getters
function getEscrowFactoryAddress(networkMode?: string): string {
return getNetworkConfig(networkMode).ethereum.escrowFactory;
}
function getHtlcBridgeAddress(networkMode?: string): string {
return getNetworkConfig(networkMode).ethereum.htlcBridge;
}
// New function to determine which contract to use based on operation type
function shouldUseHTLCContract(networkMode?: string): boolean {
const config = getNetworkConfig(networkMode);
const selectedNetwork = networkMode || DEFAULT_NETWORK_MODE;
// ✅ BOTH MAINNET AND TESTNET: Always use EscrowFactory
// HTLC only for Stellar side (non-EVM) and XLM→ETH orders
return false; // Always use EscrowFactory for ETH→XLM transactions
}
function parseCsv(value?: string): string[] {
if (!value) {
return [];
}
return value
.split(',')
.map(item => item.trim())
.filter(Boolean);
}
function withTimeout<T>(promise: Promise<T>, timeoutMs: number, errorMessage: string): Promise<T> {
return Promise.race([
promise,
new Promise<T>((_, reject) => {
setTimeout(() => reject(new Error(errorMessage)), timeoutMs);
})
]);
}
function resolveEthereumRpcUrlForRelayer(): string {
const network = DEFAULT_NETWORK_MODE === 'mainnet' ? 'mainnet' : 'testnet';
return resolveEthereumRpcUrl(network);
}
// Relayer configuration from environment variables
export const RELAYER_CONFIG = {
// Service settings
port: Number(process.env.RELAYER_PORT || process.env.PORT) || 3001,
pollInterval: Number(process.env.RELAYER_POLL_INTERVAL) || 15_000,
activePollIntervalMs: Number(process.env.RELAYER_ACTIVE_POLL_INTERVAL_MS) || 15_000,
idlePollIntervalMs: Number(process.env.RELAYER_IDLE_POLL_INTERVAL_MS) || 120_000,
visitorTtlMs: Number(process.env.RELAYER_VISITOR_TTL_MS) || 5 * 60_000,
retryAttempts: Number(process.env.RELAYER_RETRY_ATTEMPTS) || 3,
retryDelay: Number(process.env.RELAYER_RETRY_DELAY) || 2000,
// Network configuration
nodeEnv: process.env.NODE_ENV || 'development',
enableMockMode: process.env.ENABLE_MOCK_MODE === 'true',
debug: process.env.DEBUG === 'true',
resolverAllowlist: parseCsv(process.env.RELAYER_RESOLVER_ADDRESSES),
rpcTimeoutMs: Number(process.env.RELAYER_RPC_TIMEOUT_MS) || 30000,
// Ethereum configuration
ethereum: {
network: process.env.ETHEREUM_NETWORK || 'mainnet',
rpcUrl: resolveEthereumRpcUrlForRelayer(),
// ✅ Dynamic contract addresses based on network
contractAddress: getHtlcBridgeAddress(DEFAULT_NETWORK_MODE), // For EthereumEventListener (testnet only)
escrowFactoryAddress: getEscrowFactoryAddress(DEFAULT_NETWORK_MODE), // For transactions (mainnet + testnet)
fusionApiUrl: 'https://api.1inch.dev/fusion',
fusionApiKey: process.env.ONEINCH_API_KEY || '',
privateKey: process.env.RELAYER_PRIVATE_KEY || '',
gasPrice: Number(process.env.GAS_PRICE_GWEI) || 20,
gasLimit: Number(process.env.GAS_LIMIT) || 300000,
startBlock: Number(process.env.START_BLOCK_ETHEREUM) || 0,
minConfirmations: Number(process.env.MIN_CONFIRMATION_BLOCKS) || 6,
},
// Stellar configuration - DYNAMIC based on DEFAULT_NETWORK_MODE
stellar: {
network: process.env.STELLAR_NETWORK || DEFAULT_NETWORK_MODE, // ✅ DEFAULT_NETWORK_MODE kullan!
horizonUrl: process.env.STELLAR_HORIZON_URL || (
(DEFAULT_NETWORK_MODE === 'mainnet')
? 'https://horizon.stellar.org'
: 'https://horizon-testnet.stellar.org'
),
networkPassphrase: process.env.STELLAR_NETWORK_PASSPHRASE || (
(DEFAULT_NETWORK_MODE === 'mainnet')
? 'Public Global Stellar Network ; September 2015'
: 'Test SDF Network ; September 2015'
),
secretKey: process.env.RELAYER_STELLAR_SECRET || '',
publicKey: process.env.RELAYER_STELLAR_PUBLIC || '',
startLedger: Number(process.env.START_LEDGER_STELLAR) || 0,
minConfirmations: Number(process.env.STELLAR_MIN_CONFIRMATIONS) || 1,
},
// Fee and limit settings
fees: {
feeRate: Number(process.env.RELAYER_FEE_RATE) || 50, // basis points
minSwapAmountUSD: Number(process.env.MIN_SWAP_AMOUNT_USD) || 10,
maxSwapAmountUSD: Number(process.env.MAX_SWAP_AMOUNT_USD) || 100000,
maxOrderAmount: Number(process.env.MAX_ORDER_AMOUNT) || 1000000,
},
// Security settings
security: {
minTimelockDuration: Number(process.env.MIN_TIMELOCK_DURATION) || 3600,
maxTimelockDuration: Number(process.env.MAX_TIMELOCK_DURATION) || 604800,
defaultTimelockDuration: Number(process.env.DEFAULT_TIMELOCK_DURATION) || 86400,
emergencyShutdown: process.env.EMERGENCY_SHUTDOWN === 'true',
maintenanceMode: process.env.MAINTENANCE_MODE === 'true',
},
// Monitoring and logging
monitoring: {
logLevel: process.env.LOG_LEVEL || 'info',
enableRequestLogging: process.env.ENABLE_REQUEST_LOGGING === 'true',
verboseLogging: process.env.VERBOSE_LOGGING === 'true',
healthCheckInterval: Number(process.env.HEALTH_CHECK_INTERVAL) || 30000,
healthCheckTimeout: Number(process.env.HEALTH_CHECK_TIMEOUT) || 5000,
}
};
// Validate required environment variables
function validateConfig() {
const requiredVars = [
'ETHEREUM_RPC_URL',
'STELLAR_HORIZON_URL',
];
const missingVars = requiredVars.filter(varName => !process.env[varName] || process.env[varName]?.includes('YOUR_'));
if (missingVars.length > 0) {
console.warn('⚠️ Missing or placeholder environment variables:');
missingVars.forEach(varName => {
console.warn(` - ${varName}`);
});
console.warn(' Please copy env.template to .env and configure properly');
}
// Check for placeholder private keys
if (process.env.RELAYER_PRIVATE_KEY?.startsWith('0x000000')) {
console.warn('⚠️ Using placeholder private key - generate a real key for production');
}
if (process.env.RELAYER_STELLAR_SECRET?.includes('SAMPLE')) {
console.warn('⚠️ Using placeholder Stellar secret - generate real keys for production');
}
}
// Initialize relayer service
async function initializeRelayer() {
console.log('🔄 Initializing FusionBridge Relayer Service');
console.log('============================================');
// Configure Express middleware with enhanced CORS
app.use(cors({
origin: [
'http://localhost:5173',
'http://localhost:5174',
'http://127.0.0.1:5173',
'http://127.0.0.1:5174',
'https://oversync.vercel.app',
'https://oversync.vercel.app/'
],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
credentials: true
}));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));
// Validate configuration
validateConfig();
// Display configuration
console.log(`🌐 Environment: ${RELAYER_CONFIG.nodeEnv}`);
console.log(`🔗 Ethereum Network: ${RELAYER_CONFIG.ethereum.network}`);
console.log(`⭐ Stellar Network: ${RELAYER_CONFIG.stellar.network}`);
console.log(`🏃 Mock Mode: ${RELAYER_CONFIG.enableMockMode ? 'Enabled' : 'Disabled'}`);
console.log(`📊 Port: ${RELAYER_CONFIG.port}`);
console.log(`⏱️ Poll Interval: ${RELAYER_CONFIG.pollInterval}ms`);
if (RELAYER_CONFIG.security.emergencyShutdown) {
console.error('🚨 Emergency shutdown is active - service will not start');
process.exit(1);
}
if (RELAYER_CONFIG.security.maintenanceMode) {
console.warn('🔧 Maintenance mode is active');
}
// Global order storage (in production this would be a database).
// Declared early so chain pollers can skip RPC when nothing is in flight.
const activeOrders = new Map<string, any>();
const chainPollers: AdaptivePollHandle[] = [];
let escrowFactoryPoller: ContractEventPollerHandle | null = null;
let chainMonitoringStarted = false;
let chainMonitoringPromise: Promise<void> | null = null;
const wakeChainPollers = (): void => {
if (!chainMonitoringStarted) return;
ethereumListener.wakePolling();
escrowFactoryPoller?.wake();
for (const poller of chainPollers) {
poller.wake();
}
};
const storeActiveOrder = async (
orderId: string,
orderData: Record<string, unknown>
): Promise<void> => {
activeOrders.set(orderId, orderData);
if (!needsChainMonitoring(activeOrders)) return;
await ensureChainMonitoring();
wakeChainPollers();
};
const stopChainMonitoring = async (): Promise<void> => {
if (!chainMonitoringStarted) return;
console.log('💤 Stopping chain monitoring — no in-flight orders');
for (const poller of chainPollers) poller.stop();
chainPollers.length = 0;
escrowFactoryPoller?.stop();
escrowFactoryPoller = null;
try {
await ethereumListener.stopListening();
} catch {
/* already stopped */
}
chainMonitoringStarted = false;
chainMonitoringPromise = null;
};
const reconcileChainMonitoring = (): void => {
const expired = expireAbandonedOrders(activeOrders);
if (expired > 0) {
console.log(`⏱️ Expired ${expired} abandoned pre-deposit order(s)`);
}
if (chainMonitoringStarted && !needsChainMonitoring(activeOrders)) {
void stopChainMonitoring();
}
};
setInterval(reconcileChainMonitoring, 60_000);
configureSitePresence(RELAYER_CONFIG.visitorTtlMs);
/** Marks a browser session — does not touch Infura until a swap order exists. */
const handleVisitorWake = (): void => {
markVisitorPresent();
wakeChainPollers();
};
let ensureChainMonitoring: () => Promise<void> = async () => {
if (chainMonitoringStarted) return;
if (!chainMonitoringPromise) {
chainMonitoringPromise = (async () => {
chainMonitoringStarted = true;
await startChainMonitoring();
})().catch((err) => {
chainMonitoringStarted = false;
chainMonitoringPromise = null;
throw err;
});
}
await chainMonitoringPromise;
};
let startChainMonitoring: () => Promise<void> = async () => {};
// Start gas price tracking
try {
gasPriceTracker.startMonitoring(30000); // Monitor every 30 seconds
console.log('⛽ Gas price tracking started');
} catch (error) {
console.error('❌ Failed to start gas price tracking:', error);
}
// Start monitoring system
try {
const monitor = getMonitor();
monitor.registerService('ethereum', async () => ({ status: 'healthy' }));
monitor.registerService('stellar', async () => ({ status: 'healthy' }));
monitor.registerService('gas-tracker', async () => ({ status: 'healthy' }));
monitor.registerService('orders', async () => ({ status: 'healthy' }));
monitor.startMonitoring(30000); // Monitor every 30 seconds
console.log('📊 Uptime monitoring started');
} catch (error) {
console.error('❌ Failed to start monitoring system:', error);
}
// Chain listeners start lazily on the first swap order — not at boot.
// See `startChainMonitoring` below (zero Infura RPC while idle).
// ===== ORDERS API ENDPOINTS =====
// ✅ Network-aware contract logging
console.log(`🌐 Network Mode: ${DEFAULT_NETWORK_MODE.toUpperCase()}`);
if (DEFAULT_NETWORK_MODE === 'mainnet') {
console.log('🏭 MAINNET Escrow Factory:', getEscrowFactoryAddress('mainnet'));
console.log('🎯 MAINNET HTLC (XLM→ETH only):', getHtlcBridgeAddress('mainnet'));
} else {
console.log('🧪 TESTNET HTLC Bridge (Event Listener):', getHtlcBridgeAddress('testnet'));
console.log('🧪 TESTNET Escrow Factory:', getEscrowFactoryAddress('testnet'));
}
// DEBUG: Simple transaction test
app.get('/api/test-transaction', (req, res) => {
res.json({
success: true,
approvalTransaction: {
to: '0x742d35cF0b7bbF6E175239d74a0e0a3d1C7B87E4', // Simple relayer address
value: '0x71afd498d0000', // 0.001 ETH
data: '0x',
gas: '0x5208', // Standard ETH transfer gas
gasPrice: '0x4a817c800'
},
message: 'DEBUG: Simple transaction format'
});
});
// POST /api/orders/create - Create bridge order (Frontend Integration)
console.log("📍 DEBUG: About to register orders endpoint");
// Root route first
app.get('/', (req, res) => {
res.json({ message: 'FusionBridge Relayer API', status: 'running' });
});
// Simple test endpoints
app.get('/test', (req, res) => {
res.json({ message: 'ROOT test working!', timestamp: new Date().toISOString() });
});
app.get('/api/test', (req, res) => {
res.json({ message: 'API endpoints are working!', timestamp: new Date().toISOString() });
});
// Frontend calls this on page load — marks a browser session only.
// Infura RPC starts on the first swap order, not on wake.
app.post('/api/wake', (_req, res) => {
handleVisitorWake();
res.status(204).end();
});
app.get('/api/wake', (_req, res) => {
handleVisitorWake();
res.status(204).end();
});
// Debug: verify lazy monitoring + stuck orders (safe to expose — no secrets).
app.get('/api/debug/chain-monitor', (_req, res) => {
reconcileChainMonitoring();
const statuses: Record<string, number> = {};
for (const order of activeOrders.values()) {
const s = String(order?.status ?? 'unknown');
statuses[s] = (statuses[s] ?? 0) + 1;
}
res.json({
chainMonitoringStarted,
needsChainMonitoring: needsChainMonitoring(activeOrders),
activeOrderCount: activeOrders.size,
hasRecentVisitor: hasRecentVisitor(),
orderStatuses: statuses,
build: 'lazy-chain-monitor-v2',
});
});
// GET /api/prices
//
// Public, cached price feed used by the frontend to render accurate quote
// estimates *and* by external monitoring. We intentionally proxy CoinGecko
// through the relayer for two reasons:
// 1. The browser cannot call CoinGecko directly (CORS), so a previous
// build silently fell back to a hardcoded 1 ETH = 10,000 XLM rate.
// That diverged from what the relayer actually settled at swap time,
// so users were quoted ~3x more XLM than they ended up receiving.
// 2. Centralizing the fetch lets us cache (PRICE_CACHE_TTL_MS) and protect
// ourselves from CoinGecko's rate limits — a high-traffic page would
// otherwise blow through the free quota.
app.get('/api/prices', async (_req, res) => {
try {
const snapshot = await getPriceSnapshot();
res.json({
xlmUsd: snapshot.xlmUsdPrice,
ethUsd: snapshot.ethUsdPrice,
ethPerXlm: snapshot.xlmUsdPrice / snapshot.ethUsdPrice,
xlmPerEth: snapshot.ethToXlmRate,
source: snapshot.source,
fetchedAt: snapshot.fetchedAt,
// SWR window — UI can hint to users when a refresh is due.
cacheFreshMs: PRICE_CACHE_FRESH_MS,
cacheStaleMs: PRICE_CACHE_STALE_MS,
});
} catch (err: any) {
res.status(503).json({
error: 'Price feed temporarily unavailable',
details: err?.message ?? String(err),
});
}
});
console.log('📍 DEBUG: Test endpoints registered (root + api)');
console.log('📍 DEBUG: Now registering transaction history endpoint...');
// POST /api/transactions/history - RIGHT NEXT TO WORKING ENDPOINT
app.post('/api/transactions/history', async (req, res) => {
console.log('🎯 TRANSACTION HISTORY ENDPOINT HIT - NEXT TO ORDERS!');
try {
const { ethAddress, stellarAddress } = req.body;
console.log('📊 Fetching transaction history for:', { ethAddress, stellarAddress });
// Get all orders from activeOrders Map
const allOrders = Array.from(activeOrders.values());
console.log('📊 Total orders in activeOrders:', allOrders.length);
// Filter orders by user addresses and format for history
const userTransactions = allOrders
.filter(order =>
(ethAddress && order.ethAddress === ethAddress) ||
(stellarAddress && order.stellarAddress === stellarAddress)
)
.map(order => ({
id: order.orderId,
txHash: order.ethTxHash || order.stellarTxHash || order.orderId,
fromNetwork: order.direction === 'eth-to-xlm' ?
(DEFAULT_NETWORK_MODE === 'mainnet' ? 'ETH Mainnet' : 'ETH Sepolia') :
(DEFAULT_NETWORK_MODE === 'mainnet' ? 'Stellar Mainnet' : 'Stellar Testnet'),
toNetwork: order.direction === 'eth-to-xlm' ?
(DEFAULT_NETWORK_MODE === 'mainnet' ? 'Stellar Mainnet' : 'Stellar Testnet') :
(DEFAULT_NETWORK_MODE === 'mainnet' ? 'ETH Mainnet' : 'ETH Sepolia'),
fromToken: order.direction === 'eth-to-xlm' ? 'ETH' : 'XLM',
toToken: order.direction === 'eth-to-xlm' ? 'XLM' : 'ETH',
amount: order.amount || '0',
estimatedAmount: order.targetAmount ?
(parseFloat(order.targetAmount) / 1e18).toFixed(6) : '0',
status: order.status === 'completed' ? 'completed' :
order.status === 'failed' ? 'failed' :
order.status === 'cancelled' ? 'cancelled' : 'pending',
timestamp: order.timestamp || Date.now(),
ethTxHash: order.ethTxHash,
stellarTxHash: order.stellarTxHash,
direction: order.direction
}))
.sort((a, b) => b.timestamp - a.timestamp);
console.log(`📊 Found ${userTransactions.length} matching transactions for user`);
res.json({
success: true,
transactions: userTransactions,
count: userTransactions.length
});
} catch (error: any) {
console.error('❌ Transaction history fetch failed:', error);
res.status(500).json({
error: 'Failed to fetch transaction history',
details: error instanceof Error ? error.message : 'Unknown error'
});
}
});
app.post('/api/orders/create', async (req, res) => {
try {
console.log('🔍 RAW REQUEST BODY:', JSON.stringify(req.body, null, 2));
const { fromChain, toChain, fromToken, toToken, amount, ethAddress, stellarAddress, direction, exchangeRate, network, networkMode } = req.body;
console.log('🎯 EXTRACTED VALUES:', {
amount: amount,
amountType: typeof amount,
amountLength: amount ? amount.length : 'undefined',
amountString: String(amount)
});
// Validate required fields
if (!fromChain || !toChain || !fromToken || !toToken || !amount || !ethAddress || !stellarAddress) {
console.log('❌ VALIDATION FAILED:', {
fromChain: !!fromChain,
toChain: !!toChain,
fromToken: !!fromToken,
toToken: !!toToken,
amount: !!amount,
ethAddress: !!ethAddress,
stellarAddress: !!stellarAddress
});
return res.status(400).json({
error: 'Missing required fields',
required: ['fromChain', 'toChain', 'fromToken', 'toToken', 'amount', 'ethAddress', 'stellarAddress']
});
}
console.log('🌉 Creating bridge order:', {
direction,
fromChain,
toChain,
fromToken,
toToken,
amount,
exchangeRate: exchangeRate || ETH_TO_XLM_RATE,
ethAddress,
stellarAddress
});
// Normalize addresses to avoid checksum issues
const normalizedEthAddress = ethAddress.toLowerCase();
// Generate order ID
const orderId = `order_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
// Dynamic network detection from request or fallback to env
const requestNetwork = networkMode || network || (req.query.network) || DEFAULT_NETWORK_MODE;
const isMainnetRequest = requestNetwork === 'mainnet';
console.log(`🌐 Network Detection:`, {
requestNetwork,
queryParam: req.query.network,
bodyNetworkMode: networkMode,
bodyNetwork: network,
envDefault: DEFAULT_NETWORK_MODE,
finalDecision: isMainnetRequest ? 'MAINNET' : 'TESTNET'
});
// FORCE DEBUG: Always log this
console.log(`🔍 CRITICAL DEBUG:`, {
'networkMode': networkMode,
'network': network,
'req.query.network': req.query.network,
'DEFAULT_NETWORK_MODE': DEFAULT_NETWORK_MODE,
'requestNetwork': requestNetwork,
'isMainnetRequest': isMainnetRequest,
'WILL_GO_TO': isMainnetRequest ? 'MAINNET_BRANCH' : 'TESTNET_BRANCH'
});
// For ETH to XLM direction
if (direction === 'eth_to_xlm') {
if (isMainnetRequest) {
// MAINNET: Use DUAL CONTRACT APPROACH (1inch EscrowFactory + MainnetHTLC)
const useHTLC = shouldUseHTLCContract('mainnet');
console.log(`🏭 MAINNET: Using ${useHTLC ? 'HTLC + EscrowFactory' : 'EscrowFactory only'} approach...`);
// MOCK MODE for ETH→XLM
if (RELAYER_CONFIG.enableMockMode) {
console.log('🧪 MOCK MODE: Simulating ETH→XLM mainnet escrow creation...');
const userAmountWei = ethers.parseEther(amount);
const secret = ethers.hexlify(ethers.randomBytes(32));
const hashLock = ethers.keccak256(secret);
const orderData = {
orderId,
direction: 'eth_to_xlm',
amount: userAmountWei.toString(),
ethAddress: normalizedEthAddress,
stellarAddress,
exchangeRate: exchangeRate || ETH_TO_XLM_RATE,
secret,
hashLock,
created: new Date().toISOString(),
status: 'mock_escrow_created',
contractType: 'MOCK_1INCH_ESCROW_FACTORY'
};
await storeActiveOrder(orderId, orderData);
return res.json({
success: true,
orderId,
orderData,
message: '🧪 MOCK: ETH→XLM escrow created',
nextStep: 'Mock: User MetaMask transaction',
instructions: [
'🧪 MOCK MODE: No real transactions',
'1. Mock 1inch EscrowFactory createDstEscrow called',
'2. Mock safety deposit and escrow creation',
'3. Mock Stellar HTLC creation for XLM delivery'
],
ethereum: {
contractAddress: getEscrowFactoryAddress('mainnet'),
method: 'createDstEscrow',
amount: amount + ' ETH',
hashLock
},
stellar: {
htlcId: `mock-stellar-htlc-${Date.now()}`,
amount: (parseFloat(amount) * ETH_TO_XLM_RATE).toFixed(7) + ' XLM', // Mock mode uses legacy rate
hashLock
}
});
}
// Get REAL-TIME exchange rates from market for ETH→XLM
const realTimePrices = await getRealTimePrices();
const { xlmUsdPrice, ethUsdPrice, ethToXlmRate } = realTimePrices;
// amount is already a string like "0.00012", convert to wei
const userAmountWei = ethers.parseEther(amount);
console.log(`💰 User Amount: ${amount} ETH = ${userAmountWei.toString()} wei`);
// Calculate real XLM amount from ETH using market prices
const ethAmount = parseFloat(amount);
const realMarketXlmAmount = (ethAmount * ethUsdPrice) / xlmUsdPrice;
console.log('💱 REAL MARKET ETH→XLM Exchange:', {
ethAmount,
ethUsdPrice: `$${ethUsdPrice}`,
xlmUsdPrice: `$${xlmUsdPrice}`,
realMarketRate: `1 ETH = ${realMarketXlmAmount.toFixed(2)} XLM`,
ethTotalValue: `$${(ethAmount * ethUsdPrice).toFixed(4)}`,
xlmAmount: `${realMarketXlmAmount.toFixed(7)} XLM`,
xlmTotalValue: `$${(realMarketXlmAmount * xlmUsdPrice).toFixed(4)}`
});
// Generate HTLC parameters for cross-chain bridge
const secretBytes = new Uint8Array(32);
crypto.getRandomValues(secretBytes);
const secret = `0x${Array.from(secretBytes).map(b => b.toString(16).padStart(2, '0')).join('')}`;
const hashLock = ethers.keccak256(secret);
console.log('🔑 Generated HTLC parameters:', {
secret: secret.substring(0, 10) + '...',
hashLock: hashLock
});
// Calculate dynamic safety deposit with network awareness
const actualSafetyDeposit = calculateDynamicSafetyDeposit(userAmountWei, requestNetwork);
const amountInEth = parseFloat(ethers.formatEther(userAmountWei));
const amountInUsd = amountInEth * ethUsdPrice; // Use real ETH price
const safetyDepositInEth = parseFloat(ethers.formatEther(actualSafetyDeposit));
console.log(`💰 Dynamic Safety Deposit:
📊 Amount: ${amountInEth} ETH (~$${amountInUsd.toFixed(2)})
🛡️ Safety Deposit: ${safetyDepositInEth} ETH (~$${(safetyDepositInEth * 3500).toFixed(2)})`);
console.log('💰 Safety deposit:', ethers.formatEther(actualSafetyDeposit), 'ETH');
// Generate order hash for 1inch protocol
const orderHash = ethers.keccak256(
ethers.solidityPacked(
['address', 'uint256', 'bytes32', 'uint256'],
[normalizedEthAddress, userAmountWei, hashLock, Math.floor(Date.now() / 1000)]
)
);
// Store order with HTLC details
const orderData = {
orderId,
orderHash,
hashLock: hashLock,
secret: secret,
ethAddress: normalizedEthAddress,
stellarAddress,
amount: userAmountWei.toString(),
safetyDeposit: actualSafetyDeposit.toString(),
exchangeRate: ethToXlmRate, // Use real-time rate
contractType: 'ONEINCH_ESCROW_FACTORY_MAINNET_DST',
status: 'pending_dst_escrow_deployment',
network: 'ethereum',
chainId: 1,
created: new Date().toISOString()
};
// ✅ Add networkMode for XLM→ETH processing
await storeActiveOrder(orderId, {
...orderData,