1use std::path::PathBuf;
23use std::time::Duration;
24
25use alloy_dyn_abi::{DynSolValue, FunctionExt, JsonAbiExt, Specifier};
26use alloy_json_abi::Function;
27use alloy_primitives::{Address, Bytes};
28use clap::Parser;
29use serde_json::{json, Value};
30
31use super::{
32 is_proxy_rpc_url, resolve_duration, validate_override_rpc_url, CmdError, CmdResult, Ctx,
33};
34use crate::envelope::Envelope;
35
36use taskfast_agent::tempo_rpc::TempoRpcClient;
37
38#[derive(Debug, clap::Subcommand)]
39pub enum Command {
40 Call(CallArgs),
42 Send(SendArgs),
44 Rpc(RpcArgs),
46}
47
48#[derive(Debug, Parser)]
49pub struct CallArgs {
50 pub to: String,
52
53 pub sig: String,
57
58 pub args: Vec<String>,
61
62 #[arg(long, env = "TEMPO_RPC_URL")]
64 pub rpc_url: Option<String>,
65}
66
67#[derive(Debug, Parser)]
68pub struct SendArgs {
69 pub to: String,
71
72 pub sig: String,
74
75 pub args: Vec<String>,
78
79 #[arg(long, env = "TEMPO_KEY_SOURCE")]
81 pub keystore: Option<String>,
82
83 #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
85 pub wallet_password_file: Option<PathBuf>,
86
87 #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
90 pub wallet_address: Option<String>,
91
92 #[arg(long, env = "TEMPO_RPC_URL")]
94 pub rpc_url: Option<String>,
95
96 #[arg(long, env = "TASKFAST_RECEIPT_TIMEOUT", value_parser = humantime::parse_duration)]
99 pub receipt_timeout: Option<Duration>,
100}
101
102#[derive(Debug, Parser)]
103pub struct RpcArgs {
104 pub method: String,
106
107 pub params: Option<String>,
110
111 #[arg(long, env = "TEMPO_RPC_URL")]
113 pub rpc_url: Option<String>,
114}
115
116pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
117 match cmd {
118 Command::Call(a) => call(ctx, a).await,
119 Command::Send(a) => send(ctx, a).await,
120 Command::Rpc(a) => rpc(ctx, a).await,
121 }
122}
123
124async fn call(ctx: &Ctx, args: CallArgs) -> CmdResult {
125 let to = parse_to(&args.to)?;
126 let func = parse_function(&args.sig)?;
127 let values = coerce_args(&func, &args.args)?;
128 let calldata = encode_calldata(&func, &values)?;
129
130 let (rpc_url, http) = resolve_rpc(ctx, args.rpc_url.as_deref()).await?;
131 let rpc = TempoRpcClient::new(http, rpc_url);
132 let raw = rpc
133 .eth_call(to, &calldata)
134 .await
135 .map_err(|e| CmdError::Server(format!("eth_call: {e}")))?;
136
137 let decoded = if func.outputs.is_empty() {
140 Value::Null
141 } else {
142 let vals = func
143 .abi_decode_output(&raw)
144 .map_err(|e| CmdError::Decode(format!("decode output of {}: {e}", args.sig)))?;
145 Value::Array(vals.iter().map(dyn_value_to_json).collect())
146 };
147
148 Ok(Envelope::success(
149 ctx.environment,
150 ctx.dry_run,
151 json!({
152 "to": format!("{to:#x}"),
153 "sig": args.sig,
154 "raw": format!("0x{}", hex::encode(&raw)),
155 "decoded": decoded,
156 }),
157 ))
158}
159
160async fn send(ctx: &Ctx, args: SendArgs) -> CmdResult {
161 let to = parse_to(&args.to)?;
162 let func = parse_function(&args.sig)?;
163 let values = coerce_args(&func, &args.args)?;
164 let calldata = encode_calldata(&func, &values)?;
165
166 let keystore_path = super::wallet_args::resolve_keystore_path(
169 args.keystore.as_deref(),
170 ctx.keystore_path.as_deref(),
171 );
172 let signer = super::wallet_args::load_signer_and_validate(
173 keystore_path.as_deref(),
174 args.wallet_password_file.as_deref(),
175 args.wallet_address
176 .as_deref()
177 .or(ctx.wallet_address.as_deref()),
178 "cast send transaction",
179 )?;
180
181 if ctx.dry_run {
182 validate_dry_run_override(ctx, args.rpc_url.as_deref())?;
183 return Ok(Envelope::success(
184 ctx.environment,
185 ctx.dry_run,
186 json!({
187 "action": "would_send",
188 "to": format!("{to:#x}"),
189 "sig": args.sig,
190 "from": format!("{:#x}", signer.address()),
191 "calldata": format!("0x{}", hex::encode(&calldata)),
192 }),
193 ));
194 }
195
196 let (rpc_url, http) = resolve_rpc(ctx, args.rpc_url.as_deref()).await?;
197 let rpc = TempoRpcClient::new(http, rpc_url);
198
199 let default_timeout =
200 crate::tempo_session::default_receipt_timeout_for_network(ctx.environment.network());
201 let receipt_timeout =
202 resolve_duration(args.receipt_timeout, ctx.receipt_timeout, default_timeout);
203
204 let session =
205 crate::tempo_session::TempoSession::new(signer, keystore_path, rpc, receipt_timeout);
206
207 let tx_hash = session
208 .send_transaction_and_wait(to, calldata, "", None)
209 .await?;
210
211 Ok(Envelope::success(
212 ctx.environment,
213 ctx.dry_run,
214 json!({
215 "action": "sent",
216 "to": format!("{to:#x}"),
217 "sig": args.sig,
218 "from": format!("{:#x}", session.address()),
219 "tx_hash": format!("{tx_hash:#x}"),
220 }),
221 ))
222}
223
224async fn rpc(ctx: &Ctx, args: RpcArgs) -> CmdResult {
225 let params: Value = match args.params.as_deref() {
226 Some(raw) => serde_json::from_str(raw)
227 .map_err(|e| CmdError::Usage(format!("params is not valid JSON: {e}")))?,
228 None => json!([]),
229 };
230
231 if ctx.dry_run {
235 validate_dry_run_override(ctx, args.rpc_url.as_deref())?;
236 return Ok(Envelope::success(
237 ctx.environment,
238 ctx.dry_run,
239 json!({
240 "action": "would_rpc",
241 "method": args.method,
242 "params": params,
243 }),
244 ));
245 }
246
247 let (rpc_url, http) = resolve_rpc(ctx, args.rpc_url.as_deref()).await?;
248 let rpc = TempoRpcClient::new(http, rpc_url);
249 let result = rpc
250 .raw_call(&args.method, params)
251 .await
252 .map_err(|e| CmdError::Server(format!("{}: {e}", args.method)))?;
253
254 Ok(Envelope::success(
255 ctx.environment,
256 ctx.dry_run,
257 json!({
258 "method": args.method,
259 "result": result,
260 }),
261 ))
262}
263
264async fn resolve_rpc(
272 ctx: &Ctx,
273 override_url: Option<&str>,
274) -> Result<(String, reqwest::Client), CmdError> {
275 let network = ctx.environment.network();
276 if let Some(url) = override_url {
277 validate_override_rpc_url(url, network, ctx.allow_custom_endpoints)?;
278 let http = if is_proxy_rpc_url(url, ctx.base_url()) {
279 ctx.client()?.http_client()
280 } else {
281 reqwest::Client::new()
282 };
283 return Ok((url.to_string(), http));
284 }
285
286 let client = ctx.client()?;
287 let cfg = client
288 .fetch_network_config()
289 .await
290 .map_err(CmdError::from)?;
291 let name = network.as_str();
292 let entry = cfg.entry(name).map_err(|e| {
293 CmdError::Server(format!(
294 "deployment at {} does not advertise network `{name}`: {e}",
295 ctx.base_url()
296 ))
297 })?;
298 if !is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
299 return Err(CmdError::Server(format!(
300 "deployment at {} returned rpc_url {:?} for network `{name}`, which is not on \
301 the same host. Refusing to route RPC traffic off-host.",
302 ctx.base_url(),
303 entry.rpc_url,
304 )));
305 }
306 Ok((entry.rpc_url.clone(), client.http_client()))
307}
308
309fn validate_dry_run_override(ctx: &Ctx, override_url: Option<&str>) -> Result<(), CmdError> {
313 if let Some(url) = override_url {
314 validate_override_rpc_url(url, ctx.environment.network(), ctx.allow_custom_endpoints)?;
315 }
316 Ok(())
317}
318
319fn parse_to(raw: &str) -> Result<Address, CmdError> {
320 raw.parse()
321 .map_err(|e| CmdError::Usage(format!("`{raw}` is not a valid EVM address: {e}")))
322}
323
324fn parse_function(sig: &str) -> Result<Function, CmdError> {
325 Function::parse(sig).map_err(|e| {
326 CmdError::Usage(format!(
327 "invalid function signature {sig:?}: {e} \
328 (expected e.g. `transfer(address,uint256)` or `paused()(bool)`)"
329 ))
330 })
331}
332
333fn coerce_args(func: &Function, args: &[String]) -> Result<Vec<DynSolValue>, CmdError> {
335 if func.inputs.len() != args.len() {
336 return Err(CmdError::Usage(format!(
337 "`{}` takes {} argument(s), got {}",
338 func.signature(),
339 func.inputs.len(),
340 args.len()
341 )));
342 }
343 func.inputs
344 .iter()
345 .zip(args)
346 .enumerate()
347 .map(|(i, (param, raw))| {
348 let ty = param.resolve().map_err(|e| {
349 CmdError::Usage(format!("cannot resolve type of input #{i} `{param}`: {e}"))
350 })?;
351 ty.coerce_str(raw).map_err(|e| {
352 CmdError::Usage(format!("argument #{i} `{raw}` is not a valid {ty}: {e}"))
353 })
354 })
355 .collect()
356}
357
358fn encode_calldata(func: &Function, values: &[DynSolValue]) -> Result<Bytes, CmdError> {
360 func.abi_encode_input(values)
361 .map(Bytes::from)
362 .map_err(|e| CmdError::Usage(format!("encode {}: {e}", func.signature())))
363}
364
365fn dyn_value_to_json(v: &DynSolValue) -> Value {
369 match v {
370 DynSolValue::Bool(b) => json!(b),
371 DynSolValue::Int(i, _) => json!(i.to_string()),
372 DynSolValue::Uint(u, _) => json!(u.to_string()),
373 DynSolValue::FixedBytes(word, size) => {
374 json!(format!("0x{}", hex::encode(&word.as_slice()[..*size])))
375 }
376 DynSolValue::Address(a) => json!(format!("{a:#x}")),
377 DynSolValue::Function(f) => json!(format!("0x{}", hex::encode(f.as_slice()))),
378 DynSolValue::Bytes(b) => json!(format!("0x{}", hex::encode(b))),
379 DynSolValue::String(s) => json!(s),
380 DynSolValue::Array(vals) | DynSolValue::FixedArray(vals) | DynSolValue::Tuple(vals) => {
381 Value::Array(vals.iter().map(dyn_value_to_json).collect())
382 }
383 }
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389 use alloy_primitives::{address, U256};
390 use alloy_sol_types::SolCall;
391 use taskfast_agent::chain::IERC20;
392
393 const ADDR: &str = "0x00000000000000000000000000000000000000aa";
394
395 #[test]
396 fn parses_plain_signature() {
397 let f = parse_function("setSlashRecipient(address,bool)").unwrap();
398 assert_eq!(f.name, "setSlashRecipient");
399 assert_eq!(f.inputs.len(), 2);
400 assert!(f.outputs.is_empty());
401 }
402
403 #[test]
404 fn parses_cast_style_return_shorthand() {
405 let f = parse_function("paused()(bool)").unwrap();
406 assert!(f.inputs.is_empty());
407 assert_eq!(f.outputs.len(), 1);
408 assert_eq!(f.outputs[0].ty, "bool");
409 }
410
411 #[test]
412 fn rejects_garbage_signature() {
413 let err = parse_function("not a signature").unwrap_err();
414 assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
415 }
416
417 #[test]
418 fn rejects_arity_mismatch() {
419 let f = parse_function("transfer(address,uint256)").unwrap();
420 let err = coerce_args(&f, &[ADDR.to_string()]).unwrap_err();
421 match err {
422 CmdError::Usage(m) => assert!(m.contains("takes 2"), "msg: {m}"),
423 other => panic!("expected Usage, got {other:?}"),
424 }
425 }
426
427 #[test]
428 fn rejects_uncoercible_argument() {
429 let f = parse_function("transfer(address,uint256)").unwrap();
430 let err = coerce_args(&f, &[ADDR.to_string(), "not-a-number".to_string()]).unwrap_err();
431 assert!(matches!(err, CmdError::Usage(_)), "got {err:?}");
432 }
433
434 #[test]
435 fn dynamic_encoding_matches_static_sol_bindings() {
436 let f = parse_function("approve(address,uint256)").unwrap();
439 let values = coerce_args(&f, &[ADDR.to_string(), "5000000".to_string()]).unwrap();
440 let dynamic = encode_calldata(&f, &values).unwrap();
441 let expected = IERC20::approveCall {
442 spender: address!("00000000000000000000000000000000000000aa"),
443 amount: U256::from(5_000_000u64),
444 }
445 .abi_encode();
446 assert_eq!(dynamic.as_ref(), expected.as_slice());
447 }
448
449 #[test]
450 fn decodes_bool_output() {
451 let f = parse_function("paused()(bool)").unwrap();
452 let mut raw = [0u8; 32];
453 raw[31] = 1;
454 let vals = f.abi_decode_output(&raw).unwrap();
455 assert_eq!(vals.len(), 1);
456 assert_eq!(dyn_value_to_json(&vals[0]), json!(true));
457 }
458
459 #[test]
460 fn coerces_array_argument() {
461 let f = parse_function("setAll(uint256[])").unwrap();
462 let values = coerce_args(&f, &["[1, 2, 3]".to_string()]).unwrap();
463 let encoded = encode_calldata(&f, &values).unwrap();
464 assert_eq!(encoded.len(), 4 + 32 * 5);
466 }
467
468 #[test]
469 fn dyn_value_to_json_covers_scalar_and_nested_shapes() {
470 let addr = address!("00000000000000000000000000000000000000aa");
471 assert_eq!(
472 dyn_value_to_json(&DynSolValue::Address(addr)),
473 json!("0x00000000000000000000000000000000000000aa")
474 );
475 assert_eq!(
476 dyn_value_to_json(&DynSolValue::Uint(U256::MAX, 256)),
477 json!(U256::MAX.to_string())
478 );
479 assert_eq!(
480 dyn_value_to_json(&DynSolValue::Bytes(vec![0xde, 0xad])),
481 json!("0xdead")
482 );
483 assert_eq!(
484 dyn_value_to_json(&DynSolValue::String("hi".into())),
485 json!("hi")
486 );
487 let nested = DynSolValue::Tuple(vec![
488 DynSolValue::Bool(true),
489 DynSolValue::Array(vec![DynSolValue::Uint(U256::from(7u64), 256)]),
490 ]);
491 assert_eq!(dyn_value_to_json(&nested), json!([true, ["7"]]));
492 }
493}