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