Skip to content

Commit

Permalink
various clean-ups for bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
dghelm committed Oct 8, 2024
1 parent 2020121 commit b72305a
Show file tree
Hide file tree
Showing 7 changed files with 405 additions and 276 deletions.
75 changes: 59 additions & 16 deletions src/commands/helper/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ enum Layer {
export default class HelperActivity extends Command {
private providers: Record<Layer, ethers.JsonRpcProvider> = {} as Record<Layer, ethers.JsonRpcProvider>;
private rpcUrls: Record<Layer, string> = {} as Record<Layer, string>;
private flags: any;
private nonceTrackers: Record<Layer, number> = {} as Record<Layer, number>;

static description = 'Generate transactions on the specified network(s) to produce more blocks'

Expand Down Expand Up @@ -60,10 +62,30 @@ export default class HelperActivity extends Command {
char: 'r',
description: 'RPC URL (overrides config for both layers)',
}),
debug: Flags.boolean({
char: 'd',
default: false,
description: 'Enable debug mode for more detailed logging',
}),
}

private debugLog(message: string): void {
if (this.flags && this.flags.debug) {
this.log(chalk.gray(`[DEBUG] ${message}`))
}
}

private async initializeNonceTrackers(wallets: Record<Layer, ethers.Wallet>) {
for (const [layer, wallet] of Object.entries(wallets)) {
const nonce = await wallet.getNonce();
this.nonceTrackers[layer as Layer] = nonce;
this.debugLog(`Initialized nonce for ${layer}: ${nonce}`);
}
}

public async run(): Promise<void> {
const { flags } = await this.parse(HelperActivity)
this.flags = flags // Assign parsed flags to the instance property

const configPath = path.resolve(flags.config)
const config = parseTomlConfig(configPath)
Expand Down Expand Up @@ -142,22 +164,23 @@ export default class HelperActivity extends Command {
`Sender: ${publicKey} | Recipient: ${recipientAddr}`,
),
)
}

// eslint-disable-next-line no-constant-condition
layers.map(async (layer) => {
while (true) {
for (const layer of layers) {
// eslint-disable-next-line no-await-in-loop
await this.sendTransaction(wallets[layer], recipientAddr, layer)
}
await this.initializeNonceTrackers(wallets);

// eslint-disable-next-line no-await-in-loop, no-promise-executor-return
await new Promise((resolve) => setTimeout(resolve, flags.interval * 1000))
// eslint-disable-next-line no-constant-condition
layers.map(async (layer) => {
while (true) {
for (const layer of layers) {
// eslint-disable-next-line no-await-in-loop
await this.sendTransaction(wallets[layer], recipientAddr, layer)
}

})
}
// eslint-disable-next-line no-await-in-loop, no-promise-executor-return
await new Promise((resolve) => setTimeout(resolve, flags.interval * 1000))
}

})
}

private async replaceTransactions(wallet: ethers.Wallet, startNonce: number, endNonce: number, layer: Layer) {
Expand Down Expand Up @@ -210,11 +233,24 @@ export default class HelperActivity extends Command {

private async sendTransaction(wallet: ethers.Wallet, recipient: string, layer: Layer) {
try {
this.debugLog(`Preparing transaction for ${layer.toUpperCase()}`)
this.debugLog(`Sender: ${wallet.address}, Recipient: ${recipient}`)

const currentNonce = this.nonceTrackers[layer];
this.debugLog(`Current nonce for ${layer}: ${currentNonce}`);

const tx = await wallet.sendTransaction({
to: recipient,
value: ethers.parseUnits('0.1', 'gwei'),
nonce: currentNonce,
})

this.debugLog(`Transaction created: ${JSON.stringify(tx, null, 2)}`)

// Increment the nonce tracker immediately after sending the transaction
this.nonceTrackers[layer]++;
this.debugLog(`Updated nonce for ${layer}: ${this.nonceTrackers[layer]}`);

const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Transaction taking longer than expected')), 5000)
);
Expand All @@ -223,20 +259,27 @@ export default class HelperActivity extends Command {
const receipt = await Promise.race([tx.wait(), timeoutPromise]) as ethers.TransactionReceipt | null;
if (receipt) {
this.log(chalk.green(`${layer.toUpperCase()} Transaction sent: ${tx.hash} (Block: ${receipt.blockNumber})`))
this.debugLog(`Full receipt: ${JSON.stringify(receipt, null, 2)}`)
} else {
this.log(chalk.yellow(`${layer.toUpperCase()} Transaction sent: ${tx.hash} (Receipt not available)`))
}
} catch (timeoutError) {
this.log(chalk.yellow(`${layer.toUpperCase()} Transaction sent, but taking longer than expected: ${tx.hash}`))
this.log(`${JSON.stringify(tx)}`)
this.debugLog(`Timeout error: ${timeoutError}`)
}
} catch (error) {
this.log(
chalk.red(
`Failed to send ${layer.toUpperCase()} transaction: ${error instanceof Error ? error.message : 'Unknown error'
}`,
),
`Failed to send ${layer.toUpperCase()} transaction: ${error instanceof Error ? error.message : 'Unknown error'}`
)
)
if (error instanceof Error) {
this.debugLog(`Error stack: ${error.stack}`)
if ('code' in error) {
this.debugLog(`Error code: ${(error as any).code}`)
}
}
this.debugLog(`Full error object: ${JSON.stringify(error, null, 2)}`)
}
}
}
}
12 changes: 7 additions & 5 deletions src/commands/helper/fund-accounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,14 @@ export default class HelperFundAccounts extends Command {
this.blockExplorers.l1.blockExplorerURI = config?.frontend?.EXTERNAL_EXPLORER_URI_L1
this.blockExplorers.l2.blockExplorerURI = config?.frontend?.EXTERNAL_EXPLORER_URI_L2

this.l1ETHGateway = config?.contracts?.L1_ETH_GATEWAY_PROXY_ADDR
// Parse config-contracts.toml
const contractsConfigPath = path.resolve(flags.contracts)
const contractsConfig = parseTomlConfig(contractsConfigPath)
this.l1ETHGateway = contractsConfig.L1_ETH_GATEWAY_PROXY_ADDR

if (flags['private-key']) {
this.fundingWallet = new ethers.Wallet(flags['private-key'], this.l1Provider)
} else if (!flags.manual && !flags.dev) {
} else if (!flags.manual) {
this.fundingWallet = new ethers.Wallet(config.accounts.DEPLOYER_PRIVATE_KEY, this.l1Provider)
}

Expand All @@ -138,9 +141,6 @@ export default class HelperFundAccounts extends Command {
if (this.altGasTokenEnabled) {
this.log(chalk.yellow('Alternative Gas Token mode is enabled.'))

// Parse config-contracts.toml
const contractsConfigPath = path.resolve(flags.contracts)
const contractsConfig = parseTomlConfig(contractsConfigPath)
this.l1GasTokenGateway = contractsConfig.L1_GAS_TOKEN_GATEWAY_PROXY_ADDR
this.l1GasTokenAddress = contractsConfig.L1_GAS_TOKEN_ADDR

Expand Down Expand Up @@ -281,6 +281,8 @@ export default class HelperFundAccounts extends Command {
const gasLimit = BigInt(170_000)
const value = ethers.parseEther((amount + 0.001).toString())

console.log(this.l1ETHGateway);

const l1ETHGateway = new ethers.Contract(
this.l1ETHGateway,
['function depositETH(address _to, uint256 _amount, uint256 _gasLimit) payable'],
Expand Down
75 changes: 33 additions & 42 deletions src/commands/setup/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export default class SetupConfigs extends Command {
const config = toml.parse(configContent)

const services = [
'admin-system-backend', 'blockscout', 'bridge-history-api', 'bridge-history-fetcher', 'chain-monitor', 'coordinator-api', 'coordinator-cron',
'admin-system-backend', 'admin-system-cron', 'blockscout', 'bridge-history-api', 'bridge-history-fetcher', 'chain-monitor', 'coordinator-api', 'coordinator-cron',
'gas-oracle', 'l1-explorer', 'l2-sequencer', 'rollup-node'
]

Expand All @@ -132,7 +132,8 @@ export default class SetupConfigs extends Command {
// TODO: check privatekey secrets once integrated
private generateEnvContent(service: string, config: any): { [key: string]: string } {
const mapping: Record<string, string[]> = {
'admin-system-backend': ['ADMIN_SYSTEM_BACKEND_DB_CONNECTION_STRING:SCROLL_ADMIN_AUTH_DB_CONFIG', 'ADMIN_SYSTEM_BACKEND_DB_CONNECTION_STRING:SCROLL_ADMIN_DB_CONFIG_DSN', 'ADMIN_SYSTEM_BACKEND_DB_CONNECTION_STRING:SCROLL_ADMION_READ_ONLY_DB_CONFIG_DSN'],
'admin-system-backend': ['ADMIN_SYSTEM_BACKEND_DB_CONNECTION_STRING:SCROLL_ADMIN_AUTH_DB_CONFIG_DSN', 'ADMIN_SYSTEM_BACKEND_DB_CONNECTION_STRING:SCROLL_ADMIN_DB_CONFIG_DSN', 'ADMIN_SYSTEM_BACKEND_DB_CONNECTION_STRING:SCROLL_ADMIN_READ_ONLY_DB_CONFIG_DSN'],
'admin-system-cron': ['ADMIN_SYSTEM_BACKEND_DB_CONNECTION_STRING:SCROLL_ADMIN_AUTH_DB_CONFIG_DSN', 'ADMIN_SYSTEM_BACKEND_DB_CONNECTION_STRING:SCROLL_ADMIN_DB_CONFIG_DSN', 'ADMIN_SYSTEM_BACKEND_DB_CONNECTION_STRING:SCROLL_ADMIN_READ_ONLY_DB_CONFIG_DSN'],
'blockscout': ['BLOCKSCOUT_DB_CONNECTION_STRING:DATABASE_URL'],
'bridge-history-api': ['BRIDGE_HISTORY_DB_CONNECTION_STRING:SCROLL_BRIDGE_HISTORY_DB_DSN'],
'bridge-history-fetcher': ['BRIDGE_HISTORY_DB_CONNECTION_STRING:SCROLL_BRIDGE_HISTORY_DB_DSN'],
Expand Down Expand Up @@ -482,39 +483,29 @@ export default class SetupConfigs extends Command {
}

const fileMappings = [
{ source: 'admin-system-backend-config.yaml', target: 'admin-system-backend-config.yaml', prefix: 'admin-system-backend:' },
{ source: 'admin-system-backend-config.yaml', target: 'admin-system-cron-config.yaml', prefix: 'admin-system-cron:' },
{ source: 'balance-checker-config.yaml', target: 'balance-checker-config.yaml', prefix: 'balance-checker:' },
{ source: 'bridge-history-config.yaml', target: 'bridge-history-api-config.yaml', prefix: 'bridge-history-api:' },
{ source: 'bridge-history-config.yaml', target: 'bridge-history-fetcher-config.yaml', prefix: 'bridge-history-fetcher:' },
{ source: 'chain-monitor-config.yaml', target: 'chain-monitor-config.yaml', prefix: 'chain-monitor:' },
{ source: 'coordinator-config.yaml', target: 'coordinator-api-config.yaml', prefix: 'coordinator-api:' },
{ source: 'coordinator-config.yaml', target: 'coordinator-cron-config.yaml', prefix: 'coordinator-cron:' },
{ source: 'frontend-config.yaml', target: 'frontends-config.yaml', prefix: 'frontends:' },
{ source: 'genesis.yaml', target: 'genesis.yaml', prefix: 'scroll-common:' },
{ source: 'rollup-config.yaml', target: 'gas-oracle-config.yaml', prefix: 'gas-oracle:' },
{ source: 'rollup-config.yaml', target: 'rollup-node-config.yaml', prefix: 'rollup-node:' },
{ source: 'rollup-explorer-backend-config.yaml', target: 'rollup-explorer-backend-config.yaml', prefix: 'rollup-explorer-backend:' },
{ source: 'admin-system-backend-config.yaml', target: 'admin-system-backend-config.yaml' },
{ source: 'admin-system-backend-config.yaml', target: 'admin-system-cron-config.yaml' },
{ source: 'balance-checker-config.yaml', target: 'balance-checker-config.yaml' },
{ source: 'bridge-history-config.yaml', target: 'bridge-history-api-config.yaml' },
{ source: 'bridge-history-config.yaml', target: 'bridge-history-fetcher-config.yaml' },
{ source: 'chain-monitor-config.yaml', target: 'chain-monitor-config.yaml' },
{ source: 'coordinator-config.yaml', target: 'coordinator-api-config.yaml' },
{ source: 'coordinator-config.yaml', target: 'coordinator-cron-config.yaml' },
{ source: 'frontend-config.yaml', target: 'frontends-config.yaml' },
{ source: 'genesis.yaml', target: 'genesis.yaml' },
{ source: 'rollup-config.yaml', target: 'gas-oracle-config.yaml' },
{ source: 'rollup-config.yaml', target: 'rollup-node-config.yaml' },
{ source: 'rollup-explorer-backend-config.yaml', target: 'rollup-explorer-backend-config.yaml' },
];

// Read all source files first
const sourceFiles = new Map<string, string>();
// Process all mappings
for (const mapping of fileMappings) {
const sourcePath = path.join(sourceDir, mapping.source);
if (fs.existsSync(sourcePath) && !sourceFiles.has(mapping.source)) {
sourceFiles.set(mapping.source, fs.readFileSync(sourcePath, 'utf8'));
}
}
const targetPath = path.join(targetDir, mapping.target);

// Process all mappings
for (const mapping of fileMappings) {
const content = sourceFiles.get(mapping.source);
if (content) {
const targetPath = path.join(targetDir, mapping.target);
if (fs.existsSync(sourcePath)) {
try {
const indentedContent = content.split('\n').map(line => ` ${line}`).join('\n');
const newContent = `${mapping.prefix}\n${indentedContent}`;
fs.writeFileSync(targetPath, newContent);
fs.copyFileSync(sourcePath, targetPath);
this.log(chalk.green(`Processed file: ${mapping.source} -> ${mapping.target}`));
} catch (error: unknown) {
if (error instanceof Error) {
Expand All @@ -529,16 +520,18 @@ export default class SetupConfigs extends Command {
}

// Remove source files after all processing is complete
for (const sourceFile of sourceFiles.keys()) {
const sourcePath = path.join(sourceDir, sourceFile);
try {
fs.unlinkSync(sourcePath);
this.log(chalk.green(`Removed source file: ${sourceFile}`));
} catch (error: unknown) {
if (error instanceof Error) {
this.log(chalk.red(`Error removing file ${sourceFile}: ${error.message}`));
} else {
this.log(chalk.red(`Unknown error removing file ${sourceFile}`));
for (const mapping of fileMappings) {
const sourcePath = path.join(sourceDir, mapping.source);
if (fs.existsSync(sourcePath)) {
try {
fs.unlinkSync(sourcePath);
this.log(chalk.green(`Removed source file: ${mapping.source}`));
} catch (error: unknown) {
if (error instanceof Error) {
this.log(chalk.red(`Error removing file ${mapping.source}: ${error.message}`));
} else {
this.log(chalk.red(`Unknown error removing file ${mapping.source}`));
}
}
}
}
Expand All @@ -556,9 +549,7 @@ export default class SetupConfigs extends Command {
if (fs.existsSync(sourcePath)) {
const content = fs.readFileSync(sourcePath, 'utf8');
const yamlContent = {
contracts: {
[file.key]: content,
},
[file.key]: content,
};
const yamlString = yaml.dump(yamlContent, { indent: 2 });
fs.writeFileSync(targetPath, yamlString);
Expand Down
Loading

0 comments on commit b72305a

Please sign in to comment.