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