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