Skip to main content

taskfast_cli/cmd/
escrow.rs

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