taskfast_cli/cmd/stake.rs
1// SPDX-License-Identifier: MIT
2//! `taskfast stake <task_id>` — operator posts a performance stake on a
3//! direct high-assurance task (gh#54, server #482 `POST /tasks/{id}/stake`).
4//!
5//! Thin agent-key POST: with on-chain bond posting disabled (the current
6//! deployment default) the server records the bond and finalizes the
7//! assignment in-band, so there is no EIP-712 signing here — unlike
8//! `escrow sign`. When posting is enabled the bond is parked
9//! (`status: awaiting_verification`) and the operator submits the on-chain
10//! `TaskBond.post` tx out-of-band; that reporting path is tracked separately
11//! and is out of scope for this command.
12//!
13//! `--source external-backer` authenticates as an approved backer and requires
14//! `--wallet`; the server enforces the operator's backer allowlist.
15
16use clap::{Parser, ValueEnum};
17use serde_json::json;
18use uuid::Uuid;
19
20use super::{CmdError, CmdResult, Ctx};
21use crate::envelope::Envelope;
22
23use taskfast_client::api::types::{PostStakeBody, PostStakeBodyStakeSource};
24use taskfast_client::map_api_error;
25
26/// clap-friendly mirror of the generated `PostStakeBodyStakeSource` enum.
27/// Kept local (like `bid::BidStatusFilter`) so the codegen needn't grow clap
28/// derives; kebab-case renders `operator-self` / `external-backer`.
29#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
30pub enum StakeSource {
31 OperatorSelf,
32 ExternalBacker,
33}
34
35impl StakeSource {
36 fn to_api(self) -> PostStakeBodyStakeSource {
37 match self {
38 Self::OperatorSelf => PostStakeBodyStakeSource::OperatorSelf,
39 Self::ExternalBacker => PostStakeBodyStakeSource::ExternalBacker,
40 }
41 }
42
43 /// Wire value, for the `--dry-run` echo (matches the JSON the server sees).
44 fn as_str(self) -> &'static str {
45 match self {
46 Self::OperatorSelf => "operator_self",
47 Self::ExternalBacker => "external_backer",
48 }
49 }
50}
51
52#[derive(Debug, Parser)]
53pub struct Args {
54 /// Target task UUID. Must be a direct high-assurance task parked at
55 /// `awaiting_stake` whose Operator of Record you belong to.
56 pub task_id: String,
57
58 /// Stake amount in bond **base units** (integer, not a decimal). Must meet
59 /// the deployment's high-assurance minimum — the server owns that floor.
60 #[arg(long)]
61 pub amount: i64,
62
63 /// Who is posting. `operator-self` (default) authenticates with your agent
64 /// key; `external-backer` posts on the operator's behalf and needs `--wallet`.
65 #[arg(long, value_enum, default_value_t = StakeSource::OperatorSelf)]
66 pub source: StakeSource,
67
68 /// Approved backer wallet (`0x`-prefixed). Required with
69 /// `--source external-backer`; ignored otherwise.
70 #[arg(long)]
71 pub wallet: Option<String>,
72}
73
74pub async fn run(ctx: &Ctx, args: Args) -> CmdResult {
75 // Fail on a bad UUID before any HTTP so typos never 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 // Reject a non-positive amount upfront. The server owns the high-assurance
80 // floor, but `minimum: 1` is structural — no point spending a 422 on it.
81 if args.amount < 1 {
82 return Err(CmdError::Usage(
83 "--amount must be a positive integer (bond base units)".into(),
84 ));
85 }
86
87 // External-backer staking requires a posting wallet; fail fast so an
88 // orchestrator sees a never-retry Usage error rather than a server 422.
89 let wallet_address = match args.source {
90 StakeSource::ExternalBacker => match args.wallet.as_deref() {
91 Some(w) if !w.trim().is_empty() => Some(super::parse_wallet_address(w)?),
92 _ => {
93 return Err(CmdError::Usage(
94 "--wallet is required with --source external-backer".into(),
95 ));
96 }
97 },
98 // The server ignores `wallet_address` for operator-self; don't send it.
99 StakeSource::OperatorSelf => None,
100 };
101
102 if ctx.dry_run {
103 return Ok(Envelope::success(
104 ctx.environment,
105 ctx.dry_run,
106 json!({
107 "action": "would_stake",
108 "task_id": task_id.to_string(),
109 "amount": args.amount,
110 "stake_source": args.source.as_str(),
111 "wallet_address": wallet_address,
112 }),
113 ));
114 }
115
116 let client = ctx.client()?;
117 let body = PostStakeBody {
118 // Generated `amount` is `NonZeroU64` (spec `minimum: 1`); the `< 1`
119 // guard above guarantees the conversion succeeds.
120 amount: std::num::NonZeroU64::new(args.amount as u64)
121 .expect("amount validated to >= 1 above"),
122 stake_source: args.source.to_api(),
123 wallet_address,
124 };
125 let resp = match client.inner().post_stake(&task_id, &body).await {
126 Ok(v) => v.into_inner(),
127 Err(e) => return Err(map_api_error(e).await.into()),
128 };
129 Ok(Envelope::success(
130 ctx.environment,
131 ctx.dry_run,
132 json!({ "stake": resp }),
133 ))
134}