Skip to main content

taskfast_cli/cmd/
cast.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast cast` — general-purpose contract interaction (gh#101).
3//!
4//! Drop-in replacement for the foundry `cast` invocations that operator
5//! runbooks and provisioning scripts still depend on:
6//!
7//!   * `cast call <addr> '<sig>' [args…]`  → read via `eth_call`, decoded.
8//!   * `cast send <addr> '<sig>' [args…]`  → sign + broadcast + receipt.
9//!   * `cast rpc  <method> [json-params]`  → raw JSON-RPC passthrough.
10//!
11//! Signatures are parsed at runtime (`alloy-json-abi` human-readable grammar,
12//! which also accepts the cast-style `paused()(bool)` return-type shorthand),
13//! args are coerced per declared Solidity type, and calldata is encoded with
14//! the 4-byte selector via `alloy-dyn-abi` — no compile-time `sol!` bindings,
15//! so any contract works.
16//!
17//! Deliberately out of scope (YAGNI, per gh#101): `abi-encode` / `abi-decode`
18//! / `keccak` / `4byte` conveniences, `--block` on `call` (everything in-repo
19//! reads `latest`; add an additive `eth_call_at` later if needed), `--value`
20//! on `send` (every replaced invocation targets a non-payable function).
21
22use 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
39/// Receipt polling for `cast send` — network-aware defaults matching
40/// `escrow sign` / `bond post` (3min mainnet, 1min testnet), resolved from
41/// the env's compile-time network rather than a config fetch so the
42/// `--rpc-url` override path needs no API round-trip.
43const 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    /// Read-only `eth_call`; result decoded per the signature's return types.
50    Call(CallArgs),
51    /// Sign + broadcast a transaction calling an arbitrary function.
52    Send(SendArgs),
53    /// Raw JSON-RPC passthrough: method + params in, untyped result out.
54    Rpc(RpcArgs),
55}
56
57#[derive(Debug, Parser)]
58pub struct CallArgs {
59    /// Target contract address (`0x`-prefixed).
60    pub to: String,
61
62    /// Function signature, e.g. `balanceOf(address)(uint256)`. Return types
63    /// (the second parens group) are optional — without them the raw hex
64    /// response is returned undecoded.
65    pub sig: String,
66
67    /// Function arguments, one per declared input (use `--` before values
68    /// that start with a dash, e.g. negative ints).
69    pub args: Vec<String>,
70
71    /// Tempo RPC override. Defaults to the deployment's authenticated proxy URL.
72    #[arg(long, env = "TEMPO_RPC_URL")]
73    pub rpc_url: Option<String>,
74}
75
76#[derive(Debug, Parser)]
77pub struct SendArgs {
78    /// Target contract address (`0x`-prefixed).
79    pub to: String,
80
81    /// Function signature, e.g. `setSlashRecipient(address,bool)`.
82    pub sig: String,
83
84    /// Function arguments, one per declared input (use `--` before values
85    /// that start with a dash, e.g. negative ints).
86    pub args: Vec<String>,
87
88    /// Keystore reference (same form as `taskfast escrow sign`).
89    #[arg(long, env = "TEMPO_KEY_SOURCE")]
90    pub keystore: Option<String>,
91
92    /// Path to keystore password file.
93    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
94    pub wallet_password_file: Option<PathBuf>,
95
96    /// Wallet address preflight (`0x`-prefixed). When set, fail before touching
97    /// the chain if the keystore decrypts to a mismatch.
98    #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
99    pub wallet_address: Option<String>,
100
101    /// Tempo RPC override. Defaults to the deployment's authenticated proxy URL.
102    #[arg(long, env = "TEMPO_RPC_URL")]
103    pub rpc_url: Option<String>,
104
105    /// Receipt-polling ceiling — human duration (`3min`, `90s`). Falls back to
106    /// `receipt_timeout` in config, then a network-aware default.
107    #[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    /// JSON-RPC method name, e.g. `eth_chainId` or `tempo_fundAddress`.
114    pub method: String,
115
116    /// Params as a JSON value (usually an array), e.g. `'["0xabc…", true]'`.
117    /// Defaults to `[]`.
118    pub params: Option<String>,
119
120    /// Tempo RPC override. Defaults to the deployment's authenticated proxy URL.
121    #[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    // No declared return types → raw hex only (mirrors foundry cast, which
147    // prints the undecoded response when the sig carries no output parens).
148    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    // Load signer + preflight the wallet address before any network I/O —
176    // same order as `bond post`, so `--dry-run` still validates the keystore.
177    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    // A raw passthrough can't tell reads from mutations (`eth_sendRawTransaction`
262    // is one method call away), so `--dry-run` short-circuits the whole verb
263    // rather than honoring the reads-pass-through convention. Fail safe.
264    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
294/// Resolve the RPC URL + the reqwest client to hit it with. Same policy as
295/// `bond post` / `escrow sign`: an explicit `--rpc-url` / `TEMPO_RPC_URL`
296/// override goes through the endpoint guard; otherwise the deployment's
297/// `GET /config/network` supplies the authenticated same-host proxy URL.
298/// The override path only builds an API client when the URL is our own proxy
299/// (which needs the `X-API-Key` header), so pointing at a bare upstream node
300/// works without any TaskFast credentials.
301async 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
339/// Endpoint-guard check for dry-run short-circuits: `validate_override_rpc_url`
340/// is pure (no I/O), so dry-run can reject the same override URLs live mode
341/// would while still guaranteeing zero network traffic.
342fn 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
363/// Coerce each CLI string to the [`DynSolValue`] its declared input demands.
364fn 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
388/// Selector-prefixed calldata for `func(values…)`.
389fn 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
395/// Render a decoded [`DynSolValue`] as JSON for the envelope. `alloy-dyn-abi`
396/// ships no `Serialize` impl. Numbers become decimal strings (U256/I256
397/// overflow every JSON number type); byte-ish values become `0x`-hex.
398fn 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        // Cross-check the whole parse→coerce→encode pipeline against the
467        // compile-time `sol!` encoding the rest of the CLI uses.
468        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        // selector + offset + length + 3 words
495        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}