1use std::path::PathBuf;
24use std::str::FromStr;
25use std::time::Duration;
26
27use alloy_primitives::{Address, Bytes, B256, U256};
28use alloy_sol_types::SolCall;
29use clap::Parser;
30use serde_json::json;
31use uuid::Uuid;
32
33use super::{
34 is_proxy_rpc_url, network_policy_for_chain_id, parse_duration, validate_override_rpc_url,
35 CmdError, CmdResult, Ctx,
36};
37use crate::envelope::Envelope;
38
39use taskfast_agent::chain::{compute_escrow_id, EscrowIdParams, TaskEscrow};
40use taskfast_agent::tempo_rpc::TempoRpcClient;
41use taskfast_chains::tempo::{sign_distribution, DistributionDomain};
42use taskfast_client::api::types::{
43 BidEscrowFinalizeRequest, BidEscrowFinalizeRequestPosterApprovalDeadline,
44 BidEscrowParamsResponse,
45};
46use taskfast_client::map_api_error;
47
48#[derive(Debug, clap::Subcommand)]
49pub enum Command {
50 Sign(SignArgs),
52}
53
54#[derive(Debug, Parser)]
55pub struct SignArgs {
56 pub bid_id: String,
59
60 #[arg(long, env = "TEMPO_KEY_SOURCE")]
62 pub keystore: Option<String>,
63
64 #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
66 pub wallet_password_file: Option<PathBuf>,
67
68 #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
71 pub wallet_address: Option<String>,
72
73 #[arg(long, env = "TEMPO_RPC_URL")]
77 pub rpc_url: Option<String>,
78
79 #[arg(long)]
82 pub skip_allowance_check: bool,
83
84 #[arg(
88 long,
89 env = "TASKFAST_RECEIPT_TIMEOUT",
90 value_parser = parse_duration,
91 )]
92 pub receipt_timeout: Option<Duration>,
93}
94
95pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
96 match cmd {
97 Command::Sign(a) => sign(ctx, a).await,
98 }
99}
100
101async fn sign(ctx: &Ctx, args: SignArgs) -> CmdResult {
102 let bid_id = Uuid::parse_str(&args.bid_id)
104 .map_err(|e| CmdError::Usage(format!("bid id must be a UUID: {e}")))?;
105
106 let client = ctx.client()?;
107
108 let params = match client.inner().get_bid_escrow_params(&bid_id).await {
110 Ok(v) => v.into_inner(),
111 Err(e) => {
112 let mapped = map_api_error(e).await;
113 if matches!(&mapped, taskfast_client::Error::Decode(_))
120 && mapped.to_string().contains("arbitrator_address")
121 {
122 return Err(CmdError::Validation {
123 code: "server_missing_arbitrator".into(),
124 message: "server omitted `arbitrator_address`; this deployment predates \
125 v2 arbitrated escrow — upgrade the server or use a CLI version \
126 that matches it"
127 .into(),
128 });
129 }
130 if matches!(&mapped, taskfast_client::Error::Decode(_))
134 && (mapped.to_string().contains("poster_approval_deadline")
135 || mapped.to_string().contains("poster_approval_min_lifetime"))
136 {
137 return Err(CmdError::Validation {
138 code: "server_missing_approval_deadline".into(),
139 message: "server omitted `poster_approval_deadline`; this deployment predates \
140 the server-issued escrow deadline — upgrade the server or use a CLI \
141 version that matches it"
142 .into(),
143 });
144 }
145 return Err(mapped.into());
146 }
147 };
148
149 let token_address: Address = params.token_address.parse().map_err(|e| {
158 CmdError::Decode(format!(
159 "server token_address `{}` not a valid EVM address: {e}",
160 params.token_address
161 ))
162 })?;
163 let task_escrow: Address = params.task_escrow_contract.parse().map_err(|e| {
164 CmdError::Decode(format!(
165 "server task_escrow_contract `{}` not a valid EVM address: {e}",
166 params.task_escrow_contract
167 ))
168 })?;
169 let worker: Address = params.worker_address.parse().map_err(|e| {
170 CmdError::Decode(format!(
171 "server worker_address `{}` not a valid EVM address: {e}",
172 params.worker_address
173 ))
174 })?;
175 let platform_wallet: Address = params.platform_wallet.parse().map_err(|e| {
176 CmdError::Decode(format!(
177 "server platform_wallet `{}` not a valid EVM address: {e}",
178 params.platform_wallet
179 ))
180 })?;
181 let arbitrator: Address = params.arbitrator_address.parse().map_err(|e| {
185 CmdError::Decode(format!(
186 "server arbitrator_address `{}` not a valid EVM address: {e}",
187 params.arbitrator_address
188 ))
189 })?;
190 if arbitrator == Address::ZERO {
194 return Err(CmdError::Decode(
195 "server returned a zero arbitrator_address; the v2 escrow open requires a \
196 pool arbitrator and would revert (arbitrator_not_in_pool)"
197 .to_string(),
198 ));
199 }
200
201 let chain_id_u64 = u64::try_from(params.chain_id).map_err(|_| {
206 CmdError::Decode(format!(
207 "escrow params chain_id={} is negative",
208 params.chain_id
209 ))
210 })?;
211 let verifying_contract = task_escrow;
212 let domain = DistributionDomain::new(chain_id_u64, verifying_contract);
213
214 let decimals = u8::try_from(params.decimals).map_err(|_| {
215 CmdError::Decode(format!(
216 "escrow params decimals={} out of u8 range",
217 params.decimals
218 ))
219 })?;
220 let deposit = decimal_to_u256(¶ms.amount, decimals)?;
221 let platform_fee = decimal_to_u256(¶ms.platform_fee_amount, decimals)?;
222
223 let memo_hash_opt: Option<B256> = params
226 .memo_hash
227 .as_deref()
228 .map(|s| {
229 B256::from_str(s).map_err(|e| {
230 CmdError::Decode(format!(
231 "server memo_hash `{s}` not a 0x-prefixed 32-byte hex: {e}"
232 ))
233 })
234 })
235 .transpose()?;
236
237 let keystore_path = super::wallet_args::resolve_keystore_path(
239 args.keystore.as_deref(),
240 ctx.keystore_path.as_deref(),
241 );
242 let signer = super::wallet_args::load_signer_and_validate(
243 keystore_path.as_deref(),
244 args.wallet_password_file.as_deref(),
245 args.wallet_address
246 .as_deref()
247 .or(ctx.wallet_address.as_deref()),
248 "escrow approval",
249 )?;
250
251 let salt = B256::from(rand::random::<[u8; 32]>());
256 let escrow_id = compute_escrow_id(&EscrowIdParams {
257 poster: signer.address(),
258 worker,
259 token: token_address,
260 deposit,
261 platform_fee_amount: platform_fee,
262 platform: platform_wallet,
263 arbitrator,
264 salt,
265 });
266
267 let mut deadline_unix = server_deadline_or_abort(¶ms)?;
275 let mut signature_hex =
276 sign_distribution(&signer, &domain, escrow_id, U256::from(deadline_unix))?;
277
278 let open_calldata: Bytes = if let Some(memo_hash) = memo_hash_opt {
281 TaskEscrow::openWithMemoCall {
282 token: token_address,
283 deposit,
284 worker,
285 platformFeeAmount: platform_fee,
286 platform: platform_wallet,
287 arbitrator,
288 salt,
289 memoHash: memo_hash,
290 }
291 .abi_encode()
292 .into()
293 } else {
294 TaskEscrow::openCall {
295 token: token_address,
296 deposit,
297 worker,
298 platformFeeAmount: platform_fee,
299 platform: platform_wallet,
300 arbitrator,
301 salt,
302 }
303 .abi_encode()
304 .into()
305 };
306
307 let (rpc_url, _via_proxy) = if let Some(ref url) = args.rpc_url {
314 validate_override_rpc_url(
315 url,
316 network_policy_for_chain_id(chain_id_u64),
317 ctx.allow_custom_endpoints,
318 )?;
319 (url.clone(), false)
320 } else {
321 let cfg = client.fetch_network_config().await.map_err(|e| {
322 CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
323 })?;
324 let (_name, entry) = cfg.entry_by_chain_id(params.chain_id).map_err(|e| {
325 CmdError::Server(format!(
326 "deployment at {} does not advertise chain_id={}: {e}",
327 ctx.base_url(),
328 params.chain_id
329 ))
330 })?;
331 if !is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
335 return Err(CmdError::Server(format!(
336 "deployment at {} returned rpc_url {:?} for chain_id={}, \
337 which is not on the same host. Refusing to route RPC \
338 traffic off-host.",
339 ctx.base_url(),
340 entry.rpc_url,
341 params.chain_id,
342 )));
343 }
344 (entry.rpc_url.clone(), true)
345 };
346
347 if ctx.dry_run {
348 return Ok(Envelope::success(
349 ctx.environment,
350 ctx.dry_run,
351 json!({
352 "action": "would_sign_escrow",
353 "bid_id": bid_id.to_string(),
354 "task_id": params.task_id.to_string(),
355 "escrow_id": format!("{escrow_id:#x}"),
356 "arbitrator": format!("{arbitrator:#x}"),
357 "salt": format!("{salt:#x}"),
358 "deadline": deadline_unix,
359 "signature": signature_hex,
360 "open_calldata": format!("0x{}", hex::encode(&open_calldata)),
361 "memo_hash": params.memo_hash,
362 "rpc_url": rpc_url,
363 "domain": {
364 "chain_id": chain_id_u64,
365 "verifying_contract": format!("{verifying_contract:#x}"),
366 },
367 }),
368 ));
369 }
370
371 let http = ctx.rpc_http_client(&client, &rpc_url);
372 let rpc = TempoRpcClient::new(http, rpc_url);
373 let default_timeout = crate::tempo_session::default_receipt_timeout_for_chain_id(chain_id_u64);
374 let receipt_timeout =
375 super::resolve_duration(args.receipt_timeout, ctx.receipt_timeout, default_timeout);
376 let session =
377 crate::tempo_session::TempoSession::new(signer, keystore_path, rpc, receipt_timeout);
378
379 let total_required = deposit
384 .checked_add(platform_fee)
385 .ok_or_else(|| CmdError::Decode("deposit + platform_fee overflow U256".into()))?;
386
387 let mut approval_tx_hex: Option<String> = None;
388 if !args.skip_allowance_check {
389 let balance = session
390 .erc20_balance_of(token_address, session.address())
391 .await?;
392 if balance < total_required {
393 return Err(CmdError::Usage(format!(
394 "poster balance {balance} < required {total_required} (deposit {deposit} + fee {platform_fee}) on token {token_address:#x}"
395 )));
396 }
397 approval_tx_hex = session
398 .ensure_allowance(token_address, task_escrow, total_required)
399 .await?
400 .map(|h| format!("{h:#x}"));
401 }
402
403 let voucher_tx = session
405 .send_transaction_and_wait(
406 task_escrow,
407 open_calldata,
408 "open",
409 Some(" — finalize aborted"),
410 )
411 .await?;
412 let voucher_hex = format!("{voucher_tx:#x}");
413
414 let mut attempts = 0u8;
421 let resp = loop {
422 let deadline_i64 = i64::try_from(deadline_unix)
426 .map_err(|_| CmdError::Decode(format!("deadline {deadline_unix} exceeds i64 range")))?;
427 let body = BidEscrowFinalizeRequest {
428 voucher: voucher_hex.clone(),
429 poster_approval_signature: signature_hex.clone(),
430 poster_approval_deadline: BidEscrowFinalizeRequestPosterApprovalDeadline::Integer(
431 deadline_i64,
432 ),
433 memo_hash: params.memo_hash.clone(),
434 };
435 match client.inner().finalize_bid_escrow(&bid_id, &body).await {
436 Ok(r) => break r.into_inner(),
437 Err(e) => {
438 let mapped = map_api_error(e).await;
439 if attempts == 0 && is_deadline_below_minimum(&mapped) {
440 attempts += 1;
441 let fresh = match client.inner().get_bid_escrow_params(&bid_id).await {
442 Ok(v) => v.into_inner(),
443 Err(e) => return Err(map_api_error(e).await.into()),
444 };
445 deadline_unix = server_deadline_or_abort(&fresh)?;
446 signature_hex = sign_distribution(
447 session.signer(),
448 &domain,
449 escrow_id,
450 U256::from(deadline_unix),
451 )?;
452 continue;
453 }
454 return Err(mapped.into());
455 }
456 }
457 };
458
459 Ok(Envelope::success(
460 ctx.environment,
461 ctx.dry_run,
462 json!({
463 "bid_id": resp.bid_id,
464 "task_id": resp.task_id,
465 "status": resp.status,
466 "task_status": resp.task_status,
467 "escrow_id": format!("{escrow_id:#x}"),
468 "voucher_tx_hash": voucher_hex,
469 "approval_tx_hash": approval_tx_hex,
470 "deadline": deadline_unix,
471 }),
472 ))
473}
474
475fn server_deadline_or_abort(params: &BidEscrowParamsResponse) -> Result<u64, CmdError> {
482 let deadline = u64::try_from(params.poster_approval_deadline).map_err(|_| {
483 CmdError::Decode(format!(
484 "server poster_approval_deadline={} is negative",
485 params.poster_approval_deadline
486 ))
487 })?;
488 let min_lifetime = u64::try_from(params.poster_approval_min_lifetime).map_err(|_| {
489 CmdError::Decode(format!(
490 "server poster_approval_min_lifetime={} is negative",
491 params.poster_approval_min_lifetime
492 ))
493 })?;
494 let now = u64::try_from(jiff::Timestamp::now().as_second())
495 .map_err(|_| CmdError::Decode("system clock before epoch".into()))?;
496 let remaining = deadline.saturating_sub(now);
497 if remaining < min_lifetime {
498 return Err(CmdError::Validation {
499 code: "deadline_below_minimum".into(),
500 message: format!(
501 "server-issued deadline has {remaining}s remaining, below the \
502 {min_lifetime}s minimum — aborting rather than sign an approval the \
503 server will reject. Re-run once the server re-issues a deadline."
504 ),
505 });
506 }
507 Ok(deadline)
508}
509
510fn is_deadline_below_minimum(err: &taskfast_client::Error) -> bool {
513 matches!(
514 err,
515 taskfast_client::Error::Validation { code, .. } if code == "deadline_below_minimum"
516 )
517}
518
519fn decimal_to_u256(s: &str, decimals: u8) -> Result<U256, CmdError> {
523 let trimmed = s.trim();
524 if trimmed.is_empty() {
525 return Err(CmdError::Decode("empty decimal amount".into()));
526 }
527 if trimmed.starts_with('-') {
528 return Err(CmdError::Decode(format!(
529 "negative amount `{s}` disallowed"
530 )));
531 }
532 let (whole, frac) = match trimmed.split_once('.') {
533 Some((w, f)) => (w, f),
534 None => (trimmed, ""),
535 };
536 let frac_len = frac.len();
537 if frac_len > decimals as usize {
538 return Err(CmdError::Decode(format!(
539 "amount `{s}` has {frac_len} fractional digits but token has only {decimals}"
540 )));
541 }
542 let mut combined = String::with_capacity(whole.len() + decimals as usize);
543 combined.push_str(whole);
544 combined.push_str(frac);
545 for _ in 0..(decimals as usize - frac_len) {
546 combined.push('0');
547 }
548 let stripped = combined.trim_start_matches('0');
550 let digits = if stripped.is_empty() { "0" } else { stripped };
551 U256::from_str_radix(digits, 10)
552 .map_err(|e| CmdError::Decode(format!("amount `{s}` not parseable as integer: {e}")))
553}
554
555#[cfg(test)]
556mod tests {
557 use super::*;
558 use taskfast_chains::tempo::TEMPO_MAINNET_CHAIN_ID;
559
560 fn default_receipt_timeout(chain_id: i64) -> Duration {
561 match u64::try_from(chain_id) {
562 Ok(id) => crate::tempo_session::default_receipt_timeout_for_chain_id(id),
563 _ => crate::tempo_session::DEFAULT_RECEIPT_TIMEOUT_TESTNET,
564 }
565 }
566
567 #[test]
568 fn decimal_to_u256_scales_basic() {
569 assert_eq!(
570 decimal_to_u256("75.00", 6).unwrap(),
571 U256::from(75_000_000u64)
572 );
573 assert_eq!(decimal_to_u256("75", 6).unwrap(), U256::from(75_000_000u64));
574 assert_eq!(decimal_to_u256("0.5", 6).unwrap(), U256::from(500_000u64));
575 assert_eq!(decimal_to_u256("0", 6).unwrap(), U256::ZERO);
576 }
577
578 #[test]
579 fn decimal_to_u256_rejects_excess_fractional_digits() {
580 let err = decimal_to_u256("1.1234567", 6).expect_err("7 > 6 must fail");
581 matches!(err, CmdError::Decode(_));
582 }
583
584 #[test]
585 fn decimal_to_u256_rejects_negative() {
586 let err = decimal_to_u256("-1.00", 6).expect_err("negative must fail");
587 matches!(err, CmdError::Decode(_));
588 }
589
590 #[test]
591 fn chain_id_constants_match_tempo_protocol() {
592 use taskfast_chains::tempo::TEMPO_TESTNET_CHAIN_ID;
593 assert_eq!(TEMPO_MAINNET_CHAIN_ID, 4_217);
597 assert_eq!(TEMPO_TESTNET_CHAIN_ID, 42_431);
598 }
599
600 #[test]
601 fn default_receipt_timeout_mainnet_is_three_minutes() {
602 assert_eq!(default_receipt_timeout(4_217), Duration::from_mins(3));
603 }
604
605 #[test]
606 fn default_receipt_timeout_testnet_is_one_minute() {
607 assert_eq!(default_receipt_timeout(42_431), Duration::from_mins(1));
608 }
609
610 #[test]
611 fn default_receipt_timeout_unknown_chain_falls_back_to_testnet_budget() {
612 assert_eq!(default_receipt_timeout(31_337), Duration::from_mins(1));
614 }
615
616 #[test]
617 fn deadline_below_minimum_detects_only_that_code() {
618 assert!(is_deadline_below_minimum(
619 &taskfast_client::Error::Validation {
620 code: "deadline_below_minimum".into(),
621 message: "x".into(),
622 }
623 ));
624 assert!(!is_deadline_below_minimum(
625 &taskfast_client::Error::Validation {
626 code: "validation_error".into(),
627 message: "x".into(),
628 }
629 ));
630 assert!(!is_deadline_below_minimum(&taskfast_client::Error::Server(
631 "deadline_below_minimum".into()
632 )));
633 }
634}