import { writeFileSync } from 'node:fs' import type { Hex } from 'viem' type DumpStateParams = Record type DumpStateResult = Hex import { option } from 'pastel' import { z } from 'zod' import CliAction from '../components/CliAction.js' import { envVar, useAction } from '../hooks/useAction.js' // Add command description for help output export const description = 'Dump local EVM state to JSON\nExample: tevm dump-state --rpc https://mainnet.optimism.io --run --output-file state.json' // Options definitions and descriptions const optionDescriptions = { rpc: 'RPC endpoint (env: TEVM_RPC)', blockTag: 'Block tag to dump state from (latest, earliest, pending, etc.) (env: TEVM_BLOCK_TAG)', outputFile: 'Optional file path to save the state to (env: TEVM_OUTPUT_FILE)', } // Empty args tuple export const args = z.tuple([]) export const options = z.object({ // Interactive mode flag (run directly without interactive editor) run: z .boolean() .default(false) .describe( option({ description: 'Run directly without interactive parameter editing (env: TEVM_RUN)', alias: 'r', }), ), // Transport options rpc: z .string() .default(envVar('rpc') || 'http://localhost:8545') .describe( option({ description: optionDescriptions.rpc, defaultValueDescription: 'http://localhost:8545', }), ), // Block options blockTag: z .string() .optional() .describe( option({ description: optionDescriptions.blockTag, }), ), // Output options outputFile: z .string() .optional() .describe( option({ description: optionDescriptions.outputFile, }), ), // Output formatting json: z .boolean() .default(envVar('json') === 'true') .describe( option({ description: 'Emit the stable machine-readable JSON envelope (env: TEVM_JSON)', defaultValueDescription: 'false', }), ), }) type Props = { args: z.infer options: z.infer } // Default values for all parameters const defaultValues: Record = { rpc: 'http://localhost:8545', blockTag: 'latest', } export default function DumpState({ options }: Props) { // Use the action hook with inlined createParams and executeAction const actionResult = useAction({ actionName: 'dump-state', options, defaultValues, optionDescriptions, // Inlined createParams function createParams: (enhancedOptions: Record): DumpStateParams => { if (enhancedOptions['blockTag'] && enhancedOptions['blockTag'] !== 'latest') throw new Error('Only current native state can be dumped') return {} }, // Inlined executeAction function executeAction: async (client: any): Promise => { const result = await client.tevmDumpState() const outputFile = options.outputFile if (outputFile) { try { writeFileSync(outputFile, `${JSON.stringify(result)}\n`) } catch (error) { const message = error instanceof Error ? error.message : String(error) throw new Error(`Failed to write state to file ${outputFile}: ${message}`) } } return result }, }) // Render the action UI return }