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