-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchains.js
More file actions
397 lines (346 loc) · 10.3 KB
/
Copy pathchains.js
File metadata and controls
397 lines (346 loc) · 10.3 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
/**
* Chain configuration manager for the contract-analyzer CLI
*
* This module handles loading, saving, and managing custom chain configurations
* for EVM-compatible blockchains.
*/
import fs from 'fs/promises';
import path from 'path';
import os from 'os';
// Path to store the configuration
const CONFIG_DIR = path.join(os.homedir(), '.contract-analyzer');
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
// Selected configuration
const DEFAULT_CONFIG = {
chains: {},
selectedChain: null,
apiKeys: {},
preferences: {
outputFormat: 'json',
},
lastUpdated: new Date().toISOString(),
};
// Extended chains - these are available but not included by selected
// Users can add these manually with the chains add command
const EXTENDED_CHAINS = {
polygon: {
name: 'Polygon Mainnet',
blockExplorer: 'https://api.polygonscan.com/api',
blockExplorerName: 'Polygonscan',
chainId: 137,
},
arbitrum: {
name: 'Arbitrum One',
blockExplorer: 'https://api.arbiscan.io/api',
blockExplorerName: 'Arbiscan',
chainId: 42161,
},
optimism: {
name: 'Optimism',
blockExplorer: 'https://api-optimistic.etherscan.io/api',
blockExplorerName: 'Optimism Etherscan',
chainId: 10,
},
bsc: {
name: 'BNB Smart Chain',
blockExplorer: 'https://api.bscscan.com/api',
blockExplorerName: 'BscScan',
chainId: 56,
},
base: {
name: 'Base',
blockExplorer: 'https://api.basescan.org/api',
blockExplorerName: 'BaseScan',
chainId: 8453,
},
};
/**
* Load configuration from file
*
* @returns {Promise<Object>} The configuration object
*/
async function loadConfig() {
try {
const data = await fs.readFile(CONFIG_FILE, 'utf8');
return JSON.parse(data);
} catch (error) {
// Return default config if file doesn't exist or can't be parsed
return { ...DEFAULT_CONFIG };
}
}
/**
* Save configuration to file
*
* @param {Object} config - The configuration to save
* @returns {Promise<boolean>} Success status
*/
async function saveConfig(config) {
try {
await fs.mkdir(CONFIG_DIR, { recursive: true });
await fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));
return true;
} catch (error) {
console.error('Error saving configuration:', error.message);
return false;
}
}
/**
* Initialize the configuration directory and config file
*/
async function initChainConfig() {
try {
await fs.mkdir(CONFIG_DIR, { recursive: true });
// Check if config file exists, if not create it with defaults
try {
await fs.access(CONFIG_FILE);
// Config file exists, leave it as is
} catch (error) {
// File doesn't exist, create it with empty defaults
await saveConfig(DEFAULT_CONFIG);
}
return true;
} catch (error) {
console.error('Error initializing config:', error.message);
return false;
}
}
/**
* Get all chain configurations
*
* @returns {Promise<Object>} Object containing all chains
*/
async function getChains() {
await initChainConfig();
try {
const config = await loadConfig();
return config.chains || {};
} catch (error) {
console.error('Error loading chains:', error.message);
return {};
}
}
/**
* Add a new chain configuration
*
* @param {string} id - Chain identifier
* @param {Object} chainConfig - Chain configuration
* @param {string} chainConfig.name - Chain name
* @param {string} chainConfig.blockExplorer - Block explorer API URL
* @param {string} chainConfig.blockExplorerName - Block explorer name
* @param {number} [chainConfig.chainId=0] - Chain ID (optional)
* @param {string} [chainConfig.apiKey=''] - API key for the block explorer
* @returns {Promise<boolean>} Success flag
*/
async function addChain(id, chainConfig) {
if (!id || typeof id !== 'string') {
throw new Error('Chain ID is required');
}
// Validate required fields
const requiredFields = ['name', 'blockExplorer', 'blockExplorerName'];
for (const field of requiredFields) {
if (!chainConfig[field]) {
throw new Error(`Chain configuration must include ${field}`);
}
}
// Get existing config
const config = await loadConfig();
// Add the new chain
config.chains = config.chains || {};
config.chains[id.toLowerCase()] = {
name: chainConfig.name,
blockExplorer: chainConfig.blockExplorer,
blockExplorerName: chainConfig.blockExplorerName,
chainId: chainConfig.chainId || 0,
apiKey: chainConfig.apiKey || '',
};
config.lastUpdated = new Date().toISOString();
// Save the updated configuration
return await saveConfig(config);
}
/**
* Remove a chain configuration
*
* @param {string} id - Chain identifier to remove
* @returns {Promise<boolean>} Success status
*/
async function removeChain(id) {
if (!id || typeof id !== 'string') {
throw new Error('Invalid chain ID');
}
// Cannot remove ethereum
if (id.toLowerCase() === 'ethereum') {
throw new Error('Cannot remove the selected Ethereum chain');
}
// Load existing config
const config = await loadConfig();
// Check if chain exists in custom configs
if (!config.chains || !config.chains[id.toLowerCase()]) {
throw new Error(`Chain '${id}' not found`);
}
// Remove the chain
delete config.chains[id.toLowerCase()];
config.lastUpdated = new Date().toISOString();
// Save the updated configuration
return await saveConfig(config);
}
/**
* Get details for a specific chain
*
* @param {string} id - Chain identifier
* @returns {Promise<Object|null>} Chain configuration or null if not found
*/
async function getChain(id) {
if (!id || typeof id !== 'string') {
return DEFAULT_CONFIG.chains.ethereum;
}
const config = await loadConfig();
return (config.chains && config.chains[id.toLowerCase()]) || null;
}
/**
* Get example chains that can be added
*
* @returns {Array} Array of chain identifiers that can be added
*/
async function getAvailableChains() {
const config = await loadConfig();
return Object.keys(EXTENDED_CHAINS).filter(id => !config.chains || !config.chains[id]);
}
/**
* Set the selected chain
*
* @param {string} id - Chain identifier
* @returns {Promise<boolean>} Success status
*/
async function setSelectedChain(id) {
if (!id || typeof id !== 'string') {
throw new Error('Invalid chain ID');
}
const config = await loadConfig();
// Check if chain exists
if (!config.chains || !config.chains[id.toLowerCase()]) {
throw new Error(`Chain '${id}' not found`);
}
// Update selected chain
config.selectedChain = id.toLowerCase();
config.lastUpdated = new Date().toISOString();
// Save the updated configuration
return await saveConfig(config);
}
/**
* Get the selected chain
*
* @returns {Promise<string>} Selected chain identifier
*/
async function getSelectedChain() {
const config = await loadConfig();
return config.selectedChain || '';
}
/**
* Save API key for a specific chain
*
* @param {string} chain - Chain identifier
* @param {string|Object} apiKey - API key string or object with apiKey and blockscannerUrl
* @returns {Promise<boolean>} Success status
*/
async function saveApiKey(chain, apiKey) {
if (!chain || typeof chain !== 'string') {
throw new Error('Invalid chain ID');
}
const config = await loadConfig();
// Check if chain exists
if (!config.chains || !config.chains[chain.toLowerCase()]) {
throw new Error(`Chain '${chain}' not found`);
}
// Handle both string and object formats for backward compatibility
if (typeof apiKey === 'object' && apiKey !== null) {
// New format: {apiKey, blockscannerUrl}
if (apiKey.apiKey) {
config.chains[chain.toLowerCase()].apiKey = apiKey.apiKey;
// Also store in apiKeys section for backward compatibility
config.apiKeys = config.apiKeys || {};
config.apiKeys[`${chain.toUpperCase()}_EXPLORER_KEY`] = apiKey.apiKey;
}
// Update blockExplorer URL if provided
if (apiKey.blockscannerUrl) {
// Ensure the URL is in API format by adding /api if needed
const baseUrl = apiKey.blockscannerUrl.endsWith('/')
? apiKey.blockscannerUrl.slice(0, -1)
: apiKey.blockscannerUrl;
// Convert website URL to API URL
// Example: https://etherscan.io -> https://api.etherscan.io/api
let apiUrl = baseUrl;
if (!baseUrl.includes('/api') && !baseUrl.includes('api.')) {
// Replace https://DOMAIN with https://api.DOMAIN/api
const urlObj = new URL(baseUrl);
apiUrl = `https://api.${urlObj.hostname}/api`;
} else if (!baseUrl.endsWith('/api')) {
apiUrl = `${baseUrl}/api`;
}
config.chains[chain.toLowerCase()].blockExplorer = apiUrl;
}
} else {
// Old format: string (just the API key)
config.chains[chain.toLowerCase()].apiKey = apiKey;
// Also store in apiKeys section for backward compatibility
config.apiKeys = config.apiKeys || {};
config.apiKeys[`${chain.toUpperCase()}_EXPLORER_KEY`] = apiKey;
}
config.lastUpdated = new Date().toISOString();
// Save the updated configuration
return await saveConfig(config);
}
/**
* Get API key for a specific chain
*
* @param {string} chain - Chain identifier
* @returns {Promise<string>} API key
*/
async function getApiKey(chain) {
if (!chain || typeof chain !== 'string') {
return '';
}
const config = await loadConfig();
// Check in chain configuration first
if (
config.chains &&
config.chains[chain.toLowerCase()] &&
config.chains[chain.toLowerCase()].apiKey
) {
return config.chains[chain.toLowerCase()].apiKey;
}
// Fall back to apiKeys section
if (config.apiKeys && config.apiKeys[`${chain.toUpperCase()}_EXPLORER_KEY`]) {
return config.apiKeys[`${chain.toUpperCase()}_EXPLORER_KEY`];
}
return '';
}
// For backward compatibility with code using the old networks.js
const getNetworks = getChains;
const getNetwork = getChain;
const addNetwork = addChain;
const removeNetwork = removeChain;
const initNetworkConfig = initChainConfig;
const getAvailableNetworks = getAvailableChains;
const DEFAULT_NETWORKS = DEFAULT_CONFIG.chains;
const EXTENDED_NETWORKS = EXTENDED_CHAINS;
export {
getChains,
getChain,
addChain,
removeChain,
getAvailableChains,
setSelectedChain,
getSelectedChain,
saveApiKey,
getApiKey,
initChainConfig,
// Legacy exports
getNetworks,
getNetwork,
addNetwork,
removeNetwork,
initNetworkConfig,
getAvailableNetworks,
DEFAULT_NETWORKS,
EXTENDED_NETWORKS,
};