1use 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
38pub const PROMPT_ARROW: char = '➜';
40pub const PROMPT_ARROW_STR: &str = "➜";
42const DEFAULT_PROMPT: &str = "➜ ";
43
44pub const COMMAND_LEADER: char = '!';
46pub const CHISEL_CHAR: &str = "⚒️";
48
49#[derive(Debug)]
51pub struct ChiselDispatcher {
52 pub session: ChiselSession,
53 pub helper: SolidityHelper,
54}
55
56pub 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 pub fn new(config: SessionSourceConfig) -> eyre::Result<Self> {
65 let session = ChiselSession::new(config)?;
66 Ok(Self { session, helper: Default::default() })
67 }
68
69 pub fn id(&self) -> Option<&str> {
71 self.session.id.as_deref()
72 }
73
74 pub fn source(&self) -> &SessionSource {
76 &self.session.source
77 }
78
79 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 pub fn get_prompt(&self) -> Cow<'static, str> {
93 match self.session.id.as_deref() {
94 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 None => Cow::Borrowed(DEFAULT_PROMPT),
105 }
106 }
107
108 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 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 let (new_source, do_execute) = source.clone_with_new_line(input.to_string())?;
134
135 let (cf, res) = source.inspect(input).await?;
138 if let Some(res) = &res {
139 let _ = sh_println!("{res}");
140 }
141 if cf.is_break() {
142 debug!(%input, ?res, "inspect success");
143 return Ok(ControlFlow::Continue(()));
144 }
145
146 if do_execute {
147 self.execute_and_replace(new_source).await.map(ControlFlow::Continue)
148 } else {
149 let out = new_source.build()?;
150 debug!(%input, ?out, "skipped execute and rebuild source");
151 *self.source_mut() = new_source;
152 Ok(ControlFlow::Continue(()))
153 }
154 }
155
156 pub async fn decode_traces(
159 session_config: &SessionSourceConfig,
160 result: &mut ChiselResult,
161 ) -> eyre::Result<CallTraceDecoder> {
163 let mut decoder = CallTraceDecoderBuilder::new()
164 .with_labels(result.labeled_addresses.clone())
165 .with_signature_identifier(SignaturesIdentifier::from_config(
166 &session_config.foundry_config,
167 )?)
168 .build();
169
170 let mut identifier = TraceIdentifiers::new().with_etherscan(
171 &session_config.foundry_config,
172 session_config.evm_opts.get_remote_chain_id().await,
173 )?;
174 if !identifier.is_empty() {
175 for (_, trace) in &mut result.traces {
176 decoder.identify(trace, &mut identifier);
177 }
178 }
179 Ok(decoder)
180 }
181
182 pub async fn show_traces(
184 decoder: &CallTraceDecoder,
185 result: &mut ChiselResult,
186 ) -> eyre::Result<()> {
187 if result.traces.is_empty() {
188 return Ok(());
189 }
190
191 sh_println!("{}", "Traces:".green())?;
192 for (kind, trace) in &mut result.traces {
193 if matches!(kind, TraceKind::Setup | TraceKind::Execution) {
195 decode_trace_arena(trace, decoder).await;
196 sh_println!("{}", render_trace_arena(trace))?;
197 }
198 }
199
200 Ok(())
201 }
202
203 async fn execute_and_replace(&mut self, mut new_source: SessionSource) -> Result<()> {
204 let mut res = new_source.execute().await?;
205 let failed = !res.success;
206 if new_source.config.traces || failed {
207 if let Ok(decoder) = Self::decode_traces(&new_source.config, &mut res).await {
208 Self::show_traces(&decoder, &mut res).await?;
209
210 let decoded_logs = decode_console_logs(&res.logs);
212 if !decoded_logs.is_empty() {
213 let _ = sh_println!("{}", "Logs:".green());
214 for log in decoded_logs {
215 let _ = sh_println!(" {log}");
216 }
217 }
218 }
219
220 if failed {
221 eyre::bail!("Failed to execute edited contract!");
224 }
225 }
226
227 *self.source_mut() = new_source;
229
230 Ok(())
231 }
232}
233
234impl ChiselDispatcher {
236 pub async fn dispatch_command(&mut self, cmd: ChiselCommand) -> Result<ControlFlow<()>> {
238 match cmd {
239 ChiselCommand::Quit => Ok(ControlFlow::Break(())),
240 cmd => self.dispatch_command_impl(cmd).await.map(ControlFlow::Continue),
241 }
242 }
243
244 async fn dispatch_command_impl(&mut self, cmd: ChiselCommand) -> Result<()> {
245 match cmd {
246 ChiselCommand::Help => self.show_help(),
247 ChiselCommand::Quit => unreachable!(),
248 ChiselCommand::Clear => self.clear_source(),
249 ChiselCommand::Save { id } => self.save_session(id),
250 ChiselCommand::Load { id } => self.load_session(&id),
251 ChiselCommand::ListSessions => self.list_sessions(),
252 ChiselCommand::Source => self.show_source(),
253 ChiselCommand::ClearCache => self.clear_cache(),
254 ChiselCommand::Fork { url } => self.set_fork(url),
255 ChiselCommand::Traces => self.toggle_traces(),
256 ChiselCommand::Calldata { data } => self.set_calldata(data.as_deref()),
257 ChiselCommand::MemDump => self.show_mem_dump().await,
258 ChiselCommand::StackDump => self.show_stack_dump().await,
259 ChiselCommand::Export => self.export(),
260 ChiselCommand::Fetch { addr, name } => self.fetch_interface(addr, name).await,
261 ChiselCommand::Exec { command, args } => self.exec_command(command, args),
262 ChiselCommand::Edit => self.edit_session().await,
263 ChiselCommand::RawStack { var } => self.show_raw_stack(var).await,
264 }
265 }
266
267 pub(crate) fn show_help(&self) -> Result<()> {
268 sh_println!("{}", ChiselCommand::format_help())
269 }
270
271 pub(crate) fn clear_source(&mut self) -> Result<()> {
272 self.source_mut().clear();
273 sh_println!("Cleared session!")
274 }
275
276 pub(crate) fn save_session(&mut self, id: Option<String>) -> Result<()> {
277 if let Some(id) = id {
279 self.session.id = Some(id);
281 }
282
283 self.session.write()?;
284 sh_println!("Saved session to cache with ID = {}", self.session.id.as_ref().unwrap())
285 }
286
287 pub(crate) fn load_session(&mut self, id: &str) -> Result<()> {
288 if !self.source().run_code.is_empty() {
291 self.session.write()?;
292 sh_println!("{}", "Saved current session!".green())?;
293 }
294
295 let new_session = match id {
296 "latest" => ChiselSession::latest(),
297 id => ChiselSession::load(id),
298 }
299 .wrap_err("failed to load session")?;
300
301 new_session.source.build()?;
302 self.session = new_session;
303 sh_println!("Loaded Chisel session! (ID = {})", self.session.id.as_ref().unwrap())
304 }
305
306 pub(crate) fn list_sessions(&self) -> Result<()> {
307 let sessions = ChiselSession::get_sessions()?;
308 if sessions.is_empty() {
309 eyre::bail!("No sessions found. Use the `!save` command to save a session.");
310 }
311 sh_println!(
312 "{}\n{}",
313 format!("{CHISEL_CHAR} Chisel Sessions").cyan(),
314 sessions
315 .iter()
316 .map(|(time, name)| format!("{} - {}", format!("{time:?}").blue(), name))
317 .collect::<Vec<String>>()
318 .join("\n")
319 )
320 }
321
322 pub(crate) fn show_source(&self) -> Result<()> {
323 let formatted = self.format_source().wrap_err("failed to format session source")?;
324 let highlighted = self.helper.highlight(&formatted);
325 sh_println!("{highlighted}")
326 }
327
328 pub(crate) fn clear_cache(&mut self) -> Result<()> {
329 ChiselSession::clear_cache().wrap_err("failed to clear cache")?;
330 self.session.id = None;
331 sh_println!("Cleared chisel cache!")
332 }
333
334 pub(crate) fn set_fork(&mut self, url: Option<String>) -> Result<()> {
335 let Some(url) = url else {
336 self.source_mut().config.evm_opts.fork_url = None;
337 sh_println!("Now using local environment.")?;
338 return Ok(());
339 };
340
341 let endpoint = if let Some(endpoint) =
345 self.source_mut().config.foundry_config.rpc_endpoints.get(&url)
346 {
347 endpoint.clone()
348 } else {
349 RpcEndpointUrl::Env(url).into()
350 };
351 let fork_url = endpoint.resolve().url()?;
352
353 if let Err(e) = Url::parse(&fork_url) {
354 eyre::bail!("invalid fork URL: {e}");
355 }
356
357 sh_println!("Set fork URL to {}", fork_url.yellow())?;
358
359 self.source_mut().config.evm_opts.fork_url = Some(fork_url);
360 self.source_mut().config.backend = None;
363
364 Ok(())
365 }
366
367 pub(crate) fn toggle_traces(&mut self) -> Result<()> {
368 let t = &mut self.source_mut().config.traces;
369 *t = !*t;
370 sh_println!("{} traces!", if *t { "Enabled" } else { "Disabled" })
371 }
372
373 pub(crate) fn set_calldata(&mut self, data: Option<&str>) -> Result<()> {
374 let arg = data
376 .map(|s| s.trim_matches(|c: char| c.is_whitespace() || c == '"' || c == '\''))
377 .map(|s| s.strip_prefix("0x").unwrap_or(s))
378 .unwrap_or("");
379
380 if arg.is_empty() {
381 self.source_mut().config.calldata = None;
382 sh_println!("Calldata cleared.")?;
383 return Ok(());
384 }
385
386 let calldata = hex::decode(arg);
387 match calldata {
388 Ok(calldata) => {
389 self.source_mut().config.calldata = Some(calldata);
390 sh_println!("Set calldata to '{}'", arg.yellow())
391 }
392 Err(e) => {
393 eyre::bail!("Invalid calldata: {e}")
394 }
395 }
396 }
397
398 pub(crate) async fn show_mem_dump(&mut self) -> Result<()> {
399 let res = self.source_mut().execute().await?;
400 let Some((_, mem)) = res.state.as_ref() else {
401 eyre::bail!("Run function is empty.");
402 };
403 for i in (0..mem.len()).step_by(32) {
404 let _ = sh_println!(
405 "{}: {}",
406 format!("[0x{:02x}:0x{:02x}]", i, i + 32).yellow(),
407 hex::encode_prefixed(&mem[i..i + 32]).cyan()
408 );
409 }
410 Ok(())
411 }
412
413 pub(crate) async fn show_stack_dump(&mut self) -> Result<()> {
414 let res = self.source_mut().execute().await?;
415 let Some((stack, _)) = res.state.as_ref() else {
416 eyre::bail!("Run function is empty.");
417 };
418 for i in (0..stack.len()).rev() {
419 let _ = sh_println!(
420 "{}: {}",
421 format!("[{}]", stack.len() - i - 1).yellow(),
422 format!("0x{:02x}", stack[i]).cyan()
423 );
424 }
425 Ok(())
426 }
427
428 pub(crate) fn export(&self) -> Result<()> {
429 if !Path::new("foundry.toml").exists() {
431 eyre::bail!("Must be in a foundry project to export source to script.");
432 }
433
434 if !Path::new("script").exists() {
436 std::fs::create_dir_all("script")?;
437 }
438
439 let formatted_source = self.format_source()?;
440 std::fs::write(PathBuf::from("script/REPL.s.sol"), formatted_source)?;
441 sh_println!("Exported session source to script/REPL.s.sol!")
442 }
443
444 pub(crate) async fn fetch_interface(&mut self, address: Address, name: String) -> Result<()> {
446 let abis = fetch_abi_from_etherscan(address, &self.source().config.foundry_config)
447 .await
448 .wrap_err("Failed to fetch ABI from Etherscan")?;
449 let (abi, _) = abis
450 .into_iter()
451 .next()
452 .ok_or_else(|| eyre::eyre!("No ABI found for address {address} on Etherscan"))?;
453 let code = forge_fmt::format(&abi.to_sol(&name, None), FormatterConfig::default())
454 .into_result()?;
455 self.source_mut().add_global_code(&code);
456 sh_println!("Added {address}'s interface to source as `{name}`")
457 }
458
459 pub(crate) fn exec_command(&self, command: String, args: Vec<String>) -> Result<()> {
460 let mut cmd = Command::new(command);
461 cmd.args(args);
462 let _ = cmd.status()?;
463 Ok(())
464 }
465
466 pub(crate) async fn edit_session(&mut self) -> Result<()> {
467 let mut tmp = Builder::new()
469 .prefix("chisel-")
470 .suffix(".sol")
471 .tempfile()
472 .wrap_err("Could not create temporary file")?;
473 tmp.as_file_mut()
474 .write_all(self.source().run_code.as_bytes())
475 .wrap_err("Could not write to temporary file")?;
476
477 let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vim".to_string());
479 let mut cmd = Command::new(editor);
480 cmd.arg(tmp.path());
481 let st = cmd.status()?;
482 if !st.success() {
483 eyre::bail!("Editor exited with {st}");
484 }
485
486 let edited_code = std::fs::read_to_string(tmp.path())?;
487 let mut new_source = self.source().clone();
488 new_source.clear_run();
489 new_source.add_run_code(&edited_code);
490
491 self.execute_and_replace(new_source).await?;
493 sh_println!("Successfully edited `run()` function's body!")
494 }
495
496 pub(crate) async fn show_raw_stack(&mut self, var: String) -> Result<()> {
497 let source = self.source_mut();
498 let line = format!("bytes32 __raw__; assembly {{ __raw__ := {var} }}");
499 if let Ok((new_source, _)) = source.clone_with_new_line(line)
500 && let (_, Some(res)) = new_source.inspect("__raw__").await?
501 {
502 sh_println!("{res}")?;
503 return Ok(());
504 }
505
506 eyre::bail!("Variable must exist within `run()` function.")
507 }
508}
509
510fn preprocess(input: &str) -> (bool, Cow<'_, str>) {
513 let mut only_trivia = true;
514 let mut new_input = Cow::Borrowed(input);
515 for (pos, token) in solar::parse::Cursor::new(input).with_position() {
516 use RawTokenKind::*;
517
518 if matches!(token.kind, Whitespace | LineComment { .. } | BlockComment { .. }) {
519 continue;
520 }
521 only_trivia = false;
522
523 if let Literal { kind: RawLiteralKind::Int { base: Base::Hexadecimal, .. } } = token.kind
525 && token.len == 42
526 {
527 let range = pos..pos + 42;
528 if let Ok(addr) = input[range.clone()].parse::<Address>() {
529 new_input.to_mut().replace_range(range, addr.to_checksum_buffer(None).as_str());
530 }
531 }
532 }
533 (only_trivia, new_input)
534}
535
536#[cfg(test)]
537mod tests {
538 use super::*;
539
540 #[test]
541 fn test_trivia() {
542 fn only_trivia(s: &str) -> bool {
543 let (only_trivia, _new_input) = preprocess(s);
544 only_trivia
545 }
546 assert!(only_trivia("// line comment"));
547 assert!(only_trivia(" \n// line \tcomment\n"));
548 assert!(!only_trivia("// line \ncomment"));
549
550 assert!(only_trivia("/* block comment */"));
551 assert!(only_trivia(" \t\n /* block \n \t comment */\n"));
552 assert!(!only_trivia("/* block \n \t comment */\nwith \tother"));
553 }
554}