forked from jacklevin74/backpack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransaction-indexer.js
More file actions
executable file
·547 lines (470 loc) · 14.2 KB
/
transaction-indexer.js
File metadata and controls
executable file
·547 lines (470 loc) · 14.2 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
#!/usr/bin/env node
/**
* X1 Transaction Indexer
*
* This service polls the X1 blockchain RPC for new transactions and stores them
* in the SQLite database via the x1-json-server API.
*
* Features:
* - Polls X1 RPC for transaction signatures
* - Fetches and parses transaction details
* - Stores transactions in SQLite via /transactions/store endpoint
* - Supports multiple wallet addresses
* - Configurable polling interval
* - Automatic retry on errors
*/
const https = require("https");
// Configuration
const CONFIG = {
// X1 RPC endpoints
X1_TESTNET_RPC: "https://rpc.testnet.x1.xyz",
X1_MAINNET_RPC: "https://rpc.mainnet.x1.xyz",
// Solana RPC endpoints (using QuickNode for mainnet)
SOLANA_MAINNET_RPC: "https://capable-autumn-thunder.solana-mainnet.quiknode.pro/3d4ed46b454fa0ca3df983502fdf15fe87145d9e/",
SOLANA_DEVNET_RPC: "https://api.devnet.solana.com",
SOLANA_TESTNET_RPC: "https://api.testnet.solana.com",
// API server endpoint
API_SERVER: "http://localhost:4000",
// Polling configuration
POLL_INTERVAL_MS: 30000, // 30 seconds
MAX_SIGNATURES_PER_POLL: 50,
// Retry configuration
MAX_RETRIES: 3,
RETRY_DELAY_MS: 5000,
// Dynamic wallet loading - wallets are now loaded from API
// To add wallets, they will be auto-registered when querying transactions
// Or manually register via: POST /wallets/register
};
// Track last processed signature for each wallet
const lastProcessedSignatures = new Map();
/**
* Make RPC call to X1 blockchain
*/
function rpcCall(endpoint, method, params) {
return new Promise((resolve, reject) => {
const postData = JSON.stringify({
jsonrpc: "2.0",
id: 1,
method,
params,
});
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(postData),
},
};
const req = https.request(endpoint, options, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
try {
const response = JSON.parse(data);
if (response.error) {
reject(new Error(response.error.message || "RPC error"));
} else {
resolve(response.result);
}
} catch (error) {
reject(error);
}
});
});
req.on("error", (error) => {
reject(error);
});
req.write(postData);
req.end();
});
}
/**
* Fetch transaction signatures for an address
* Note: RPC returns signatures in descending order (newest first)
* We fetch the latest signatures and filter out ones we've already processed
*/
async function getSignaturesForAddress(
rpcUrl,
address,
limit = 50,
lastProcessed = null
) {
const params = [address, { limit }];
// Don't use 'before' parameter - always fetch latest signatures
// We'll filter out already-processed ones locally
const result = await rpcCall(rpcUrl, "getSignaturesForAddress", params);
if (!result || !lastProcessed) {
return result;
}
// Filter out signatures we've already processed
// Stop at the last processed signature
const newSignatures = [];
for (const sig of result) {
if (sig.signature === lastProcessed) {
break; // Found the last one we processed, stop here
}
newSignatures.push(sig);
}
return newSignatures;
}
/**
* Fetch transaction details
*/
async function getTransaction(rpcUrl, signature) {
return await rpcCall(rpcUrl, "getTransaction", [
signature,
{
encoding: "jsonParsed",
maxSupportedTransactionVersion: 0,
},
]);
}
/**
* Parse and format transaction for storage
* @param {object} txData - Transaction data from RPC
* @param {string} signature - Transaction signature/hash
* @param {string} walletAddress - The wallet address we're indexing for
* @param {string} blockchain - The blockchain type ("x1" or "solana")
*/
function parseTransaction(txData, signature, walletAddress, blockchain = "x1") {
try {
const tx = txData.transaction;
const meta = txData.meta;
// Determine token name and symbol based on blockchain
const tokenName = blockchain === "solana" ? "Solana" : "X1 Token";
const tokenSymbol = blockchain === "solana" ? "SOL" : "XNT";
// Determine transaction type based on instructions
let type = "UNKNOWN";
let amount = null;
let description = null;
// Find which account index corresponds to our wallet
let walletAccountIndex = -1;
if (tx.message && tx.message.accountKeys) {
walletAccountIndex = tx.message.accountKeys.findIndex(
(acc) => acc.pubkey === walletAddress
);
}
// Determine type based on balance change for THIS wallet
if (
meta &&
meta.postBalances &&
meta.preBalances &&
walletAccountIndex >= 0
) {
const balanceChange =
meta.postBalances[walletAccountIndex] -
meta.preBalances[walletAccountIndex];
if (balanceChange > 0) {
type = "RECEIVE";
amount = (balanceChange / 1e9).toFixed(9);
description = `Received ${tokenSymbol}`;
} else if (balanceChange < 0) {
type = "SEND";
amount = (Math.abs(balanceChange) / 1e9).toFixed(9);
description = `Sent ${tokenSymbol}`;
}
}
// Get timestamp
const timestamp = txData.blockTime
? new Date(txData.blockTime * 1000).toISOString()
: new Date().toISOString();
// Get fee
const fee = meta && meta.fee ? (meta.fee / 1e9).toFixed(9) : "0";
return {
hash: signature,
type,
timestamp,
amount,
tokenName,
tokenSymbol,
fee,
feePayer: tx.message?.accountKeys?.[0]?.pubkey || null,
description: description || `${type} transaction`,
error: meta && meta.err ? JSON.stringify(meta.err) : null,
source: "wallet",
nfts: [],
};
} catch (error) {
console.error(`Error parsing transaction ${signature}:`, error);
// Return minimal transaction data
const tokenName = blockchain === "solana" ? "Solana" : "X1 Token";
const tokenSymbol = blockchain === "solana" ? "SOL" : "XNT";
return {
hash: signature,
type: "UNKNOWN",
timestamp: new Date().toISOString(),
amount: null,
tokenName,
tokenSymbol,
fee: "0",
feePayer: null,
description: "Parse error",
error: error.message,
source: "wallet",
nfts: [],
};
}
}
/**
* Fetch registered wallets from API
*/
async function fetchRegisteredWallets() {
return new Promise((resolve, reject) => {
const url = new URL(`${CONFIG.API_SERVER}/wallets`);
const req = require("http").request(url, { method: "GET" }, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
try {
const response = JSON.parse(data);
if (response.success) {
resolve(response.wallets);
} else {
reject(new Error("Failed to fetch wallets"));
}
} catch (error) {
reject(error);
}
});
});
req.on("error", (error) => {
reject(error);
});
req.end();
});
}
/**
* Update last indexed timestamp for a wallet
*/
async function updateLastIndexed(address) {
return new Promise((resolve, reject) => {
const postData = JSON.stringify({ address });
const url = new URL(`${CONFIG.API_SERVER}/wallets/update-indexed`);
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(postData),
},
};
const req = require("http").request(url, options, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
resolve();
});
});
req.on("error", (error) => {
// Don't reject, just log - this is not critical
console.error(
` Warning: Failed to update last_indexed timestamp:`,
error.message
);
resolve();
});
req.write(postData);
req.end();
});
}
/**
* Store transactions via API
*/
async function storeTransactions(address, providerId, transactions) {
return new Promise((resolve, reject) => {
const postData = JSON.stringify({
address,
providerId,
transactions,
});
const url = new URL(`${CONFIG.API_SERVER}/transactions/store`);
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(postData),
},
};
const req = require("http").request(url, options, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
try {
const response = JSON.parse(data);
resolve(response);
} catch (error) {
reject(error);
}
});
});
req.on("error", (error) => {
reject(error);
});
req.write(postData);
req.end();
});
}
/**
* Index transactions for a wallet
*/
async function indexWallet(wallet) {
const { address, network, enabled } = wallet;
if (!enabled) {
console.log(`⏭️ Skipping disabled wallet: ${address.substring(0, 8)}...`);
return;
}
// Determine RPC URL and provider ID based on network
let rpcUrl;
let providerId;
let blockchain = "x1"; // Default to X1
// Support both X1 and Solana networks
if (network === "mainnet" || network === "X1-mainnet") {
rpcUrl = CONFIG.X1_MAINNET_RPC;
providerId = "X1-mainnet";
blockchain = "x1";
} else if (network === "testnet" || network === "X1-testnet") {
rpcUrl = CONFIG.X1_TESTNET_RPC;
providerId = "X1-testnet";
blockchain = "x1";
} else if (network === "SOLANA-mainnet") {
rpcUrl = CONFIG.SOLANA_MAINNET_RPC;
providerId = "SOLANA-mainnet";
blockchain = "solana";
} else if (network === "SOLANA-devnet") {
rpcUrl = CONFIG.SOLANA_DEVNET_RPC;
providerId = "SOLANA-devnet";
blockchain = "solana";
} else if (network === "SOLANA-testnet") {
rpcUrl = CONFIG.SOLANA_TESTNET_RPC;
providerId = "SOLANA-testnet";
blockchain = "solana";
} else {
// Default to X1 testnet
rpcUrl = CONFIG.X1_TESTNET_RPC;
providerId = "X1-testnet";
blockchain = "x1";
}
console.log(
`\n🔍 Indexing wallet: ${address.substring(0, 8)}... (${network})`
);
try {
// Fetch signatures
const lastSig = lastProcessedSignatures.get(address);
const signatures = await getSignaturesForAddress(
rpcUrl,
address,
CONFIG.MAX_SIGNATURES_PER_POLL,
lastSig
);
if (!signatures || signatures.length === 0) {
console.log(` No new transactions found`);
return;
}
console.log(` Found ${signatures.length} signatures`);
// Fetch and parse transactions
const transactions = [];
for (const sigInfo of signatures) {
try {
const txData = await getTransaction(rpcUrl, sigInfo.signature);
const parsed = parseTransaction(txData, sigInfo.signature, address, blockchain);
transactions.push(parsed);
} catch (error) {
console.error(
` ❌ Error fetching tx ${sigInfo.signature}:`,
error.message
);
}
}
if (transactions.length === 0) {
console.log(` No transactions to store`);
return;
}
// Store transactions
console.log(` 💾 Storing ${transactions.length} transactions...`);
const result = await storeTransactions(address, providerId, transactions);
console.log(
` ✅ Stored: ${result.inserted} new, ${result.duplicates} duplicates, ${result.errors} errors`
);
// Update last processed signature
if (signatures.length > 0) {
lastProcessedSignatures.set(address, signatures[0].signature);
}
// Update last indexed timestamp in database
await updateLastIndexed(address);
} catch (error) {
console.error(` ❌ Error indexing wallet:`, error.message);
}
}
/**
* Main polling loop
*/
async function pollAll() {
console.log(`\n${"=".repeat(80)}`);
console.log(`⏰ Polling cycle started: ${new Date().toISOString()}`);
console.log(`${"=".repeat(80)}`);
try {
// Fetch wallets from API
const wallets = await fetchRegisteredWallets();
console.log(`👛 Found ${wallets.length} registered wallet(s)\n`);
for (const wallet of wallets) {
try {
await indexWallet(wallet);
} catch (error) {
console.error(`Error processing wallet ${wallet.address}:`, error);
}
}
} catch (error) {
console.error(`❌ Error fetching wallets:`, error.message);
console.log(` Will retry on next poll cycle`);
}
console.log(
`\n✓ Polling cycle complete. Next poll in ${CONFIG.POLL_INTERVAL_MS / 1000}s\n`
);
}
/**
* Start the indexer
*/
async function start() {
console.log("\n" + "=".repeat(80));
console.log("🚀 X1 & Solana Transaction Indexer Started");
console.log("=".repeat(80));
console.log(`📡 X1 Testnet RPC: ${CONFIG.X1_TESTNET_RPC}`);
console.log(`📡 X1 Mainnet RPC: ${CONFIG.X1_MAINNET_RPC}`);
console.log(`📡 Solana Mainnet RPC: ${CONFIG.SOLANA_MAINNET_RPC}`);
console.log(`📡 Solana Devnet RPC: ${CONFIG.SOLANA_DEVNET_RPC}`);
console.log(`📡 Solana Testnet RPC: ${CONFIG.SOLANA_TESTNET_RPC}`);
console.log(`🔗 API Server: ${CONFIG.API_SERVER}`);
console.log(`⏱️ Poll Interval: ${CONFIG.POLL_INTERVAL_MS / 1000}s`);
console.log(`\n💡 Wallets are loaded dynamically from the database`);
console.log(`💡 Wallets are auto-registered when querying transactions`);
console.log(
`💡 Or manually register via: POST ${CONFIG.API_SERVER}/wallets/register`
);
console.log("=".repeat(80) + "\n");
// Run first poll immediately
await pollAll();
// Schedule recurring polls
setInterval(pollAll, CONFIG.POLL_INTERVAL_MS);
}
// Graceful shutdown
process.on("SIGINT", () => {
console.log("\n\n👋 Shutting down indexer...");
console.log("✅ Indexer stopped");
process.exit(0);
});
// Handle errors
process.on("unhandledRejection", (error) => {
console.error("❌ Unhandled rejection:", error);
});
// Start the indexer
start().catch((error) => {
console.error("❌ Failed to start indexer:", error);
process.exit(1);
});