Skip to main content

taskfast_cli/cmd/
post.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast post` — two-phase task creation (prepare → sign+broadcast → submit).
3//!
4//! Supersedes the `scripts/post-task` shell flow whose defect chain is tracked
5//! under am-q1m. Server contract (`lib/task_fast/payments/tempo_provider.ex`
6//! `charge_submission_fee/4`) accepts **two voucher forms** on
7//! `POST /api/task_drafts/{id}/submit`:
8//!
9//!   - `0x<64hex>` → already-broadcast tx hash; server polls for confirmation.
10//!   - any other hex → raw RLP-encoded signed tx; server broadcasts via
11//!     `eth_sendRawTransaction`.
12//!
13//! We take the **tx-hash voucher path**: the client signs + broadcasts the
14//! ERC-20 transfer locally, then hands the server just the hash. Rationale:
15//! failures on the broadcast side surface to the agent as a concrete RPC
16//! error before we pollute the server's draft state with a would-be-bad
17//! voucher.
18//!
19//! `payload_to_sign` (despite its historical name) is **not** an ECDSA signing
20//! payload — it's the encoded ERC-20 `transfer` calldata. We wrap it in a
21//! replay-safe legacy tx and sign the transaction hash via
22//! [`taskfast_agent::tempo_rpc::sign_and_broadcast_erc20_transfer`].
23
24use std::path::PathBuf;
25
26use alloy_primitives::{Address, Bytes};
27use clap::Parser;
28use serde_json::json;
29use uuid::Uuid;
30
31use super::{is_proxy_rpc_url, validate_override_rpc_url, CmdError, CmdResult, Ctx};
32use crate::envelope::Envelope;
33
34use taskfast_agent::tempo_rpc::{sign_and_broadcast_erc20_transfer, TempoRpcClient};
35use taskfast_chains::tempo::{is_allowed_fee_token, is_known_network};
36use taskfast_client::api::types::{
37    CompletionCriterionInput, TaskDraftPrepareRequest, TaskDraftPrepareRequestAssignmentType,
38    TaskDraftPrepareRequestPickupDeadlineHours, TaskDraftSubmitRequest,
39    TaskDraftSubmitRequestSignature,
40};
41use taskfast_client::{map_api_error, TaskFastClient};
42
43#[derive(Debug, Parser)]
44pub struct Args {
45    /// Task title (required).
46    #[arg(long)]
47    pub title: String,
48
49    /// Task description (required, non-empty). Validated client-side so a
50    /// typoed script fails fast instead of paying for a server 422 round-trip.
51    #[arg(long)]
52    pub description: String,
53
54    /// Max budget the poster will pay, as a decimal string ("2.50"). Passed
55    /// through as `budget_max` on the draft.
56    #[arg(long)]
57    pub budget: Option<String>,
58
59    /// Capability tags required from the assignee. Comma-separated.
60    #[arg(long, value_delimiter = ',')]
61    pub capabilities: Vec<String>,
62
63    /// Completion-criterion payout gate as a JSON object. Repeat `--criterion`
64    /// for multiple gates. Shape matches `CompletionCriterionInput`:
65    /// `{"description":"…","check_type":"json_schema|regex|count|http_status|file_exists",`
66    /// `"check_expression":"…","expected_value":"…","target_artifact_pattern":null}`.
67    /// Missing ⇒ no objective gate; server policy decides payout.
68    #[arg(long = "criterion")]
69    pub criteria: Vec<String>,
70
71    /// Path to a JSON file containing an array of `CompletionCriterionInput`
72    /// objects. Merged before any `--criterion` flags (file entries first).
73    /// Use this when you have many gates or want to keep them in version
74    /// control alongside the task.
75    #[arg(long)]
76    pub criteria_file: Option<PathBuf>,
77
78    /// Pickup window in hours: how long the task stays open for bidding
79    /// before closing. Required. The server owns the set of allowed windows
80    /// (`422 pickup_deadline_required` on an invalid choice).
81    #[arg(long)]
82    pub pickup_deadline_hours: i64,
83
84    /// Execution deadline (RFC3339 timestamp).
85    #[arg(long)]
86    pub execution_deadline: Option<String>,
87
88    /// Settlement venue `chain_key` (e.g. `tempo-zone-moderato`) electing the
89    /// settlement rail/chain for this task (ADR 0011 §5). Omit to settle on the
90    /// deployment's default venue (L1). The server validates the key (must
91    /// reference an active venue) and binds it once at creation, immutably.
92    #[arg(long)]
93    pub venue: Option<String>,
94
95    /// Assignment model: `open` (auction to any qualified bidder) or
96    /// `direct` (assign to a specific agent; requires `--direct-agent-id`).
97    #[arg(long, default_value = "open")]
98    pub assignment_type: AssignmentType,
99
100    /// Direct assignment target. Required when `--assignment-type=direct`.
101    #[arg(long)]
102    pub direct_agent_id: Option<String>,
103
104    /// Poster's on-chain wallet address (0x-prefixed). Matches `TEMPO_WALLET_ADDRESS`
105    /// written by `taskfast init`.
106    #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
107    pub wallet_address: Option<String>,
108
109    /// Keystore reference. Accepts a bare path (`/.../abc.json`) or the
110    /// `file:/path` form `taskfast init` writes to `TEMPO_KEY_SOURCE`.
111    /// Keychain backends will slot in later under the same flag.
112    #[arg(long, env = "TEMPO_KEY_SOURCE")]
113    pub keystore: Option<String>,
114
115    /// Path to a file holding the keystore password (mode-0400 recommended).
116    /// Preferred over `TASKFAST_WALLET_PASSWORD` — files don't leak via
117    /// process args or `/proc/self/environ`.
118    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
119    pub wallet_password_file: Option<PathBuf>,
120
121    /// Tempo RPC endpoint. Defaults to the canonical proxy URL the
122    /// deployment advertises for the env's network.
123    #[arg(long, env = "TEMPO_RPC_URL")]
124    pub rpc_url: Option<String>,
125
126    /// Acknowledge oversized budgets. Required when the budget exceeds
127    /// `confirm_above_budget` in the config. No-op when the gate is unset
128    /// or when the budget is below it. Fail-closed by design (no TTY
129    /// prompt) so a CI script accident doesn't broadcast a huge approve.
130    #[arg(long)]
131    pub yes: bool,
132}
133
134#[derive(Debug, Clone, Copy, clap::ValueEnum)]
135pub enum AssignmentType {
136    Open,
137    Direct,
138}
139
140impl AssignmentType {
141    fn as_str(self) -> &'static str {
142        match self {
143            Self::Open => "open",
144            Self::Direct => "direct",
145        }
146    }
147}
148
149impl From<AssignmentType> for TaskDraftPrepareRequestAssignmentType {
150    fn from(a: AssignmentType) -> Self {
151        match a {
152            AssignmentType::Open => Self::Open,
153            AssignmentType::Direct => Self::Direct,
154        }
155    }
156}
157
158/// Convert `--pickup-deadline-hours` to the wire type generated from the
159/// vendored spec. The generated newtype is the only encoding of the allowed
160/// set — the CLI never restates it, so a server policy change flows in via a
161/// spec re-vendor with no code edit here.
162fn pickup_hours_to_wire(
163    hours: i64,
164) -> Result<TaskDraftPrepareRequestPickupDeadlineHours, CmdError> {
165    TaskDraftPrepareRequestPickupDeadlineHours::try_from(hours).map_err(|_| CmdError::Validation {
166        code: "pickup_deadline_invalid".into(),
167        message: format!(
168            "pickup window of {hours}h is not an allowed bidding window per the \
169             API contract; the server owns the valid set (422 pickup_deadline_required)"
170        ),
171    })
172}
173
174pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
175    // gh#144: validate every local input in ONE pass before any HTTP,
176    // keystore prompt, or signing — the old sequential early-returns cost an
177    // agent one full retry cycle per missing flag / guard conflict.
178    let pre = preflight(ctx, &args)?;
179
180    let prep_body = TaskDraftPrepareRequest {
181        assignment_type: args.assignment_type.into(),
182        budget_max: args.budget.clone(),
183        completion_criteria: pre.completion_criteria,
184        description: args.description.clone(),
185        direct_agent_id: pre.direct_agent_id,
186        execution_deadline: pre.execution_deadline,
187        pickup_deadline_hours: pre.pickup_hours,
188        poster_wallet_address: pre
189            .wallet_address
190            .parse()
191            .map_err(|e| CmdError::Usage(format!("--wallet-address rejected by schema: {e}")))?,
192        required_capabilities: args.capabilities.clone(),
193        settlement_venue: args.venue.clone(),
194        title: args.title.clone(),
195    };
196
197    // Dry-run must perform zero HTTP. Predict the proxy URL locally so the
198    // envelope still reports what the real path would have used.
199    if ctx.dry_run {
200        let rpc_url = match pre.rpc_url_override {
201            Some(override_url) => override_url,
202            None => format!(
203                "{}/rpc/{}",
204                ctx.base_url().trim_end_matches('/'),
205                ctx.environment.network().as_str()
206            ),
207        };
208        return Ok(Envelope::success(
209            ctx.environment,
210            ctx.dry_run,
211            json!({
212                "action": "would_post",
213                "draft_id": serde_json::Value::Null,
214                "title": args.title,
215                "assignment_type": args.assignment_type.as_str(),
216                "budget_max": args.budget,
217                "settlement_venue": args.venue,
218                "required_capabilities": args.capabilities,
219                "completion_criteria_count": prep_body.completion_criteria.len(),
220                "rpc_url": rpc_url,
221                "wallet_address": pre.wallet_address,
222            }),
223        ));
224    }
225
226    let client = ctx.client()?;
227
228    // Resolve the RPC URL. Default path: pull it from the deployment's
229    // `GET /config/network` (public). Override path: user supplied
230    // `--rpc-url` / `TEMPO_RPC_URL` and must also pass
231    // `--allow-custom-endpoints` (already checked in preflight).
232    let rpc_url = match pre.rpc_url_override {
233        Some(override_url) => override_url,
234        None => resolve_proxy_rpc_url(&client, ctx).await?,
235    };
236
237    // Phase 1 — prepare. Server returns ERC-20 transfer calldata + draft_id.
238    let prep = match client.inner().prepare_task_draft(&prep_body).await {
239        Ok(r) => r.into_inner(),
240        Err(e) => return Err(map_api_error(e).await.into()),
241    };
242
243    let token_address: Address = prep.token_address.parse().map_err(|e| {
244        CmdError::Server(format!(
245            "server returned invalid token_address `{}`: {e}",
246            prep.token_address
247        ))
248    })?;
249    let calldata = decode_0x_bytes(&prep.payload_to_sign)
250        .map_err(|e| CmdError::Server(format!("server returned invalid payload_to_sign: {e}")))?;
251
252    // Load signer only after prepare succeeds — avoids prompting the user for
253    // a keystore password on a request that never leaves local validation.
254    let keystore_ref = args.keystore.as_deref().map(str::to_string).or_else(|| {
255        ctx.keystore_path
256            .as_deref()
257            .and_then(|p| p.to_str().map(str::to_string))
258    });
259    let signer = super::wallet_args::load_signer(
260        keystore_ref.as_deref(),
261        args.wallet_password_file.as_deref(),
262        "submission fee",
263    )?;
264    // Sanity: the wallet address in the draft must match what we're signing
265    // with. A mismatch means the server recorded a charge on a wallet we
266    // don't control, which would poll forever.
267    let parsed_wallet_address = pre
268        .wallet_address
269        .parse::<Address>()
270        .map_err(|_| CmdError::Usage(format!("invalid wallet address: {}", pre.wallet_address)))?;
271    if signer.address() != parsed_wallet_address {
272        return Err(CmdError::Usage(format!(
273            "keystore address {:#x} does not match --wallet-address {}",
274            signer.address(),
275            pre.wallet_address
276        )));
277    }
278
279    // Pick the http client by URL, not by resolution branch: any URL
280    // landing on `{api_base}/rpc/` is the authenticated proxy and
281    // needs `X-API-Key` (set as a default header on `client.http_client()`).
282    // A `--rpc-url`/`TEMPO_RPC_URL` override that points at the proxy
283    // hit this same path; the prior `via_proxy` flag missed that case
284    // and dropped the header, returning 401 "missing API key".
285    let http = ctx.rpc_http_client(&client, &rpc_url);
286    let rpc = TempoRpcClient::new(http, rpc_url.clone());
287
288    // F1: consult the chain's own `eth_chainId` (not anything the server
289    // claims) and refuse to sign a `transfer` against a token that isn't
290    // on the PathUSD allowlist for that chain. A compromised TaskFast API
291    // returning an attacker `token_address` is the fund-drain vector here.
292    let chain_id = rpc
293        .chain_id()
294        .await
295        .map_err(|e| CmdError::Server(format!("tempo rpc eth_chainId: {e}")))?;
296    if !ctx.allow_custom_endpoints && !is_known_network(chain_id) {
297        return Err(CmdError::Validation {
298            code: "unknown_chain".into(),
299            message: format!(
300                "RPC reports chain_id={chain_id} which is not a known Tempo or \
301                 local-dev network; refusing to sign. Pass --allow-custom-endpoints \
302                 to override."
303            ),
304        });
305    }
306    if !is_allowed_fee_token(chain_id, &prep.token_address) {
307        return Err(CmdError::Validation {
308            code: "fee_token_not_allowed".into(),
309            message: format!(
310                "server returned token_address {} which is not on the PathUSD \
311                 allowlist for chain_id={chain_id}. Refusing to sign — this would \
312                 redirect your fee transfer to an arbitrary ERC-20 contract.",
313                prep.token_address
314            ),
315        });
316    }
317
318    // Audit line — always emitted to stderr so a CI log captures the exact
319    // recipient+token+chain we committed funds to. Not a prompt: CLI stays
320    // non-interactive.
321    eprintln!(
322        "taskfast: signing submission-fee transfer — token={} chain_id={} rpc={}",
323        prep.token_address, chain_id, rpc_url
324    );
325
326    // F9: serialize nonce-consuming sign+broadcast per wallet. `_guard`
327    // holds the exclusive file lock from here until function return,
328    // which scope-covers both eth_getTransactionCount (inside
329    // sign_and_broadcast_erc20_transfer) and eth_sendRawTransaction.
330    // Locked on the keystore path (stripping the optional `file:` prefix
331    // that `taskfast init` writes) so two processes sharing a keystore
332    // can't race, while distinct wallets proceed in parallel.
333    let _guard = if let Some(ref raw) = keystore_ref {
334        let path_str = raw.strip_prefix("file:").unwrap_or(raw);
335        Some(crate::wallet_lock::acquire(std::path::Path::new(path_str))?)
336    } else {
337        None
338    };
339
340    let tx_hash =
341        sign_and_broadcast_erc20_transfer(&rpc, &signer, token_address, Bytes::from(calldata))
342            .await
343            .map_err(|e| CmdError::Server(format!("tempo rpc: {e}")))?;
344    let tx_hash_hex = format!("{tx_hash:#x}");
345
346    // Phase 2 — submit voucher. The field is named `signature` for historical
347    // reasons; semantically it's a voucher (tx hash, in our path).
348    let signature: TaskDraftSubmitRequestSignature = tx_hash_hex
349        .parse()
350        .map_err(|e| CmdError::Server(format!("tx hash rejected by schema pattern: {e}")))?;
351    let submit_body = TaskDraftSubmitRequest { signature };
352    let submitted = match client
353        .inner()
354        .submit_task_draft(&prep.draft_id, &submit_body)
355        .await
356    {
357        Ok(r) => r.into_inner(),
358        Err(e) => return Err(map_api_error(e).await.into()),
359    };
360
361    Ok(Envelope::success(
362        ctx.environment,
363        ctx.dry_run,
364        json!({
365            "task_id": submitted.id,
366            "draft_id": prep.draft_id,
367            "submission_fee_tx_hash": tx_hash_hex,
368            "status": submitted.status,
369            "submission_fee_status": submitted.submission_fee_status,
370        }),
371    ))
372}
373
374/// Everything [`run`] needs from local validation, parsed once by
375/// [`preflight`] so the runtime path never re-validates (gh#144).
376struct Preflight {
377    wallet_address: String,
378    direct_agent_id: Option<Uuid>,
379    execution_deadline: Option<chrono::DateTime<chrono::Utc>>,
380    completion_criteria: Vec<CompletionCriterionInput>,
381    pickup_hours: TaskDraftPrepareRequestPickupDeadlineHours,
382    /// User-supplied `--rpc-url` / `TEMPO_RPC_URL`, already through the
383    /// custom-endpoint guard. `None` = resolve the deployment's proxy URL.
384    rpc_url_override: Option<String>,
385}
386
387/// Bare problem text for the preflight list — `Display` on these variants
388/// carries an `usage:` / `validation [code]:` prefix that reads as noise
389/// inside an enumerated list (the envelope's `error.code` already classifies).
390fn problem_text(e: &CmdError) -> String {
391    match e {
392        CmdError::Usage(m) => m.clone(),
393        CmdError::Validation { message, .. } => message.clone(),
394        other => other.to_string(),
395    }
396}
397
398/// gh#144 one-pass input validation. Every locally-checkable problem with
399/// the invocation — missing/blank required values, malformed addresses and
400/// UUIDs, bad timestamps, unparseable criteria, out-of-contract pickup
401/// windows, endpoint-guard conflicts, the budget gate — is collected and
402/// reported in a single enumerated `Usage` error, so fixing one problem
403/// never reveals exactly one more. Runs before any HTTP, keystore prompt,
404/// or signing, and short-circuits `--dry-run` the same way.
405///
406/// Error message texts are unchanged from the former sequential checks —
407/// orchestrators scraping them see the same strings, just together.
408fn preflight(ctx: &Ctx, args: &Args) -> Result<Preflight, CmdError> {
409    let mut problems: Vec<String> = Vec::new();
410    // Each check stores one validated field as `Option`; `None` marks
411    // "check failed, problem already recorded" so every later check still
412    // runs and reports too.
413
414    if args.description.trim().is_empty() {
415        problems.push(
416            "--description must not be empty (server requires a non-blank description)".into(),
417        );
418    }
419
420    if let Err(e) = ctx.enforce_budget_gate(args.budget.as_deref(), args.yes, "post a task") {
421        problems.push(problem_text(&e));
422    }
423
424    let wallet_address = match args
425        .wallet_address
426        .as_deref()
427        .or(ctx.wallet_address.as_deref())
428    {
429        Some(w) => match w.parse::<Address>() {
430            Ok(_) => Some(w.to_string()),
431            Err(e) => {
432                problems.push(format!("--wallet-address is not a valid EVM address: {e}"));
433                None
434            }
435        },
436        None => {
437            problems.push(
438                "--wallet-address (or TEMPO_WALLET_ADDRESS, or wallet_address in config) required to post a task".into(),
439            );
440            None
441        }
442    };
443
444    let direct_agent_id = match (args.assignment_type, args.direct_agent_id.as_deref()) {
445        (AssignmentType::Direct, Some(s)) => match Uuid::parse_str(s) {
446            Ok(u) => Some(Some(u)),
447            Err(e) => {
448                problems.push(format!("--direct-agent-id not a UUID: {e}"));
449                None
450            }
451        },
452        (AssignmentType::Direct, None) => {
453            problems.push("--assignment-type=direct requires --direct-agent-id".into());
454            None
455        }
456        (AssignmentType::Open, _) => Some(None),
457    };
458
459    let execution_deadline =
460        match parse_iso_opt(args.execution_deadline.as_deref(), "--execution-deadline") {
461            Ok(v) => Some(v),
462            Err(e) => {
463                problems.push(problem_text(&e));
464                None
465            }
466        };
467
468    let completion_criteria = match resolve_criteria(args.criteria_file.as_deref(), &args.criteria)
469    {
470        Ok(v) => Some(v),
471        Err(e) => {
472            problems.push(problem_text(&e));
473            None
474        }
475    };
476
477    let pickup_hours = match pickup_hours_to_wire(args.pickup_deadline_hours) {
478        Ok(w) => Some(w),
479        Err(e) => {
480            problems.push(problem_text(&e));
481            None
482        }
483    };
484
485    let rpc_url_override = match args.rpc_url.as_deref() {
486        Some(u) => match validate_override_rpc_url(
487            u,
488            ctx.environment.network(),
489            ctx.allow_custom_endpoints,
490        ) {
491            Ok(u) => Some(Some(u.to_string())),
492            Err(e) => {
493                problems.push(problem_text(&e));
494                None
495            }
496        },
497        None => Some(None),
498    };
499
500    if !problems.is_empty() {
501        let n = problems.len();
502        let list = problems
503            .iter()
504            .enumerate()
505            .map(|(i, p)| format!("  {}. {p}", i + 1))
506            .collect::<Vec<_>>()
507            .join("\n");
508        return Err(CmdError::Usage(format!(
509            "post preflight found {n} problem{}:\n{list}",
510            if n == 1 { "" } else { "s" }
511        )));
512    }
513
514    Ok(Preflight {
515        wallet_address: wallet_address.expect("no problems ⇒ wallet present"),
516        direct_agent_id: direct_agent_id.expect("no problems ⇒ direct id resolved"),
517        execution_deadline: execution_deadline.expect("no problems ⇒ deadline resolved"),
518        completion_criteria: completion_criteria.expect("no problems ⇒ criteria resolved"),
519        pickup_hours: pickup_hours.expect("no problems ⇒ pickup hours valid"),
520        rpc_url_override: rpc_url_override.expect("no problems ⇒ rpc override resolved"),
521    })
522}
523
524/// Resolve the deployment's proxied RPC endpoint for a post invocation that
525/// did not supply `--rpc-url` (the override path is handled in [`preflight`]).
526///
527/// The deployment's `/config/network` entry for the selected network points
528/// the CLI at `{api_base}/rpc/{network}`, which the server proxies to its
529/// own Tempo upstream (Alchemy by default). The caller should carry the
530/// authenticated reqwest::Client through to `TempoRpcClient`.
531async fn resolve_proxy_rpc_url(client: &TaskFastClient, ctx: &Ctx) -> Result<String, CmdError> {
532    let cfg = client.fetch_network_config().await.map_err(|e| match e {
533        taskfast_client::Error::Auth(_) | taskfast_client::Error::Validation { .. } => {
534            CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
535        }
536        other => CmdError::from(other),
537    })?;
538    // Runtime invariant — issue #62 (server-side): the env's deployment must
539    // advertise exactly its one network, and nothing else.
540    //
541    // Today's deployments still advertise multiple networks per response;
542    // until #62 lands, a `len != 1` mismatch logs a warn and continues.
543    // Set TASKFAST_STRICT_ENV_NETWORK=1 to fail-closed.
544    // `--allow-custom-endpoints` and `Environment::Local` bypass entirely
545    // (matches `enforce_endpoint_guard`).
546    let name = ctx.environment.network().as_str();
547    if !ctx.allow_custom_endpoints
548        && ctx.environment != crate::Environment::Local
549        && cfg.networks.len() != 1
550    {
551        let advertised: Vec<&str> = cfg.networks.keys().map(String::as_str).collect();
552        let strict = std::env::var("TASKFAST_STRICT_ENV_NETWORK")
553            .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
554        if strict {
555            return Err(CmdError::Server(format!(
556                "deployment at {} advertises networks {advertised:?}; env {} requires \
557                 exactly [{name}]. Server-side fix tracked in issue #62. Unset \
558                 TASKFAST_STRICT_ENV_NETWORK or pass --allow-custom-endpoints to bypass.",
559                ctx.base_url(),
560                ctx.environment.as_str(),
561            )));
562        }
563        tracing::warn!(
564            api_base = %ctx.base_url(),
565            env = ctx.environment.as_str(),
566            expected = name,
567            advertised = ?advertised,
568            "deployment advertises additional networks; server-side fix tracked in #62. \
569             Set TASKFAST_STRICT_ENV_NETWORK=1 to fail-closed."
570        );
571    }
572    let entry = cfg.entry(name).map_err(|e| {
573        CmdError::Server(format!(
574            "deployment at {} does not advertise network `{name}`: {e}",
575            ctx.base_url()
576        ))
577    })?;
578    // F2-equivalent guard, minus the static allowlist: the old
579    // WELL_KNOWN_TEMPO_RPCS check trusted exactly two hardcoded URLs. The
580    // replacement says "the proxy must live on the same host as the api_base
581    // the endpoint-guard already approved" — the path it's mounted at
582    // (`/rpc/…` or `/api/rpc/…`) is the server's choice. Catches (a) a
583    // misconfigured deployment returning an upstream URL instead of its own
584    // proxy, and (b) a compromised backend trying to steer RPC traffic
585    // off-host — minus a full MITM on api_base itself (which has its own
586    // F5/F6 defenses).
587    if !is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
588        return Err(CmdError::Server(format!(
589            "deployment at {} returned rpc_url {:?} for network `{name}`, \
590             which is not on the same host. Refusing to route RPC traffic \
591             off-host.",
592            ctx.base_url(),
593            entry.rpc_url,
594        )));
595    }
596    Ok(entry.rpc_url.clone())
597}
598
599/// Merge file-sourced and inline `--criterion` payloads into one validated
600/// list of `CompletionCriterionInput`. File entries are prepended so a
601/// shared base file can be augmented with one-off overrides on the command
602/// line. Any shape/parse failure is a `Usage` error — the CLI catches it
603/// before the request ever reaches the server, so the exit-code contract
604/// (Auth=re-credential, Validation=server-rejected payload) stays clean.
605fn resolve_criteria(
606    file: Option<&std::path::Path>,
607    inline: &[String],
608) -> Result<Vec<CompletionCriterionInput>, CmdError> {
609    let mut out = Vec::with_capacity(inline.len());
610    if let Some(path) = file {
611        let raw = std::fs::read_to_string(path).map_err(|e| {
612            CmdError::Usage(format!("read --criteria-file {}: {e}", path.display()))
613        })?;
614        let parsed: Vec<CompletionCriterionInput> = serde_json::from_str(&raw).map_err(|e| {
615            CmdError::Usage(format!(
616                "--criteria-file {} is not a JSON array of CompletionCriterionInput: {e}",
617                path.display()
618            ))
619        })?;
620        out.extend(parsed);
621    }
622    for (i, raw) in inline.iter().enumerate() {
623        let one: CompletionCriterionInput = serde_json::from_str(raw)
624            .map_err(|e| CmdError::Usage(format!("--criterion[{i}] not valid JSON: {e}")))?;
625        out.push(one);
626    }
627    Ok(out)
628}
629
630fn parse_iso_opt(
631    s: Option<&str>,
632    flag: &str,
633) -> Result<Option<chrono::DateTime<chrono::Utc>>, CmdError> {
634    match s {
635        None => Ok(None),
636        Some(raw) => chrono::DateTime::parse_from_rfc3339(raw)
637            .map(|d| Some(d.with_timezone(&chrono::Utc)))
638            .map_err(|e| CmdError::Usage(format!("{flag} not a valid RFC3339 timestamp: {e}"))),
639    }
640}
641
642fn decode_0x_bytes(s: &str) -> Result<Vec<u8>, String> {
643    let stripped = s.strip_prefix("0x").unwrap_or(s);
644    hex::decode(stripped).map_err(|e| e.to_string())
645}
646
647#[cfg(test)]
648mod tests {
649    use super::*;
650    use crate::Network;
651
652    #[test]
653    fn validate_override_rejects_without_opt_in() {
654        let err = validate_override_rpc_url("https://mallory.example", Network::Mainnet, false)
655            .expect_err("override without opt-in must be refused");
656        match err {
657            CmdError::Usage(msg) => {
658                assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
659            }
660            other => panic!("expected Usage, got {other:?}"),
661        }
662    }
663
664    #[test]
665    fn validate_override_accepts_with_opt_in() {
666        validate_override_rpc_url("https://my-node.example", Network::Testnet, true)
667            .expect("opt-in bypasses the guard");
668    }
669
670    #[test]
671    fn validate_override_rejects_plain_http_on_mainnet() {
672        let err = validate_override_rpc_url("http://my-node.example", Network::Mainnet, true)
673            .expect_err("plain-http on mainnet is always refused (except loopback)");
674        assert!(matches!(err, CmdError::Usage(msg) if msg.contains("plain-HTTP")));
675    }
676
677    #[test]
678    fn validate_override_allows_plain_http_loopback_on_mainnet() {
679        validate_override_rpc_url("http://127.0.0.1:8545", Network::Mainnet, true)
680            .expect("loopback bypasses mainnet-HTTPS check");
681        validate_override_rpc_url("http://localhost:8545", Network::Mainnet, true)
682            .expect("loopback bypasses mainnet-HTTPS check");
683    }
684
685    #[test]
686    fn validate_override_allows_plain_http_on_testnet() {
687        validate_override_rpc_url("http://my-testnet.example", Network::Testnet, true)
688            .expect("testnet does not enforce HTTPS");
689    }
690
691    #[test]
692    fn pickup_hours_conversion_follows_api_contract() {
693        // The allowed set lives only in the vendored spec (via the generated
694        // newtype) — an out-of-set value maps to a validation error without
695        // the CLI restating the list anywhere.
696        let err = pickup_hours_to_wire(3).expect_err("3 is outside the contract set");
697        assert!(matches!(err, CmdError::Validation { .. }));
698        // A contract-valid choice converts to the exact wire integer.
699        let wire = pickup_hours_to_wire(24).expect("24 is contract-valid");
700        assert_eq!(i64::from(wire), 24);
701    }
702
703    #[test]
704    fn network_name_matches_config_map_keys() {
705        // The lookup key into `GET /config/network`'s `networks` map.
706        // Must stay in sync with what the deployment advertises.
707        assert_eq!(Network::Mainnet.as_str(), "mainnet");
708        assert_eq!(Network::Testnet.as_str(), "testnet");
709    }
710}