1use 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
51const 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
58const 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#[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 Post(PostArgs),
100}
101
102#[derive(Debug, Parser)]
103pub struct PostArgs {
104 pub task_id: String,
106
107 #[arg(long, env = "BOND_ADDRESS")]
111 pub task_bond: Option<String>,
112
113 #[arg(long)]
116 pub token: Option<String>,
117
118 #[arg(long)]
122 pub amount: Option<i64>,
123
124 #[arg(long, value_enum, default_value_t = BondStakeSource::OperatorSelf)]
127 pub source: BondStakeSource,
128
129 #[arg(long, env = "TEMPO_KEY_SOURCE")]
131 pub keystore: Option<String>,
132
133 #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
135 pub wallet_password_file: Option<PathBuf>,
136
137 #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
140 pub wallet_address: Option<String>,
141
142 #[arg(long, env = "TEMPO_RPC_URL")]
144 pub rpc_url: Option<String>,
145
146 #[arg(long)]
150 pub skip_allowance_check: bool,
151
152 #[arg(long, env = "TASKFAST_RECEIPT_TIMEOUT", value_parser = humantime::parse_duration)]
155 pub receipt_timeout: Option<Duration>,
156
157 #[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 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 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 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 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 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 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 let task_ref = compute_task_ref(task_id);
303 let salt = B256::from(rand::random::<[u8; 32]>());
304
305 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 let receipt_timeout = resolve_duration(
336 args.receipt_timeout,
337 ctx.receipt_timeout,
338 default_receipt_timeout(chain_id),
339 );
340
341 let http = ctx.rpc_http_client(&client, &rpc_url);
343 let rpc = TempoRpcClient::new(http, rpc_url.clone());
344
345 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 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 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 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 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
438async 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
467async 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_override_rpc_url(override_url, network, ctx.allow_custom_endpoints)?;
496 override_url.clone()
497 } else {
498 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
518async 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 let raw = rpc
529 .eth_call(token, &calldata)
530 .await
531 .map_err(|e| CmdError::Server(format!("balanceOf rpc: {e}")))?;
532 decode_u256(&raw, "balanceOf")
533}
534
535async fn erc20_allowance(
536 rpc: &TempoRpcClient,
537 token: Address,
538 owner: Address,
539 spender: Address,
540) -> Result<U256, CmdError> {
541 let calldata: Bytes = IERC20::allowanceCall { owner, spender }.abi_encode().into();
542 let raw = rpc
543 .eth_call(token, &calldata)
544 .await
545 .map_err(|e| CmdError::Server(format!("allowance rpc: {e}")))?;
546 decode_u256(&raw, "allowance")
547}
548
549fn decode_u256(bytes: &[u8], label: &str) -> Result<U256, CmdError> {
550 if bytes.len() < 32 {
551 return Err(CmdError::Decode(format!(
552 "{label} returned {} bytes, expected >=32",
553 bytes.len()
554 )));
555 }
556 Ok(U256::from_be_slice(&bytes[..32]))
557}