forked from dz951014619/backpack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathx1-json-server.js
More file actions
executable file
·1249 lines (1108 loc) · 35.5 KB
/
x1-json-server.js
File metadata and controls
executable file
·1249 lines (1108 loc) · 35.5 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
#!/usr/bin/env node
/**
* X1 JSON Server for Backpack Wallet
*
* This server provides token balance, price data, and transaction activity for X1 blockchain wallets.
* It responds to requests from the Backpack wallet extension.
*
* Endpoints:
*
* 1. GET /wallet/:address?providerId=X1
* Returns wallet balance and token data
* Response: { balance: number, tokens: [...] }
*
* 2. POST /transactions
* Returns transaction activity for a wallet
* Request: { address: string, providerId: string, limit: number, offset: number }
* Response: { transactions: [...], hasMore: boolean, totalCount: number }
*
* 3. POST /v2/graphql
* Handles GraphQL queries (priority fees, etc.)
*
* 4. GET /test
* Test page for wallet integration
*/
const http = require("http");
const https = require("https");
const url = require("url");
const sqlite3 = require("sqlite3").verbose();
const path = require("path");
const PORT = 4000;
const X1_MAINNET_RPC_URL = "https://rpc.mainnet.x1.xyz";
const X1_TESTNET_RPC_URL = "https://rpc.testnet.x1.xyz";
const SOLANA_MAINNET_RPC_URL =
"https://capable-autumn-thunder.solana-mainnet.quiknode.pro/3d4ed46b454fa0ca3df983502fdf15fe87145d9e/";
const SOLANA_DEVNET_RPC_URL = "https://api.devnet.solana.com";
const SOLANA_TESTNET_RPC_URL = "https://api.testnet.solana.com";
const XNT_PRICE = 1.0; // $1 per XNT
const DB_PATH = path.join(__dirname, "transactions.db");
// Balance cache to avoid hitting RPC too frequently
// Cache expires after 2 seconds for real-time updates
const balanceCache = new Map();
const CACHE_TTL_MS = 2000; // 2 seconds
// ============================================================================
// SQLite Database Setup
// ============================================================================
let db;
function initializeDatabase() {
return new Promise((resolve, reject) => {
db = new sqlite3.Database(DB_PATH, (err) => {
if (err) {
console.error("❌ Error opening database:", err);
reject(err);
return;
}
console.log("📁 Database connected:", DB_PATH);
// Create transactions table
db.run(
`CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
wallet_prefix TEXT NOT NULL,
wallet_address TEXT NOT NULL,
hash TEXT NOT NULL,
type TEXT NOT NULL,
timestamp TEXT NOT NULL,
amount TEXT,
token_name TEXT,
token_symbol TEXT,
fee TEXT,
fee_payer TEXT,
description TEXT,
error TEXT,
source TEXT,
nfts TEXT,
provider_id TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(hash, wallet_address)
)`,
(err) => {
if (err) {
console.error("❌ Error creating table:", err);
reject(err);
return;
}
// Create indexes
db.run(
`CREATE INDEX IF NOT EXISTS idx_wallet_prefix ON transactions(wallet_prefix)`,
(err) => {
if (err)
console.error(
"Warning: Error creating wallet_prefix index:",
err
);
}
);
db.run(
`CREATE INDEX IF NOT EXISTS idx_timestamp ON transactions(timestamp DESC)`,
(err) => {
if (err)
console.error("Warning: Error creating timestamp index:", err);
}
);
db.run(
`CREATE INDEX IF NOT EXISTS idx_hash ON transactions(hash)`,
(err) => {
if (err)
console.error("Warning: Error creating hash index:", err);
}
);
// Create wallets table for tracking which wallets to index
db.run(
`CREATE TABLE IF NOT EXISTS wallets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
address TEXT NOT NULL UNIQUE,
network TEXT NOT NULL DEFAULT 'testnet',
enabled INTEGER NOT NULL DEFAULT 1,
last_indexed TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`,
(err) => {
if (err) {
console.error("❌ Error creating wallets table:", err);
reject(err);
return;
}
db.run(
`CREATE INDEX IF NOT EXISTS idx_wallet_address ON wallets(address)`,
(err) => {
if (err)
console.error(
"Warning: Error creating wallet_address index:",
err
);
}
);
console.log("✅ Database initialized");
resolve();
}
);
}
);
});
});
}
// Get first 8 characters of wallet address as prefix
function getWalletPrefix(address) {
return address.substring(0, 8).toLowerCase();
}
// Insert transaction into database
function insertTransaction(walletAddress, transaction, providerId) {
return new Promise((resolve, reject) => {
const prefix = getWalletPrefix(walletAddress);
const nftsJson = transaction.nfts ? JSON.stringify(transaction.nfts) : null;
const sql = `INSERT OR REPLACE INTO transactions
(wallet_prefix, wallet_address, hash, type, timestamp, amount, token_name,
token_symbol, fee, fee_payer, description, error, source, nfts, provider_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
const params = [
prefix,
walletAddress,
transaction.hash,
transaction.type,
transaction.timestamp,
transaction.amount,
transaction.tokenName,
transaction.tokenSymbol,
transaction.fee,
transaction.feePayer,
transaction.description,
transaction.error,
transaction.source,
nftsJson,
providerId,
];
db.run(sql, params, function (err) {
if (err) {
reject(err);
} else {
resolve(this.lastID);
}
});
});
}
// Get transactions for a wallet address
function getTransactions(walletAddress, providerId, limit = 50, offset = 0) {
return new Promise((resolve, reject) => {
const prefix = getWalletPrefix(walletAddress);
const sql = `SELECT * FROM transactions
WHERE wallet_prefix = ? AND provider_id = ?
ORDER BY timestamp DESC
LIMIT ? OFFSET ?`;
db.all(sql, [prefix, providerId, limit, offset], (err, rows) => {
if (err) {
reject(err);
return;
}
// Transform database rows to transaction objects
const transactions = rows.map((row) => ({
hash: row.hash,
type: row.type,
timestamp: row.timestamp,
amount: row.amount,
tokenName: row.token_name,
tokenSymbol: row.token_symbol,
fee: row.fee,
feePayer: row.fee_payer,
description: row.description,
error: row.error,
source: row.source,
nfts: row.nfts ? JSON.parse(row.nfts) : [],
}));
resolve(transactions);
});
});
}
// Get total count of transactions for a wallet
function getTransactionCount(walletAddress, providerId) {
return new Promise((resolve, reject) => {
const prefix = getWalletPrefix(walletAddress);
const sql = `SELECT COUNT(*) as count FROM transactions
WHERE wallet_prefix = ? AND provider_id = ?`;
db.get(sql, [prefix, providerId], (err, row) => {
if (err) {
reject(err);
} else {
resolve(row.count);
}
});
});
}
// ============================================================================
// Wallet Registry Functions
// ============================================================================
// Register a wallet for indexing
function registerWallet(address, network = "testnet", enabled = true) {
return new Promise((resolve, reject) => {
const sql = `INSERT OR REPLACE INTO wallets (address, network, enabled)
VALUES (?, ?, ?)`;
db.run(sql, [address, network, enabled ? 1 : 0], function (err) {
if (err) {
reject(err);
} else {
resolve(this.lastID);
}
});
});
}
// Get all wallets for indexing
function getRegisteredWallets() {
return new Promise((resolve, reject) => {
const sql = `SELECT address, network, enabled, last_indexed
FROM wallets
ORDER BY created_at DESC`;
db.all(sql, [], (err, rows) => {
if (err) {
reject(err);
} else {
resolve(
rows.map((row) => ({
address: row.address,
network: row.network,
enabled: row.enabled === 1,
lastIndexed: row.last_indexed,
}))
);
}
});
});
}
// Update last indexed timestamp
function updateLastIndexed(address) {
return new Promise((resolve, reject) => {
const sql = `UPDATE wallets SET last_indexed = ? WHERE address = ?`;
const timestamp = new Date().toISOString();
db.run(sql, [timestamp, address], function (err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
// Auto-register wallet when it queries transactions (if not already registered)
function autoRegisterWallet(address, providerId) {
return new Promise((resolve, reject) => {
// Use the full providerId as network (e.g., "X1-mainnet", "SOLANA-mainnet")
// This ensures wallets are indexed separately for each blockchain
const network = providerId;
const sql = `INSERT OR IGNORE INTO wallets (address, network, enabled)
VALUES (?, ?, 1)`;
db.run(sql, [address, network], function (err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
// ============================================================================
// Transaction Mock Data Functions
// ============================================================================
function createMockTransaction(index, offset = 0) {
const types = [
"SEND",
"RECEIVE",
"SWAP",
"STAKE",
"UNSTAKE",
"NFT_MINT",
"NFT_SALE",
];
const now = new Date();
const hoursAgo = (index + offset) * 3;
const timestamp = new Date(now.getTime() - hoursAgo * 60 * 60 * 1000);
const type = types[index % types.length];
const isSend = type === "SEND";
const isNFT = type.startsWith("NFT_");
return {
hash: `${Math.random().toString(36).substring(2, 15)}${Math.random().toString(36).substring(2, 15)}${Math.random().toString(36).substring(2, 15)}`,
type: type,
timestamp: timestamp.toISOString(),
amount: isNFT ? "1" : (Math.random() * 100).toFixed(2),
tokenName: isNFT ? "Cool NFT Collection" : "X1 Token",
tokenSymbol: isNFT ? "CNFT" : "XNT",
fee: (Math.random() * 0.001).toFixed(6),
feePayer: "mock" + Math.random().toString(36).substring(2, 15),
description: getTransactionDescription(type, index),
error: null,
source: getTransactionSource(type),
nfts: isNFT
? [
{
mint: "NFTmint" + Math.random().toString(36).substring(2, 15),
name: `Cool NFT #${1000 + index}`,
image: `https://example.com/nft/${1000 + index}.png`,
},
]
: [],
};
}
function getTransactionDescription(type, index) {
const descriptions = {
SEND: ["Transfer to wallet", "Payment sent", "Sent to friend"],
RECEIVE: ["Received payment", "Incoming transfer", "Payment received"],
SWAP: ["Swapped XNT for USDC", "Token swap", "Exchanged tokens"],
STAKE: ["Staked to validator", "Staking rewards", "Validator stake"],
UNSTAKE: ["Unstaked tokens", "Withdrew stake", "Unstake from validator"],
NFT_MINT: ["Minted NFT", "NFT created", "New NFT minted"],
NFT_SALE: ["Sold NFT", "NFT sale", "NFT transferred"],
};
const options = descriptions[type] || ["Transaction"];
return options[index % options.length];
}
function getTransactionSource(type) {
if (type.startsWith("NFT_")) return "marketplace";
if (type === "SWAP") return "dex";
if (type === "STAKE" || type === "UNSTAKE") return "staking";
return "wallet";
}
function getCachedBalance(address, network) {
const cacheKey = `${address}-${network}`;
const cached = balanceCache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
console.log(` ⚡ Using cached balance for ${address}`);
return cached.balance;
}
return null;
}
function setCachedBalance(address, network, balance) {
const cacheKey = `${address}-${network}`;
balanceCache.set(cacheKey, {
balance,
timestamp: Date.now(),
});
}
// Oracle endpoint for real-time prices
const ORACLE_ENDPOINT = "http://oracle.mainnet.x1.xyz:3000/api/state";
// Get SOL price from Oracle (with caching)
let solPriceCache = { price: 158, timestamp: 0 }; // Default $158, cache for 5 minutes
async function getSolPrice() {
const now = Date.now();
if (now - solPriceCache.timestamp < 300000) {
// 5 minutes
return solPriceCache.price;
}
try {
const response = await fetch(ORACLE_ENDPOINT);
const data = await response.json();
const solPrice = parseFloat(data.agg.SOL.avg);
if (solPrice && solPrice > 0) {
solPriceCache = { price: solPrice, timestamp: now };
return solPrice;
}
// Fallback to cached price if invalid response
return solPriceCache.price;
} catch (error) {
console.error("Error fetching SOL price from oracle:", error);
return solPriceCache.price; // Return cached price on error
}
}
// Fetch real balance from X1 or Solana RPC
async function getX1Balance(address, rpcUrl) {
return new Promise((resolve, reject) => {
const postData = JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "getBalance",
params: [address],
});
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(postData),
},
};
const req = https.request(rpcUrl, options, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
try {
const response = JSON.parse(data);
if (response.result && response.result.value !== undefined) {
// Convert lamports to XNT (9 decimals)
const lamports = response.result.value;
const xnt = lamports / 1e9;
resolve(xnt);
} else {
reject(new Error("Invalid RPC response"));
}
} catch (error) {
reject(error);
}
});
});
req.on("error", (error) => {
reject(error);
});
req.write(postData);
req.end();
});
}
// Get wallet data with real balance from X1 RPC
async function getWalletData(address, network = "mainnet", blockchain = "x1") {
// Determine RPC URL based on blockchain and network
let rpcUrl;
let tokenSymbol;
let tokenName;
if (blockchain === "solana") {
// Solana blockchain
if (network === "devnet") {
rpcUrl = SOLANA_DEVNET_RPC_URL;
} else if (network === "testnet") {
rpcUrl = SOLANA_TESTNET_RPC_URL;
} else {
rpcUrl = SOLANA_MAINNET_RPC_URL;
}
tokenSymbol = "SOL";
tokenName = "Solana";
} else {
// X1 blockchain
rpcUrl = network === "testnet" ? X1_TESTNET_RPC_URL : X1_MAINNET_RPC_URL;
tokenSymbol = "XNT";
tokenName = "X1 Native Token";
}
console.log(` Using ${blockchain} ${network} RPC: ${rpcUrl}`);
try {
// Check cache first (cache key includes blockchain)
let balance = getCachedBalance(address, `${blockchain}-${network}`);
if (balance === null) {
// Not in cache or expired, fetch from RPC
balance = await getX1Balance(address, rpcUrl);
setCachedBalance(address, `${blockchain}-${network}`, balance);
console.log(
` Balance from ${blockchain.toUpperCase()} RPC: ${balance} ${tokenSymbol}`
);
}
// Determine logo based on blockchain
const logo = blockchain === "solana" ? "./solana.png" : "./x1.png";
// Get real SOL price or use fixed XNT price
const price = blockchain === "solana" ? await getSolPrice() : XNT_PRICE;
return {
balance: balance,
tokens: [
{
mint: "11111111111111111111111111111111", // Native token address for SVM chains
decimals: 9,
balance: balance,
logo: logo,
name: tokenName,
symbol: tokenSymbol,
price: price,
valueUSD: balance * price,
},
],
};
} catch (error) {
console.error(` ❌ Error fetching balance: ${error.message}`);
// Return default data on error
return {
balance: 0,
tokens: [
{
mint: "XNT111111111111111111111111111111111111111",
decimals: 9,
balance: 0,
logo: "./x1.png",
name: "X1 Native Token",
symbol: "XNT",
price: XNT_PRICE,
valueUSD: 0,
},
],
};
}
}
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const pathname = parsedUrl.pathname;
const query = parsedUrl.query;
// CORS headers
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
res.setHeader("Content-Type", "application/json");
// Handle OPTIONS request for CORS
if (req.method === "OPTIONS") {
res.writeHead(200);
res.end();
return;
}
// Log request
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
// Handle GraphQL endpoint for priority fees
if (pathname === "/v2/graphql" && req.method === "POST") {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", () => {
try {
const graphqlRequest = JSON.parse(body);
console.log(`📊 GraphQL Query: ${graphqlRequest.operationName}`);
// Handle GetSolanaPriorityFee query
if (graphqlRequest.operationName === "GetSolanaPriorityFee") {
const response = {
data: {
solanaPriorityFeeEstimate: "1000", // 1000 microlamports
},
};
res.writeHead(200);
res.end(JSON.stringify(response));
} else {
// Return empty data for other queries
res.writeHead(200);
res.end(JSON.stringify({ data: {} }));
}
} catch (error) {
console.error(`GraphQL error: ${error.message}`);
res.writeHead(400);
res.end(
JSON.stringify({ errors: [{ message: "Invalid GraphQL request" }] })
);
}
});
return;
}
// Handle /transactions endpoint for activity page
if (pathname === "/transactions" && req.method === "POST") {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", async () => {
try {
const requestData = JSON.parse(body);
const {
address,
providerId,
limit = 50,
offset = 0,
tokenMint,
} = requestData;
console.log(`\n📥 Transaction Activity Request:`);
console.log(
` Address: ${address} (prefix: ${getWalletPrefix(address)})`
);
console.log(` Provider: ${providerId}`);
console.log(` Limit: ${limit}, Offset: ${offset}`);
if (tokenMint) console.log(` Token Mint: ${tokenMint}`);
const actualLimit = Math.min(limit, 50);
// Auto-register wallet for indexing
await autoRegisterWallet(address, providerId);
// Fetch from database
const transactions = await getTransactions(
address,
providerId,
actualLimit,
offset
);
const totalCount = await getTransactionCount(address, providerId);
const hasMore = offset + transactions.length < totalCount;
const response = {
transactions,
hasMore,
totalCount,
requestParams: {
address,
providerId,
limit: actualLimit,
offset,
},
meta: {
timestamp: new Date().toISOString(),
version: "1.0.0",
},
};
console.log(
`✅ Returning ${transactions.length} transactions from DB (total: ${totalCount}, hasMore: ${hasMore})\n`
);
res.writeHead(200);
res.end(JSON.stringify(response, null, 2));
} catch (error) {
console.error(`❌ Transaction request error: ${error.message}`);
res.writeHead(500);
res.end(
JSON.stringify({
error: "Internal Server Error",
message: error.message,
})
);
}
});
return;
}
// Handle GET /transactions/:address for activity page (alternative to POST)
if (pathname.startsWith("/transactions/") && req.method === "GET") {
(async () => {
try {
// Extract address from URL path
const pathParts = pathname.split("/");
const address = pathParts[2];
// Parse query parameters
const queryParams = new URLSearchParams(parsedUrl.search || "");
const providerId = queryParams.get("providerId") || "X1-mainnet";
const limit = Math.min(parseInt(queryParams.get("limit") || "50"), 50);
const offset = parseInt(queryParams.get("offset") || "0");
const tokenMint = queryParams.get("tokenMint");
console.log(`\n📥 Transaction Activity Request (GET):`);
console.log(
` Address: ${address} (prefix: ${getWalletPrefix(address)})`
);
console.log(` Provider: ${providerId}`);
console.log(` Limit: ${limit}, Offset: ${offset}`);
if (tokenMint) console.log(` Token Mint: ${tokenMint}`);
// Auto-register wallet for indexing
await autoRegisterWallet(address, providerId);
// Fetch from database
const transactions = await getTransactions(
address,
providerId,
limit,
offset
);
const totalCount = await getTransactionCount(address, providerId);
const hasMore = offset + transactions.length < totalCount;
const response = {
transactions,
hasMore,
totalCount,
requestParams: {
address,
providerId,
limit,
offset,
},
meta: {
timestamp: new Date().toISOString(),
version: "1.0.0",
},
};
console.log(
`✅ Returning ${transactions.length} transactions from DB (total: ${totalCount}, hasMore: ${hasMore})\n`
);
res.writeHead(200);
res.end(JSON.stringify(response, null, 2));
} catch (error) {
console.error(`❌ GET Transaction request error: ${error.message}`);
res.writeHead(500);
res.end(
JSON.stringify({
error: "Internal Server Error",
message: error.message,
})
);
}
})();
return;
}
// Handle /transactions/store endpoint to add transactions to database
if (pathname === "/transactions/store" && req.method === "POST") {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", async () => {
try {
const requestData = JSON.parse(body);
const { address, providerId, transactions } = requestData;
if (
!address ||
!providerId ||
!transactions ||
!Array.isArray(transactions)
) {
res.writeHead(400);
res.end(
JSON.stringify({
error: "Bad Request",
message:
"Required fields: address, providerId, transactions (array)",
})
);
return;
}
console.log(
`\n💾 Storing ${transactions.length} transactions for ${getWalletPrefix(address)}`
);
const results = [];
for (const tx of transactions) {
try {
const id = await insertTransaction(address, tx, providerId);
results.push({ hash: tx.hash, id, status: "inserted" });
} catch (err) {
if (err.message.includes("UNIQUE constraint")) {
results.push({ hash: tx.hash, status: "duplicate" });
} else {
results.push({
hash: tx.hash,
status: "error",
error: err.message,
});
}
}
}
const inserted = results.filter((r) => r.status === "inserted").length;
const duplicates = results.filter(
(r) => r.status === "duplicate"
).length;
const errors = results.filter((r) => r.status === "error").length;
console.log(
`✅ Stored: ${inserted} inserted, ${duplicates} duplicates, ${errors} errors\n`
);
res.writeHead(200);
res.end(
JSON.stringify({
success: true,
inserted,
duplicates,
errors,
results,
})
);
} catch (error) {
console.error(`❌ Store transaction error: ${error.message}`);
res.writeHead(500);
res.end(
JSON.stringify({
error: "Internal Server Error",
message: error.message,
})
);
}
});
return;
}
// Handle /wallets endpoint to list registered wallets
if (pathname === "/wallets" && req.method === "GET") {
(async () => {
try {
const wallets = await getRegisteredWallets();
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify(
{
success: true,
wallets,
count: wallets.length,
},
null,
2
)
);
} catch (error) {
console.error(`❌ Get wallets error: ${error.message}`);
res.writeHead(500);
res.end(
JSON.stringify({
error: "Internal Server Error",
message: error.message,
})
);
}
})();
return;
}
// Handle /wallets/register endpoint to manually register a wallet
if (pathname === "/wallets/register" && req.method === "POST") {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", async () => {
try {
const requestData = JSON.parse(body);
const { address, network = "testnet", enabled = true } = requestData;
if (!address) {
res.writeHead(400);
res.end(
JSON.stringify({
error: "Bad Request",
message: "Required field: address",
})
);
return;
}
await registerWallet(address, network, enabled);
console.log(`✅ Registered wallet: ${address} (${network})`);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify(
{
success: true,
wallet: { address, network, enabled },
},
null,
2
)
);
} catch (error) {
console.error(`❌ Register wallet error: ${error.message}`);
res.writeHead(500);
res.end(
JSON.stringify({
error: "Internal Server Error",
message: error.message,
})
);
}
});
return;
}
// Handle /wallets/update-indexed endpoint to update last indexed timestamp
if (pathname === "/wallets/update-indexed" && req.method === "POST") {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", async () => {
try {
const requestData = JSON.parse(body);
const { address } = requestData;
if (!address) {
res.writeHead(400);
res.end(
JSON.stringify({
error: "Bad Request",
message: "Required field: address",
})
);
return;
}
await updateLastIndexed(address);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
success: true,
})
);