Skip to content

Commit

Permalink
feat(cast): call json flag (#8618)
Browse files Browse the repository at this point in the history
* add call json flag

* update json param to option

* address comments
  • Loading branch information
minhd-vu authored Aug 8, 2024
1 parent 8390f2d commit 7f0f5b4
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
7 changes: 6 additions & 1 deletion crates/cast/bin/cmd/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ pub struct CallArgs {
#[arg(long, short)]
block: Option<BlockId>,

/// Print the decoded output as JSON.
#[arg(long, short, help_heading = "Display options")]
json: bool,

#[command(subcommand)]
command: Option<CallSubcommands>,

Expand Down Expand Up @@ -112,6 +116,7 @@ impl CallArgs {
decode_internal,
labels,
data,
json,
} = self;

if let Some(data) = data {
Expand Down Expand Up @@ -190,7 +195,7 @@ impl CallArgs {
return Ok(());
}

println!("{}", Cast::new(provider).call(&tx, func.as_ref(), block).await?);
println!("{}", Cast::new(provider).call(&tx, func.as_ref(), block, json).await?);

Ok(())
}
Expand Down
6 changes: 5 additions & 1 deletion crates/cast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ where
/// let tx = TransactionRequest::default().to(to).input(bytes.into());
/// let tx = WithOtherFields::new(tx);
/// let cast = Cast::new(alloy_provider);
/// let data = cast.call(&tx, None, None).await?;
/// let data = cast.call(&tx, None, None, false).await?;
/// println!("{}", data);
/// # Ok(())
/// # }
Expand All @@ -128,6 +128,7 @@ where
req: &WithOtherFields<TransactionRequest>,
func: Option<&Function>,
block: Option<BlockId>,
json: bool,
) -> Result<String> {
let res = self.provider.call(req).block(block.unwrap_or_default()).await?;

Expand Down Expand Up @@ -168,6 +169,9 @@ where
// handle case when return type is not specified
Ok(if decoded.is_empty() {
format!("{res}\n")
} else if json {
let tokens = decoded.iter().map(format_token_raw).collect::<Vec<_>>();
serde_json::to_string_pretty(&tokens).unwrap()
} else {
// seth compatible user-friendly return type conversions
decoded.iter().map(format_token).collect::<Vec<_>>().join("\n")
Expand Down

0 comments on commit 7f0f5b4

Please sign in to comment.