chisel/
dispatcher.rs

1//! Dispatcher
2//!
3//! This module contains the `ChiselDispatcher` struct, which handles the dispatching
4//! of both builtin commands and Solidity snippets.
5
6use crate::{
7    prelude::{ChiselCommand, ChiselResult, ChiselSession, SessionSourceConfig, SolidityHelper},
8    source::SessionSource,
9};
10use alloy_primitives::{Address, hex};
11use eyre::{Context, Result};
12use forge_fmt::FormatterConfig;
13use foundry_cli::utils::fetch_abi_from_etherscan;
14use foundry_config::RpcEndpointUrl;
15use foundry_evm::{
16    decode::decode_console_logs,
17    traces::{
18        CallTraceDecoder, CallTraceDecoderBuilder, TraceKind, decode_trace_arena,
19        identifier::{SignaturesIdentifier, TraceIdentifiers},
20        render_trace_arena,
21    },
22};
23use reqwest::Url;
24use solar::{
25    parse::lexer::token::{RawLiteralKind, RawTokenKind},
26    sema::ast::Base,
27};
28use std::{
29    borrow::Cow,
30    io::Write,
31    ops::ControlFlow,
32    path::{Path, PathBuf},
33    process::Command,
34};
35use tempfile::Builder;
36use yansi::Paint;
37
38/// Prompt arrow character.
39pub const PROMPT_ARROW: char = '➜';
40/// Prompt arrow string.
41pub const PROMPT_ARROW_STR: &str = "➜";
42const DEFAULT_PROMPT: &str = "➜ ";
43
44/// Command leader character
45pub const COMMAND_LEADER: char = '!';
46/// Chisel character
47pub const CHISEL_CHAR: &str = "⚒️";
48
49/// Chisel input dispatcher
50#[derive(Debug)]
51pub struct ChiselDispatcher {
52    pub session: ChiselSession,
53    pub helper: SolidityHelper,
54}
55
56/// Helper function that formats solidity source with the given [FormatterConfig]
57pub fn format_source(source: &str, config: FormatterConfig) -> eyre::Result<String> {
58    let formatted = forge_fmt::format(source, config).into_result()?;
59    Ok(formatted)
60}
61
62impl ChiselDispatcher {
63    /// Associated public function to create a new Dispatcher instance
64    pub fn new(config: SessionSourceConfig) -> eyre::Result<Self> {
65        let session = ChiselSession::new(config)?;
66        Ok(Self { session, helper: Default::default() })
67    }
68
69    /// Returns the optional ID of the current session.
70    pub fn id(&self) -> Option<&str> {
71        self.session.id.as_deref()
72    }
73
74    /// Returns the [`SessionSource`].
75    pub fn source(&self) -> &SessionSource {
76        &self.session.source
77    }
78
79    /// Returns the [`SessionSource`].
80    pub fn source_mut(&mut self) -> &mut SessionSource {
81        &mut self.session.source
82    }
83
84    fn format_source(&self) -> eyre::Result<String> {
85        format_source(
86            &self.source().to_repl_source(),
87            self.source().config.foundry_config.fmt.clone(),
88        )
89    }
90
91    /// Returns the prompt based on the current status of the Dispatcher
92    pub fn get_prompt(&self) -> Cow<'static, str> {
93        match self.session.id.as_deref() {
94            // `(ID: {id}) ➜ `
95            Some(id) => {
96                let mut prompt = String::with_capacity(DEFAULT_PROMPT.len() + id.len() + 7);
97                prompt.push_str("(ID: ");
98                prompt.push_str(id);
99                prompt.push_str(") ");
100                prompt.push_str(DEFAULT_PROMPT);
101                Cow::Owned(prompt)
102            }
103            // `➜ `
104            None => Cow::Borrowed(DEFAULT_PROMPT),
105        }
106    }
107
108    /// Dispatches an input as a command via [Self::dispatch_command] or as a Solidity snippet.
109    pub async fn dispatch(&mut self, mut input: &str) -> Result<ControlFlow<()>> {
110        if let Some(command) = input.strip_prefix(COMMAND_LEADER) {
111            return match ChiselCommand::parse(command) {
112                Ok(cmd) => self.dispatch_command(cmd).await,
113                Err(e) => eyre::bail!("unrecognized command: {e}"),
114            };
115        }
116
117        let source = self.source_mut();
118
119        input = input.trim();
120        let (only_trivia, new_input) = preprocess(input);
121        input = &*new_input;
122
123        // If the input is a comment, add it to the run code so we avoid running with empty input
124        if only_trivia {
125            debug!(?input, "matched trivia");
126            if !input.is_empty() {
127                source.add_run_code(input);
128            }
129            return Ok(ControlFlow::Continue(()));
130        }
131
132        // Create new source with exact input appended and parse
133        let (new_source, do_execute) = source.clone_with_new_line(input.to_string())?;
134
135        let (cf, res) = source.inspect(input).await?;
136        if let Some(res) = &res {
137            let _ = sh_println!("{res}");
138        }
139        if cf.is_break() {
140            debug!(%input, ?res, "inspect success");
141            return Ok(ControlFlow::Continue(()));
142        }
143
144        if do_execute {
145            self.execute_and_replace(new_source).await.map(ControlFlow::Continue)
146        } else {
147            let out = new_source.build()?;
148            debug!(%input, ?out, "skipped execute and rebuild source");
149            *self.source_mut() = new_source;
150            Ok(ControlFlow::Continue(()))
151        }
152    }
153
154    /// Decodes traces in the given [`ChiselResult`].
155    // TODO: Add `known_contracts` back in.
156    pub async fn decode_traces(
157        session_config: &SessionSourceConfig,
158        result: &mut ChiselResult,
159        // known_contracts: &ContractsByArtifact,
160    ) -> eyre::Result<CallTraceDecoder> {
161        let mut decoder = CallTraceDecoderBuilder::new()
162            .with_labels(result.labeled_addresses.clone())
163            .with_signature_identifier(SignaturesIdentifier::from_config(
164                &session_config.foundry_config,
165            )?)
166            .build();
167
168        let mut identifier = TraceIdentifiers::new().with_external(
169            &session_config.foundry_config,
170            session_config.evm_opts.get_remote_chain_id().await,
171        )?;
172        if !identifier.is_empty() {
173            for (_, trace) in &mut result.traces {
174                decoder.identify(trace, &mut identifier);
175            }
176        }
177        Ok(decoder)
178    }
179
180    /// Display the gathered traces of a REPL execution.
181    pub async fn show_traces(
182        decoder: &CallTraceDecoder,
183        result: &mut ChiselResult,
184    ) -> eyre::Result<()> {
185        if result.traces.is_empty() {
186            return Ok(());
187        }
188
189        sh_println!("{}", "Traces:".green())?;
190        for (kind, trace) in &mut result.traces {
191            // Display all Setup + Execution traces.
192            if matches!(kind, TraceKind::Setup | TraceKind::Execution) {
193                decode_trace_arena(trace, decoder).await;
194                sh_println!("{}", render_trace_arena(trace))?;
195            }
196        }
197
198        Ok(())
199    }
200
201    async fn execute_and_replace(&mut self, mut new_source: SessionSource) -> Result<()> {
202        let mut res = new_source.execute().await?;
203        let failed = !res.success;
204        if new_source.config.traces || failed {
205            if let Ok(decoder) = Self::decode_traces(&new_source.config, &mut res).await {
206                Self::show_traces(&decoder, &mut res).await?;
207
208                // Show console logs, if there are any
209                let decoded_logs = decode_console_logs(&res.logs);
210                if !decoded_logs.is_empty() {
211                    let _ = sh_println!("{}", "Logs:".green());
212                    for log in decoded_logs {
213                        let _ = sh_println!("  {log}");
214                    }
215                }
216            }
217
218            if failed {
219                // If the contract execution failed, continue on without
220                // updating the source.
221                eyre::bail!("Failed to execute edited contract!");
222            }
223        }
224
225        // the code could be compiled, save it
226        *self.source_mut() = new_source;
227
228        Ok(())
229    }
230}
231
232/// [`ChiselCommand`] implementations.
233impl ChiselDispatcher {
234    /// Dispatches a [`ChiselCommand`].
235    pub async fn dispatch_command(&mut self, cmd: ChiselCommand) -> Result<ControlFlow<()>> {
236        match cmd {
237            ChiselCommand::Quit => Ok(ControlFlow::Break(())),
238            cmd => self.dispatch_command_impl(cmd).await.map(ControlFlow::Continue),
239        }
240    }
241
242    async fn dispatch_command_impl(&mut self, cmd: ChiselCommand) -> Result<()> {
243        match cmd {
244            ChiselCommand::Help => self.show_help(),
245            ChiselCommand::Quit => unreachable!(),
246            ChiselCommand::Clear => self.clear_source(),
247            ChiselCommand::Save { id } => self.save_session(id),
248            ChiselCommand::Load { id } => self.load_session(&id),
249            ChiselCommand::ListSessions => self.list_sessions(),
250            ChiselCommand::Source => self.show_source(),
251            ChiselCommand::ClearCache => self.clear_cache(),
252            ChiselCommand::Fork { url } => self.set_fork(url),
253            ChiselCommand::Traces => self.toggle_traces(),
254            ChiselCommand::Calldata { data } => self.set_calldata(data.as_deref()),
255            ChiselCommand::MemDump => self.show_mem_dump().await,
256            ChiselCommand::StackDump => self.show_stack_dump().await,
257            ChiselCommand::Export => self.export(),
258            ChiselCommand::Fetch { addr, name } => self.fetch_interface(addr, name).await,
259            ChiselCommand::Exec { command, args } => self.exec_command(command, args),
260            ChiselCommand::Edit => self.edit_session().await,
261            ChiselCommand::RawStack { var } => self.show_raw_stack(var).await,
262        }
263    }
264
265    pub(crate) fn show_help(&self) -> Result<()> {
266        sh_println!("{}", ChiselCommand::format_help())
267    }
268
269    pub(crate) fn clear_source(&mut self) -> Result<()> {
270        self.source_mut().clear();
271        sh_println!("Cleared session!")
272    }
273
274    pub(crate) fn save_session(&mut self, id: Option<String>) -> Result<()> {
275        // If a new name was supplied, overwrite the ID of the current session.
276        if let Some(id) = id {
277            // TODO: Should we delete the old cache file if the id of the session changes?
278            self.session.id = Some(id);
279        }
280
281        self.session.write()?;
282        sh_println!("Saved session to cache with ID = {}", self.session.id.as_ref().unwrap())
283    }
284
285    pub(crate) fn load_session(&mut self, id: &str) -> Result<()> {
286        // Try to save the current session before loading another.
287        // Don't save an empty session.
288        if !self.source().run_code.is_empty() {
289            self.session.write()?;
290            sh_println!("{}", "Saved current session!".green())?;
291        }
292
293        let new_session = match id {
294            "latest" => ChiselSession::latest(),
295            id => ChiselSession::load(id),
296        }
297        .wrap_err("failed to load session")?;
298
299        new_session.source.build()?;
300        self.session = new_session;
301        sh_println!("Loaded Chisel session! (ID = {})", self.session.id.as_ref().unwrap())
302    }
303
304    pub(crate) fn list_sessions(&self) -> Result<()> {
305        let sessions = ChiselSession::get_sessions()?;
306        if sessions.is_empty() {
307            eyre::bail!("No sessions found. Use the `!save` command to save a session.");
308        }
309        sh_println!(
310            "{}\n{}",
311            format!("{CHISEL_CHAR} Chisel Sessions").cyan(),
312            sessions
313                .iter()
314                .map(|(time, name)| format!("{} - {}", format!("{time:?}").blue(), name))
315                .collect::<Vec<String>>()
316                .join("\n")
317        )
318    }
319
320    pub(crate) fn show_source(&self) -> Result<()> {
321        let formatted = self.format_source().wrap_err("failed to format session source")?;
322        let highlighted = self.helper.highlight(&formatted);
323        sh_println!("{highlighted}")
324    }
325
326    pub(crate) fn clear_cache(&mut self) -> Result<()> {
327        ChiselSession::clear_cache().wrap_err("failed to clear cache")?;
328        self.session.id = None;
329        sh_println!("Cleared chisel cache!")
330    }
331
332    pub(crate) fn set_fork(&mut self, url: Option<String>) -> Result<()> {
333        let Some(url) = url else {
334            self.source_mut().config.evm_opts.fork_url = None;
335            sh_println!("Now using local environment.")?;
336            return Ok(());
337        };
338
339        // If the argument is an RPC alias designated in the
340        // `[rpc_endpoints]` section of the `foundry.toml` within
341        // the pwd, use the URL matched to the key.
342        let endpoint = if let Some(endpoint) =
343            self.source_mut().config.foundry_config.rpc_endpoints.get(&url)
344        {
345            endpoint.clone()
346        } else {
347            RpcEndpointUrl::Env(url).into()
348        };
349        let fork_url = endpoint.resolve().url()?;
350
351        if let Err(e) = Url::parse(&fork_url) {
352            eyre::bail!("invalid fork URL: {e}");
353        }
354
355        sh_println!("Set fork URL to {}", fork_url.yellow())?;
356
357        self.source_mut().config.evm_opts.fork_url = Some(fork_url);
358        // Clear the backend so that it is re-instantiated with the new fork
359        // upon the next execution of the session source.
360        self.source_mut().config.backend = None;
361
362        Ok(())
363    }
364
365    pub(crate) fn toggle_traces(&mut self) -> Result<()> {
366        let t = &mut self.source_mut().config.traces;
367        *t = !*t;
368        sh_println!("{} traces!", if *t { "Enabled" } else { "Disabled" })
369    }
370
371    pub(crate) fn set_calldata(&mut self, data: Option<&str>) -> Result<()> {
372        // remove empty space, double quotes, and 0x prefix
373        let arg = data
374            .map(|s| s.trim_matches(|c: char| c.is_whitespace() || c == '"' || c == '\''))
375            .map(|s| s.strip_prefix("0x").unwrap_or(s))
376            .unwrap_or("");
377
378        if arg.is_empty() {
379            self.source_mut().config.calldata = None;
380            sh_println!("Calldata cleared.")?;
381            return Ok(());
382        }
383
384        let calldata = hex::decode(arg);
385        match calldata {
386            Ok(calldata) => {
387                self.source_mut().config.calldata = Some(calldata);
388                sh_println!("Set calldata to '{}'", arg.yellow())
389            }
390            Err(e) => {
391                eyre::bail!("Invalid calldata: {e}")
392            }
393        }
394    }
395
396    pub(crate) async fn show_mem_dump(&mut self) -> Result<()> {
397        let res = self.source_mut().execute().await?;
398        let Some((_, mem)) = res.state.as_ref() else {
399            eyre::bail!("Run function is empty.");
400        };
401        for i in (0..mem.len()).step_by(32) {
402            let _ = sh_println!(
403                "{}: {}",
404                format!("[0x{:02x}:0x{:02x}]", i, i + 32).yellow(),
405                hex::encode_prefixed(&mem[i..i + 32]).cyan()
406            );
407        }
408        Ok(())
409    }
410
411    pub(crate) async fn show_stack_dump(&mut self) -> Result<()> {
412        let res = self.source_mut().execute().await?;
413        let Some((stack, _)) = res.state.as_ref() else {
414            eyre::bail!("Run function is empty.");
415        };
416        for i in (0..stack.len()).rev() {
417            let _ = sh_println!(
418                "{}: {}",
419                format!("[{}]", stack.len() - i - 1).yellow(),
420                format!("0x{:02x}", stack[i]).cyan()
421            );
422        }
423        Ok(())
424    }
425
426    pub(crate) fn export(&self) -> Result<()> {
427        // Check if the pwd is a foundry project
428        if !Path::new("foundry.toml").exists() {
429            eyre::bail!("Must be in a foundry project to export source to script.");
430        }
431
432        // Create "script" dir if it does not already exist.
433        if !Path::new("script").exists() {
434            std::fs::create_dir_all("script")?;
435        }
436
437        let formatted_source = self.format_source()?;
438        std::fs::write(PathBuf::from("script/REPL.s.sol"), formatted_source)?;
439        sh_println!("Exported session source to script/REPL.s.sol!")
440    }
441
442    /// Fetches an interface from Etherscan
443    pub(crate) async fn fetch_interface(&mut self, address: Address, name: String) -> Result<()> {
444        let abis = fetch_abi_from_etherscan(address, &self.source().config.foundry_config)
445            .await
446            .wrap_err("Failed to fetch ABI from Etherscan")?;
447        let (abi, _) = abis
448            .into_iter()
449            .next()
450            .ok_or_else(|| eyre::eyre!("No ABI found for address {address} on Etherscan"))?;
451        let code = forge_fmt::format(&abi.to_sol(&name, None), FormatterConfig::default())
452            .into_result()?;
453        self.source_mut().add_global_code(&code);
454        sh_println!("Added {address}'s interface to source as `{name}`")
455    }
456
457    pub(crate) fn exec_command(&self, command: String, args: Vec<String>) -> Result<()> {
458        let mut cmd = Command::new(command);
459        cmd.args(args);
460        let _ = cmd.status()?;
461        Ok(())
462    }
463
464    pub(crate) async fn edit_session(&mut self) -> Result<()> {
465        // create a temp file with the content of the run code
466        let mut tmp = Builder::new()
467            .prefix("chisel-")
468            .suffix(".sol")
469            .tempfile()
470            .wrap_err("Could not create temporary file")?;
471        tmp.as_file_mut()
472            .write_all(self.source().run_code.as_bytes())
473            .wrap_err("Could not write to temporary file")?;
474
475        // open the temp file with the editor
476        let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vim".to_string());
477        let mut cmd = Command::new(editor);
478        cmd.arg(tmp.path());
479        let st = cmd.status()?;
480        if !st.success() {
481            eyre::bail!("Editor exited with {st}");
482        }
483
484        let edited_code = std::fs::read_to_string(tmp.path())?;
485        let mut new_source = self.source().clone();
486        new_source.clear_run();
487        new_source.add_run_code(&edited_code);
488
489        // if the editor exited successfully, try to compile the new code
490        self.execute_and_replace(new_source).await?;
491        sh_println!("Successfully edited `run()` function's body!")
492    }
493
494    pub(crate) async fn show_raw_stack(&mut self, var: String) -> Result<()> {
495        let source = self.source_mut();
496        let line = format!("bytes32 __raw__; assembly {{ __raw__ := {var} }}");
497        if let Ok((new_source, _)) = source.clone_with_new_line(line)
498            && let (_, Some(res)) = new_source.inspect("__raw__").await?
499        {
500            sh_println!("{res}")?;
501            return Ok(());
502        }
503
504        eyre::bail!("Variable must exist within `run()` function.")
505    }
506}
507
508/// Preprocesses addresses to ensure they are correctly checksummed and returns whether the input
509/// only contained trivia (comments, whitespace).
510fn preprocess(input: &str) -> (bool, Cow<'_, str>) {
511    let mut only_trivia = true;
512    let mut new_input = Cow::Borrowed(input);
513    for (pos, token) in solar::parse::Cursor::new(input).with_position() {
514        use RawTokenKind::*;
515
516        if matches!(token.kind, Whitespace | LineComment { .. } | BlockComment { .. }) {
517            continue;
518        }
519        only_trivia = false;
520
521        // Ensure that addresses are correctly checksummed.
522        if let Literal { kind: RawLiteralKind::Int { base: Base::Hexadecimal, .. } } = token.kind
523            && token.len == 42
524        {
525            let range = pos..pos + 42;
526            if let Ok(addr) = input[range.clone()].parse::<Address>() {
527                new_input.to_mut().replace_range(range, addr.to_checksum_buffer(None).as_str());
528            }
529        }
530    }
531    (only_trivia, new_input)
532}
533
534#[cfg(test)]
535mod tests {
536    use super::*;
537
538    #[test]
539    fn test_trivia() {
540        fn only_trivia(s: &str) -> bool {
541            let (only_trivia, _new_input) = preprocess(s);
542            only_trivia
543        }
544        assert!(only_trivia("// line comment"));
545        assert!(only_trivia("  \n// line \tcomment\n"));
546        assert!(!only_trivia("// line \ncomment"));
547
548        assert!(only_trivia("/* block comment */"));
549        assert!(only_trivia(" \t\n  /* block \n \t comment */\n"));
550        assert!(!only_trivia("/* block \n \t comment */\nwith \tother"));
551    }
552}