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