|
| 1 | +import { existsSync, readFileSync, writeFileSync } from 'fs'; |
| 2 | +import { dirname, join } from 'path'; |
| 3 | +import { fileURLToPath } from 'url'; |
| 4 | + |
| 5 | +// Get current file directory in ESM |
| 6 | +const __filename = fileURLToPath(import.meta.url); |
| 7 | +const __dirname = dirname(__filename); |
| 8 | + |
| 9 | +const { NETWORK_NAME, START_BLOCK } = process.env; // Get the network name from env |
| 10 | + |
| 11 | +// Path to the networks.json file (one directory up) |
| 12 | +const networksFilePath = join(__dirname, 'networks.json'); |
| 13 | + |
| 14 | +/** |
| 15 | + * Update networks.json file with the current block number |
| 16 | + */ |
| 17 | +async function updateNetworksFile() { |
| 18 | + if (!NETWORK_NAME) { |
| 19 | + console.warn( |
| 20 | + 'No NETWORK_NAME environment variable provided. The networks.json file will not be updated.', |
| 21 | + ); |
| 22 | + return; |
| 23 | + } |
| 24 | + if (!START_BLOCK) { |
| 25 | + console.warn( |
| 26 | + 'No START_BLOCK environment variable provided. The networks.json file will not be updated.', |
| 27 | + ); |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + if (!existsSync(networksFilePath)) { |
| 32 | + console.warn(`networks.json file not found at ${networksFilePath}`); |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + try { |
| 37 | + // Read the current networks.json file |
| 38 | + const networksData = JSON.parse(readFileSync(networksFilePath, 'utf8')); |
| 39 | + |
| 40 | + // Check if the specified network exists in the file |
| 41 | + if (networksData[NETWORK_NAME]) { |
| 42 | + console.log(`Updating startBlock for network '${NETWORK_NAME}' to ${START_BLOCK}`); |
| 43 | + |
| 44 | + // Update all startBlock values for the specified network |
| 45 | + Object.keys(networksData[NETWORK_NAME]).forEach((contract) => { |
| 46 | + networksData[NETWORK_NAME][contract].startBlock = parseInt(START_BLOCK, 10); |
| 47 | + }); |
| 48 | + |
| 49 | + // Write the updated networks.json file |
| 50 | + writeFileSync(networksFilePath, JSON.stringify(networksData, null, 4)); |
| 51 | + console.log(`Successfully updated ${networksFilePath}`); |
| 52 | + } else { |
| 53 | + console.warn(`Network '${NETWORK_NAME}' not found in networks.json. File unchanged.`); |
| 54 | + } |
| 55 | + } catch (error) { |
| 56 | + console.error(`Error updating networks.json file: ${error}`); |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +/** |
| 61 | + * Main function to orchestrate the process |
| 62 | + */ |
| 63 | +async function main() { |
| 64 | + try { |
| 65 | + await updateNetworksFile(); |
| 66 | + } catch (error) { |
| 67 | + console.error(error); |
| 68 | + process.exit(1); |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +// Run the main function |
| 73 | +main(); |
0 commit comments