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. EIP-712 `DistributionDomain` from those params (chain_id +
10//!     task_escrow_contract) — the venue's escrow for zone-bound tasks.
11//!  3. ERC-20 `allowance` preflight; `approve` if short.
12//!  4. Random 32-byte salt → `compute_escrow_id` (matches Solidity).
13//!  5. EIP-712 `DistributionApproval(escrowId, deadline)` — `sign_distribution`.
14//!  6. `TaskEscrow.open` / `openWithMemo` — broadcast + wait for receipt.
15//!  7. `POST /bids/:id/escrow/finalize` with voucher + sig + deadline.
16//!
17//! Memo is server-driven: `memo_hash` in the params payload selects
18//! `openWithMemo` vs `open`. No `--memo` flag.
19//!
20//! Error mapping delegates to `map_api_error` (401|403→Auth, 409|422→
21//! Validation). Keystore / signing failures surface as `Wallet` (exit 5).
22
23use std::path::PathBuf;
24use std::str::FromStr;
25use std::time::Duration;
26
27use alloy_primitives::{Address, Bytes, B256, U256};
28use alloy_sol_types::SolCall;
29use clap::Parser;
30use serde_json::json;
31use uuid::Uuid;
32
33use super::{
34    is_proxy_rpc_url, network_policy_for_chain_id, parse_duration, validate_override_rpc_url,
35    CmdError, CmdResult, Ctx,
36};
37use crate::envelope::Envelope;
38
39use taskfast_agent::chain::{compute_escrow_id, EscrowIdParams, TaskEscrow};
40use taskfast_agent::tempo_rpc::TempoRpcClient;
41use taskfast_chains::tempo::{sign_distribution, DistributionDomain};
42use taskfast_client::api::types::{
43    BidEscrowFinalizeRequest, BidEscrowFinalizeRequestPosterApprovalDeadline,
44    BidEscrowParamsResponse,
45};
46use taskfast_client::map_api_error;
47
48#[derive(Debug, clap::Subcommand)]
49pub enum Command {
50    /// Sign + broadcast the on-chain escrow for a deferred bid; POST finalize.
51    Sign(SignArgs),
52}
53
54#[derive(Debug, Parser)]
55pub struct SignArgs {
56    /// Bid UUID. Bid must be in `:accepted_pending_escrow`; caller must be
57    /// the parent task's poster.
58    pub bid_id: String,
59
60    /// Keystore reference (same form as `taskfast post` / `settle`).
61    #[arg(long, env = "TEMPO_KEY_SOURCE")]
62    pub keystore: Option<String>,
63
64    /// Path to keystore password file.
65    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
66    pub wallet_password_file: Option<PathBuf>,
67
68    /// Poster wallet address preflight (0x-prefixed). When set, we fail
69    /// before touching the chain if the keystore decrypts to a mismatch.
70    #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
71    pub wallet_address: Option<String>,
72
73    /// Tempo RPC override. Defaults to the deployment's authenticated
74    /// proxy URL for `params.chain_id` (reverse-looked-up in the
75    /// `GET /config/network` map returned by the backend).
76    #[arg(long, env = "TEMPO_RPC_URL")]
77    pub rpc_url: Option<String>,
78
79    /// Skip the on-chain `allowance` preflight + `approve` tx. Only safe when
80    /// the caller already granted a sufficient allowance out-of-band.
81    #[arg(long)]
82    pub skip_allowance_check: bool,
83
84    /// Receipt-polling ceiling — human duration (`3min`, `90s`). Falls
85    /// back to `receipt_timeout` in config, then a chain-aware default
86    /// (3min mainnet, 1min testnet).
87    #[arg(
88        long,
89        env = "TASKFAST_RECEIPT_TIMEOUT",
90        value_parser = parse_duration,
91    )]
92    pub receipt_timeout: Option<Duration>,
93}
94
95pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
96    match cmd {
97        Command::Sign(a) => sign(ctx, a).await,
98    }
99}
100
101async fn sign(ctx: &Ctx, args: SignArgs) -> CmdResult {
102    // 1. Validate bid UUID locally.
103    let bid_id = Uuid::parse_str(&args.bid_id)
104        .map_err(|e| CmdError::Usage(format!("bid id must be a UUID: {e}")))?;
105
106    let client = ctx.client()?;
107
108    // 2. Fetch escrow params — server enforces poster-auth + bid status.
109    let params = match client.inner().get_bid_escrow_params(&bid_id).await {
110        Ok(v) => v.into_inner(),
111        Err(e) => {
112            let mapped = map_api_error(e).await;
113            // Version-skew hint: a server predating the v2 arbitrated-escrow
114            // rollout omits `arbitrator_address`, which this CLI now requires,
115            // so the 200 body fails to deserialize into a generic serde
116            // "missing field" decode error. Surface something actionable.
117            // ponytail: substring-match the stable serde message; revisit if
118            // the generated field is ever renamed.
119            if matches!(&mapped, taskfast_client::Error::Decode(_))
120                && mapped.to_string().contains("arbitrator_address")
121            {
122                return Err(CmdError::Validation {
123                    code: "server_missing_arbitrator".into(),
124                    message: "server omitted `arbitrator_address`; this deployment predates \
125                              v2 arbitrated escrow — upgrade the server or use a CLI version \
126                              that matches it"
127                        .into(),
128                });
129            }
130            // Same version-skew shape for the server-issued deadline: a server
131            // predating the deadline-floor rollout omits `poster_approval_*`,
132            // which this CLI now requires (it no longer computes a deadline).
133            if matches!(&mapped, taskfast_client::Error::Decode(_))
134                && (mapped.to_string().contains("poster_approval_deadline")
135                    || mapped.to_string().contains("poster_approval_min_lifetime"))
136            {
137                return Err(CmdError::Validation {
138                    code: "server_missing_approval_deadline".into(),
139                    message: "server omitted `poster_approval_deadline`; this deployment predates \
140                              the server-issued escrow deadline — upgrade the server or use a CLI \
141                              version that matches it"
142                        .into(),
143                });
144            }
145            return Err(mapped.into());
146        }
147    };
148
149    // 3. The EIP-712 signing domain comes from the escrow params themselves
150    //    (chain_id + task_escrow_contract), built below once task_escrow is
151    //    parsed. For a zone-bound task that is the venue's escrow — the
152    //    contract that verifies the DistributionApproval. Sourcing the domain
153    //    from the global `GET /agents/me/readiness` settlement_domain instead
154    //    hard-failed zone tasks whose escrow lives off the L1 contract (gh#111).
155
156    // 4. Parse addresses + scale decimal amounts to U256 raw units.
157    let token_address: Address = params.token_address.parse().map_err(|e| {
158        CmdError::Decode(format!(
159            "server token_address `{}` not a valid EVM address: {e}",
160            params.token_address
161        ))
162    })?;
163    let task_escrow: Address = params.task_escrow_contract.parse().map_err(|e| {
164        CmdError::Decode(format!(
165            "server task_escrow_contract `{}` not a valid EVM address: {e}",
166            params.task_escrow_contract
167        ))
168    })?;
169    let worker: Address = params.worker_address.parse().map_err(|e| {
170        CmdError::Decode(format!(
171            "server worker_address `{}` not a valid EVM address: {e}",
172            params.worker_address
173        ))
174    })?;
175    let platform_wallet: Address = params.platform_wallet.parse().map_err(|e| {
176        CmdError::Decode(format!(
177            "server platform_wallet `{}` not a valid EVM address: {e}",
178            params.platform_wallet
179        ))
180    })?;
181    // Canonical v2 ArbitratedEscrow binds the arbitrator into open/openWithMemo,
182    // the escrow-id preimage, and EscrowOpened. Omitting it reverts the open on
183    // the v2 contract and breaks server-side arbitrator validation (gh#674).
184    let arbitrator: Address = params.arbitrator_address.parse().map_err(|e| {
185        CmdError::Decode(format!(
186            "server arbitrator_address `{}` not a valid EVM address: {e}",
187            params.arbitrator_address
188        ))
189    })?;
190    // A zero arbitrator is never valid on v2: `open` reverts with
191    // arbitrator_not_in_pool. Reject it client-side before signing/broadcast
192    // rather than burning the approve tx's gas on a doomed open (gh#674).
193    if arbitrator == Address::ZERO {
194        return Err(CmdError::Decode(
195            "server returned a zero arbitrator_address; the v2 escrow open requires a \
196             pool arbitrator and would revert (arbitrator_not_in_pool)"
197                .to_string(),
198        ));
199    }
200
201    // Signing domain: the escrow that will verify the DistributionApproval is
202    // task_escrow_contract itself (the venue's escrow for a zone-bound task),
203    // so it is the EIP-712 verifying contract. chain_id likewise comes from the
204    // per-task params, not the global readiness domain (gh#111).
205    let chain_id_u64 = u64::try_from(params.chain_id).map_err(|_| {
206        CmdError::Decode(format!(
207            "escrow params chain_id={} is negative",
208            params.chain_id
209        ))
210    })?;
211    let verifying_contract = task_escrow;
212    let domain = DistributionDomain::new(chain_id_u64, verifying_contract);
213
214    let decimals = u8::try_from(params.decimals).map_err(|_| {
215        CmdError::Decode(format!(
216            "escrow params decimals={} out of u8 range",
217            params.decimals
218        ))
219    })?;
220    let deposit = decimal_to_u256(&params.amount, decimals)?;
221    let platform_fee = decimal_to_u256(&params.platform_fee_amount, decimals)?;
222
223    // 5. Optional memo — pass through exactly; server re-derives authoritative
224    //    memo on finalize, so a client mismatch is a Validation error there.
225    let memo_hash_opt: Option<B256> = params
226        .memo_hash
227        .as_deref()
228        .map(|s| {
229            B256::from_str(s).map_err(|e| {
230                CmdError::Decode(format!(
231                    "server memo_hash `{s}` not a 0x-prefixed 32-byte hex: {e}"
232                ))
233            })
234        })
235        .transpose()?;
236
237    // 6. Load signer + preflight address equality.
238    let keystore_path = super::wallet_args::resolve_keystore_path(
239        args.keystore.as_deref(),
240        ctx.keystore_path.as_deref(),
241    );
242    let signer = super::wallet_args::load_signer_and_validate(
243        keystore_path.as_deref(),
244        args.wallet_password_file.as_deref(),
245        args.wallet_address
246            .as_deref()
247            .or(ctx.wallet_address.as_deref()),
248        "escrow approval",
249    )?;
250
251    // 7. Derive random salt + predicted escrow_id. Must byte-match Solidity
252    //    `TaskEscrow.computeEscrowId`. See
253    //    `taskfast-agent::chain::compute_escrow_id` for the caveat on
254    //    fee-on-transfer tokens.
255    let salt = B256::from(rand::random::<[u8; 32]>());
256    let escrow_id = compute_escrow_id(&EscrowIdParams {
257        poster: signer.address(),
258        worker,
259        token: token_address,
260        deposit,
261        platform_fee_amount: platform_fee,
262        platform: platform_wallet,
263        arbitrator,
264        salt,
265    });
266
267    // 8. Sign DistributionApproval(escrowId, deadline). The deadline is the
268    //    server-issued `poster_approval_deadline` (absolute Unix seconds), signed
269    //    verbatim — the CLI is a dumb orchestrator and does not own this policy
270    //    value. Defense-in-depth: if the just-fetched deadline already has less
271    //    than `poster_approval_min_lifetime` remaining, abort *before* any tx so
272    //    we never strand funds behind an approval the server would reject at
273    //    finalize (gh#118 / taskfast#935).
274    let mut deadline_unix = server_deadline_or_abort(&params)?;
275    let mut signature_hex =
276        sign_distribution(&signer, &domain, escrow_id, U256::from(deadline_unix))?;
277
278    // 9. Build open / openWithMemo calldata up front — we reuse it for the
279    //    dry-run envelope and the live broadcast.
280    let open_calldata: Bytes = if let Some(memo_hash) = memo_hash_opt {
281        TaskEscrow::openWithMemoCall {
282            token: token_address,
283            deposit,
284            worker,
285            platformFeeAmount: platform_fee,
286            platform: platform_wallet,
287            arbitrator,
288            salt,
289            memoHash: memo_hash,
290        }
291        .abi_encode()
292        .into()
293    } else {
294        TaskEscrow::openCall {
295            token: token_address,
296            deposit,
297            worker,
298            platformFeeAmount: platform_fee,
299            platform: platform_wallet,
300            arbitrator,
301            salt,
302        }
303        .abi_encode()
304        .into()
305    };
306
307    // Resolve RPC URL. Override flows to a bare upstream gateway; default
308    // path pulls the deployment's proxy URL from `GET /config/network`
309    // (reverse-lookup by chain_id, so the selected entry matches the
310    // server-returned escrow params). The proxy URL is sanity-checked to
311    // live under the authenticated api_base — catches a misconfigured (or
312    // malicious) deployment returning an off-host upstream.
313    let (rpc_url, _via_proxy) = if let Some(ref url) = args.rpc_url {
314        validate_override_rpc_url(
315            url,
316            network_policy_for_chain_id(chain_id_u64),
317            ctx.allow_custom_endpoints,
318        )?;
319        (url.clone(), false)
320    } else {
321        let cfg = client.fetch_network_config().await.map_err(|e| {
322            CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
323        })?;
324        let (_name, entry) = cfg.entry_by_chain_id(params.chain_id).map_err(|e| {
325            CmdError::Server(format!(
326                "deployment at {} does not advertise chain_id={}: {e}",
327                ctx.base_url(),
328                params.chain_id
329            ))
330        })?;
331        // Same-host guard as post::resolve_proxy_rpc_url — the proxy may be mounted
332        // at any path on api_base (`/rpc/…` or `/api/rpc/…`); only the host
333        // must match so the API key never leaves the approved deployment.
334        if !is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
335            return Err(CmdError::Server(format!(
336                "deployment at {} returned rpc_url {:?} for chain_id={}, \
337                 which is not on the same host. Refusing to route RPC \
338                 traffic off-host.",
339                ctx.base_url(),
340                entry.rpc_url,
341                params.chain_id,
342            )));
343        }
344        (entry.rpc_url.clone(), true)
345    };
346
347    if ctx.dry_run {
348        return Ok(Envelope::success(
349            ctx.environment,
350            ctx.dry_run,
351            json!({
352                "action": "would_sign_escrow",
353                "bid_id": bid_id.to_string(),
354                "task_id": params.task_id.to_string(),
355                "escrow_id": format!("{escrow_id:#x}"),
356                "arbitrator": format!("{arbitrator:#x}"),
357                "salt": format!("{salt:#x}"),
358                "deadline": deadline_unix,
359                "signature": signature_hex,
360                "open_calldata": format!("0x{}", hex::encode(&open_calldata)),
361                "memo_hash": params.memo_hash,
362                "rpc_url": rpc_url,
363                "domain": {
364                    "chain_id": chain_id_u64,
365                    "verifying_contract": format!("{verifying_contract:#x}"),
366                },
367            }),
368        ));
369    }
370
371    let http = ctx.rpc_http_client(&client, &rpc_url);
372    let rpc = TempoRpcClient::new(http, rpc_url);
373    let default_timeout = crate::tempo_session::default_receipt_timeout_for_chain_id(chain_id_u64);
374    let receipt_timeout =
375        super::resolve_duration(args.receipt_timeout, ctx.receipt_timeout, default_timeout);
376    let session =
377        crate::tempo_session::TempoSession::new(signer, keystore_path, rpc, receipt_timeout);
378
379    // 10. Live RPC: allowance preflight + optional approve.
380    //     TaskEscrow.open calls transferFrom for `deposit + platformFeeAmount` in a
381    //     single call, so balance/allowance/approve must cover the sum — not
382    //     just deposit.
383    let total_required = deposit
384        .checked_add(platform_fee)
385        .ok_or_else(|| CmdError::Decode("deposit + platform_fee overflow U256".into()))?;
386
387    let mut approval_tx_hex: Option<String> = None;
388    if !args.skip_allowance_check {
389        let balance = session
390            .erc20_balance_of(token_address, session.address())
391            .await?;
392        if balance < total_required {
393            return Err(CmdError::Usage(format!(
394                "poster balance {balance} < required {total_required} (deposit {deposit} + fee {platform_fee}) on token {token_address:#x}"
395            )));
396        }
397        approval_tx_hex = session
398            .ensure_allowance(token_address, task_escrow, total_required)
399            .await?
400            .map(|h| format!("{h:#x}"));
401    }
402
403    // 11. Broadcast TaskEscrow.open / openWithMemo, wait for receipt.
404    let voucher_tx = session
405        .send_transaction_and_wait(
406            task_escrow,
407            open_calldata,
408            "open",
409            Some(" — finalize aborted"),
410        )
411        .await?;
412    let voucher_hex = format!("{voucher_tx:#x}");
413
414    // 12. POST finalize. The escrow is already funded on-chain, so the voucher
415    //     (open tx hash / escrowId) and salt are fixed. If the server rejects the
416    //     signed deadline as `deadline_below_minimum` (a fetch gone stale between
417    //     params and finalize), re-fetch params and re-sign *the same voucher*
418    //     with the fresh deadline — a cheap re-sign, no new tx, no orphaned
419    //     escrow. Bounded to one retry; the pre-broadcast abort makes it rare.
420    let mut attempts = 0u8;
421    let resp = loop {
422        // Checked back to i64 at the API boundary — `deadline_unix` originates as
423        // the i64 `poster_approval_deadline`, so this always fits, but an explicit
424        // conversion refuses to silently wrap if the generated type ever widens.
425        let deadline_i64 = i64::try_from(deadline_unix)
426            .map_err(|_| CmdError::Decode(format!("deadline {deadline_unix} exceeds i64 range")))?;
427        let body = BidEscrowFinalizeRequest {
428            voucher: voucher_hex.clone(),
429            poster_approval_signature: signature_hex.clone(),
430            poster_approval_deadline: BidEscrowFinalizeRequestPosterApprovalDeadline::Integer(
431                deadline_i64,
432            ),
433            memo_hash: params.memo_hash.clone(),
434        };
435        match client.inner().finalize_bid_escrow(&bid_id, &body).await {
436            Ok(r) => break r.into_inner(),
437            Err(e) => {
438                let mapped = map_api_error(e).await;
439                if attempts == 0 && is_deadline_below_minimum(&mapped) {
440                    attempts += 1;
441                    let fresh = match client.inner().get_bid_escrow_params(&bid_id).await {
442                        Ok(v) => v.into_inner(),
443                        Err(e) => return Err(map_api_error(e).await.into()),
444                    };
445                    deadline_unix = server_deadline_or_abort(&fresh)?;
446                    signature_hex = sign_distribution(
447                        session.signer(),
448                        &domain,
449                        escrow_id,
450                        U256::from(deadline_unix),
451                    )?;
452                    continue;
453                }
454                return Err(mapped.into());
455            }
456        }
457    };
458
459    Ok(Envelope::success(
460        ctx.environment,
461        ctx.dry_run,
462        json!({
463            "bid_id": resp.bid_id,
464            "task_id": resp.task_id,
465            "status": resp.status,
466            "task_status": resp.task_status,
467            "escrow_id": format!("{escrow_id:#x}"),
468            "voucher_tx_hash": voucher_hex,
469            "approval_tx_hash": approval_tx_hex,
470            "deadline": deadline_unix,
471        }),
472    ))
473}
474
475/// Return the server-issued `poster_approval_deadline` (Unix seconds) after the
476/// defense-in-depth floor check: if it already carries less than
477/// `poster_approval_min_lifetime` remaining, abort so no tx is ever broadcast
478/// against an approval the server would reject at finalize (gh#118). This should
479/// never fire when params are fetched immediately before signing — it catches a
480/// stale fetch, clock skew, or a retry.
481fn server_deadline_or_abort(params: &BidEscrowParamsResponse) -> Result<u64, CmdError> {
482    let deadline = u64::try_from(params.poster_approval_deadline).map_err(|_| {
483        CmdError::Decode(format!(
484            "server poster_approval_deadline={} is negative",
485            params.poster_approval_deadline
486        ))
487    })?;
488    let min_lifetime = u64::try_from(params.poster_approval_min_lifetime).map_err(|_| {
489        CmdError::Decode(format!(
490            "server poster_approval_min_lifetime={} is negative",
491            params.poster_approval_min_lifetime
492        ))
493    })?;
494    let now = u64::try_from(jiff::Timestamp::now().as_second())
495        .map_err(|_| CmdError::Decode("system clock before epoch".into()))?;
496    let remaining = deadline.saturating_sub(now);
497    if remaining < min_lifetime {
498        return Err(CmdError::Validation {
499            code: "deadline_below_minimum".into(),
500            message: format!(
501                "server-issued deadline has {remaining}s remaining, below the \
502                 {min_lifetime}s minimum — aborting rather than sign an approval the \
503                 server will reject. Re-run once the server re-issues a deadline."
504            ),
505        });
506    }
507    Ok(deadline)
508}
509
510/// True when the API surfaced the server's `deadline_below_minimum` finalize
511/// rejection, so the caller can re-fetch params + re-sign rather than fail hard.
512fn is_deadline_below_minimum(err: &taskfast_client::Error) -> bool {
513    matches!(
514        err,
515        taskfast_client::Error::Validation { code, .. } if code == "deadline_below_minimum"
516    )
517}
518
519/// Scale a decimal string (`"75.00"`) to raw U256 token units given `decimals`.
520/// Rejects negatives, exponential notation, and fractional digits that exceed
521/// `decimals` (would silently truncate user intent).
522fn decimal_to_u256(s: &str, decimals: u8) -> Result<U256, CmdError> {
523    let trimmed = s.trim();
524    if trimmed.is_empty() {
525        return Err(CmdError::Decode("empty decimal amount".into()));
526    }
527    if trimmed.starts_with('-') {
528        return Err(CmdError::Decode(format!(
529            "negative amount `{s}` disallowed"
530        )));
531    }
532    let (whole, frac) = match trimmed.split_once('.') {
533        Some((w, f)) => (w, f),
534        None => (trimmed, ""),
535    };
536    let frac_len = frac.len();
537    if frac_len > decimals as usize {
538        return Err(CmdError::Decode(format!(
539            "amount `{s}` has {frac_len} fractional digits but token has only {decimals}"
540        )));
541    }
542    let mut combined = String::with_capacity(whole.len() + decimals as usize);
543    combined.push_str(whole);
544    combined.push_str(frac);
545    for _ in 0..(decimals as usize - frac_len) {
546        combined.push('0');
547    }
548    // Strip leading zeros but keep at least one digit so "0" parses.
549    let stripped = combined.trim_start_matches('0');
550    let digits = if stripped.is_empty() { "0" } else { stripped };
551    U256::from_str_radix(digits, 10)
552        .map_err(|e| CmdError::Decode(format!("amount `{s}` not parseable as integer: {e}")))
553}
554
555#[cfg(test)]
556mod tests {
557    use super::*;
558    use taskfast_chains::tempo::TEMPO_MAINNET_CHAIN_ID;
559
560    fn default_receipt_timeout(chain_id: i64) -> Duration {
561        match u64::try_from(chain_id) {
562            Ok(id) => crate::tempo_session::default_receipt_timeout_for_chain_id(id),
563            _ => crate::tempo_session::DEFAULT_RECEIPT_TIMEOUT_TESTNET,
564        }
565    }
566
567    #[test]
568    fn decimal_to_u256_scales_basic() {
569        assert_eq!(
570            decimal_to_u256("75.00", 6).unwrap(),
571            U256::from(75_000_000u64)
572        );
573        assert_eq!(decimal_to_u256("75", 6).unwrap(), U256::from(75_000_000u64));
574        assert_eq!(decimal_to_u256("0.5", 6).unwrap(), U256::from(500_000u64));
575        assert_eq!(decimal_to_u256("0", 6).unwrap(), U256::ZERO);
576    }
577
578    #[test]
579    fn decimal_to_u256_rejects_excess_fractional_digits() {
580        let err = decimal_to_u256("1.1234567", 6).expect_err("7 > 6 must fail");
581        matches!(err, CmdError::Decode(_));
582    }
583
584    #[test]
585    fn decimal_to_u256_rejects_negative() {
586        let err = decimal_to_u256("-1.00", 6).expect_err("negative must fail");
587        matches!(err, CmdError::Decode(_));
588    }
589
590    #[test]
591    fn chain_id_constants_match_tempo_protocol() {
592        use taskfast_chains::tempo::TEMPO_TESTNET_CHAIN_ID;
593        // Pinned against server truth (`lib/task_fast/payments/tempo_constants.ex`)
594        // and the `DistributionDomain` domain-separator consumer. Drift here
595        // would desync the EIP-712 signing domain from the on-chain verifier.
596        assert_eq!(TEMPO_MAINNET_CHAIN_ID, 4_217);
597        assert_eq!(TEMPO_TESTNET_CHAIN_ID, 42_431);
598    }
599
600    #[test]
601    fn default_receipt_timeout_mainnet_is_three_minutes() {
602        assert_eq!(default_receipt_timeout(4_217), Duration::from_mins(3));
603    }
604
605    #[test]
606    fn default_receipt_timeout_testnet_is_one_minute() {
607        assert_eq!(default_receipt_timeout(42_431), Duration::from_mins(1));
608    }
609
610    #[test]
611    fn default_receipt_timeout_unknown_chain_falls_back_to_testnet_budget() {
612        // Dev / anvil chains get the shorter budget — mirrors `default_rpc_for`.
613        assert_eq!(default_receipt_timeout(31_337), Duration::from_mins(1));
614    }
615
616    #[test]
617    fn deadline_below_minimum_detects_only_that_code() {
618        assert!(is_deadline_below_minimum(
619            &taskfast_client::Error::Validation {
620                code: "deadline_below_minimum".into(),
621                message: "x".into(),
622            }
623        ));
624        assert!(!is_deadline_below_minimum(
625            &taskfast_client::Error::Validation {
626                code: "validation_error".into(),
627                message: "x".into(),
628            }
629        ));
630        assert!(!is_deadline_below_minimum(&taskfast_client::Error::Server(
631            "deadline_below_minimum".into()
632        )));
633    }
634}