Skip to content

Commit

Permalink
add cast abi-encode (#374)
Browse files Browse the repository at this point in the history
  • Loading branch information
charisma98 committed Jan 5, 2022
1 parent 30cd6e7 commit 161e067
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
21 changes: 21 additions & 0 deletions cast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,27 @@ impl SimpleCast {
foundry_utils::abi_decode(sig, calldata, input)
}

/// Performs ABI encoding based off of the function signature. Does not include
/// the function selector in the result.
///
/// ```
/// # use cast::SimpleCast as Cast;
///
/// # fn main() -> eyre::Result<()> {
/// assert_eq!(
/// "0x0000000000000000000000000000000000000000000000000000000000000001",
/// Cast::abi_encode("f(uint a)", &["1"]).unwrap().as_str()
/// );
/// # Ok(())
/// # }
/// ```
pub fn abi_encode(sig: &str, args: &[impl AsRef<str>]) -> Result<String> {
let func = AbiParser::default().parse_function(sig.as_ref())?;
let calldata = encode_args(&func, args)?.to_hex::<String>();
let encoded = &calldata[8..];
Ok(format!("0x{}", encoded))
}

/// Converts decimal input to hex
///
/// ```
Expand Down
3 changes: 3 additions & 0 deletions cli/src/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,9 @@ async fn main() -> eyre::Result<()> {
let tokens = foundry_utils::format_tokens(&tokens);
tokens.for_each(|t| println!("{}", t));
}
Subcommands::AbiEncode { sig, args } => {
println!("{}", SimpleCast::abi_encode(&sig, &args)?);
}
Subcommands::FourByte { selector } => {
let sigs = foundry_utils::fourbyte(&selector).await?;
sigs.iter().for_each(|sig| println!("{}", sig.0));
Expand Down
10 changes: 10 additions & 0 deletions cli/src/opts/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,16 @@ pub enum Subcommands {
#[structopt(long, short, help = "the encoded output, in hex format")]
input: bool,
},
#[structopt(name = "abi-encode")]
#[structopt(
help = "ABI encodes the given arguments with the function signature, excluidng the selector"
)]
AbiEncode {
#[structopt(help = "the function signature")]
sig: String,
#[structopt(help = "the list of function arguments")]
args: Vec<String>,
},
#[structopt(name = "4byte")]
#[structopt(about = "Fetches function signatures given the selector from 4byte.directory")]
FourByte {
Expand Down

0 comments on commit 161e067

Please sign in to comment.