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