use std::path::PathBuf;
use std::time::Duration;
use alloy_dyn_abi::{DynSolValue, FunctionExt, JsonAbiExt, Specifier};
use alloy_json_abi::Function;
use alloy_primitives::{Address, Bytes};
use clap::Parser;
use serde_json::{json, Value};
use super::{
is_proxy_rpc_url, resolve_duration, validate_override_rpc_url, CmdError, CmdResult, Ctx,
};
use crate::envelope::Envelope;
use taskfast_agent::tempo_rpc::TempoRpcClient;
#[derive(Debug, clap::Subcommand)]
pub enum Command {
Call(CallArgs),
Send(SendArgs),
Rpc(RpcArgs),
}
#[derive(Debug, Parser)]
pub struct CallArgs {
pub to: String,
pub sig: String,
pub args: Vec<String>,
#[arg(long, env = "TEMPO_RPC_URL")]
pub rpc_url: Option<String>,
}
#[derive(Debug, Parser)]
pub struct SendArgs {
pub to: String,
pub sig: String,
pub args: Vec<String>,
#[arg(long, env = "TEMPO_KEY_SOURCE")]
pub keystore: Option<String>,
#[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
pub wallet_password_file: Option<PathBuf>,
#[arg(long, env = "TEMPO_WALLET_ADDRESS")]
pub wallet_address: Option<String>,
#[arg(long, env = "TEMPO_RPC_URL")]
pub rpc_url: Option<String>,
#[arg(long, env = "TASKFAST_RECEIPT_TIMEOUT", value_parser = humantime::parse_duration)]
pub receipt_timeout: Option<Duration>,
}
#[derive(Debug, Parser)]
pub struct RpcArgs {
pub method: String,
pub params: Option<String>,
#[arg(long, env = "TEMPO_RPC_URL")]
pub rpc_url: Option<String>,
}
pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
match cmd {
Command::Call(a) => call(ctx, a).await,
Command::Send(a) => send(ctx, a).await,
Command::Rpc(a) => rpc(ctx, a).await,
}
}
async fn call(ctx: &Ctx, args: CallArgs) -> CmdResult {
let to = parse_to(&args.to)?;
let func = parse_function(&args.sig)?;
let values = coerce_args(&func, &args.args)?;
let calldata = encode_calldata(&func, &values)?;
let (rpc_url, http) = resolve_rpc(ctx, args.rpc_url.as_deref()).await?;
let rpc = TempoRpcClient::new(http, rpc_url);
let raw = rpc
.eth_call(to, &calldata)
.await
.map_err(|e| CmdError::Server(format!("eth_call: {e}")))?;
let decoded = if func.outputs.is_empty() {
Value::Null
} else {
let vals = func
.abi_decode_output(&raw)
.map_err(|e| CmdError::Decode(format!("decode output of {}: {e}", args.sig)))?;
Value::Array(vals.iter().map(dyn_value_to_json).collect())
};
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"to": format!("{to:#x}"),
"sig": args.sig,
"raw": format!("0x{}", hex::encode(&raw)),
"decoded": decoded,
}),
))
}
async fn send(ctx: &Ctx, args: SendArgs) -> CmdResult {
let to = parse_to(&args.to)?;
let func = parse_function(&args.sig)?;
let values = coerce_args(&func, &args.args)?;
let calldata = encode_calldata(&func, &values)?;
let keystore_path = super::wallet_args::resolve_keystore_path(
args.keystore.as_deref(),
ctx.keystore_path.as_deref(),
);
let signer = super::wallet_args::load_signer_and_validate(
keystore_path.as_deref(),
args.wallet_password_file.as_deref(),
args.wallet_address
.as_deref()
.or(ctx.wallet_address.as_deref()),
"cast send transaction",
)?;
if ctx.dry_run {
validate_dry_run_override(ctx, args.rpc_url.as_deref())?;
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": "would_send",
"to": format!("{to:#x}"),
"sig": args.sig,
"from": format!("{:#x}", signer.address()),
"calldata": format!("0x{}", hex::encode(&calldata)),
}),
));
}
let (rpc_url, http) = resolve_rpc(ctx, args.rpc_url.as_deref()).await?;
let rpc = TempoRpcClient::new(http, rpc_url);
let default_timeout =
crate::tempo_session::default_receipt_timeout_for_network(ctx.environment.network());
let receipt_timeout =
resolve_duration(args.receipt_timeout, ctx.receipt_timeout, default_timeout);
let session =
crate::tempo_session::TempoSession::new(signer, keystore_path, rpc, receipt_timeout);
let tx_hash = session
.send_transaction_and_wait(to, calldata, "", None)
.await?;
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": "sent",
"to": format!("{to:#x}"),
"sig": args.sig,
"from": format!("{:#x}", session.address()),
"tx_hash": format!("{tx_hash:#x}"),
}),
))
}
async fn rpc(ctx: &Ctx, args: RpcArgs) -> CmdResult {
let params: Value = match args.params.as_deref() {
Some(raw) => serde_json::from_str(raw)
.map_err(|e| CmdError::Usage(format!("params is not valid JSON: {e}")))?,
None => json!([]),
};
if ctx.dry_run {
validate_dry_run_override(ctx, args.rpc_url.as_deref())?;
return Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"action": "would_rpc",
"method": args.method,
"params": params,
}),
));
}
let (rpc_url, http) = resolve_rpc(ctx, args.rpc_url.as_deref()).await?;
let rpc = TempoRpcClient::new(http, rpc_url);
let result = rpc
.raw_call(&args.method, params)
.await
.map_err(|e| CmdError::Server(format!("{}: {e}", args.method)))?;
Ok(Envelope::success(
ctx.environment,
ctx.dry_run,
json!({
"method": args.method,
"result": result,
}),
))
}
async fn resolve_rpc(
ctx: &Ctx,
override_url: Option<&str>,
) -> Result<(String, reqwest::Client), CmdError> {
let network = ctx.environment.network();
if let Some(url) = override_url {
validate_override_rpc_url(url, network, ctx.allow_custom_endpoints)?;
let http = if is_proxy_rpc_url(url, ctx.base_url()) {
ctx.client()?.http_client()
} else {
reqwest::Client::new()
};
return Ok((url.to_string(), http));
}
let client = ctx.client()?;
let cfg = client
.fetch_network_config()
.await
.map_err(CmdError::from)?;
let name = network.as_str();
let entry = cfg.entry(name).map_err(|e| {
CmdError::Server(format!(
"deployment at {} does not advertise network `{name}`: {e}",
ctx.base_url()
))
})?;
if !is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
return Err(CmdError::Server(format!(
"deployment at {} returned rpc_url {:?} for network `{name}`, which is not on \
the same host. Refusing to route RPC traffic off-host.",
ctx.base_url(),
entry.rpc_url,
)));
}
Ok((entry.rpc_url.clone(), client.http_client()))
}
fn validate_dry_run_override(ctx: &Ctx, override_url: Option<&str>) -> Result<(), CmdError> {
if let Some(url) = override_url {
validate_override_rpc_url(url, ctx.environment.network(), ctx.allow_custom_endpoints)?;
}
Ok(())
}
fn parse_to(raw: &str) -> Result<Address, CmdError> {
raw.parse()
.map_err(|e| CmdError::Usage(format!("`{raw}` is not a valid EVM address: {e}")))
}
fn parse_function(sig: &str) -> Result<Function, CmdError> {
Function::parse(sig).map_err(|e| {
CmdError::Usage(format!(
"invalid function signature {sig:?}: {e} \
(expected e.g. `transfer(address,uint256)` or `paused()(bool)`)"
))
})
}
fn coerce_args(func: &Function, args: &[String]) -> Result<Vec<DynSolValue>, CmdError> {
if func.inputs.len() != args.len() {
return Err(CmdError::Usage(format!(
"`{}` takes {} argument(s), got {}",
func.signature(),
func.inputs.len(),
args.len()
)));
}
func.inputs
.iter()
.zip(args)
.enumerate()
.map(|(i, (param, raw))| {
let ty = param.resolve().map_err(|e| {
CmdError::Usage(format!("cannot resolve type of input #{i} `{param}`: {e}"))
})?;
ty.coerce_str(raw).map_err(|e| {
CmdError::Usage(format!("argument #{i} `{raw}` is not a valid {ty}: {e}"))
})
})
.collect()
}
fn encode_calldata(func: &Function, values: &[DynSolValue]) -> Result<Bytes, CmdError> {
func.abi_encode_input(values)
.map(Bytes::from)
.map_err(|e| CmdError::Usage(format!("encode {}: {e}", func.signature())))
}
fn dyn_value_to_json(v: &DynSolValue) -> Value {
match v {
DynSolValue::Bool(b) => json!(b),
DynSolValue::Int(i, _) => json!(i.to_string()),
DynSolValue::Uint(u, _) => json!(u.to_string()),
DynSolValue::FixedBytes(word, size) => {
json!(format!("0x{}", hex::encode(&word.as_slice()[..*size])))
}
DynSolValue::Address(a) => json!(format!("{a:#x}")),
DynSolValue::Function(f) => json!(format!("0x{}", hex::encode(f.as_slice()))),
DynSolValue::Bytes(b) => json!(format!("0x{}", hex::encode(b))),
DynSolValue::String(s) => json!(s),
DynSolValue::Array(vals) | DynSolValue::FixedArray(vals) | DynSolValue::Tuple(vals) => {
Value::Array(vals.iter().map(dyn_value_to_json).collect())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloy_primitives::{address, U256};
use alloy_sol_types::SolCall;
use taskfast_agent::chain::IERC20;
const ADDR: &str = "0x00000000000000000000000000000000000000aa";
#[test]
fn parses_plain_signature() {
let f = parse_function("setSlashRecipient(address,bool)").unwrap();
assert_eq!(f.name, "setSlashRecipient");
assert_eq!(f.inputs.len(), 2);
assert!(f.outputs.is_empty());
}
#[test]
fn parses_cast_style_return_shorthand() {
let f = parse_function("paused()(bool)").unwrap();
assert!(f.inputs.is_empty());
assert_eq!(f.outputs.len(), 1);
assert_eq!(f.outputs[0].ty, "bool");
}
#[test]
fn rejects_garbage_signature() {
let err = parse_function("not a signature").unwrap_err();
assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
}
#[test]
fn rejects_arity_mismatch() {
let f = parse_function("transfer(address,uint256)").unwrap();
let err = coerce_args(&f, &[ADDR.to_string()]).unwrap_err();
match err {
CmdError::Usage(m) => assert!(m.contains("takes 2"), "msg: {m}"),
other => panic!("expected Usage, got {other:?}"),
}
}
#[test]
fn rejects_uncoercible_argument() {
let f = parse_function("transfer(address,uint256)").unwrap();
let err = coerce_args(&f, &[ADDR.to_string(), "not-a-number".to_string()]).unwrap_err();
assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
}
#[test]
fn dynamic_encoding_matches_static_sol_bindings() {
let f = parse_function("approve(address,uint256)").unwrap();
let values = coerce_args(&f, &[ADDR.to_string(), "5000000".to_string()]).unwrap();
let dynamic = encode_calldata(&f, &values).unwrap();
let expected = IERC20::approveCall {
spender: address!("00000000000000000000000000000000000000aa"),
amount: U256::from(5_000_000u64),
}
.abi_encode();
assert_eq!(dynamic.as_ref(), expected.as_slice());
}
#[test]
fn decodes_bool_output() {
let f = parse_function("paused()(bool)").unwrap();
let mut raw = [0u8; 32];
raw[31] = 1;
let vals = f.abi_decode_output(&raw).unwrap();
assert_eq!(vals.len(), 1);
assert_eq!(dyn_value_to_json(&vals[0]), json!(true));
}
#[test]
fn coerces_array_argument() {
let f = parse_function("setAll(uint256[])").unwrap();
let values = coerce_args(&f, &["[1, 2, 3]".to_string()]).unwrap();
let encoded = encode_calldata(&f, &values).unwrap();
assert_eq!(encoded.len(), 4 + 32 * 5);
}
#[test]
fn dyn_value_to_json_covers_scalar_and_nested_shapes() {
let addr = address!("00000000000000000000000000000000000000aa");
assert_eq!(
dyn_value_to_json(&DynSolValue::Address(addr)),
json!("0x00000000000000000000000000000000000000aa")
);
assert_eq!(
dyn_value_to_json(&DynSolValue::Uint(U256::MAX, 256)),
json!(U256::MAX.to_string())
);
assert_eq!(
dyn_value_to_json(&DynSolValue::Bytes(vec![0xde, 0xad])),
json!("0xdead")
);
assert_eq!(
dyn_value_to_json(&DynSolValue::String("hi".into())),
json!("hi")
);
let nested = DynSolValue::Tuple(vec![
DynSolValue::Bool(true),
DynSolValue::Array(vec![DynSolValue::Uint(U256::from(7u64), 256)]),
]);
assert_eq!(dyn_value_to_json(&nested), json!([true, ["7"]]));
}
}