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