-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·1822 lines (1603 loc) · 53.8 KB
/
index.js
File metadata and controls
executable file
·1822 lines (1603 loc) · 53.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
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
import { keccak256, toHex, createPublicClient, http, formatUnits } from "viem";
import { mainnet } from "viem/chains";
import {
HypersyncClient,
LogField,
JoinMode,
TransactionField,
Decoder,
} from "@envio-dev/hypersync-client";
import chalk from "chalk";
import figlet from "figlet";
import { Command } from "commander";
import ora from "ora";
import readline from "readline";
import boxen from "boxen";
import fs from "fs";
import path from "path";
import Table from "cli-table3";
import { fileURLToPath } from "url";
import { dirname } from "path";
// Get directory of current module
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Import extraRpcs dynamically
let extraRpcs = {};
try {
const extraRpcsPath = path.resolve(__dirname, "./extraRpcs.js");
if (fs.existsSync(extraRpcsPath)) {
const module = await import(extraRpcsPath);
extraRpcs = module.default || {};
}
} catch (error) {
console.warn(
chalk.yellow(`Warning: Could not load extraRpcs.js: ${error.message}`)
);
}
// List of safe chalk colors for dynamically assigned chains
const SAFE_COLORS = [
"green",
"yellow",
"blue",
"magenta",
"cyan",
"white",
"gray",
"redBright",
"greenBright",
"yellowBright",
"blueBright",
"magentaBright",
"cyanBright",
"whiteBright",
];
// Load chain data from networkCache.json or fetch from API
let networkData = [];
try {
const networkCachePath = path.resolve(__dirname, "./networkCache.json");
if (fs.existsSync(networkCachePath)) {
networkData = JSON.parse(fs.readFileSync(networkCachePath, "utf8"));
} else {
// In a production app, we'd fetch from API here
console.warn(chalk.yellow("Warning: Could not find networkCache.json"));
}
} catch (error) {
console.warn(
chalk.yellow(`Warning: Could not load networkCache.json: ${error.message}`)
);
}
// List of preferred chains to include by default
const PREFERRED_CHAINS = [
"eth",
"optimism",
"arbitrum",
"gnosis",
"xdc",
"unichain",
"avalanche",
];
// Create a map of name to chain data for quick lookup
const chainNameToData = {};
networkData.forEach((chain) => {
chainNameToData[chain.name] = chain;
});
// Create dynamic SUPPORTED_CHAINS object with colors
const SUPPORTED_CHAINS = {};
// First, add all chains from networkCache.json
networkData.forEach((chain, index) => {
if (chain.ecosystem === "evm" && chain.chain_id) {
// Assign a color from the safe colors array, cycling through them if needed
const colorIndex = index % SAFE_COLORS.length;
const color = SAFE_COLORS[colorIndex];
// Capitalize first letter of chain name
const displayName =
chain.name.charAt(0).toUpperCase() + chain.name.slice(1);
SUPPORTED_CHAINS[chain.chain_id] = {
name: displayName,
color: color,
hypersyncUrl: `http://${chain.chain_id}.hypersync.xyz`,
};
}
});
// Apply special color assignments for well-known chains
if (SUPPORTED_CHAINS[1]) SUPPORTED_CHAINS[1].color = "cyan"; // Ethereum
if (SUPPORTED_CHAINS[10]) SUPPORTED_CHAINS[10].color = "redBright"; // Optimism
if (SUPPORTED_CHAINS[137]) SUPPORTED_CHAINS[137].color = "magenta"; // Polygon
if (SUPPORTED_CHAINS[42161]) SUPPORTED_CHAINS[42161].color = "blue"; // Arbitrum
if (SUPPORTED_CHAINS[8453]) SUPPORTED_CHAINS[8453].color = "blue"; // Base
if (SUPPORTED_CHAINS[100]) SUPPORTED_CHAINS[100].color = "green"; // Gnosis
if (SUPPORTED_CHAINS[43114]) SUPPORTED_CHAINS[43114].color = "red"; // Avalanche
// If no chains were loaded, provide fallbacks for core chains
if (Object.keys(SUPPORTED_CHAINS).length === 0) {
console.warn(chalk.yellow("Warning: Using fallback chain configuration"));
// Fallback to core chains
const fallbackChains = {
1: {
name: "Ethereum",
color: "cyan",
hypersyncUrl: "http://1.hypersync.xyz",
},
10: {
name: "Optimism",
color: "redBright",
hypersyncUrl: "http://10.hypersync.xyz",
},
137: {
name: "Polygon",
color: "magenta",
hypersyncUrl: "http://137.hypersync.xyz",
},
42161: {
name: "Arbitrum",
color: "blue",
hypersyncUrl: "http://42161.hypersync.xyz",
},
8453: {
name: "Base",
color: "greenBright",
hypersyncUrl: "http://8453.hypersync.xyz",
},
100: {
name: "Gnosis",
color: "green",
hypersyncUrl: "http://100.hypersync.xyz",
},
43114: {
name: "Avalanche",
color: "red",
hypersyncUrl: "http://43114.hypersync.xyz",
},
};
Object.assign(SUPPORTED_CHAINS, fallbackChains);
}
// Get default chain IDs string
const DEFAULT_CHAIN_IDS = Object.keys(SUPPORTED_CHAINS).join(",");
// Cache for token metadata
const tokenMetadataCache = new Map();
// ERC20 ABI for token metadata
const ERC20_ABI = [
{
constant: true,
inputs: [],
name: "name",
outputs: [{ name: "", type: "string" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "symbol",
outputs: [{ name: "", type: "string" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "decimals",
outputs: [{ name: "", type: "uint8" }],
payable: false,
stateMutability: "view",
type: "function",
},
];
// Fetch token metadata from a list of RPCs with improved retry logic
async function fetchTokenMetadata(tokenAddress, chainId = 1) {
// Check cache first
const cacheKey = `${chainId}:${tokenAddress}`;
if (tokenMetadataCache.has(cacheKey)) {
return tokenMetadataCache.get(cacheKey);
}
// Get RPC URLs for the chain
let rpcUrls = [];
if (extraRpcs[chainId]) {
extraRpcs[chainId].rpcs.forEach((rpc) => {
if (typeof rpc === "string") {
rpcUrls.push(rpc);
} else if (rpc.url) {
rpcUrls.push(rpc.url);
}
});
}
// If no RPCs available, return default values
if (rpcUrls.length === 0) {
return {
success: false,
name: "Unknown Token",
symbol: "???",
decimals: 18,
formattedName: "Unknown Token (???)",
};
}
// Shuffle RPC URLs to avoid always hitting the same one first
rpcUrls = shuffleArray([...rpcUrls]);
let lastError = null;
let retryCount = 0;
// Try each RPC until one works, with exponential backoff between retries
for (const rpcUrl of rpcUrls) {
try {
if (rpcUrl.startsWith("wss://")) continue; // Skip WebSocket RPCs for now
// Add a small delay between retries with exponential backoff
if (retryCount > 0) {
await new Promise((resolve) =>
setTimeout(resolve, Math.min(200 * Math.pow(1.5, retryCount), 2000))
);
}
retryCount++;
// Create a viem client with timeout
const client = createPublicClient({
chain: mainnet, // This is just for typing, we'll override with custom endpoint
transport: http(rpcUrl, {
timeout: 3000, // 3 second timeout for RPC calls
fetchOptions: {
headers: {
"Content-Type": "application/json",
},
},
}),
});
// Fetch token metadata (name, symbol, decimals) in parallel
const [name, symbol, decimals] = await Promise.all([
client
.readContract({
address: tokenAddress,
abi: ERC20_ABI,
functionName: "name",
})
.catch((e) => null),
client
.readContract({
address: tokenAddress,
abi: ERC20_ABI,
functionName: "symbol",
})
.catch((e) => null),
client
.readContract({
address: tokenAddress,
abi: ERC20_ABI,
functionName: "decimals",
})
.catch((e) => 18),
]);
// If we got at least one piece of metadata
if (name !== null || symbol !== null) {
const finalName = name || "Unknown Token";
const finalSymbol = symbol || "???";
const metadata = {
success: true,
name: finalName,
symbol: finalSymbol,
decimals,
formattedName: `${finalName} (${finalSymbol})`,
};
// Cache the result
tokenMetadataCache.set(cacheKey, metadata);
return metadata;
}
// If both name and symbol are null, consider this attempt failed
lastError = new Error("Token metadata not available");
} catch (error) {
lastError = error;
// Continue to the next RPC if this one fails
}
}
// If we have a default (placeholder) metadata in cache from a previous failed attempt,
// use that instead of creating a new default object every time
const defaultMetadata = {
success: false,
name: "Unknown Token",
symbol: "???",
decimals: 18,
formattedName: "Unknown Token (???)",
};
// Cache the default result to avoid repeated failed requests
tokenMetadataCache.set(cacheKey, defaultMetadata);
return defaultMetadata;
}
// Utility to shuffle array (for randomizing RPC order)
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
// Format token amounts with proper decimals
function formatTokenAmount(amount, decimals) {
if (!amount) return "0";
try {
return formatUnits(amount, decimals);
} catch (error) {
return amount.toString();
}
}
// Global variables for interactive mode
let approvalsList = [];
let selectedApprovalIndex = 0;
let currentPage = 0;
const PAGE_SIZE = 8; // Number of approvals to show per page
// Group approvals by token for better display
let groupedApprovals = {};
// Scanning stats to preserve after completion
let chainStats = {};
// Create global readline interface
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: true,
});
// CLI setup - note the change to use DEFAULT_CHAIN_IDS
const program = new Command();
program
.name("snubb")
.description("Terminal UI for finding and revoking Ethereum token approvals")
.version("1.0.0")
.option("-a, --address <address>", "Ethereum address to check approvals for")
.option(
"-c, --chains <chainIds>",
"Comma-separated chain IDs or 'many-networks' to scan multiple networks (default: 1 - Ethereum only)",
"1"
)
.option(
"--list-chains",
"Display a list of all supported chains from networkCache.json"
)
.parse(process.argv);
const options = program.opts();
// Check if user wants to list all supported chains
if (options.listChains) {
console.log(
chalk.bold.cyan(figlet.textSync("Supported Chains", { font: "Small" }))
);
console.log(
chalk.bold.cyan("List of all supported chains from networkCache.json\n")
);
// Create a table for better display
const chainsTable = new Table({
head: [
chalk.cyan.bold("CHAIN ID"),
chalk.cyan.bold("NAME"),
chalk.cyan.bold("TIER"),
],
colWidths: [12, 25, 12],
style: {
head: [], // No additional styling for headers
border: [], // No additional styling for borders
},
});
// Sort networkData by chain ID for easier reading
const sortedChains = [...networkData]
.filter((chain) => chain.ecosystem === "evm") // Only show EVM chains
.sort((a, b) => a.chain_id - b.chain_id);
// Add each chain to the table
sortedChains.forEach((chain) => {
chainsTable.push([chain.chain_id.toString(), chain.name, chain.tier]);
});
// Display the table
console.log(chainsTable.toString());
console.log(
`\nTo use: ${chalk.green(
"snubb --address <your-address> --chains <comma-separated-chain-ids>"
)}`
);
process.exit(0);
}
// Check if we have an address
let TARGET_ADDRESS = options.address;
if (!TARGET_ADDRESS) {
console.log(
chalk.bold.cyan(
figlet.textSync("snubb", {
font: "ANSI Shadow",
horizontalLayout: "full",
})
)
);
console.log(
chalk.bold.cyan("multichain token approval scanner") +
" - " +
chalk.cyan("powered by ") +
chalk.cyan.underline("envio.dev") +
"\n"
);
console.log(chalk.yellow("Usage:"));
console.log(
chalk.green(
" snubb --address 0x7C25a8C86A04f40F2Db0434ab3A24b051FB3cA58\n"
)
);
console.log(chalk.yellow("Options:"));
console.log(
chalk.green(
` --chains <chainIds> Comma-separated chain IDs to scan (default: 1 - Ethereum only)\n`
)
);
console.log(
chalk.green(
` --chains many-networks Scan multiple supported networks (${PREFERRED_CHAINS.join(
", "
)})\n`
)
);
console.log(
chalk.green(` --list-chains Display a list of all supported chains\n`)
);
process.exit(0);
}
// Get chain IDs from options
let CHAIN_IDS = [];
// Check if 'many-networks' keyword is used
if (options.chains.toLowerCase() === "many-networks") {
// Use all preferred networks
for (const chainName of PREFERRED_CHAINS) {
const chain = chainNameToData[chainName];
if (chain) {
CHAIN_IDS.push(chain.chain_id);
}
}
} else {
// Otherwise use the specified chains
const requestedChainIds = options.chains
.split(",")
.map((id) => parseInt(id.trim()));
for (const chainId of requestedChainIds) {
// Check if this chain ID exists in networkData (networkCache.json)
const chainData = networkData.find(
(chain) => chain.chain_id === chainId && chain.ecosystem === "evm"
);
if (chainData) {
// If in networkData, check if already added to SUPPORTED_CHAINS
if (!SUPPORTED_CHAINS[chainId]) {
// Get a color from SAFE_COLORS
const colorIndex = Math.floor(Math.random() * SAFE_COLORS.length);
const color = SAFE_COLORS[colorIndex];
// Add to SUPPORTED_CHAINS
SUPPORTED_CHAINS[chainId] = {
name:
chainData.name.charAt(0).toUpperCase() + chainData.name.slice(1),
color: color,
hypersyncUrl: `http://${chainId}.hypersync.xyz`,
};
}
// Now add to CHAIN_IDS
CHAIN_IDS.push(chainId);
} else {
// Chain not in networkCache.json - this is an error
console.error(chalk.red(`Error: Chain ID ${chainId} is not supported.`));
console.error(
chalk.yellow(
`Run '${chalk.green(
"snubb --list-chains"
)}' to see all supported chains.`
)
);
process.exit(1);
}
}
}
// If no valid chains, use Ethereum mainnet
if (CHAIN_IDS.length === 0) {
CHAIN_IDS.push(1); // Fallback to Ethereum mainnet
}
// Normalize address
TARGET_ADDRESS = TARGET_ADDRESS.toLowerCase();
if (!TARGET_ADDRESS.startsWith("0x")) {
TARGET_ADDRESS = "0x" + TARGET_ADDRESS;
}
// Address formatting for topic filtering
const TARGET_ADDRESS_NO_PREFIX = TARGET_ADDRESS.substring(2).toLowerCase();
const TARGET_ADDRESS_PADDED =
"0x000000000000000000000000" + TARGET_ADDRESS_NO_PREFIX;
// Define ERC20 event signatures
const event_signatures = [
"Transfer(address,address,uint256)",
"Approval(address,address,uint256)",
];
// Create topic0 hashes from event signatures
const topic0_list = event_signatures.map((sig) => keccak256(toHex(sig)));
// Store individual topic hashes for easier comparison
const TRANSFER_TOPIC = topic0_list[0];
const APPROVAL_TOPIC = topic0_list[1];
// Create mapping from topic0 hash to event name
const topic0ToName = {};
topic0ToName[TRANSFER_TOPIC] = "Transfer";
topic0ToName[APPROVAL_TOPIC] = "Approval";
// Helper functions for UI
const formatNumber = (num) => {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
const formatToken = (tokenAddress, tokenMetadata) => {
if (tokenMetadata && tokenMetadata.success) {
return tokenMetadata.formattedName;
}
if (tokenAddress.length <= 12) return tokenAddress;
return `${tokenAddress.slice(0, 6)}...${tokenAddress.slice(-6)}`;
};
// Check if an amount is effectively unlimited (close to 2^256-1)
const isEffectivelyUnlimited = (amount) => {
// Common unlimited values (2^256-1 and similar large numbers)
const MAX_UINT256 = BigInt(
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
);
const LARGE_THRESHOLD = MAX_UINT256 - MAX_UINT256 / BigInt(1000); // Within 0.1% of max
return amount > LARGE_THRESHOLD;
};
const formatAmount = (amount, tokenMetadata) => {
if (!amount) return "0";
// Check for unlimited or very large approval (effectively unlimited)
if (
amount === BigInt(2) ** BigInt(256) - BigInt(1) ||
amount ===
BigInt(
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
) ||
isEffectivelyUnlimited(amount)
) {
return "∞ (Unlimited)";
}
// Format with decimals if available
if (tokenMetadata && tokenMetadata.success) {
return formatTokenAmount(amount, tokenMetadata.decimals);
}
// Format large numbers with abbr (fallback)
if (amount > BigInt(1000000000000)) {
return `${Number(amount / BigInt(1000000000000)).toFixed(2)}T`;
} else if (amount > BigInt(1000000000)) {
return `${Number(amount / BigInt(1000000000)).toFixed(2)}B`;
} else if (amount > BigInt(1000000)) {
return `${Number(amount / BigInt(1000000)).toFixed(2)}M`;
} else if (amount > BigInt(1000)) {
return `${Number(amount / BigInt(1000)).toFixed(2)}K`;
}
return amount.toString();
};
// Format chain name with color (safely)
const formatChainName = (chainId) => {
if (!SUPPORTED_CHAINS[chainId]) {
return chalk.white(`Chain ${chainId}`);
}
const chain = SUPPORTED_CHAINS[chainId];
const colorName = chain.color || "white";
// Safely apply color
try {
if (chalk[colorName]) {
return chalk[colorName](chain.name);
} else {
return chalk.white(chain.name);
}
} catch (error) {
return chalk.white(chain.name);
}
};
// Draw progress bar with safe color handling
function drawProgressBar(progress, width = 40, colorName = "cyan") {
const filledWidth = Math.floor(width * progress);
const emptyWidth = width - filledWidth;
// Ensure we draw something even at 100%
const filledChar = "█";
const emptyChar = "░";
const filledBar = filledChar.repeat(Math.max(1, filledWidth));
const emptyBar = emptyChar.repeat(emptyWidth);
// Safely apply color
try {
if (chalk[colorName]) {
return chalk[colorName](filledBar) + emptyBar;
} else {
return chalk.cyan(filledBar) + emptyBar;
}
} catch (error) {
return chalk.cyan(filledBar) + emptyBar;
}
}
// Create a query for ERC20 events related to our target address
const createQuery = (fromBlock) => ({
fromBlock,
logs: [
// Filter for Approval events where target address is the owner (topic1)
{
topics: [[APPROVAL_TOPIC], [TARGET_ADDRESS_PADDED], []],
},
// Filter for Transfer events where target address is from (topic1)
{
topics: [[TRANSFER_TOPIC], [TARGET_ADDRESS_PADDED], []],
},
// Also get Transfer events where target address is to (topic2)
{
topics: [[TRANSFER_TOPIC], [], [TARGET_ADDRESS_PADDED]],
},
],
// Also filter for transactions involving the target address
transactions: [
{
from: [TARGET_ADDRESS],
},
{
to: [TARGET_ADDRESS],
},
],
fieldSelection: {
log: [
LogField.BlockNumber,
LogField.LogIndex,
LogField.TransactionIndex,
LogField.TransactionHash,
LogField.Data,
LogField.Address,
LogField.Topic0,
LogField.Topic1,
LogField.Topic2,
LogField.Topic3,
],
transaction: [
TransactionField.From,
TransactionField.To,
TransactionField.Hash,
],
},
joinMode: JoinMode.JoinTransactions,
});
// Add a new state variable near the other global variables
let detailsExpanded = false;
// Function to display the approvals list
async function displayApprovalsList() {
console.clear();
// Display header with logo and stats
console.log(chalk.bold.cyan(figlet.textSync("snubb", { font: "Doom" })));
console.log(
chalk.bold.cyan("multichain token approval scanner") +
" - " +
chalk.cyan("powered by ") +
chalk.cyan.underline("envio.dev") +
"\n"
);
// Display scan progress and summary separately
displayScanSummary();
// Calculate page bounds
const startIdx = currentPage * PAGE_SIZE;
const endIdx = Math.min(startIdx + PAGE_SIZE, approvalsList.length);
const totalPages = Math.ceil(approvalsList.length / PAGE_SIZE);
// Navigation header with enhanced information
console.log(
boxen(
chalk.bold.cyan(
`OUTSTANDING APPROVALS (${currentPage + 1}/${totalPages}) - Showing ${
startIdx + 1
}-${endIdx} of ${approvalsList.length}`
),
{
padding: { top: 0, bottom: 0, left: 1, right: 1 },
borderColor: "yellow",
borderStyle: "round",
}
)
);
// Create a more structured table for approvals with proper hierarchy
displayApprovalsTable(startIdx, endIdx);
// Display details of the selected approval only if expanded
if (approvalsList.length > 0 && detailsExpanded) {
const approval = approvalsList[selectedApprovalIndex];
// Use cached token metadata if available
const tokenMetadata = tokenMetadataCache.get(
`${approval.chainId}:${approval.tokenAddress}`
);
// Display approval details with available metadata
displayApprovalDetails(approval, tokenMetadata || { success: false });
} else if (approvalsList.length > 0) {
// Show a hint to expand details
console.log(
boxen(
chalk.dim(
"Press ENTER to view detailed information for the selected approval"
),
{
padding: { top: 0, bottom: 0, left: 1, right: 1 },
borderColor: "blue",
borderStyle: "round",
}
)
);
}
// Add revoke.cash link right above navigation commands
const revokeLink = `https://revoke.cash/address/${TARGET_ADDRESS}`;
console.log(
boxen(
chalk.bold.white(
`⚠️ REVOKE APPROVALS: ${chalk.bold.cyan.underline(revokeLink)}`
),
{
padding: { top: 0, bottom: 0, left: 2, right: 2 },
margin: { top: 1, bottom: 0 },
borderColor: "red",
borderStyle: "round",
}
)
);
// Move navigation instructions to the bottom near the input prompt
console.log(
"\n" +
boxen(
[
chalk.cyan("Navigation Commands:"),
`${chalk.yellow("n")} - Next approval ${chalk.yellow(
"p"
)} - Previous approval`,
`${chalk.yellow(">")} - Next page ${chalk.yellow(
"<"
)} - Previous page`,
`${chalk.yellow("ENTER")} - Show/hide details`,
`${chalk.yellow("q")} - Quit ${chalk.yellow("h")} - Help`,
].join("\n"),
{
padding: { top: 1, bottom: 1, left: 2, right: 2 },
margin: { top: 0, bottom: 1 },
borderColor: "magenta",
borderStyle: "round",
}
)
);
// Start fetching metadata in the background
fetchTokenMetadataInBackground(startIdx, endIdx);
}
// Function to display approvals in a professionally formatted table
function displayApprovalsTable(startIdx, endIdx) {
// Create a new table for approvals with clean styling
const approvalsTable = new Table({
head: [
chalk.cyan.bold("CHAIN"),
chalk.cyan.bold("TOKEN"),
chalk.cyan.bold("SPENDER"),
chalk.cyan.bold("AMOUNT"),
],
colWidths: [10, 18, 23, 35],
style: {
head: [], // No additional styling for headers
border: [], // No additional styling for borders
compact: true, // More compact table
},
chars: {
top: "━",
"top-mid": "┳",
"top-left": "┏",
"top-right": "┓",
bottom: "━",
"bottom-mid": "┻",
"bottom-left": "┗",
"bottom-right": "┛",
left: "┃",
"left-mid": "",
mid: "",
"mid-mid": "",
right: "┃",
"right-mid": "",
middle: "┃",
},
});
// Keep track of current chain to handle grouping
let currentChainId = null;
let currentTokenAddress = null;
// Display the approvals with token metadata when available
for (let i = startIdx; i < endIdx; i++) {
const approval = approvalsList[i];
const isSelected = i === selectedApprovalIndex;
// Check if this is a new chain
const isNewChain = currentChainId !== approval.chainId;
const isNewToken =
currentTokenAddress !== approval.tokenAddress || isNewChain;
// Get token metadata
const tokenMetadata = tokenMetadataCache.get(
`${approval.chainId}:${approval.tokenAddress}`
);
// Format token display based on available metadata
const tokenDisplay =
tokenMetadata && tokenMetadata.success
? `${chalk.cyan(tokenMetadata.symbol)}`
: chalk.cyan(approval.tokenAddress.slice(0, 6) + "...");
// Format spender display with selection indicator and truncation if needed
const spenderText = formatToken(approval.spender);
// Truncate long spender addresses to fit column
const displaySpender =
spenderText.length > 18
? spenderText.slice(0, 8) + "..." + spenderText.slice(-8)
: spenderText;
const spenderDisplay = isSelected
? chalk.yellow.bold(`→ ${displaySpender}`)
: chalk.yellow(displaySpender);
// Update unlimited flag for effectively unlimited values
const isEffectiveUnlimited = isEffectivelyUnlimited(
approval.remainingApproval
);
const displayAsUnlimited = approval.isUnlimited || isEffectiveUnlimited;
// Format amount display
const amountDisplay = displayAsUnlimited
? isSelected
? chalk.red.bold("⚠️ UNLIMITED")
: chalk.red.bold("⚠️ ∞")
: chalk.green(formatAmount(approval.remainingApproval, tokenMetadata));
// Handle chain grouping - only show chain name for the first entry of the chain
const chainCell = isNewChain ? formatChainName(approval.chainId) : "";
// Add row to table
approvalsTable.push([
chainCell,
tokenDisplay,
spenderDisplay,
amountDisplay,
]);
// Update tracking variables
if (isNewChain) {
currentChainId = approval.chainId;
}
if (isNewToken) {
currentTokenAddress = approval.tokenAddress;
}
}
// Display the table
console.log(approvalsTable.toString());
}
// Function to display progress bars and summary table sequentially
function displayScanSummary() {
// Calculate maximum width needed for chain names
const chainNameWidth =
Math.max(
...CHAIN_IDS.map((id) => formatChainName(id).length),
10 // Minimum width
) + 2; // Add some padding
// Display progress bars header
console.log(chalk.bold.yellow("SCAN PROGRESS"));
// Display progress bars
for (const chainId of CHAIN_IDS) {
if (chainStats[chainId]) {
const stats = chainStats[chainId];
// Use consistent padding and formatting for all chains
const chainName = formatChainName(chainId);
const paddedChainName = chainName.padEnd(chainNameWidth);
// Create progress bar line with fixed spacing
console.log(
` ${paddedChainName}: [${stats.progressBar}] 100.00% ${chalk.green(
"✓ Complete"
)}`
);
}
}
// Create summary table
console.log(chalk.bold.yellow("\nSUMMARY"));
const statsTable = new Table({
head: [
chalk.cyan("CHAIN"),
chalk.cyan("HEIGHT"),
chalk.cyan("EVENTS"),
chalk.cyan("TIME"),
chalk.cyan("APPROVALS"),
],
colWidths: [15, 15, 10, 8, 10],
style: {
head: [], // No additional styling for headers
border: [], // No additional styling for borders
compact: true, // More compact table with less padding
},
});
// Add rows to the table from chain stats
let totalApprovals = 0;
for (const chainId of CHAIN_IDS) {
if (chainStats[chainId]) {