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, IERC20};
44use taskfast_agent::tempo_rpc::{sign_and_broadcast_tx, TempoRpcClient};
45use taskfast_chains::tempo::TEMPO_MAINNET_CHAIN_ID;
46use taskfast_client::api::types::{
47    GetStakeQuoteStakeSource, ReportStakePostTxBody, ReportStakePostTxBodyStakeSource,
48};
49use taskfast_client::map_api_error;
50
51/// `TaskBond.post` receipt polling defaults (same shape as `escrow sign`):
52/// 3min mainnet, 1min testnet, 1min for unknown chains. The mainnet chain-id
53/// constant lives once, in `taskfast_chains::tempo`.
54const DEFAULT_RECEIPT_TIMEOUT_MAINNET: Duration = Duration::from_mins(3);
55const DEFAULT_RECEIPT_TIMEOUT_TESTNET: Duration = Duration::from_mins(1);
56const RECEIPT_POLL_INTERVAL: Duration = Duration::from_secs(2);
57
58/// Server-side `BondPosted` verification is asynchronous, so after reporting we
59/// re-quote until `bond_status=posted`. Bounded so the command still returns if
60/// verification lags; a timeout is reported as `posting`, not a failure.
61const DEFAULT_VERIFY_TIMEOUT: Duration = Duration::from_mins(1);
62const VERIFY_POLL_INTERVAL: Duration = Duration::from_secs(3);
63
64fn default_receipt_timeout(chain_id: i64) -> Duration {
65    match u64::try_from(chain_id) {
66        Ok(TEMPO_MAINNET_CHAIN_ID) => DEFAULT_RECEIPT_TIMEOUT_MAINNET,
67        _ => DEFAULT_RECEIPT_TIMEOUT_TESTNET,
68    }
69}
70
71/// clap-friendly mirror of the generated stake-source enums (kept local, like
72/// `stake::StakeSource`, so codegen needn't grow clap derives). kebab-case
73/// renders `operator-self` / `external-backer`.
74#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
75pub enum BondStakeSource {
76    OperatorSelf,
77    ExternalBacker,
78}
79
80impl BondStakeSource {
81    fn to_quote(self) -> GetStakeQuoteStakeSource {
82        match self {
83            Self::OperatorSelf => GetStakeQuoteStakeSource::OperatorSelf,
84            Self::ExternalBacker => GetStakeQuoteStakeSource::ExternalBacker,
85        }
86    }
87
88    fn to_report(self) -> ReportStakePostTxBodyStakeSource {
89        match self {
90            Self::OperatorSelf => ReportStakePostTxBodyStakeSource::OperatorSelf,
91            Self::ExternalBacker => ReportStakePostTxBodyStakeSource::ExternalBacker,
92        }
93    }
94}
95
96#[derive(Debug, clap::Subcommand)]
97pub enum Command {
98    /// Quote, approve, post `TaskBond.post`, and report — for an auction task.
99    Post(PostArgs),
100}
101
102#[derive(Debug, Parser)]
103pub struct PostArgs {
104    /// Target task UUID. The auction task whose operator bond you are posting.
105    pub task_id: String,
106
107    /// TaskBond contract address (`0x`-prefixed). Defaults to the deployment's
108    /// `task_bond_contract` from `GET /config/network`; pass this only to
109    /// override (e.g. custom-endpoint development).
110    #[arg(long, env = "BOND_ADDRESS")]
111    pub task_bond: Option<String>,
112
113    /// Bond ERC-20 token address (`0x`-prefixed). Defaults to the deployment's
114    /// `default_stablecoin` from `GET /config/network`.
115    #[arg(long)]
116    pub token: Option<String>,
117
118    /// Override the posted amount (bond base units). Defaults to the quote's
119    /// `required_amount`. Must be at least the required amount — less never
120    /// verifies.
121    #[arg(long)]
122    pub amount: Option<i64>,
123
124    /// Who is posting. `operator-self` (default) authenticates with your agent
125    /// key; `external-backer` authenticates as the bond's recorded backer.
126    #[arg(long, value_enum, default_value_t = BondStakeSource::OperatorSelf)]
127    pub source: BondStakeSource,
128
129    /// Keystore reference (same form as `taskfast escrow sign`).
130    #[arg(long, env = "TEMPO_KEY_SOURCE")]
131    pub keystore: Option<String>,
132
133    /// Path to keystore password file.
134    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
135    pub wallet_password_file: Option<PathBuf>,
136
137    /// Wallet address preflight (`0x`-prefixed). When set, fail before touching
138    /// the chain if the keystore decrypts to a mismatch.
139    #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
140    pub wallet_address: Option<String>,
141
142    /// Tempo RPC override. Defaults to the deployment's authenticated proxy URL.
143    #[arg(long, env = "TEMPO_RPC_URL")]
144    pub rpc_url: Option<String>,
145
146    /// Skip the on-chain `allowance` preflight + `approve` tx (the balance
147    /// preflight still runs). Only safe when a sufficient allowance was already
148    /// granted to the TaskBond contract.
149    #[arg(long)]
150    pub skip_allowance_check: bool,
151
152    /// Receipt-polling ceiling — human duration (`3min`, `90s`). Falls back to
153    /// `receipt_timeout` in config, then a chain-aware default.
154    #[arg(long, env = "TASKFAST_RECEIPT_TIMEOUT", value_parser = humantime::parse_duration)]
155    pub receipt_timeout: Option<Duration>,
156
157    /// How long to poll the quote for `bond_status=posted` after reporting.
158    /// A timeout returns `posting` (the tx is on-chain; verification is async),
159    /// not an error.
160    #[arg(long, env = "TASKFAST_BOND_VERIFY_TIMEOUT", value_parser = humantime::parse_duration)]
161    pub verify_timeout: Option<Duration>,
162}
163
164pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
165    match cmd {
166        Command::Post(a) => post(ctx, a).await,
167    }
168}
169
170async fn post(ctx: &Ctx, args: PostArgs) -> CmdResult {
171    // 1. Validate the task UUID before any HTTP so typos never cost a round-trip.
172    let task_id = Uuid::parse_str(&args.task_id)
173        .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
174
175    let client = ctx.client()?;
176
177    // 2. Quote. Server prices from task value; if a bond already exists the
178    //    recorded pricing is authoritative. An already-`posted` bond is a no-op.
179    let quote = match client
180        .inner()
181        .get_stake_quote(&task_id, Some(args.source.to_quote()))
182        .await
183    {
184        Ok(v) => v.into_inner(),
185        Err(e) => return Err(map_api_error(e).await.into()),
186    };
187    if quote.bond_status.as_deref() == Some("posted") {
188        return Ok(Envelope::success(
189            ctx.environment,
190            ctx.dry_run,
191            json!({
192                "action": "already_posted",
193                "task_id": task_id.to_string(),
194                "bond_status": "posted",
195            }),
196        ));
197    }
198
199    // 3. Resolve amount (base units). Default to the required amount; a smaller
200    //    override never verifies, so reject it before spending gas.
201    let amount_i64 = args.amount.unwrap_or(quote.required_amount);
202    if amount_i64 < quote.required_amount {
203        return Err(CmdError::Usage(format!(
204            "--amount {amount_i64} is below the quoted required_amount {}; a smaller bond never verifies",
205            quote.required_amount
206        )));
207    }
208    let amount = U256::from(u64::try_from(amount_i64).map_err(|_| {
209        CmdError::Usage(format!(
210            "amount {amount_i64} must be a non-negative integer"
211        ))
212    })?);
213    if amount.is_zero() {
214        return Err(CmdError::Usage("bond amount resolves to 0".into()));
215    }
216
217    // 4. Parse an explicit TaskBond override up front so a typo fails before
218    //    any signing or network round-trip; the server-advertised default is
219    //    resolved after the network-config fetch (step 6).
220    let task_bond_override: Option<Address> = args
221        .task_bond
222        .as_deref()
223        .map(|tb| {
224            tb.parse().map_err(|e| {
225                CmdError::Usage(format!(
226                    "--task-bond `{tb}` is not a valid EVM address: {e}"
227                ))
228            })
229        })
230        .transpose()?;
231
232    // 5. Load signer + preflight the wallet address.
233    let keystore_ref = args.keystore.as_deref().map(str::to_string).or_else(|| {
234        ctx.keystore_path
235            .as_deref()
236            .and_then(|p| p.to_str().map(str::to_string))
237    });
238    let signer = super::wallet_args::load_signer(
239        keystore_ref.as_deref(),
240        args.wallet_password_file.as_deref(),
241        "bond post",
242    )?;
243    let wallet_address_for_check = args
244        .wallet_address
245        .as_deref()
246        .or(ctx.wallet_address.as_deref());
247    if let Some(expected) = wallet_address_for_check {
248        let expected_addr: Address = expected.parse().map_err(|e| {
249            CmdError::Usage(format!("--wallet-address is not a valid EVM address: {e}"))
250        })?;
251        if signer.address() != expected_addr {
252            return Err(CmdError::Usage(format!(
253                "keystore address {:#x} does not match --wallet-address {expected}",
254                signer.address(),
255            )));
256        }
257    }
258
259    // 6. Resolve chain + token + contracts + RPC URL from the deployment's
260    //    network config.
261    let (rpc_url, chain_id, default_stablecoin, task_bond_contract) =
262        resolve_network(ctx, &client, &args).await?;
263    let task_bond: Address = match task_bond_override {
264        Some(a) => a,
265        None => {
266            let tb = task_bond_contract.ok_or_else(|| {
267                CmdError::Server(
268                    "deployment does not advertise a TaskBond contract \
269                     (`task_bond_contract` in /config/network) for this network; \
270                     pass --task-bond to override"
271                        .into(),
272                )
273            })?;
274            tb.parse().map_err(|e| {
275                CmdError::Server(format!(
276                    "deployment task_bond_contract `{tb}` is not a valid EVM address: {e}"
277                ))
278            })?
279        }
280    };
281    let token: Address = match args.token.as_deref() {
282        Some(t) => t.parse().map_err(|e| {
283            CmdError::Usage(format!("--token `{t}` is not a valid EVM address: {e}"))
284        })?,
285        None => {
286            let ds = default_stablecoin.ok_or_else(|| {
287                CmdError::Usage(
288                    "no --token given and the deployment advertises no default_stablecoin; \
289                     pass --token <erc20-address>"
290                        .into(),
291                )
292            })?;
293            ds.parse().map_err(|e| {
294                CmdError::Server(format!(
295                    "deployment default_stablecoin `{ds}` is not a valid EVM address: {e}"
296                ))
297            })?
298        }
299    };
300
301    // 7. Derive taskRef (server verifier layout) + a random salt.
302    let task_ref = compute_task_ref(task_id);
303    let salt = B256::from(rand::random::<[u8; 32]>());
304
305    // 8. Build TaskBond.post calldata up front — reused for dry-run + broadcast.
306    let post_calldata: Bytes = TaskBond::postCall {
307        token,
308        amount,
309        taskRef: task_ref,
310        salt,
311    }
312    .abi_encode()
313    .into();
314
315    if ctx.dry_run {
316        return Ok(Envelope::success(
317            ctx.environment,
318            ctx.dry_run,
319            json!({
320                "action": "would_post_bond",
321                "task_id": task_id.to_string(),
322                "task_bond": format!("{task_bond:#x}"),
323                "token": format!("{token:#x}"),
324                "amount": amount_i64,
325                "task_ref": format!("{task_ref:#x}"),
326                "salt": format!("{salt:#x}"),
327                "post_calldata": format!("0x{}", hex::encode(&post_calldata)),
328                "rpc_url": rpc_url,
329                "chain_id": chain_id,
330            }),
331        ));
332    }
333
334    // Receipt-timeout precedence: flag > config > chain-aware default.
335    let receipt_timeout = resolve_duration(
336        args.receipt_timeout,
337        ctx.receipt_timeout,
338        default_receipt_timeout(chain_id),
339    );
340
341    // 9. Live RPC: balance preflight, then allowance preflight + approve.
342    let http = ctx.rpc_http_client(&client, &rpc_url);
343    let rpc = TempoRpcClient::new(http, rpc_url.clone());
344
345    // Balance preflight always runs — independent of --skip-allowance-check,
346    // which governs only the allowance + approve path — so an underfunded
347    // poster fails fast before broadcasting anything.
348    let balance = erc20_balance_of(&rpc, token, signer.address()).await?;
349    if balance < amount {
350        return Err(CmdError::Usage(format!(
351            "poster balance {balance} < required bond {amount} on token {token:#x}"
352        )));
353    }
354
355    let mut approval_tx_hex: Option<String> = None;
356    if !args.skip_allowance_check {
357        let current_allowance = erc20_allowance(&rpc, token, signer.address(), task_bond).await?;
358        if current_allowance < amount {
359            let approve_calldata: Bytes = IERC20::approveCall {
360                spender: task_bond,
361                amount,
362            }
363            .abi_encode()
364            .into();
365            let approve_hash = sign_and_broadcast_tx(&rpc, &signer, token, approve_calldata)
366                .await
367                .map_err(|e| CmdError::Server(format!("approve broadcast failed: {e}")))?;
368            let ok = rpc
369                .wait_for_receipt(approve_hash, receipt_timeout, RECEIPT_POLL_INTERVAL)
370                .await
371                .map_err(|e| CmdError::Server(format!("approve receipt: {e}")))?;
372            if !ok {
373                return Err(CmdError::Server(format!(
374                    "approve tx {approve_hash:#x} reverted on-chain"
375                )));
376            }
377            // Re-read allowance: a non-standard or no-op approve can leave it
378            // short, which would revert TaskBond.post and waste gas (mirrors
379            // `escrow sign`).
380            let new_allowance = erc20_allowance(&rpc, token, signer.address(), task_bond).await?;
381            if new_allowance < amount {
382                return Err(CmdError::Server(format!(
383                    "allowance still {new_allowance} after approve tx {approve_hash:#x} (needed {amount})"
384                )));
385            }
386            approval_tx_hex = Some(format!("{approve_hash:#x}"));
387        }
388    }
389
390    // 10. Broadcast TaskBond.post, wait for receipt.
391    let post_tx = sign_and_broadcast_tx(&rpc, &signer, task_bond, post_calldata)
392        .await
393        .map_err(|e| CmdError::Server(format!("TaskBond.post broadcast failed: {e}")))?;
394    let post_ok = rpc
395        .wait_for_receipt(post_tx, receipt_timeout, RECEIPT_POLL_INTERVAL)
396        .await
397        .map_err(|e| CmdError::Server(format!("post receipt: {e}")))?;
398    if !post_ok {
399        return Err(CmdError::Server(format!(
400            "TaskBond.post tx {post_tx:#x} reverted on-chain — report aborted"
401        )));
402    }
403    let post_tx_hex = format!("{post_tx:#x}");
404
405    // 11. Report the tx hash. The server enqueues `BondPosted` verification.
406    let body = ReportStakePostTxBody {
407        tx_hash: post_tx_hex.clone(),
408        stake_source: args.source.to_report(),
409    };
410    let report = match client.inner().report_stake_post_tx(&task_id, &body).await {
411        Ok(r) => r.into_inner(),
412        Err(e) => return Err(map_api_error(e).await.into()),
413    };
414
415    // 12. Poll the quote until `bond_status=posted` (async verification). A
416    //     timeout is not a failure — the tx is on-chain and confirmed.
417    let verify_timeout = args.verify_timeout.unwrap_or(DEFAULT_VERIFY_TIMEOUT);
418    let final_status = poll_until_posted(&client, &task_id, args.source, verify_timeout).await;
419
420    Ok(Envelope::success(
421        ctx.environment,
422        ctx.dry_run,
423        json!({
424            "task_id": report.task_id,
425            "status": report.status,
426            "verification": report.verification,
427            "bond_status": final_status,
428            "post_tx_hash": post_tx_hex,
429            "approval_tx_hash": approval_tx_hex,
430            "token": format!("{token:#x}"),
431            "amount": amount_i64,
432            "task_ref": format!("{task_ref:#x}"),
433            "salt": format!("{salt:#x}"),
434        }),
435    ))
436}
437
438/// Re-quote until `bond_status=posted` or `timeout` elapses. Returns the last
439/// observed `bond_status` (`None` if the quote never carried one). Transient
440/// quote errors are swallowed — the report already succeeded.
441async fn poll_until_posted(
442    client: &taskfast_client::TaskFastClient,
443    task_id: &Uuid,
444    source: BondStakeSource,
445    timeout: Duration,
446) -> Option<String> {
447    let deadline = tokio::time::Instant::now() + timeout;
448    let mut last: Option<String> = None;
449    loop {
450        if let Ok(v) = client
451            .inner()
452            .get_stake_quote(task_id, Some(source.to_quote()))
453            .await
454        {
455            last = v.into_inner().bond_status;
456            if last.as_deref() == Some("posted") {
457                return last;
458            }
459        }
460        if tokio::time::Instant::now() + VERIFY_POLL_INTERVAL >= deadline {
461            return last;
462        }
463        tokio::time::sleep(VERIFY_POLL_INTERVAL).await;
464    }
465}
466
467/// Resolve `(rpc_url, chain_id, default_stablecoin, task_bond_contract)` from
468/// `GET /config/network` for this environment's network. Mirrors
469/// `post::resolve_proxy_rpc_url`'s same-host proxy guard, but
470/// also surfaces `chain_id` and the bond token + contract addresses, which
471/// the bond flow needs from the same entry.
472async fn resolve_network(
473    ctx: &Ctx,
474    client: &taskfast_client::TaskFastClient,
475    args: &PostArgs,
476) -> Result<(String, i64, Option<String>, Option<String>), CmdError> {
477    let network = ctx.environment.network();
478    let cfg = client.fetch_network_config().await.map_err(|e| match e {
479        taskfast_client::Error::Auth(_) | taskfast_client::Error::Validation { .. } => {
480            CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
481        }
482        other => CmdError::from(other),
483    })?;
484    let name = network.as_str();
485    let entry = cfg.entry(name).map_err(|e| {
486        CmdError::Server(format!(
487            "deployment at {} does not advertise network `{name}`: {e}",
488            ctx.base_url()
489        ))
490    })?;
491
492    let rpc_url = if let Some(ref override_url) = args.rpc_url {
493        // Validate against the env-derived network policy (as post/escrow do),
494        // not the advertised chain_id — the env is the trust anchor.
495        validate_override_rpc_url(override_url, network, ctx.allow_custom_endpoints)?;
496        override_url.clone()
497    } else {
498        // Same-host guard: the proxy may be mounted at any path on api_base, but
499        // must live on the same host so the API key never leaves the deployment.
500        if !is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
501            return Err(CmdError::Server(format!(
502                "deployment at {} returned rpc_url {:?} for network `{name}`, which is not on \
503                 the same host. Refusing to route RPC traffic off-host.",
504                ctx.base_url(),
505                entry.rpc_url,
506            )));
507        }
508        entry.rpc_url.clone()
509    };
510    Ok((
511        rpc_url,
512        entry.chain_id,
513        entry.default_stablecoin.clone(),
514        entry.task_bond_contract.clone(),
515    ))
516}
517
518// ponytail: these three ERC-20 read helpers are copied verbatim from
519// `escrow.rs` (which keeps them private). Duplicating ~30 trivial lines is a
520// smaller, lower-risk diff than hoisting them into a shared module and
521// touching the escrow path; hoist if a third caller appears.
522async fn erc20_balance_of(
523    rpc: &TempoRpcClient,
524    token: Address,
525    owner: Address,
526) -> Result<U256, CmdError> {
527    let calldata: Bytes = IERC20::balanceOfCall { account: owner }.abi_encode().into();
528    // from = owner: zone TIP-20 balance privacy (see TempoRpcClient::eth_call_from).
529    let raw = rpc
530        .eth_call_from(owner, token, &calldata)
531        .await
532        .map_err(|e| CmdError::Server(format!("balanceOf rpc: {e}")))?;
533    decode_u256(&raw, "balanceOf")
534}
535
536async fn erc20_allowance(
537    rpc: &TempoRpcClient,
538    token: Address,
539    owner: Address,
540    spender: Address,
541) -> Result<U256, CmdError> {
542    let calldata: Bytes = IERC20::allowanceCall { owner, spender }.abi_encode().into();
543    // from = owner: zone TIP-20 balance privacy (see TempoRpcClient::eth_call_from).
544    let raw = rpc
545        .eth_call_from(owner, token, &calldata)
546        .await
547        .map_err(|e| CmdError::Server(format!("allowance rpc: {e}")))?;
548    decode_u256(&raw, "allowance")
549}
550
551fn decode_u256(bytes: &[u8], label: &str) -> Result<U256, CmdError> {
552    if bytes.len() < 32 {
553        return Err(CmdError::Decode(format!(
554            "{label} returned {} bytes, expected >=32",
555            bytes.len()
556        )));
557    }
558    Ok(U256::from_be_slice(&bytes[..32]))
559}