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, TaskDraftPrepareRequestPosterWalletAddress,
39    TaskDraftSubmitRequest, 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; one of 1, 4, 12, 24, 72 (server contract).
80    /// Validated client-side so a bad value fails before the server 422.
81    #[arg(long)]
82    pub pickup_deadline_hours: PickupDeadlineHours,
83
84    /// Execution deadline (RFC3339 timestamp).
85    #[arg(long)]
86    pub execution_deadline: Option<String>,
87
88    /// Assignment model: `open` (auction to any qualified bidder) or
89    /// `direct` (assign to a specific agent; requires `--direct-agent-id`).
90    #[arg(long, default_value = "open")]
91    pub assignment_type: AssignmentType,
92
93    /// Direct assignment target. Required when `--assignment-type=direct`.
94    #[arg(long)]
95    pub direct_agent_id: Option<String>,
96
97    /// Poster's on-chain wallet address (0x-prefixed). Matches `TEMPO_WALLET_ADDRESS`
98    /// written by `taskfast init`.
99    #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
100    pub wallet_address: Option<String>,
101
102    /// Keystore reference. Accepts a bare path (`/.../abc.json`) or the
103    /// `file:/path` form `taskfast init` writes to `TEMPO_KEY_SOURCE`.
104    /// Keychain backends will slot in later under the same flag.
105    #[arg(long, env = "TEMPO_KEY_SOURCE")]
106    pub keystore: Option<String>,
107
108    /// Path to a file holding the keystore password (mode-0400 recommended).
109    /// Preferred over `TASKFAST_WALLET_PASSWORD` — files don't leak via
110    /// process args or `/proc/self/environ`.
111    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
112    pub wallet_password_file: Option<PathBuf>,
113
114    /// Tempo RPC endpoint. Defaults to the canonical proxy URL the
115    /// deployment advertises for the env's network.
116    #[arg(long, env = "TEMPO_RPC_URL")]
117    pub rpc_url: Option<String>,
118
119    /// Acknowledge oversized budgets. Required when the budget exceeds
120    /// `confirm_above_budget` in the config. No-op when the gate is unset
121    /// or when the budget is below it. Fail-closed by design (no TTY
122    /// prompt) so a CI script accident doesn't broadcast a huge approve.
123    #[arg(long)]
124    pub yes: bool,
125}
126
127#[derive(Debug, Clone, Copy, clap::ValueEnum)]
128pub enum AssignmentType {
129    Open,
130    Direct,
131}
132
133impl AssignmentType {
134    fn as_str(self) -> &'static str {
135        match self {
136            Self::Open => "open",
137            Self::Direct => "direct",
138        }
139    }
140}
141
142impl From<AssignmentType> for TaskDraftPrepareRequestAssignmentType {
143    fn from(a: AssignmentType) -> Self {
144        match a {
145            AssignmentType::Open => Self::Open,
146            AssignmentType::Direct => Self::Direct,
147        }
148    }
149}
150
151/// Allowed pickup-window lengths (hours). The server rejects anything outside
152/// this set (`422 pickup_deadline_required`); clap enforces it up front so a
153/// typoed value fails before the paid round-trip.
154#[derive(Debug, Clone, Copy, clap::ValueEnum)]
155pub enum PickupDeadlineHours {
156    #[value(name = "1")]
157    H1,
158    #[value(name = "4")]
159    H4,
160    #[value(name = "12")]
161    H12,
162    #[value(name = "24")]
163    H24,
164    #[value(name = "72")]
165    H72,
166}
167
168impl PickupDeadlineHours {
169    fn as_i64(self) -> i64 {
170        match self {
171            Self::H1 => 1,
172            Self::H4 => 4,
173            Self::H12 => 12,
174            Self::H24 => 24,
175            Self::H72 => 72,
176        }
177    }
178}
179
180impl From<PickupDeadlineHours> for TaskDraftPrepareRequestPickupDeadlineHours {
181    fn from(h: PickupDeadlineHours) -> Self {
182        // Infallible: the variants are exactly the schema's allowed set, so the
183        // generated newtype's membership check cannot reject them here.
184        Self::try_from(h.as_i64()).expect("pickup window is a schema-valid choice")
185    }
186}
187
188pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
189    if args.description.trim().is_empty() {
190        return Err(CmdError::Usage(
191            "--description must not be empty (server requires a non-blank description)".into(),
192        ));
193    }
194    ctx.enforce_budget_gate(args.budget.as_deref(), args.yes, "post a task")?;
195    let wallet_address = args
196        .wallet_address
197        .as_deref()
198        .or(ctx.wallet_address.as_deref())
199        .ok_or_else(|| {
200            CmdError::Usage(
201                "--wallet-address (or TEMPO_WALLET_ADDRESS, or wallet_address in config) required to post a task".into(),
202            )
203        })?;
204    // Validate shape upfront so a typo never makes it to the server.
205    let _: Address = wallet_address.parse().map_err(|e| {
206        CmdError::Usage(format!("--wallet-address is not a valid EVM address: {e}"))
207    })?;
208
209    let direct_agent_id = match (args.assignment_type, args.direct_agent_id.as_deref()) {
210        (AssignmentType::Direct, Some(s)) => Some(
211            Uuid::parse_str(s)
212                .map_err(|e| CmdError::Usage(format!("--direct-agent-id not a UUID: {e}")))?,
213        ),
214        (AssignmentType::Direct, None) => {
215            return Err(CmdError::Usage(
216                "--assignment-type=direct requires --direct-agent-id".into(),
217            ));
218        }
219        (AssignmentType::Open, _) => None,
220    };
221
222    let execution_deadline =
223        parse_iso_opt(args.execution_deadline.as_deref(), "--execution-deadline")?;
224
225    let poster_wallet: TaskDraftPrepareRequestPosterWalletAddress = wallet_address
226        .parse()
227        .map_err(|e| CmdError::Usage(format!("--wallet-address rejected by schema: {e}")))?;
228
229    let completion_criteria = resolve_criteria(args.criteria_file.as_deref(), &args.criteria)?;
230
231    let prep_body = TaskDraftPrepareRequest {
232        assignment_type: args.assignment_type.into(),
233        budget_max: args.budget.clone(),
234        completion_criteria,
235        description: args.description.clone(),
236        direct_agent_id,
237        execution_deadline,
238        pickup_deadline_hours: args.pickup_deadline_hours.into(),
239        poster_wallet_address: poster_wallet,
240        required_capabilities: args.capabilities.clone(),
241        title: args.title.clone(),
242    };
243
244    // Dry-run must perform zero HTTP. Predict the proxy URL locally so the
245    // envelope still reports what the real path would have used.
246    if ctx.dry_run {
247        let network = ctx.environment.network();
248        let rpc_url = if let Some(ref override_url) = args.rpc_url {
249            validate_override_rpc_url(override_url, network, ctx.allow_custom_endpoints)?;
250            override_url.clone()
251        } else {
252            format!(
253                "{}/rpc/{}",
254                ctx.base_url().trim_end_matches('/'),
255                network.as_str()
256            )
257        };
258        return Ok(Envelope::success(
259            ctx.environment,
260            ctx.dry_run,
261            json!({
262                "action": "would_post",
263                "draft_id": serde_json::Value::Null,
264                "title": args.title,
265                "assignment_type": args.assignment_type.as_str(),
266                "budget_max": args.budget,
267                "required_capabilities": args.capabilities,
268                "completion_criteria_count": prep_body.completion_criteria.len(),
269                "rpc_url": rpc_url,
270                "wallet_address": wallet_address,
271            }),
272        ));
273    }
274
275    let client = ctx.client()?;
276
277    // Resolve the RPC URL. Default path: pull it from the deployment's
278    // `GET /config/network` (public). Override path: user supplied
279    // `--rpc-url` / `TEMPO_RPC_URL` and must also pass
280    // `--allow-custom-endpoints`.
281    let (rpc_url, _via_proxy) = resolve_rpc_url(&client, &args, ctx).await?;
282
283    // Phase 1 — prepare. Server returns ERC-20 transfer calldata + draft_id.
284    let prep = match client.inner().prepare_task_draft(&prep_body).await {
285        Ok(r) => r.into_inner(),
286        Err(e) => return Err(map_api_error(e).await.into()),
287    };
288
289    let token_address: Address = prep.token_address.parse().map_err(|e| {
290        CmdError::Server(format!(
291            "server returned invalid token_address `{}`: {e}",
292            prep.token_address
293        ))
294    })?;
295    let calldata = decode_0x_bytes(&prep.payload_to_sign)
296        .map_err(|e| CmdError::Server(format!("server returned invalid payload_to_sign: {e}")))?;
297
298    // Load signer only after prepare succeeds — avoids prompting the user for
299    // a keystore password on a request that never leaves local validation.
300    let keystore_ref = args.keystore.as_deref().map(str::to_string).or_else(|| {
301        ctx.keystore_path
302            .as_deref()
303            .and_then(|p| p.to_str().map(str::to_string))
304    });
305    let signer = super::wallet_args::load_signer(
306        keystore_ref.as_deref(),
307        args.wallet_password_file.as_deref(),
308        "submission fee",
309    )?;
310    // Sanity: the wallet address in the draft must match what we're signing
311    // with. A mismatch means the server recorded a charge on a wallet we
312    // don't control, which would poll forever.
313    let parsed_wallet_address = wallet_address
314        .parse::<Address>()
315        .map_err(|_| CmdError::Usage(format!("invalid wallet address: {}", wallet_address)))?;
316    if signer.address() != parsed_wallet_address {
317        return Err(CmdError::Usage(format!(
318            "keystore address {:#x} does not match --wallet-address {}",
319            signer.address(),
320            wallet_address
321        )));
322    }
323
324    // Pick the http client by URL, not by resolution branch: any URL
325    // landing on `{api_base}/rpc/` is the authenticated proxy and
326    // needs `X-API-Key` (set as a default header on `client.http_client()`).
327    // A `--rpc-url`/`TEMPO_RPC_URL` override that points at the proxy
328    // hit this same path; the prior `via_proxy` flag missed that case
329    // and dropped the header, returning 401 "missing API key".
330    let http = ctx.rpc_http_client(&client, &rpc_url);
331    let rpc = TempoRpcClient::new(http, rpc_url.clone());
332
333    // F1: consult the chain's own `eth_chainId` (not anything the server
334    // claims) and refuse to sign a `transfer` against a token that isn't
335    // on the PathUSD allowlist for that chain. A compromised TaskFast API
336    // returning an attacker `token_address` is the fund-drain vector here.
337    let chain_id = rpc
338        .chain_id()
339        .await
340        .map_err(|e| CmdError::Server(format!("tempo rpc eth_chainId: {e}")))?;
341    if !ctx.allow_custom_endpoints && !is_known_network(chain_id) {
342        return Err(CmdError::Validation {
343            code: "unknown_chain".into(),
344            message: format!(
345                "RPC reports chain_id={chain_id} which is not a known Tempo or \
346                 local-dev network; refusing to sign. Pass --allow-custom-endpoints \
347                 to override."
348            ),
349        });
350    }
351    if !is_allowed_fee_token(chain_id, &prep.token_address) {
352        return Err(CmdError::Validation {
353            code: "fee_token_not_allowed".into(),
354            message: format!(
355                "server returned token_address {} which is not on the PathUSD \
356                 allowlist for chain_id={chain_id}. Refusing to sign — this would \
357                 redirect your fee transfer to an arbitrary ERC-20 contract.",
358                prep.token_address
359            ),
360        });
361    }
362
363    // Audit line — always emitted to stderr so a CI log captures the exact
364    // recipient+token+chain we committed funds to. Not a prompt: CLI stays
365    // non-interactive.
366    eprintln!(
367        "taskfast: signing submission-fee transfer — token={} chain_id={} rpc={}",
368        prep.token_address, chain_id, rpc_url
369    );
370
371    // F9: serialize nonce-consuming sign+broadcast per wallet. `_guard`
372    // holds the exclusive file lock from here until function return,
373    // which scope-covers both eth_getTransactionCount (inside
374    // sign_and_broadcast_erc20_transfer) and eth_sendRawTransaction.
375    // Locked on the keystore path (stripping the optional `file:` prefix
376    // that `taskfast init` writes) so two processes sharing a keystore
377    // can't race, while distinct wallets proceed in parallel.
378    let _guard = if let Some(ref raw) = keystore_ref {
379        let path_str = raw.strip_prefix("file:").unwrap_or(raw);
380        Some(crate::wallet_lock::acquire(std::path::Path::new(path_str))?)
381    } else {
382        None
383    };
384
385    let tx_hash =
386        sign_and_broadcast_erc20_transfer(&rpc, &signer, token_address, Bytes::from(calldata))
387            .await
388            .map_err(|e| CmdError::Server(format!("tempo rpc: {e}")))?;
389    let tx_hash_hex = format!("{tx_hash:#x}");
390
391    // Phase 2 — submit voucher. The field is named `signature` for historical
392    // reasons; semantically it's a voucher (tx hash, in our path).
393    let signature: TaskDraftSubmitRequestSignature = tx_hash_hex
394        .parse()
395        .map_err(|e| CmdError::Server(format!("tx hash rejected by schema pattern: {e}")))?;
396    let submit_body = TaskDraftSubmitRequest { signature };
397    let submitted = match client
398        .inner()
399        .submit_task_draft(&prep.draft_id, &submit_body)
400        .await
401    {
402        Ok(r) => r.into_inner(),
403        Err(e) => return Err(map_api_error(e).await.into()),
404    };
405
406    Ok(Envelope::success(
407        ctx.environment,
408        ctx.dry_run,
409        json!({
410            "task_id": submitted.id,
411            "draft_id": prep.draft_id,
412            "submission_fee_tx_hash": tx_hash_hex,
413            "status": submitted.status,
414            "submission_fee_status": submitted.submission_fee_status,
415        }),
416    ))
417}
418
419/// Resolve the RPC endpoint for a post invocation.
420///
421/// Returns `(url, via_proxy)`:
422///   * `(override, false)` — user supplied `--rpc-url` / `TEMPO_RPC_URL`,
423///     passed the custom-endpoint guard, and will hit a bare upstream RPC.
424///   * `(proxy_url, true)` — default path: the deployment's
425///     `/config/network` entry for the selected network points the CLI
426///     at `{api_base}/rpc/{network}`, which the server proxies to its
427///     own Tempo upstream (Alchemy by default). The caller should carry
428///     the authenticated reqwest::Client through to `TempoRpcClient`.
429async fn resolve_rpc_url(
430    client: &TaskFastClient,
431    args: &Args,
432    ctx: &Ctx,
433) -> Result<(String, bool), CmdError> {
434    let network = ctx.environment.network();
435    if let Some(ref override_url) = args.rpc_url {
436        validate_override_rpc_url(override_url, network, ctx.allow_custom_endpoints)?;
437        return Ok((override_url.clone(), false));
438    }
439    let cfg = client.fetch_network_config().await.map_err(|e| match e {
440        taskfast_client::Error::Auth(_) | taskfast_client::Error::Validation { .. } => {
441            CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
442        }
443        other => CmdError::from(other),
444    })?;
445    // Runtime invariant — issue #62 (server-side): the env's deployment must
446    // advertise exactly its one network, and nothing else.
447    //
448    // Today's deployments still advertise multiple networks per response;
449    // until #62 lands, a `len != 1` mismatch logs a warn and continues.
450    // Set TASKFAST_STRICT_ENV_NETWORK=1 to fail-closed.
451    // `--allow-custom-endpoints` and `Environment::Local` bypass entirely
452    // (matches `enforce_endpoint_guard`).
453    let name = network.as_str();
454    if !ctx.allow_custom_endpoints
455        && ctx.environment != crate::Environment::Local
456        && cfg.networks.len() != 1
457    {
458        let advertised: Vec<&str> = cfg.networks.keys().map(String::as_str).collect();
459        let strict = std::env::var("TASKFAST_STRICT_ENV_NETWORK")
460            .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
461        if strict {
462            return Err(CmdError::Server(format!(
463                "deployment at {} advertises networks {advertised:?}; env {} requires \
464                 exactly [{name}]. Server-side fix tracked in issue #62. Unset \
465                 TASKFAST_STRICT_ENV_NETWORK or pass --allow-custom-endpoints to bypass.",
466                ctx.base_url(),
467                ctx.environment.as_str(),
468            )));
469        }
470        tracing::warn!(
471            api_base = %ctx.base_url(),
472            env = ctx.environment.as_str(),
473            expected = name,
474            advertised = ?advertised,
475            "deployment advertises additional networks; server-side fix tracked in #62. \
476             Set TASKFAST_STRICT_ENV_NETWORK=1 to fail-closed."
477        );
478    }
479    let entry = cfg.entry(name).map_err(|e| {
480        CmdError::Server(format!(
481            "deployment at {} does not advertise network `{name}`: {e}",
482            ctx.base_url()
483        ))
484    })?;
485    // F2-equivalent guard, minus the static allowlist: the old
486    // WELL_KNOWN_TEMPO_RPCS check trusted exactly two hardcoded URLs. The
487    // replacement says "the proxy must live on the same host as the api_base
488    // the endpoint-guard already approved" — the path it's mounted at
489    // (`/rpc/…` or `/api/rpc/…`) is the server's choice. Catches (a) a
490    // misconfigured deployment returning an upstream URL instead of its own
491    // proxy, and (b) a compromised backend trying to steer RPC traffic
492    // off-host — minus a full MITM on api_base itself (which has its own
493    // F5/F6 defenses).
494    if !is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
495        return Err(CmdError::Server(format!(
496            "deployment at {} returned rpc_url {:?} for network `{name}`, \
497             which is not on the same host. Refusing to route RPC traffic \
498             off-host.",
499            ctx.base_url(),
500            entry.rpc_url,
501        )));
502    }
503    Ok((entry.rpc_url.clone(), true))
504}
505
506/// Merge file-sourced and inline `--criterion` payloads into one validated
507/// list of `CompletionCriterionInput`. File entries are prepended so a
508/// shared base file can be augmented with one-off overrides on the command
509/// line. Any shape/parse failure is a `Usage` error — the CLI catches it
510/// before the request ever reaches the server, so the exit-code contract
511/// (Auth=re-credential, Validation=server-rejected payload) stays clean.
512fn resolve_criteria(
513    file: Option<&std::path::Path>,
514    inline: &[String],
515) -> Result<Vec<CompletionCriterionInput>, CmdError> {
516    let mut out = Vec::with_capacity(inline.len());
517    if let Some(path) = file {
518        let raw = std::fs::read_to_string(path).map_err(|e| {
519            CmdError::Usage(format!("read --criteria-file {}: {e}", path.display()))
520        })?;
521        let parsed: Vec<CompletionCriterionInput> = serde_json::from_str(&raw).map_err(|e| {
522            CmdError::Usage(format!(
523                "--criteria-file {} is not a JSON array of CompletionCriterionInput: {e}",
524                path.display()
525            ))
526        })?;
527        out.extend(parsed);
528    }
529    for (i, raw) in inline.iter().enumerate() {
530        let one: CompletionCriterionInput = serde_json::from_str(raw)
531            .map_err(|e| CmdError::Usage(format!("--criterion[{i}] not valid JSON: {e}")))?;
532        out.push(one);
533    }
534    Ok(out)
535}
536
537fn parse_iso_opt(
538    s: Option<&str>,
539    flag: &str,
540) -> Result<Option<chrono::DateTime<chrono::Utc>>, CmdError> {
541    match s {
542        None => Ok(None),
543        Some(raw) => chrono::DateTime::parse_from_rfc3339(raw)
544            .map(|d| Some(d.with_timezone(&chrono::Utc)))
545            .map_err(|e| CmdError::Usage(format!("{flag} not a valid RFC3339 timestamp: {e}"))),
546    }
547}
548
549fn decode_0x_bytes(s: &str) -> Result<Vec<u8>, String> {
550    let stripped = s.strip_prefix("0x").unwrap_or(s);
551    hex::decode(stripped).map_err(|e| e.to_string())
552}
553
554#[cfg(test)]
555mod tests {
556    use super::*;
557    use crate::Network;
558
559    #[test]
560    fn validate_override_rejects_without_opt_in() {
561        let err = validate_override_rpc_url("https://mallory.example", Network::Mainnet, false)
562            .expect_err("override without opt-in must be refused");
563        match err {
564            CmdError::Usage(msg) => {
565                assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
566            }
567            other => panic!("expected Usage, got {other:?}"),
568        }
569    }
570
571    #[test]
572    fn validate_override_accepts_with_opt_in() {
573        validate_override_rpc_url("https://my-node.example", Network::Testnet, true)
574            .expect("opt-in bypasses the guard");
575    }
576
577    #[test]
578    fn validate_override_rejects_plain_http_on_mainnet() {
579        let err = validate_override_rpc_url("http://my-node.example", Network::Mainnet, true)
580            .expect_err("plain-http on mainnet is always refused (except loopback)");
581        assert!(matches!(err, CmdError::Usage(msg) if msg.contains("plain-HTTP")));
582    }
583
584    #[test]
585    fn validate_override_allows_plain_http_loopback_on_mainnet() {
586        validate_override_rpc_url("http://127.0.0.1:8545", Network::Mainnet, true)
587            .expect("loopback bypasses mainnet-HTTPS check");
588        validate_override_rpc_url("http://localhost:8545", Network::Mainnet, true)
589            .expect("loopback bypasses mainnet-HTTPS check");
590    }
591
592    #[test]
593    fn validate_override_allows_plain_http_on_testnet() {
594        validate_override_rpc_url("http://my-testnet.example", Network::Testnet, true)
595            .expect("testnet does not enforce HTTPS");
596    }
597
598    #[test]
599    fn pickup_hours_rejects_out_of_set_and_maps_to_wire() {
600        use clap::ValueEnum;
601        // clap rejects a value outside the schema's allowed set — client-side,
602        // before any request is built.
603        assert!(PickupDeadlineHours::from_str("3", false).is_err());
604        // A valid choice parses and converts to the exact wire integer.
605        let hours = PickupDeadlineHours::from_str("24", false).expect("24 is valid");
606        let wire: TaskDraftPrepareRequestPickupDeadlineHours = hours.into();
607        assert_eq!(i64::from(wire), 24);
608    }
609
610    #[test]
611    fn network_name_matches_config_map_keys() {
612        // The lookup key into `GET /config/network`'s `networks` map.
613        // Must stay in sync with what the deployment advertises.
614        assert_eq!(Network::Mainnet.as_str(), "mainnet");
615        assert_eq!(Network::Testnet.as_str(), "testnet");
616    }
617}