Skip to main content

taskfast_cli/cmd/
escrow.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast escrow sign <bid_id>` — headless poster escrow signing.
3//!
4//! Replaces the web-UI-only wagmi + passkey path at `assets/js/escrow_sign.js`.
5//! Picks up bids the server parked in `:accepted_pending_escrow` after
6//! `taskfast bid accept` and drives them to `:accepted` without a browser:
7//!
8//!  1. `GET /bids/:id/escrow/params` → server-derived on-chain params.
9//!  2. `GET /agents/me/readiness` → EIP-712 `DistributionDomain`.
10//!  3. ERC-20 `allowance` preflight; `approve` if short.
11//!  4. Random 32-byte salt → `compute_escrow_id` (matches Solidity).
12//!  5. EIP-712 `DistributionApproval(escrowId, deadline)` — `sign_distribution`.
13//!  6. `TaskEscrow.open` / `openWithMemo` — broadcast + wait for receipt.
14//!  7. `POST /bids/:id/escrow/finalize` with voucher + sig + deadline.
15//!
16//! Memo is server-driven: `memo_hash` in the params payload selects
17//! `openWithMemo` vs `open`. No `--memo` flag.
18//!
19//! Error mapping delegates to `map_api_error` (401|403→Auth, 409|422→
20//! Validation). Keystore / signing failures surface as `Wallet` (exit 5).
21
22use std::path::PathBuf;
23use std::str::FromStr;
24use std::time::Duration;
25
26use alloy_primitives::{Address, Bytes, B256, U256};
27use alloy_sol_types::SolCall;
28use clap::Parser;
29use serde_json::json;
30use uuid::Uuid;
31
32use super::{network_policy_for_chain_id, validate_override_rpc_url, CmdError, CmdResult, Ctx};
33use crate::envelope::Envelope;
34
35use taskfast_agent::bootstrap;
36use taskfast_agent::chain::{compute_escrow_id, TaskEscrow, IERC20};
37use taskfast_agent::tempo_rpc::{sign_and_broadcast_tx, TempoRpcClient};
38use taskfast_chains::tempo::{sign_distribution, DistributionDomain};
39use taskfast_client::api::types::{
40    BidEscrowFinalizeRequest, BidEscrowFinalizeRequestPosterApprovalDeadline,
41};
42use taskfast_client::map_api_error;
43
44/// Tempo chain IDs — must match `DistributionDomain::mainnet`/`testnet`.
45/// Used by the network-aware receipt-timeout default. RPC URLs are no
46/// longer hardcoded here; they come from `GET /config/network`.
47const TEMPO_MAINNET_CHAIN_ID: i64 = 4217;
48const TEMPO_TESTNET_CHAIN_ID: i64 = 42_431;
49
50/// Poster approval deadline horizon — built-in default when neither the
51/// `--approval-horizon` flag nor `approval_horizon` in the config file
52/// is set. 7 days tightens the blast radius on a leaked keystore vs the
53/// prior 30-day hardcode; CI flows that need the old window set
54/// `TASKFAST_APPROVAL_HORIZON=30d` or the config field.
55const DEFAULT_APPROVAL_HORIZON: Duration = Duration::from_hours(24 * 7);
56
57/// `TaskEscrow.open()` receipt polling defaults. Mainnet gets a 3min
58/// ceiling to ride out block-time jitter under congestion; testnet keeps
59/// the prior 1min budget. Unknown chain_ids fall back to 1min.
60const DEFAULT_RECEIPT_TIMEOUT_MAINNET: Duration = Duration::from_mins(3);
61const DEFAULT_RECEIPT_TIMEOUT_TESTNET: Duration = Duration::from_mins(1);
62const RECEIPT_POLL_INTERVAL: Duration = Duration::from_secs(2);
63
64/// Network-aware default receipt-timeout used when the caller supplies
65/// neither `--receipt-timeout` nor `receipt_timeout` in config.
66fn default_receipt_timeout(chain_id: i64) -> Duration {
67    match chain_id {
68        TEMPO_MAINNET_CHAIN_ID => DEFAULT_RECEIPT_TIMEOUT_MAINNET,
69        TEMPO_TESTNET_CHAIN_ID => DEFAULT_RECEIPT_TIMEOUT_TESTNET,
70        _ => DEFAULT_RECEIPT_TIMEOUT_TESTNET,
71    }
72}
73
74#[derive(Debug, clap::Subcommand)]
75pub enum Command {
76    /// Sign + broadcast the on-chain escrow for a deferred bid; POST finalize.
77    Sign(SignArgs),
78}
79
80#[derive(Debug, Parser)]
81pub struct SignArgs {
82    /// Bid UUID. Bid must be in `:accepted_pending_escrow`; caller must be
83    /// the parent task's poster.
84    pub bid_id: String,
85
86    /// Keystore reference (same form as `taskfast post` / `settle`).
87    #[arg(long, env = "TEMPO_KEY_SOURCE")]
88    pub keystore: Option<String>,
89
90    /// Path to keystore password file.
91    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
92    pub wallet_password_file: Option<PathBuf>,
93
94    /// Poster wallet address preflight (0x-prefixed). When set, we fail
95    /// before touching the chain if the keystore decrypts to a mismatch.
96    #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
97    pub wallet_address: Option<String>,
98
99    /// Tempo RPC override. Defaults to the deployment's authenticated
100    /// proxy URL for `params.chain_id` (reverse-looked-up in the
101    /// `GET /config/network` map returned by the backend).
102    #[arg(long, env = "TEMPO_RPC_URL")]
103    pub rpc_url: Option<String>,
104
105    /// Skip the on-chain `allowance` preflight + `approve` tx. Only safe when
106    /// the caller already granted a sufficient allowance out-of-band.
107    #[arg(long)]
108    pub skip_allowance_check: bool,
109
110    /// Poster approval-deadline horizon — accepts human durations like
111    /// `7d`, `24h`, `3600s`. Falls back to `approval_horizon` in config,
112    /// then the built-in 7-day default.
113    #[arg(
114        long,
115        env = "TASKFAST_APPROVAL_HORIZON",
116        value_parser = humantime::parse_duration,
117    )]
118    pub approval_horizon: Option<Duration>,
119
120    /// Receipt-polling ceiling — human duration (`3min`, `90s`). Falls
121    /// back to `receipt_timeout` in config, then a chain-aware default
122    /// (3min mainnet, 1min testnet).
123    #[arg(
124        long,
125        env = "TASKFAST_RECEIPT_TIMEOUT",
126        value_parser = humantime::parse_duration,
127    )]
128    pub receipt_timeout: Option<Duration>,
129}
130
131pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
132    match cmd {
133        Command::Sign(a) => sign(ctx, a).await,
134    }
135}
136
137async fn sign(ctx: &Ctx, args: SignArgs) -> CmdResult {
138    // 1. Validate bid UUID locally.
139    let bid_id = Uuid::parse_str(&args.bid_id)
140        .map_err(|e| CmdError::Usage(format!("bid id must be a UUID: {e}")))?;
141
142    let client = ctx.client()?;
143
144    // 2. Fetch escrow params — server enforces poster-auth + bid status.
145    let params = match client.inner().get_bid_escrow_params(&bid_id).await {
146        Ok(v) => v.into_inner(),
147        Err(e) => return Err(map_api_error(e).await.into()),
148    };
149
150    // 3. Readiness → EIP-712 domain. settlement_domain must be populated
151    //    and cross-consistent with params.chain_id.
152    let readiness = bootstrap::get_readiness(&client)
153        .await
154        .map_err(CmdError::from)?;
155    let domain_spec = readiness.settlement_domain;
156    if domain_spec.chain_id != params.chain_id {
157        return Err(CmdError::Decode(format!(
158            "readiness chain_id={} disagrees with escrow params chain_id={}",
159            domain_spec.chain_id, params.chain_id
160        )));
161    }
162    let verifying_contract_str = domain_spec.verifying_contract.to_string();
163    let verifying_contract: Address = verifying_contract_str.parse().map_err(|e| {
164        CmdError::Decode(format!(
165            "readiness returned invalid verifying_contract `{verifying_contract_str}`: {e}"
166        ))
167    })?;
168    let chain_id_u64 = u64::try_from(params.chain_id).map_err(|_| {
169        CmdError::Decode(format!(
170            "escrow params chain_id={} is negative",
171            params.chain_id
172        ))
173    })?;
174    let domain = DistributionDomain::new(chain_id_u64, verifying_contract);
175
176    // 4. Parse addresses + scale decimal amounts to U256 raw units.
177    let token_address: Address = params.token_address.parse().map_err(|e| {
178        CmdError::Decode(format!(
179            "server token_address `{}` not a valid EVM address: {e}",
180            params.token_address
181        ))
182    })?;
183    let task_escrow: Address = params.task_escrow_contract.parse().map_err(|e| {
184        CmdError::Decode(format!(
185            "server task_escrow_contract `{}` not a valid EVM address: {e}",
186            params.task_escrow_contract
187        ))
188    })?;
189    let worker: Address = params.worker_address.parse().map_err(|e| {
190        CmdError::Decode(format!(
191            "server worker_address `{}` not a valid EVM address: {e}",
192            params.worker_address
193        ))
194    })?;
195    let platform_wallet: Address = params.platform_wallet.parse().map_err(|e| {
196        CmdError::Decode(format!(
197            "server platform_wallet `{}` not a valid EVM address: {e}",
198            params.platform_wallet
199        ))
200    })?;
201
202    // Cross-check: the readiness domain's verifying_contract must equal the
203    // task_escrow contract returned by params. A mismatch means the server
204    // is stitching two different chain configs — signing against that would
205    // yield an unrecoverable signature.
206    if verifying_contract != task_escrow {
207        return Err(CmdError::Decode(format!(
208            "readiness verifying_contract={verifying_contract:#x} \
209             disagrees with escrow params task_escrow_contract={task_escrow:#x}"
210        )));
211    }
212
213    let decimals = u8::try_from(params.decimals).map_err(|_| {
214        CmdError::Decode(format!(
215            "escrow params decimals={} out of u8 range",
216            params.decimals
217        ))
218    })?;
219    let deposit = decimal_to_u256(&params.amount, decimals)?;
220    let platform_fee = decimal_to_u256(&params.platform_fee_amount, decimals)?;
221
222    // 5. Optional memo — pass through exactly; server re-derives authoritative
223    //    memo on finalize, so a client mismatch is a Validation error there.
224    let memo_hash_opt: Option<B256> = params
225        .memo_hash
226        .as_deref()
227        .map(|s| {
228            B256::from_str(s).map_err(|e| {
229                CmdError::Decode(format!(
230                    "server memo_hash `{s}` not a 0x-prefixed 32-byte hex: {e}"
231                ))
232            })
233        })
234        .transpose()?;
235
236    // 6. Load signer + preflight address equality.
237    let keystore_ref = args.keystore.as_deref().map(str::to_string).or_else(|| {
238        ctx.keystore_path
239            .as_deref()
240            .and_then(|p| p.to_str().map(str::to_string))
241    });
242    let signer = super::wallet_args::load_signer(
243        keystore_ref.as_deref(),
244        args.wallet_password_file.as_deref(),
245        "escrow approval",
246    )?;
247    let wallet_address_for_check = args
248        .wallet_address
249        .as_deref()
250        .or(ctx.wallet_address.as_deref());
251    if let Some(expected) = wallet_address_for_check {
252        let expected_addr: Address = expected.parse().map_err(|e| {
253            CmdError::Usage(format!("--wallet-address is not a valid EVM address: {e}"))
254        })?;
255        if signer.address() != expected_addr {
256            return Err(CmdError::Usage(format!(
257                "keystore address {:#x} does not match --wallet-address {}",
258                signer.address(),
259                expected
260            )));
261        }
262    }
263
264    // 7. Derive random salt + predicted escrow_id. Must byte-match Solidity
265    //    `TaskEscrow.computeEscrowId`. See
266    //    `taskfast-agent::chain::compute_escrow_id` for the caveat on
267    //    fee-on-transfer tokens.
268    let salt = B256::from(rand::random::<[u8; 32]>());
269    let escrow_id = compute_escrow_id(
270        signer.address(),
271        worker,
272        token_address,
273        deposit,
274        platform_fee,
275        platform_wallet,
276        salt,
277    );
278
279    // 8. Sign DistributionApproval(escrowId, deadline). Deadline is absolute
280    //    seconds. Horizon precedence: flag > config > 7d built-in default.
281    let approval_horizon = super::resolve_duration(
282        args.approval_horizon,
283        ctx.approval_horizon,
284        DEFAULT_APPROVAL_HORIZON,
285    );
286    let deadline_unix = u64::try_from(chrono::Utc::now().timestamp())
287        .map_err(|_| CmdError::Decode("system clock before epoch".into()))?
288        .saturating_add(approval_horizon.as_secs());
289    let deadline = U256::from(deadline_unix);
290    let signature_hex = sign_distribution(&signer, &domain, escrow_id, deadline)?;
291
292    // 9. Build open / openWithMemo calldata up front — we reuse it for the
293    //    dry-run envelope and the live broadcast.
294    let open_calldata: Bytes = if let Some(memo_hash) = memo_hash_opt {
295        TaskEscrow::openWithMemoCall {
296            token: token_address,
297            deposit,
298            worker,
299            platformFeeAmount: platform_fee,
300            platform: platform_wallet,
301            salt,
302            memoHash: memo_hash,
303        }
304        .abi_encode()
305        .into()
306    } else {
307        TaskEscrow::openCall {
308            token: token_address,
309            deposit,
310            worker,
311            platformFeeAmount: platform_fee,
312            platform: platform_wallet,
313            salt,
314        }
315        .abi_encode()
316        .into()
317    };
318
319    // Resolve RPC URL. Override flows to a bare upstream gateway; default
320    // path pulls the deployment's proxy URL from `GET /config/network`
321    // (reverse-lookup by chain_id, so the selected entry matches the
322    // server-returned escrow params). The proxy URL is sanity-checked to
323    // live under the authenticated api_base — catches a misconfigured (or
324    // malicious) deployment returning an off-host upstream.
325    let (rpc_url, _via_proxy) = if let Some(ref url) = args.rpc_url {
326        validate_override_rpc_url(
327            url,
328            network_policy_for_chain_id(chain_id_u64),
329            ctx.allow_custom_endpoints,
330        )?;
331        (url.clone(), false)
332    } else {
333        let cfg = client.fetch_network_config().await.map_err(|e| {
334            CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
335        })?;
336        let (_name, entry) = cfg.entry_by_chain_id(params.chain_id).map_err(|e| {
337            CmdError::Server(format!(
338                "deployment at {} does not advertise chain_id={}: {e}",
339                ctx.base_url(),
340                params.chain_id
341            ))
342        })?;
343        let expected_prefix = format!("{}/rpc/", ctx.base_url().trim_end_matches('/'));
344        if !entry.rpc_url.starts_with(&expected_prefix) {
345            return Err(CmdError::Server(format!(
346                "deployment at {} returned rpc_url {:?} for chain_id={}, \
347                 which does not live under `{expected_prefix}…`. Refusing \
348                 to route RPC traffic off-host.",
349                ctx.base_url(),
350                entry.rpc_url,
351                params.chain_id,
352            )));
353        }
354        (entry.rpc_url.clone(), true)
355    };
356
357    if ctx.dry_run {
358        return Ok(Envelope::success(
359            ctx.environment,
360            ctx.dry_run,
361            json!({
362                "action": "would_sign_escrow",
363                "bid_id": bid_id.to_string(),
364                "task_id": params.task_id.to_string(),
365                "escrow_id": format!("{escrow_id:#x}"),
366                "salt": format!("{salt:#x}"),
367                "deadline": deadline_unix,
368                "signature": signature_hex,
369                "open_calldata": format!("0x{}", hex::encode(&open_calldata)),
370                "memo_hash": params.memo_hash,
371                "rpc_url": rpc_url,
372                "domain": {
373                    "chain_id": chain_id_u64,
374                    "verifying_contract": format!("{verifying_contract:#x}"),
375                },
376            }),
377        ));
378    }
379
380    // Receipt-timeout precedence: flag > config > network-aware default.
381    // Resolved here (post-`params.chain_id`) so both approve + open receipts
382    // share the same ceiling.
383    let receipt_timeout = super::resolve_duration(
384        args.receipt_timeout,
385        ctx.receipt_timeout,
386        default_receipt_timeout(params.chain_id),
387    );
388
389    // 10. Live RPC: allowance preflight + optional approve.
390    //     TaskEscrow.open calls transferFrom for `deposit + platformFeeAmount` in a
391    //     single call, so balance/allowance/approve must cover the sum — not
392    //     just deposit.
393    let total_required = deposit
394        .checked_add(platform_fee)
395        .ok_or_else(|| CmdError::Decode("deposit + platform_fee overflow U256".into()))?;
396    // Pick the http client by URL prefix (any URL on `{api_base}/rpc/`
397    // is our authenticated proxy and needs `X-API-Key`); see
398    // `Ctx::rpc_http_client` for the rationale. A `--rpc-url` override that
399    // happens to point at the proxy still gets the authenticated client.
400    let http = ctx.rpc_http_client(&client, &rpc_url);
401    let rpc = TempoRpcClient::new(http, rpc_url.clone());
402    let mut approval_tx_hex: Option<String> = None;
403    if !args.skip_allowance_check {
404        let balance = erc20_balance_of(&rpc, token_address, signer.address()).await?;
405        if balance < total_required {
406            return Err(CmdError::Usage(format!(
407                "poster balance {balance} < required {total_required} (deposit {deposit} + fee {platform_fee}) on token {token_address:#x}"
408            )));
409        }
410        let current_allowance =
411            erc20_allowance(&rpc, token_address, signer.address(), task_escrow).await?;
412        if current_allowance < total_required {
413            let approve_calldata: Bytes = IERC20::approveCall {
414                spender: task_escrow,
415                amount: total_required,
416            }
417            .abi_encode()
418            .into();
419            let approve_hash =
420                sign_and_broadcast_tx(&rpc, &signer, token_address, approve_calldata)
421                    .await
422                    .map_err(|e| CmdError::Server(format!("approve broadcast failed: {e}")))?;
423            let ok = rpc
424                .wait_for_receipt(approve_hash, receipt_timeout, RECEIPT_POLL_INTERVAL)
425                .await
426                .map_err(|e| CmdError::Server(format!("approve receipt: {e}")))?;
427            if !ok {
428                return Err(CmdError::Server(format!(
429                    "approve tx {approve_hash:#x} reverted on-chain"
430                )));
431            }
432            let new_allowance =
433                erc20_allowance(&rpc, token_address, signer.address(), task_escrow).await?;
434            if new_allowance < total_required {
435                return Err(CmdError::Server(format!(
436                    "allowance still {new_allowance} after approve tx {approve_hash:#x} (needed {total_required})"
437                )));
438            }
439            approval_tx_hex = Some(format!("{approve_hash:#x}"));
440        }
441    }
442
443    // 11. Broadcast TaskEscrow.open / openWithMemo, wait for receipt.
444    let voucher_tx = sign_and_broadcast_tx(&rpc, &signer, task_escrow, open_calldata)
445        .await
446        .map_err(|e| CmdError::Server(format!("open broadcast failed: {e}")))?;
447    let voucher_ok = rpc
448        .wait_for_receipt(voucher_tx, receipt_timeout, RECEIPT_POLL_INTERVAL)
449        .await
450        .map_err(|e| CmdError::Server(format!("open receipt: {e}")))?;
451    if !voucher_ok {
452        return Err(CmdError::Server(format!(
453            "open tx {voucher_tx:#x} reverted on-chain — finalize aborted"
454        )));
455    }
456    let voucher_hex = format!("{voucher_tx:#x}");
457
458    // 12. POST finalize.
459    let body = BidEscrowFinalizeRequest {
460        voucher: voucher_hex.clone(),
461        poster_approval_signature: signature_hex.clone(),
462        poster_approval_deadline: BidEscrowFinalizeRequestPosterApprovalDeadline::Integer(
463            deadline_unix as i64,
464        ),
465        memo_hash: params.memo_hash.clone(),
466    };
467    let resp = match client.inner().finalize_bid_escrow(&bid_id, &body).await {
468        Ok(r) => r.into_inner(),
469        Err(e) => return Err(map_api_error(e).await.into()),
470    };
471
472    Ok(Envelope::success(
473        ctx.environment,
474        ctx.dry_run,
475        json!({
476            "bid_id": resp.bid_id,
477            "task_id": resp.task_id,
478            "status": resp.status,
479            "task_status": resp.task_status,
480            "escrow_id": format!("{escrow_id:#x}"),
481            "voucher_tx_hash": voucher_hex,
482            "approval_tx_hash": approval_tx_hex,
483            "deadline": deadline_unix,
484        }),
485    ))
486}
487
488async fn erc20_balance_of(
489    rpc: &TempoRpcClient,
490    token: Address,
491    owner: Address,
492) -> Result<U256, CmdError> {
493    let calldata: Bytes = IERC20::balanceOfCall { account: owner }.abi_encode().into();
494    let raw = rpc
495        .eth_call(token, &calldata)
496        .await
497        .map_err(|e| CmdError::Server(format!("balanceOf rpc: {e}")))?;
498    decode_u256(&raw, "balanceOf")
499}
500
501async fn erc20_allowance(
502    rpc: &TempoRpcClient,
503    token: Address,
504    owner: Address,
505    spender: Address,
506) -> Result<U256, CmdError> {
507    let calldata: Bytes = IERC20::allowanceCall { owner, spender }.abi_encode().into();
508    let raw = rpc
509        .eth_call(token, &calldata)
510        .await
511        .map_err(|e| CmdError::Server(format!("allowance rpc: {e}")))?;
512    decode_u256(&raw, "allowance")
513}
514
515fn decode_u256(bytes: &[u8], label: &str) -> Result<U256, CmdError> {
516    if bytes.len() < 32 {
517        return Err(CmdError::Decode(format!(
518            "{label} returned {} bytes, expected >=32",
519            bytes.len()
520        )));
521    }
522    Ok(U256::from_be_slice(&bytes[..32]))
523}
524
525/// Scale a decimal string (`"75.00"`) to raw U256 token units given `decimals`.
526/// Rejects negatives, exponential notation, and fractional digits that exceed
527/// `decimals` (would silently truncate user intent).
528fn decimal_to_u256(s: &str, decimals: u8) -> Result<U256, CmdError> {
529    let trimmed = s.trim();
530    if trimmed.is_empty() {
531        return Err(CmdError::Decode("empty decimal amount".into()));
532    }
533    if trimmed.starts_with('-') {
534        return Err(CmdError::Decode(format!(
535            "negative amount `{s}` disallowed"
536        )));
537    }
538    let (whole, frac) = match trimmed.split_once('.') {
539        Some((w, f)) => (w, f),
540        None => (trimmed, ""),
541    };
542    let frac_len = frac.len();
543    if frac_len > decimals as usize {
544        return Err(CmdError::Decode(format!(
545            "amount `{s}` has {frac_len} fractional digits but token has only {decimals}"
546        )));
547    }
548    let mut combined = String::with_capacity(whole.len() + decimals as usize);
549    combined.push_str(whole);
550    combined.push_str(frac);
551    for _ in 0..(decimals as usize - frac_len) {
552        combined.push('0');
553    }
554    // Strip leading zeros but keep at least one digit so "0" parses.
555    let stripped = combined.trim_start_matches('0');
556    let digits = if stripped.is_empty() { "0" } else { stripped };
557    U256::from_str_radix(digits, 10)
558        .map_err(|e| CmdError::Decode(format!("amount `{s}` not parseable as integer: {e}")))
559}
560
561#[cfg(test)]
562mod tests {
563    use super::*;
564
565    #[test]
566    fn decimal_to_u256_scales_basic() {
567        assert_eq!(
568            decimal_to_u256("75.00", 6).unwrap(),
569            U256::from(75_000_000u64)
570        );
571        assert_eq!(decimal_to_u256("75", 6).unwrap(), U256::from(75_000_000u64));
572        assert_eq!(decimal_to_u256("0.5", 6).unwrap(), U256::from(500_000u64));
573        assert_eq!(decimal_to_u256("0", 6).unwrap(), U256::ZERO);
574    }
575
576    #[test]
577    fn decimal_to_u256_rejects_excess_fractional_digits() {
578        let err = decimal_to_u256("1.1234567", 6).expect_err("7 > 6 must fail");
579        matches!(err, CmdError::Decode(_));
580    }
581
582    #[test]
583    fn decimal_to_u256_rejects_negative() {
584        let err = decimal_to_u256("-1.00", 6).expect_err("negative must fail");
585        matches!(err, CmdError::Decode(_));
586    }
587
588    #[test]
589    fn chain_id_constants_match_tempo_protocol() {
590        // Pinned against server truth (`lib/task_fast/payments/tempo_constants.ex`)
591        // and the `DistributionDomain` domain-separator consumer. Drift here
592        // would desync the EIP-712 signing domain from the on-chain verifier.
593        assert_eq!(TEMPO_MAINNET_CHAIN_ID, 4_217);
594        assert_eq!(TEMPO_TESTNET_CHAIN_ID, 42_431);
595    }
596
597    #[test]
598    fn default_receipt_timeout_mainnet_is_three_minutes() {
599        assert_eq!(
600            default_receipt_timeout(TEMPO_MAINNET_CHAIN_ID),
601            Duration::from_mins(3),
602        );
603    }
604
605    #[test]
606    fn default_receipt_timeout_testnet_is_one_minute() {
607        assert_eq!(
608            default_receipt_timeout(TEMPO_TESTNET_CHAIN_ID),
609            Duration::from_mins(1),
610        );
611    }
612
613    #[test]
614    fn default_receipt_timeout_unknown_chain_falls_back_to_testnet_budget() {
615        // Dev / anvil chains get the shorter budget — mirrors `default_rpc_for`.
616        assert_eq!(default_receipt_timeout(31_337), Duration::from_mins(1));
617    }
618
619    #[test]
620    fn default_approval_horizon_is_seven_days() {
621        // Pinned: the whole point of #9 is trimming the 30-day hardcode to
622        // 7 days. If someone widens it, the gate-tightening premise breaks.
623        assert_eq!(DEFAULT_APPROVAL_HORIZON, Duration::from_hours(24 * 7));
624    }
625}