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_client::api::types::{
46 GetStakeQuoteStakeSource, ReportStakePostTxBody, ReportStakePostTxBodyStakeSource,
47};
48use taskfast_client::map_api_error;
49
50const TEMPO_MAINNET_CHAIN_ID: i64 = 4217;
53
54const 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
60const 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#[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 Post(PostArgs),
102}
103
104#[derive(Debug, Parser)]
105pub struct PostArgs {
106 pub task_id: String,
108
109 #[arg(long, env = "TASKFAST_TASK_BOND_ADDRESS")]
113 pub task_bond: String,
114
115 #[arg(long)]
118 pub token: Option<String>,
119
120 #[arg(long)]
124 pub amount: Option<i64>,
125
126 #[arg(long, value_enum, default_value_t = BondStakeSource::OperatorSelf)]
129 pub source: BondStakeSource,
130
131 #[arg(long, env = "TEMPO_KEY_SOURCE")]
133 pub keystore: Option<String>,
134
135 #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
137 pub wallet_password_file: Option<PathBuf>,
138
139 #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
142 pub wallet_address: Option<String>,
143
144 #[arg(long, env = "TEMPO_RPC_URL")]
146 pub rpc_url: Option<String>,
147
148 #[arg(long)]
152 pub skip_allowance_check: bool,
153
154 #[arg(long, env = "TASKFAST_RECEIPT_TIMEOUT", value_parser = humantime::parse_duration)]
157 pub receipt_timeout: Option<Duration>,
158
159 #[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 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 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 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 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 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 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 let task_ref = compute_task_ref(task_id);
278 let salt = B256::from(rand::random::<[u8; 32]>());
279
280 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 let receipt_timeout = resolve_duration(
311 args.receipt_timeout,
312 ctx.receipt_timeout,
313 default_receipt_timeout(chain_id),
314 );
315
316 let http = ctx.rpc_http_client(&client, &rpc_url);
318 let rpc = TempoRpcClient::new(http, rpc_url.clone());
319
320 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 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 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 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 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
413async 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
442async 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_override_rpc_url(override_url, network, ctx.allow_custom_endpoints)?;
470 override_url.clone()
471 } else {
472 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
487async 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}