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