Skip to main content

taskfast_cli/cmd/
bond.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast bond post <task_id>` — auction-task operator posts the on-chain
3//! performance bond in one step (gh#95).
4//!
5//! `taskfast stake` is HA-direct-only (auction tasks reject with
6//! `not_high_assurance`); the working bond flow for an auction task had to be
7//! hand-run with raw `cast`. This command drives it end to end:
8//!
9//!  1. `GET /tasks/:id/stake/quote` → `required_amount` (bond base units).
10//!  2. Resolve the bond ERC-20 token, chain, and TaskBond contract from
11//!     `GET /config/network` (`default_stablecoin`, `task_bond_contract`).
12//!  3. Derive `taskRef` (16 zero bytes ++ task UUID) + a random `salt`.
13//!  4. ERC-20 `allowance` preflight; `approve` the TaskBond contract if short.
14//!  5. `TaskBond.post(token, amount, taskRef, salt)` — broadcast + wait receipt.
15//!  6. `POST /tasks/:id/stake/report {tx_hash}` — a claim, not proof.
16//!  7. Poll the quote until `bond_status=posted` (server verifies `BondPosted`
17//!     asynchronously).
18//!
19//! Token and TaskBond contract both come from the deployment's network config
20//! (`--token`/`--task-bond` override for custom-endpoint development). The
21//! quote does not yet return `task_ref`/`salt`, so `taskRef` is derived
22//! locally per the verifier's layout. The verifier matches
23//! contract/token/taskRef/amount and does not pin salt, so a random salt is
24//! accepted.
25//!
26//! Error mapping delegates to `map_api_error` (401|403→Auth, 409|422→
27//! Validation). Keystore / signing failures surface as `Wallet` (exit 5).
28
29use std::path::PathBuf;
30use std::time::Duration;
31
32use alloy_primitives::{Address, Bytes, B256, U256};
33use alloy_sol_types::SolCall;
34use clap::{Parser, ValueEnum};
35use serde_json::json;
36use uuid::Uuid;
37
38use super::{
39    is_proxy_rpc_url, resolve_duration, validate_override_rpc_url, CmdError, CmdResult, Ctx,
40};
41use crate::envelope::Envelope;
42
43use taskfast_agent::chain::{compute_task_ref, TaskBond};
44use taskfast_agent::tempo_rpc::TempoRpcClient;
45use taskfast_client::api::types::{
46    GetStakeQuoteStakeSource, ReportStakePostTxBody, ReportStakePostTxBodyStakeSource,
47};
48use taskfast_client::map_api_error;
49
50/// Server-side `BondPosted` verification is asynchronous, so after reporting we
51/// re-quote until `bond_status=posted`. Bounded so the command still returns if
52/// verification lags; a timeout is reported as `posting`, not a failure.
53const DEFAULT_VERIFY_TIMEOUT: Duration = Duration::from_mins(1);
54const VERIFY_POLL_INTERVAL: Duration = Duration::from_secs(3);
55
56fn default_receipt_timeout(chain_id: i64) -> Duration {
57    match u64::try_from(chain_id) {
58        Ok(id) => crate::tempo_session::default_receipt_timeout_for_chain_id(id),
59        _ => crate::tempo_session::DEFAULT_RECEIPT_TIMEOUT_TESTNET,
60    }
61}
62
63/// clap-friendly mirror of the generated stake-source enums (kept local, like
64/// `stake::StakeSource`, so codegen needn't grow clap derives). kebab-case
65/// renders `operator-self` / `external-backer`.
66#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
67pub enum BondStakeSource {
68    OperatorSelf,
69    ExternalBacker,
70}
71
72impl BondStakeSource {
73    fn to_quote(self) -> GetStakeQuoteStakeSource {
74        match self {
75            Self::OperatorSelf => GetStakeQuoteStakeSource::OperatorSelf,
76            Self::ExternalBacker => GetStakeQuoteStakeSource::ExternalBacker,
77        }
78    }
79
80    fn to_report(self) -> ReportStakePostTxBodyStakeSource {
81        match self {
82            Self::OperatorSelf => ReportStakePostTxBodyStakeSource::OperatorSelf,
83            Self::ExternalBacker => ReportStakePostTxBodyStakeSource::ExternalBacker,
84        }
85    }
86}
87
88#[derive(Debug, clap::Subcommand)]
89pub enum Command {
90    /// Quote, approve, post `TaskBond.post`, and report — for an auction task.
91    Post(PostArgs),
92}
93
94#[derive(Debug, Parser)]
95pub struct PostArgs {
96    /// Target task UUID. The auction task whose operator bond you are posting.
97    pub task_id: String,
98
99    /// TaskBond contract address (`0x`-prefixed). Defaults to the deployment's
100    /// `task_bond_contract` from `GET /config/network`; pass this only to
101    /// override (e.g. custom-endpoint development).
102    #[arg(long, env = "BOND_ADDRESS")]
103    pub task_bond: Option<String>,
104
105    /// Bond ERC-20 token address (`0x`-prefixed). Defaults to the deployment's
106    /// `default_stablecoin` from `GET /config/network`.
107    #[arg(long)]
108    pub token: Option<String>,
109
110    /// Override the posted amount (bond base units). Defaults to the quote's
111    /// `required_amount`. Must be at least the required amount — less never
112    /// verifies.
113    #[arg(long)]
114    pub amount: Option<i64>,
115
116    /// Who is posting. `operator-self` (default) authenticates with your agent
117    /// key; `external-backer` authenticates as the bond's recorded backer.
118    #[arg(long, value_enum, default_value_t = BondStakeSource::OperatorSelf)]
119    pub source: BondStakeSource,
120
121    /// Keystore reference (same form as `taskfast escrow sign`).
122    #[arg(long, env = "TEMPO_KEY_SOURCE")]
123    pub keystore: Option<String>,
124
125    /// Path to keystore password file.
126    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
127    pub wallet_password_file: Option<PathBuf>,
128
129    /// Wallet address preflight (`0x`-prefixed). When set, fail before touching
130    /// the chain if the keystore decrypts to a mismatch.
131    #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
132    pub wallet_address: Option<String>,
133
134    /// Tempo RPC override. Defaults to the deployment's authenticated proxy URL.
135    #[arg(long, env = "TEMPO_RPC_URL")]
136    pub rpc_url: Option<String>,
137
138    /// Skip the on-chain `allowance` preflight + `approve` tx (the balance
139    /// preflight still runs). Only safe when a sufficient allowance was already
140    /// granted to the TaskBond contract.
141    #[arg(long)]
142    pub skip_allowance_check: bool,
143
144    /// Receipt-polling ceiling — human duration (`3min`, `90s`). Falls back to
145    /// `receipt_timeout` in config, then a chain-aware default.
146    #[arg(long, env = "TASKFAST_RECEIPT_TIMEOUT", value_parser = humantime::parse_duration)]
147    pub receipt_timeout: Option<Duration>,
148
149    /// How long to poll the quote for `bond_status=posted` after reporting.
150    /// A timeout returns `posting` (the tx is on-chain; verification is async),
151    /// not an error.
152    #[arg(long, env = "TASKFAST_BOND_VERIFY_TIMEOUT", value_parser = humantime::parse_duration)]
153    pub verify_timeout: Option<Duration>,
154}
155
156pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
157    match cmd {
158        Command::Post(a) => post(ctx, a).await,
159    }
160}
161
162async fn post(ctx: &Ctx, args: PostArgs) -> CmdResult {
163    // 1. Validate the task UUID before any HTTP so typos never cost a round-trip.
164    let task_id = Uuid::parse_str(&args.task_id)
165        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
166
167    let client = ctx.client()?;
168
169    // 2. Quote. Server prices from task value; if a bond already exists the
170    //    recorded pricing is authoritative. An already-`posted` bond is a no-op.
171    let quote = match client
172        .inner()
173        .get_stake_quote(&task_id, Some(args.source.to_quote()))
174        .await
175    {
176        Ok(v) => v.into_inner(),
177        Err(e) => return Err(map_api_error(e).await.into()),
178    };
179    if quote.bond_status.as_deref() == Some("posted") {
180        return Ok(Envelope::success(
181            ctx.environment,
182            ctx.dry_run,
183            json!({
184                "action": "already_posted",
185                "task_id": task_id.to_string(),
186                "bond_status": "posted",
187            }),
188        ));
189    }
190
191    // 3. Resolve amount (base units). Default to the required amount; a smaller
192    //    override never verifies, so reject it before spending gas.
193    let amount_i64 = args.amount.unwrap_or(quote.required_amount);
194    if amount_i64 < quote.required_amount {
195        return Err(CmdError::Usage(format!(
196            "--amount {amount_i64} is below the quoted required_amount {}; a smaller bond never verifies",
197            quote.required_amount
198        )));
199    }
200    let amount = U256::from(u64::try_from(amount_i64).map_err(|_| {
201        CmdError::Usage(format!(
202            "amount {amount_i64} must be a non-negative integer"
203        ))
204    })?);
205    if amount.is_zero() {
206        return Err(CmdError::Usage("bond amount resolves to 0".into()));
207    }
208
209    // 4. Parse an explicit TaskBond override up front so a typo fails before
210    //    any signing or network round-trip; the server-advertised default is
211    //    resolved after the network-config fetch (step 6).
212    let task_bond_override: Option<Address> = args
213        .task_bond
214        .as_deref()
215        .map(|tb| {
216            tb.parse().map_err(|e| {
217                CmdError::Usage(format!(
218                    "--task-bond `{tb}` is not a valid EVM address: {e}"
219                ))
220            })
221        })
222        .transpose()?;
223
224    // 5. Load signer + preflight the wallet address.
225    let keystore_path = super::wallet_args::resolve_keystore_path(
226        args.keystore.as_deref(),
227        ctx.keystore_path.as_deref(),
228    );
229    let signer = super::wallet_args::load_signer_and_validate(
230        keystore_path.as_deref(),
231        args.wallet_password_file.as_deref(),
232        args.wallet_address
233            .as_deref()
234            .or(ctx.wallet_address.as_deref()),
235        "bond post",
236    )?;
237
238    // 6. Resolve chain + token + contracts + RPC URL from the deployment's
239    //    network config.
240    let (rpc_url, chain_id, default_stablecoin, task_bond_contract) =
241        resolve_network(ctx, &client, &args).await?;
242    let task_bond: Address = match task_bond_override {
243        Some(a) => a,
244        None => {
245            let tb = task_bond_contract.ok_or_else(|| {
246                CmdError::Server(
247                    "deployment does not advertise a TaskBond contract \
248                     (`task_bond_contract` in /config/network) for this network; \
249                     pass --task-bond to override"
250                        .into(),
251                )
252            })?;
253            tb.parse().map_err(|e| {
254                CmdError::Server(format!(
255                    "deployment task_bond_contract `{tb}` is not a valid EVM address: {e}"
256                ))
257            })?
258        }
259    };
260    let token: Address = match args.token.as_deref() {
261        Some(t) => t.parse().map_err(|e| {
262            CmdError::Usage(format!("--token `{t}` is not a valid EVM address: {e}"))
263        })?,
264        None => {
265            let ds = default_stablecoin.ok_or_else(|| {
266                CmdError::Usage(
267                    "no --token given and the deployment advertises no default_stablecoin; \
268                     pass --token <erc20-address>"
269                        .into(),
270                )
271            })?;
272            ds.parse().map_err(|e| {
273                CmdError::Server(format!(
274                    "deployment default_stablecoin `{ds}` is not a valid EVM address: {e}"
275                ))
276            })?
277        }
278    };
279
280    // 7. Derive taskRef (server verifier layout) + a random salt.
281    let task_ref = compute_task_ref(task_id);
282    let salt = B256::from(rand::random::<[u8; 32]>());
283
284    // 8. Build TaskBond.post calldata up front — reused for dry-run + broadcast.
285    let post_calldata: Bytes = TaskBond::postCall {
286        token,
287        amount,
288        taskRef: task_ref,
289        salt,
290    }
291    .abi_encode()
292    .into();
293
294    if ctx.dry_run {
295        return Ok(Envelope::success(
296            ctx.environment,
297            ctx.dry_run,
298            json!({
299                "action": "would_post_bond",
300                "task_id": task_id.to_string(),
301                "task_bond": format!("{task_bond:#x}"),
302                "token": format!("{token:#x}"),
303                "amount": amount_i64,
304                "task_ref": format!("{task_ref:#x}"),
305                "salt": format!("{salt:#x}"),
306                "post_calldata": format!("0x{}", hex::encode(&post_calldata)),
307                "rpc_url": rpc_url,
308                "chain_id": chain_id,
309            }),
310        ));
311    }
312
313    let http = ctx.rpc_http_client(&client, &rpc_url);
314    let rpc = TempoRpcClient::new(http, rpc_url.clone());
315    let receipt_timeout = resolve_duration(
316        args.receipt_timeout,
317        ctx.receipt_timeout,
318        default_receipt_timeout(chain_id),
319    );
320    let session =
321        crate::tempo_session::TempoSession::new(signer, keystore_path, rpc, receipt_timeout);
322
323    // Balance preflight always runs — independent of --skip-allowance-check,
324    // which governs only the allowance + approve path — so an underfunded
325    // poster fails fast before broadcasting anything.
326    let balance = session.erc20_balance_of(token, session.address()).await?;
327    if balance < amount {
328        return Err(CmdError::Usage(format!(
329            "poster balance {balance} < required bond {amount} on token {token:#x}"
330        )));
331    }
332
333    let mut approval_tx_hex: Option<String> = None;
334    if !args.skip_allowance_check {
335        approval_tx_hex = session
336            .ensure_allowance(token, task_bond, amount)
337            .await?
338            .map(|h| format!("{h:#x}"));
339    }
340
341    // 10. Broadcast TaskBond.post, wait for receipt.
342    let post_tx = session
343        .send_transaction_and_wait(
344            task_bond,
345            post_calldata,
346            "TaskBond.post",
347            Some(" — report aborted"),
348        )
349        .await?;
350    let post_tx_hex = format!("{post_tx:#x}");
351
352    // 11. Report the tx hash. The server enqueues `BondPosted` verification.
353    let body = ReportStakePostTxBody {
354        tx_hash: post_tx_hex.clone(),
355        stake_source: args.source.to_report(),
356    };
357    let report = match client.inner().report_stake_post_tx(&task_id, &body).await {
358        Ok(r) => r.into_inner(),
359        Err(e) => return Err(map_api_error(e).await.into()),
360    };
361
362    // 12. Poll the quote until `bond_status=posted` (async verification). A
363    //     timeout is not a failure — the tx is on-chain and confirmed.
364    let verify_timeout = args.verify_timeout.unwrap_or(DEFAULT_VERIFY_TIMEOUT);
365    let final_status = poll_until_posted(&client, &task_id, args.source, verify_timeout).await;
366
367    Ok(Envelope::success(
368        ctx.environment,
369        ctx.dry_run,
370        json!({
371            "task_id": report.task_id,
372            "status": report.status,
373            "verification": report.verification,
374            "bond_status": final_status,
375            "post_tx_hash": post_tx_hex,
376            "approval_tx_hash": approval_tx_hex,
377            "token": format!("{token:#x}"),
378            "amount": amount_i64,
379            "task_ref": format!("{task_ref:#x}"),
380            "salt": format!("{salt:#x}"),
381        }),
382    ))
383}
384
385/// Re-quote until `bond_status=posted` or `timeout` elapses. Returns the last
386/// observed `bond_status` (`None` if the quote never carried one). Transient
387/// quote errors are swallowed — the report already succeeded.
388async fn poll_until_posted(
389    client: &taskfast_client::TaskFastClient,
390    task_id: &Uuid,
391    source: BondStakeSource,
392    timeout: Duration,
393) -> Option<String> {
394    let deadline = tokio::time::Instant::now() + timeout;
395    let mut last: Option<String> = None;
396    loop {
397        if let Ok(v) = client
398            .inner()
399            .get_stake_quote(task_id, Some(source.to_quote()))
400            .await
401        {
402            last = v.into_inner().bond_status;
403            if last.as_deref() == Some("posted") {
404                return last;
405            }
406        }
407        if tokio::time::Instant::now() + VERIFY_POLL_INTERVAL >= deadline {
408            return last;
409        }
410        tokio::time::sleep(VERIFY_POLL_INTERVAL).await;
411    }
412}
413
414/// Resolve `(rpc_url, chain_id, default_stablecoin, task_bond_contract)` from
415/// `GET /config/network` for this environment's network. Mirrors
416/// `post::resolve_proxy_rpc_url`'s same-host proxy guard, but
417/// also surfaces `chain_id` and the bond token + contract addresses, which
418/// the bond flow needs from the same entry.
419async fn resolve_network(
420    ctx: &Ctx,
421    client: &taskfast_client::TaskFastClient,
422    args: &PostArgs,
423) -> Result<(String, i64, Option<String>, Option<String>), CmdError> {
424    let network = ctx.environment.network();
425    let cfg = client.fetch_network_config().await.map_err(|e| match e {
426        taskfast_client::Error::Auth(_) | taskfast_client::Error::Validation { .. } => {
427            CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
428        }
429        other => CmdError::from(other),
430    })?;
431    let name = network.as_str();
432    let entry = cfg.entry(name).map_err(|e| {
433        CmdError::Server(format!(
434            "deployment at {} does not advertise network `{name}`: {e}",
435            ctx.base_url()
436        ))
437    })?;
438
439    let rpc_url = if let Some(ref override_url) = args.rpc_url {
440        // Validate against the env-derived network policy (as post/escrow do),
441        // not the advertised chain_id — the env is the trust anchor.
442        validate_override_rpc_url(override_url, network, ctx.allow_custom_endpoints)?;
443        override_url.clone()
444    } else {
445        // Same-host guard: the proxy may be mounted at any path on api_base, but
446        // must live on the same host so the API key never leaves the deployment.
447        if !is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
448            return Err(CmdError::Server(format!(
449                "deployment at {} returned rpc_url {:?} for network `{name}`, which is not on \
450                 the same host. Refusing to route RPC traffic off-host.",
451                ctx.base_url(),
452                entry.rpc_url,
453            )));
454        }
455        entry.rpc_url.clone()
456    };
457    Ok((
458        rpc_url,
459        entry.chain_id,
460        entry.default_stablecoin.clone(),
461        entry.task_bond_contract.clone(),
462    ))
463}