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