Skip to main content

taskfast_cli/cmd/
settle.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast settle` — poster signs an EIP-712 `DistributionApproval` and
3//! POSTs it to `/tasks/{id}/settle` to release escrowed funds.
4//!
5//! Pairs with server bead am-iyp6. The signing surface is identical to the
6//! one pinned in `taskfast_chains::tempo::sign_distribution`. The domain
7//! (`chain_id`, `verifying_contract`) prefers the task's per-task
8//! `settlement_domain` (venue-scoped — a Tempo Zone escrow for a zone-bound
9//! task; gh#865, ADR 0011 §5) and falls back to the global
10//! `GET /agents/me/readiness` domain when the task carries none, so the same
11//! binary signs correctly on L1 testnet/mainnet and in a zone without
12//! client-side chain config.
13//!
14//! Flow: parse UUID → `get_task` (pull `escrow_id` + `settlement_deadline` +
15//! `settlement_domain`) → readiness only if no per-task domain → sign →
16//! `POST /tasks/{id}/settle`. Dry-run skips the final POST but still signs
17//! so the envelope carries a real signature the caller can audit.
18//!
19//! Error mapping delegates to the shared `map_api_error` (401|403→Auth,
20//! 409|422→Validation); signing/keystore failures surface as `Wallet`
21//! (exit 5) via `SigningError`/`KeystoreError` → `CmdError`.
22
23use std::path::PathBuf;
24use std::str::FromStr;
25
26use alloy_primitives::{Address, B256, U256};
27use clap::Parser;
28use serde_json::json;
29use uuid::Uuid;
30
31use super::{CmdError, CmdResult, Ctx};
32use crate::envelope::Envelope;
33
34use taskfast_agent::bootstrap;
35use taskfast_chains::tempo::{sign_distribution, DistributionDomain};
36use taskfast_client::api::types::SettleTaskBody;
37use taskfast_client::map_api_error;
38
39#[derive(Debug, Parser)]
40pub struct Args {
41    /// Task UUID to settle. Task must have `escrow_id` + `settlement_deadline`
42    /// populated (i.e. escrow was created) and be in `:complete` or
43    /// `:disbursement_pending` on the server.
44    pub task_id: String,
45
46    /// Override the deadline signed into the approval. Defaults to the task's
47    /// `settlement_deadline` returned by `GET /tasks/{id}`. Unix seconds.
48    #[arg(long)]
49    pub deadline_unix: Option<u64>,
50
51    /// Keystore reference. Accepts a bare path (`/.../wallet.json`) or the
52    /// `file:/path` form written by `taskfast init` to `TEMPO_KEY_SOURCE`.
53    /// Mirrors `taskfast post`'s flag so a single keystore serves both verbs.
54    #[arg(long, env = "TEMPO_KEY_SOURCE")]
55    pub keystore: Option<String>,
56
57    /// Path to a file holding the keystore password (mode-0400 recommended).
58    /// `TASKFAST_WALLET_PASSWORD` env wins over this when both are set so CI
59    /// workflows can keep using the env-var form.
60    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
61    pub wallet_password_file: Option<PathBuf>,
62
63    /// Poster's wallet address (0x-prefixed). When present, we fail early if
64    /// the keystore decrypts to a different address — otherwise the server
65    /// would 422 after the round-trip. Purely a UX preflight.
66    #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
67    pub wallet_address: Option<String>,
68
69    /// Acknowledge oversized budgets. Required when the task's budget
70    /// exceeds `confirm_above_budget` in the config. Mirrors the same
71    /// gate on `taskfast post`; both fail closed before any keystore
72    /// prompt or signing.
73    #[arg(long)]
74    pub yes: bool,
75}
76
77pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
78    // 1. Validate UUID upfront — bad input must not cost a round-trip.
79    let task_id = Uuid::parse_str(&args.task_id)
80        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
81
82    let client = ctx.client()?;
83
84    // 2. Fetch task detail — we need escrow_id + settlement_deadline.
85    let task = match client.inner().get_task(&task_id).await {
86        Ok(v) => v.into_inner(),
87        Err(e) => return Err(map_api_error(e).await.into()),
88    };
89
90    // Fail-closed budget gate before keystore prompt or signing — a
91    // fat-finger settle on a huge task should die immediately.
92    ctx.enforce_budget_gate(task.budget_max.as_deref(), args.yes, "settle this task")?;
93
94    let escrow_id_hex: String =
95        task.escrow_id
96            .as_ref()
97            .map(|e| e.to_string())
98            .ok_or_else(|| {
99                CmdError::Usage(
100                    "task has no escrow_id; settle requires an initialized escrow \
101                 (task must be in :complete or :disbursement_pending)"
102                        .into(),
103                )
104            })?;
105
106    // 3. Resolve deadline: explicit override wins; otherwise require the
107    //    server-stored value. Either can be absent but not both.
108    let deadline_unix: u64 = match args.deadline_unix {
109        Some(n) => n,
110        None => {
111            let dt = task.settlement_deadline.ok_or_else(|| {
112                CmdError::Usage(
113                    "task has no settlement_deadline; either wait for escrow \
114                     creation or pass --deadline-unix explicitly"
115                        .into(),
116                )
117            })?;
118            // `timestamp()` is i64; clamp to u64 for the uint256. A negative
119            // server-side deadline is nonsensical; treat as decode.
120            u64::try_from(dt.timestamp()).map_err(|_| {
121                CmdError::Decode(format!(
122                    "task settlement_deadline is before epoch: {}",
123                    dt.to_rfc3339()
124                ))
125            })?
126        }
127    };
128
129    // 4. EIP-712 domain. Prefer the task's per-task `settlement_domain` — the
130    //    venue-scoped domain (a Tempo Zone escrow + chain_id for a zone-bound
131    //    task) that this task's escrow actually verifies against. Fall back to
132    //    the global `GET /agents/me/readiness` domain only when the task carries
133    //    none — a default-venue task, whose venue IS the readiness L1 domain, so
134    //    the two are identical. Signing a zone task against the L1 domain would
135    //    verify against the wrong escrow and the server would reject it (gh#865,
136    //    ADR 0011 §5; mirrors the `escrow sign` fix in gh#111).
137    let (raw_chain_id, verifying_contract_str): (i64, String) =
138        match task.settlement_domain.as_ref() {
139            Some(d) => (d.chain_id, d.verifying_contract.to_string()),
140            None => {
141                let readiness = bootstrap::get_readiness(&client)
142                    .await
143                    .map_err(CmdError::from)?;
144                let d = readiness.settlement_domain;
145                (d.chain_id, d.verifying_contract.to_string())
146            }
147        };
148    let verifying_contract: Address = verifying_contract_str.parse().map_err(|e| {
149        CmdError::Decode(format!(
150            "settlement domain has invalid verifying_contract `{verifying_contract_str}`: {e}"
151        ))
152    })?;
153    let chain_id: u64 = u64::try_from(raw_chain_id).map_err(|_| {
154        CmdError::Decode(format!(
155            "settlement domain has negative chain_id: {raw_chain_id}"
156        ))
157    })?;
158    let domain = DistributionDomain::new(chain_id, verifying_contract);
159
160    // 5. Parse escrow_id. The server's schema already regex-validates the
161    //    shape; we re-parse locally to produce a `B256` for signing. A parse
162    //    failure here would be a server contract violation.
163    let escrow_id: B256 = B256::from_str(&escrow_id_hex).map_err(|e| {
164        CmdError::Decode(format!(
165            "server returned invalid escrow_id `{escrow_id_hex}`: {e}"
166        ))
167    })?;
168    let deadline = U256::from(deadline_unix);
169
170    // 6. Load keystore. Bead spec calls for the signature to appear in the
171    //    dry-run envelope, so we sign even in dry-run and never short-circuit
172    //    before keystore resolution.
173    let keystore_ref = args.keystore.as_deref().map(str::to_string).or_else(|| {
174        ctx.keystore_path
175            .as_deref()
176            .and_then(|p| p.to_str().map(str::to_string))
177    });
178    let signer = super::wallet_args::load_signer(
179        keystore_ref.as_deref(),
180        args.wallet_password_file.as_deref(),
181        "settlement approval",
182    )?;
183
184    // 7. Optional preflight: keystore must match --wallet-address if given.
185    //    Without this, a mismatch surfaces as a server 422 after the full
186    //    round-trip (including the get_task + readiness calls above).
187    let wallet_address_for_check = args
188        .wallet_address
189        .as_deref()
190        .or(ctx.wallet_address.as_deref());
191    if let Some(expected) = wallet_address_for_check {
192        let expected_addr: Address = expected.parse().map_err(|e| {
193            CmdError::Usage(format!("--wallet-address is not a valid EVM address: {e}"))
194        })?;
195        if signer.address() != expected_addr {
196            return Err(CmdError::Usage(format!(
197                "keystore address {:#x} does not match --wallet-address {}",
198                signer.address(),
199                expected
200            )));
201        }
202    }
203
204    // 8. Sign the DistributionApproval. `sign_distribution` returns the
205    //    132-char 0x-prefixed `r||s||v` shape the server's verifier expects.
206    let signature_hex = sign_distribution(&signer, &domain, escrow_id, deadline)?;
207
208    // 9. Dry-run fork — envelope carries the real signature so callers can
209    //    audit it (e.g., `cast wallet verify` or the Elixir verifier fixture)
210    //    before committing the live POST.
211    if ctx.dry_run {
212        return Ok(Envelope::success(
213            ctx.environment,
214            ctx.dry_run,
215            json!({
216                "action": "would_settle",
217                "task_id": task_id.to_string(),
218                "escrow_id": escrow_id_hex,
219                "deadline": deadline_unix,
220                "domain": {
221                    "chain_id": chain_id,
222                    "verifying_contract": verifying_contract_str,
223                },
224                "signature": signature_hex,
225            }),
226        ));
227    }
228
229    // 10. Live POST. `signature` is a plain string in the current spec; the
230    //     `0x`-prefixed 65-byte EIP-712 shape is validated server-side. A
231    //     malformed value here would mean `sign_distribution` regressed
232    //     (crypto-layer bug), not a network/server issue.
233    let body = SettleTaskBody {
234        signature: signature_hex,
235    };
236    let resp = match client.inner().settle_task(&task_id, &body).await {
237        Ok(v) => v.into_inner(),
238        Err(e) => return Err(map_api_error(e).await.into()),
239    };
240
241    Ok(Envelope::success(
242        ctx.environment,
243        ctx.dry_run,
244        json!({
245            "task_id": resp.task_id,
246            "status": resp.status,
247        }),
248    ))
249}