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 = match task.escrow_id.as_ref().map(|e| e.to_string()) {
95        Some(e) => e,
96        None => {
97            // gh#143: dev auto-disburse settles without waiting for the
98            // poster's explicit `settle`, clearing the escrow data. When the
99            // task already reached (or is passing through) the settle target,
100            // report success with a note instead of the "no escrow_id" usage
101            // error — the goal the caller wanted is met. Missing escrow in
102            // any other state is a genuine not-ready error.
103            if let Some(note) = task.status.as_deref().and_then(settlement_note) {
104                return Ok(Envelope::success(
105                    ctx.environment,
106                    ctx.dry_run,
107                    json!({
108                        "task_id": task_id.to_string(),
109                        "status": task.status,
110                        "note": note,
111                    }),
112                ));
113            }
114            return Err(CmdError::Usage(
115                "task has no escrow_id; settle requires an initialized escrow \
116                 (task must be in :complete or :disbursement_pending)"
117                    .into(),
118            ));
119        }
120    };
121
122    // 3. Resolve deadline: explicit override wins; otherwise require the
123    //    server-stored value. Either can be absent but not both.
124    let deadline_unix: u64 = match args.deadline_unix {
125        Some(n) => n,
126        None => {
127            let dt = task.settlement_deadline.ok_or_else(|| {
128                CmdError::Usage(
129                    "task has no settlement_deadline; either wait for escrow \
130                     creation or pass --deadline-unix explicitly"
131                        .into(),
132                )
133            })?;
134            // `timestamp()` is i64; clamp to u64 for the uint256. A negative
135            // server-side deadline is nonsensical; treat as decode.
136            u64::try_from(dt.timestamp()).map_err(|_| {
137                CmdError::Decode(format!(
138                    "task settlement_deadline is before epoch: {}",
139                    dt.to_rfc3339()
140                ))
141            })?
142        }
143    };
144
145    // 4. EIP-712 domain. Prefer the task's per-task `settlement_domain` — the
146    //    venue-scoped domain (a Tempo Zone escrow + chain_id for a zone-bound
147    //    task) that this task's escrow actually verifies against. Fall back to
148    //    the global `GET /agents/me/readiness` domain only when the task carries
149    //    none — a default-venue task, whose venue IS the readiness L1 domain, so
150    //    the two are identical. Signing a zone task against the L1 domain would
151    //    verify against the wrong escrow and the server would reject it (gh#865,
152    //    ADR 0011 §5; mirrors the `escrow sign` fix in gh#111).
153    let (raw_chain_id, verifying_contract_str): (i64, String) =
154        match task.settlement_domain.as_ref() {
155            Some(d) => (d.chain_id, d.verifying_contract.to_string()),
156            None => {
157                let readiness = bootstrap::get_readiness(&client)
158                    .await
159                    .map_err(CmdError::from)?;
160                let d = readiness.settlement_domain;
161                (d.chain_id, d.verifying_contract.to_string())
162            }
163        };
164    let verifying_contract: Address = verifying_contract_str.parse().map_err(|e| {
165        CmdError::Decode(format!(
166            "settlement domain has invalid verifying_contract `{verifying_contract_str}`: {e}"
167        ))
168    })?;
169    let chain_id: u64 = u64::try_from(raw_chain_id).map_err(|_| {
170        CmdError::Decode(format!(
171            "settlement domain has negative chain_id: {raw_chain_id}"
172        ))
173    })?;
174    let domain = DistributionDomain::new(chain_id, verifying_contract);
175
176    // 5. Parse escrow_id. The server's schema already regex-validates the
177    //    shape; we re-parse locally to produce a `B256` for signing. A parse
178    //    failure here would be a server contract violation.
179    let escrow_id: B256 = B256::from_str(&escrow_id_hex).map_err(|e| {
180        CmdError::Decode(format!(
181            "server returned invalid escrow_id `{escrow_id_hex}`: {e}"
182        ))
183    })?;
184    let deadline = U256::from(deadline_unix);
185
186    // 6. Load keystore and validate --wallet-address preflight.
187    //    Bead spec calls for the signature to appear in the dry-run envelope,
188    //    so we sign even in dry-run and never short-circuit before keystore resolution.
189    let keystore_path = super::wallet_args::resolve_keystore_path(
190        args.keystore.as_deref(),
191        ctx.keystore_path.as_deref(),
192    );
193    let signer = super::wallet_args::load_signer_and_validate(
194        keystore_path.as_deref(),
195        args.wallet_password_file.as_deref(),
196        args.wallet_address
197            .as_deref()
198            .or(ctx.wallet_address.as_deref()),
199        "settlement approval",
200    )?;
201
202    // 8. Sign the DistributionApproval. `sign_distribution` returns the
203    //    132-char 0x-prefixed `r||s||v` shape the server's verifier expects.
204    let signature_hex = sign_distribution(&signer, &domain, escrow_id, deadline)?;
205
206    // 9. Dry-run fork — envelope carries the real signature so callers can
207    //    audit it (e.g., `cast wallet verify` or the Elixir verifier fixture)
208    //    before committing the live POST.
209    if ctx.dry_run {
210        return Ok(Envelope::success(
211            ctx.environment,
212            ctx.dry_run,
213            json!({
214                "action": "would_settle",
215                "task_id": task_id.to_string(),
216                "escrow_id": escrow_id_hex,
217                "deadline": deadline_unix,
218                "domain": {
219                    "chain_id": chain_id,
220                    "verifying_contract": verifying_contract_str,
221                },
222                "signature": signature_hex,
223            }),
224        ));
225    }
226
227    // 10. Live POST. `signature` is a plain string in the current spec; the
228    //     `0x`-prefixed 65-byte EIP-712 shape is validated server-side. A
229    //     malformed value here would mean `sign_distribution` regressed
230    //     (crypto-layer bug), not a network/server issue.
231    let body = SettleTaskBody {
232        signature: signature_hex,
233    };
234    let resp = match client.inner().settle_task(&task_id, &body).await {
235        Ok(v) => v.into_inner(),
236        Err(e) => {
237            let err = map_api_error(e).await;
238            // gh#143: auto-disburse can win the race between our preflight
239            // GET and this signed POST — a 409 `task_not_eligible` /
240            // `escrow_not_ready` then describes a task that already settled.
241            // Re-check the status and report success with a note. Genuine
242            // rejections (deadline_expired, signer_mismatch, …) and a
243            // re-check that finds no advancement stay errors.
244            if matches!(&err, taskfast_client::Error::Validation { code, .. }
245                if matches!(code.as_str(), "task_not_eligible" | "escrow_not_ready"))
246            {
247                if let Ok(advanced) = client.inner().get_task(&task_id).await {
248                    let advanced = advanced.into_inner();
249                    if let Some(note) = advanced.status.as_deref().and_then(settlement_note) {
250                        return Ok(Envelope::success(
251                            ctx.environment,
252                            ctx.dry_run,
253                            json!({
254                                "task_id": task_id.to_string(),
255                                "status": advanced.status,
256                                "note": note,
257                            }),
258                        ));
259                    }
260                }
261            }
262            return Err(err.into());
263        }
264    };
265
266    Ok(Envelope::success(
267        ctx.environment,
268        ctx.dry_run,
269        json!({
270            "task_id": resp.task_id,
271            "status": resp.status,
272        }),
273    ))
274}
275
276/// gh#143 note for a task whose settlement already happened (or is in
277/// flight) without this poster's explicit settle — the dev auto-disburse
278/// race. Every other status returns `None`: a settle problem there is a
279/// genuine failure, not an idempotent replay.
280fn settlement_note(status: &str) -> Option<&'static str> {
281    match status {
282        "settled" => Some("already settled"),
283        "disbursement_pending" => Some("settlement underway"),
284        _ => None,
285    }
286}