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