Skip to content

Commit

Permalink
Add some seth compatibility for call with input/output types (gakonst…
Browse files Browse the repository at this point in the history
…#328)

* Add some seth compatibility with input/output type

+ input address can start with 0x
+ output for uint/int is decimal by default

* chore(cast): make output parsing more idiomatic

* chore: strip 0x from input addr idiomatically

Co-authored-by: Georgios Konstantopoulos <[email protected]>
  • Loading branch information
syspulse and gakonst authored Jan 1, 2022
1 parent 8600860 commit df557cf
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 12 deletions.
36 changes: 24 additions & 12 deletions cast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ use ethers_core::{
types::*,
utils::{self, keccak256},
};

use ethers_providers::{Middleware, PendingTransaction};
use eyre::Result;
use eyre::{Context, Result};
use rustc_hex::{FromHexIter, ToHex};
use std::str::FromStr;

Expand Down Expand Up @@ -75,20 +76,31 @@ where
let res = self.provider.call(&tx, None).await?;

// decode args into tokens
let decoded = func.decode_output(res.as_ref())?;
let decoded = func.decode_output(res.as_ref()).wrap_err(
"could not decode output. did you specify the wrong function return data type perhaps?",
)?;
// handle case when return type is not specified
if decoded.is_empty() {
Ok(format!("{}\n", res))
Ok(if decoded.is_empty() {
format!("{}\n", res)
} else {
// concatenate them
let mut s = String::new();
for output in decoded {
s.push_str(&format!("0x{}\n", output));
}
// seth compatible user-friendly return type conversions
let out = decoded
.iter()
.map(|item| {
match item {
Token::Address(inner) => format!("{:?}", inner),
// add 0x
Token::Bytes(inner) => format!("0x{}", hex::encode(inner)),
Token::FixedBytes(inner) => format!("0x{}", hex::encode(inner)),
// print as decimal
Token::Uint(inner) | Token::Int(inner) => inner.to_string(),
_ => format!("{}", item),
}
})
.collect::<Vec<_>>();

// return string
Ok(s)
}
out.join("\n")
})
}

pub async fn balance<T: Into<NameOrAddress> + Send + Sync>(
Expand Down
5 changes: 5 additions & 0 deletions utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,11 @@ pub fn parse_tokens<'a, I: IntoIterator<Item = (&'a ParamType, &'a str)>>(
params
.into_iter()
.map(|(param, value)| {
let value = match param {
// allow addresses to be passed with "0x"
ParamType::Address => value.strip_prefix("0x").unwrap_or(value),
_ => value,
};
if lenient {
LenientTokenizer::tokenize(param, value)
} else {
Expand Down

0 comments on commit df557cf

Please sign in to comment.