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};
44use taskfast_agent::tempo_rpc::TempoRpcClient;
45use taskfast_client::api::types::{
46 GetStakeQuoteStakeSource, ReportStakePostTxBody, ReportStakePostTxBodyStakeSource,
47};
48use taskfast_client::map_api_error;
49
50const DEFAULT_VERIFY_TIMEOUT: Duration = Duration::from_mins(1);
54const VERIFY_POLL_INTERVAL: Duration = Duration::from_secs(3);
55
56fn default_receipt_timeout(chain_id: i64) -> Duration {
57 match u64::try_from(chain_id) {
58 Ok(id) => crate::tempo_session::default_receipt_timeout_for_chain_id(id),
59 _ => crate::tempo_session::DEFAULT_RECEIPT_TIMEOUT_TESTNET,
60 }
61}
62
63#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
67pub enum BondStakeSource {
68 OperatorSelf,
69 ExternalBacker,
70}
71
72impl BondStakeSource {
73 fn to_quote(self) -> GetStakeQuoteStakeSource {
74 match self {
75 Self::OperatorSelf => GetStakeQuoteStakeSource::OperatorSelf,
76 Self::ExternalBacker => GetStakeQuoteStakeSource::ExternalBacker,
77 }
78 }
79
80 fn to_report(self) -> ReportStakePostTxBodyStakeSource {
81 match self {
82 Self::OperatorSelf => ReportStakePostTxBodyStakeSource::OperatorSelf,
83 Self::ExternalBacker => ReportStakePostTxBodyStakeSource::ExternalBacker,
84 }
85 }
86}
87
88#[derive(Debug, clap::Subcommand)]
89pub enum Command {
90 Post(PostArgs),
92}
93
94#[derive(Debug, Parser)]
95pub struct PostArgs {
96 pub task_id: String,
98
99 #[arg(long, env = "BOND_ADDRESS")]
103 pub task_bond: Option<String>,
104
105 #[arg(long)]
108 pub token: Option<String>,
109
110 #[arg(long)]
114 pub amount: Option<i64>,
115
116 #[arg(long, value_enum, default_value_t = BondStakeSource::OperatorSelf)]
119 pub source: BondStakeSource,
120
121 #[arg(long, env = "TEMPO_KEY_SOURCE")]
123 pub keystore: Option<String>,
124
125 #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
127 pub wallet_password_file: Option<PathBuf>,
128
129 #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
132 pub wallet_address: Option<String>,
133
134 #[arg(long, env = "TEMPO_RPC_URL")]
136 pub rpc_url: Option<String>,
137
138 #[arg(long)]
142 pub skip_allowance_check: bool,
143
144 #[arg(long, env = "TASKFAST_RECEIPT_TIMEOUT", value_parser = humantime::parse_duration)]
147 pub receipt_timeout: Option<Duration>,
148
149 #[arg(long, env = "TASKFAST_BOND_VERIFY_TIMEOUT", value_parser = humantime::parse_duration)]
153 pub verify_timeout: Option<Duration>,
154}
155
156pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
157 match cmd {
158 Command::Post(a) => post(ctx, a).await,
159 }
160}
161
162async fn post(ctx: &Ctx, args: PostArgs) -> CmdResult {
163 let task_id = Uuid::parse_str(&args.task_id)
165 .map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))?;
166
167 let client = ctx.client()?;
168
169 let quote = match client
172 .inner()
173 .get_stake_quote(&task_id, Some(args.source.to_quote()))
174 .await
175 {
176 Ok(v) => v.into_inner(),
177 Err(e) => return Err(map_api_error(e).await.into()),
178 };
179 if quote.bond_status.as_deref() == Some("posted") {
180 return Ok(Envelope::success(
181 ctx.environment,
182 ctx.dry_run,
183 json!({
184 "action": "already_posted",
185 "task_id": task_id.to_string(),
186 "bond_status": "posted",
187 }),
188 ));
189 }
190
191 let amount_i64 = args.amount.unwrap_or(quote.required_amount);
194 if amount_i64 < quote.required_amount {
195 return Err(CmdError::Usage(format!(
196 "--amount {amount_i64} is below the quoted required_amount {}; a smaller bond never verifies",
197 quote.required_amount
198 )));
199 }
200 let amount = U256::from(u64::try_from(amount_i64).map_err(|_| {
201 CmdError::Usage(format!(
202 "amount {amount_i64} must be a non-negative integer"
203 ))
204 })?);
205 if amount.is_zero() {
206 return Err(CmdError::Usage("bond amount resolves to 0".into()));
207 }
208
209 let task_bond_override: Option<Address> = args
213 .task_bond
214 .as_deref()
215 .map(|tb| {
216 tb.parse().map_err(|e| {
217 CmdError::Usage(format!(
218 "--task-bond `{tb}` is not a valid EVM address: {e}"
219 ))
220 })
221 })
222 .transpose()?;
223
224 let keystore_path = super::wallet_args::resolve_keystore_path(
226 args.keystore.as_deref(),
227 ctx.keystore_path.as_deref(),
228 );
229 let signer = super::wallet_args::load_signer_and_validate(
230 keystore_path.as_deref(),
231 args.wallet_password_file.as_deref(),
232 args.wallet_address
233 .as_deref()
234 .or(ctx.wallet_address.as_deref()),
235 "bond post",
236 )?;
237
238 let (rpc_url, chain_id, default_stablecoin, task_bond_contract) =
241 resolve_network(ctx, &client, &args).await?;
242 let task_bond: Address = match task_bond_override {
243 Some(a) => a,
244 None => {
245 let tb = task_bond_contract.ok_or_else(|| {
246 CmdError::Server(
247 "deployment does not advertise a TaskBond contract \
248 (`task_bond_contract` in /config/network) for this network; \
249 pass --task-bond to override"
250 .into(),
251 )
252 })?;
253 tb.parse().map_err(|e| {
254 CmdError::Server(format!(
255 "deployment task_bond_contract `{tb}` is not a valid EVM address: {e}"
256 ))
257 })?
258 }
259 };
260 let token: Address = match args.token.as_deref() {
261 Some(t) => t.parse().map_err(|e| {
262 CmdError::Usage(format!("--token `{t}` is not a valid EVM address: {e}"))
263 })?,
264 None => {
265 let ds = default_stablecoin.ok_or_else(|| {
266 CmdError::Usage(
267 "no --token given and the deployment advertises no default_stablecoin; \
268 pass --token <erc20-address>"
269 .into(),
270 )
271 })?;
272 ds.parse().map_err(|e| {
273 CmdError::Server(format!(
274 "deployment default_stablecoin `{ds}` is not a valid EVM address: {e}"
275 ))
276 })?
277 }
278 };
279
280 let task_ref = compute_task_ref(task_id);
282 let salt = B256::from(rand::random::<[u8; 32]>());
283
284 let post_calldata: Bytes = TaskBond::postCall {
286 token,
287 amount,
288 taskRef: task_ref,
289 salt,
290 }
291 .abi_encode()
292 .into();
293
294 if ctx.dry_run {
295 return Ok(Envelope::success(
296 ctx.environment,
297 ctx.dry_run,
298 json!({
299 "action": "would_post_bond",
300 "task_id": task_id.to_string(),
301 "task_bond": format!("{task_bond:#x}"),
302 "token": format!("{token:#x}"),
303 "amount": amount_i64,
304 "task_ref": format!("{task_ref:#x}"),
305 "salt": format!("{salt:#x}"),
306 "post_calldata": format!("0x{}", hex::encode(&post_calldata)),
307 "rpc_url": rpc_url,
308 "chain_id": chain_id,
309 }),
310 ));
311 }
312
313 let http = ctx.rpc_http_client(&client, &rpc_url);
314 let rpc = TempoRpcClient::new(http, rpc_url.clone());
315 let receipt_timeout = resolve_duration(
316 args.receipt_timeout,
317 ctx.receipt_timeout,
318 default_receipt_timeout(chain_id),
319 );
320 let session =
321 crate::tempo_session::TempoSession::new(signer, keystore_path, rpc, receipt_timeout);
322
323 let balance = session.erc20_balance_of(token, session.address()).await?;
327 if balance < amount {
328 return Err(CmdError::Usage(format!(
329 "poster balance {balance} < required bond {amount} on token {token:#x}"
330 )));
331 }
332
333 let mut approval_tx_hex: Option<String> = None;
334 if !args.skip_allowance_check {
335 approval_tx_hex = session
336 .ensure_allowance(token, task_bond, amount)
337 .await?
338 .map(|h| format!("{h:#x}"));
339 }
340
341 let post_tx = session
343 .send_transaction_and_wait(
344 task_bond,
345 post_calldata,
346 "TaskBond.post",
347 Some(" — report aborted"),
348 )
349 .await?;
350 let post_tx_hex = format!("{post_tx:#x}");
351
352 let body = ReportStakePostTxBody {
354 tx_hash: post_tx_hex.clone(),
355 stake_source: args.source.to_report(),
356 };
357 let report = match client.inner().report_stake_post_tx(&task_id, &body).await {
358 Ok(r) => r.into_inner(),
359 Err(e) => return Err(map_api_error(e).await.into()),
360 };
361
362 let verify_timeout = args.verify_timeout.unwrap_or(DEFAULT_VERIFY_TIMEOUT);
365 let final_status = poll_until_posted(&client, &task_id, args.source, verify_timeout).await;
366
367 Ok(Envelope::success(
368 ctx.environment,
369 ctx.dry_run,
370 json!({
371 "task_id": report.task_id,
372 "status": report.status,
373 "verification": report.verification,
374 "bond_status": final_status,
375 "post_tx_hash": post_tx_hex,
376 "approval_tx_hash": approval_tx_hex,
377 "token": format!("{token:#x}"),
378 "amount": amount_i64,
379 "task_ref": format!("{task_ref:#x}"),
380 "salt": format!("{salt:#x}"),
381 }),
382 ))
383}
384
385async fn poll_until_posted(
389 client: &taskfast_client::TaskFastClient,
390 task_id: &Uuid,
391 source: BondStakeSource,
392 timeout: Duration,
393) -> Option<String> {
394 let deadline = tokio::time::Instant::now() + timeout;
395 let mut last: Option<String> = None;
396 loop {
397 if let Ok(v) = client
398 .inner()
399 .get_stake_quote(task_id, Some(source.to_quote()))
400 .await
401 {
402 last = v.into_inner().bond_status;
403 if last.as_deref() == Some("posted") {
404 return last;
405 }
406 }
407 if tokio::time::Instant::now() + VERIFY_POLL_INTERVAL >= deadline {
408 return last;
409 }
410 tokio::time::sleep(VERIFY_POLL_INTERVAL).await;
411 }
412}
413
414async fn resolve_network(
420 ctx: &Ctx,
421 client: &taskfast_client::TaskFastClient,
422 args: &PostArgs,
423) -> Result<(String, i64, Option<String>, Option<String>), CmdError> {
424 let network = ctx.environment.network();
425 let cfg = client.fetch_network_config().await.map_err(|e| match e {
426 taskfast_client::Error::Auth(_) | taskfast_client::Error::Validation { .. } => {
427 CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
428 }
429 other => CmdError::from(other),
430 })?;
431 let name = network.as_str();
432 let entry = cfg.entry(name).map_err(|e| {
433 CmdError::Server(format!(
434 "deployment at {} does not advertise network `{name}`: {e}",
435 ctx.base_url()
436 ))
437 })?;
438
439 let rpc_url = if let Some(ref override_url) = args.rpc_url {
440 validate_override_rpc_url(override_url, network, ctx.allow_custom_endpoints)?;
443 override_url.clone()
444 } else {
445 if !is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
448 return Err(CmdError::Server(format!(
449 "deployment at {} returned rpc_url {:?} for network `{name}`, which is not on \
450 the same host. Refusing to route RPC traffic off-host.",
451 ctx.base_url(),
452 entry.rpc_url,
453 )));
454 }
455 entry.rpc_url.clone()
456 };
457 Ok((
458 rpc_url,
459 entry.chain_id,
460 entry.default_stablecoin.clone(),
461 entry.task_bond_contract.clone(),
462 ))
463}