1use std::path::PathBuf;
28use std::str::FromStr;
29use std::time::Duration;
30
31use alloy_primitives::{Address, Bytes, B256, U256};
32use alloy_sol_types::SolCall;
33use clap::Parser;
34use serde_json::json;
35use uuid::Uuid;
36
37use super::{
38 is_proxy_rpc_url, network_policy_for_chain_id, parse_duration, validate_override_rpc_url,
39 CmdError, CmdResult, Ctx,
40};
41use crate::envelope::Envelope;
42
43use taskfast_agent::chain::{compute_escrow_id, EscrowIdParams, TaskEscrow};
44use taskfast_agent::tempo_rpc::TempoRpcClient;
45use taskfast_chains::tempo::{sign_distribution, DistributionDomain};
46use taskfast_client::api::types::{
47 BidEscrowFinalizeRequest, BidEscrowFinalizeRequestPosterApprovalDeadline,
48 BidEscrowParamsResponse, GetBidEscrowParamsReviewClock,
49};
50use taskfast_client::{map_api_error, TaskFastClient};
51
52#[derive(Debug, clap::Subcommand)]
53pub enum Command {
54 Sign(SignArgs),
56}
57
58#[derive(Debug, Parser)]
59pub struct SignArgs {
60 pub bid_id: String,
63
64 #[arg(long, env = "TEMPO_KEY_SOURCE")]
66 pub keystore: Option<String>,
67
68 #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
70 pub wallet_password_file: Option<PathBuf>,
71
72 #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
75 pub wallet_address: Option<String>,
76
77 #[arg(long, env = "TEMPO_RPC_URL")]
81 pub rpc_url: Option<String>,
82
83 #[arg(long)]
86 pub skip_allowance_check: bool,
87
88 #[arg(
92 long,
93 env = "TASKFAST_RECEIPT_TIMEOUT",
94 value_parser = parse_duration,
95 )]
96 pub receipt_timeout: Option<Duration>,
97}
98
99pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
100 match cmd {
101 Command::Sign(a) => sign(ctx, a).await,
102 }
103}
104
105async fn sign(ctx: &Ctx, args: SignArgs) -> CmdResult {
106 let bid_id = Uuid::parse_str(&args.bid_id)
108 .map_err(|e| CmdError::Usage(format!("bid id must be a UUID: {e}")))?;
109
110 let client = ctx.client()?;
111
112 let params = match fetch_params(&client, &bid_id).await {
114 Ok(v) => v,
115 Err(mapped) => {
116 if matches!(&mapped, taskfast_client::Error::Decode(_))
123 && mapped.to_string().contains("arbitrator_address")
124 {
125 return Err(CmdError::Validation {
126 code: "server_missing_arbitrator".into(),
127 message: "server omitted `arbitrator_address`; this deployment predates \
128 v2 arbitrated escrow — upgrade the server or use a CLI version \
129 that matches it"
130 .into(),
131 });
132 }
133 if matches!(&mapped, taskfast_client::Error::Decode(_))
137 && (mapped.to_string().contains("poster_approval_deadline")
138 || mapped.to_string().contains("poster_approval_min_lifetime"))
139 {
140 return Err(CmdError::Validation {
141 code: "server_missing_approval_deadline".into(),
142 message: "server omitted `poster_approval_deadline`; this deployment predates \
143 the server-issued escrow deadline — upgrade the server or use a CLI \
144 version that matches it"
145 .into(),
146 });
147 }
148 if let taskfast_client::Error::Decode(m) = &mapped {
151 return Err(CmdError::Decode(format!(
152 "server escrow params response is malformed ({m}); no transaction was sent"
153 )));
154 }
155 return Err(mapped.into());
156 }
157 };
158
159 let token_address: Address = params.token_address.parse().map_err(|e| {
168 CmdError::Decode(format!(
169 "server token_address `{}` not a valid EVM address: {e}",
170 params.token_address
171 ))
172 })?;
173 let task_escrow: Address = params.task_escrow_contract.parse().map_err(|e| {
174 CmdError::Decode(format!(
175 "server task_escrow_contract `{}` not a valid EVM address: {e}",
176 params.task_escrow_contract
177 ))
178 })?;
179 let worker: Address = params.worker_address.parse().map_err(|e| {
180 CmdError::Decode(format!(
181 "server worker_address `{}` not a valid EVM address: {e}",
182 params.worker_address
183 ))
184 })?;
185 let platform_wallet: Address = params.platform_wallet.parse().map_err(|e| {
186 CmdError::Decode(format!(
187 "server platform_wallet `{}` not a valid EVM address: {e}",
188 params.platform_wallet
189 ))
190 })?;
191 let arbitrator: Address = params.arbitrator_address.parse().map_err(|e| {
195 CmdError::Decode(format!(
196 "server arbitrator_address `{}` not a valid EVM address: {e}",
197 params.arbitrator_address
198 ))
199 })?;
200 if arbitrator == Address::ZERO {
204 return Err(CmdError::Decode(
205 "server returned a zero arbitrator_address; the v2 escrow open requires a \
206 pool arbitrator and would revert (arbitrator_not_in_pool)"
207 .to_string(),
208 ));
209 }
210
211 let chain_id_u64 = u64::try_from(params.chain_id).map_err(|_| {
216 CmdError::Decode(format!(
217 "escrow params chain_id={} is negative",
218 params.chain_id
219 ))
220 })?;
221 let verifying_contract = task_escrow;
222 let domain = DistributionDomain::new(chain_id_u64, verifying_contract);
223
224 let decimals = u8::try_from(params.decimals).map_err(|_| {
225 CmdError::Decode(format!(
226 "escrow params decimals={} out of u8 range",
227 params.decimals
228 ))
229 })?;
230 let deposit = decimal_to_u256(¶ms.amount, decimals)?;
231 let platform_fee = decimal_to_u256(¶ms.platform_fee_amount, decimals)?;
232
233 let memo_hash_opt: Option<B256> = params
236 .memo_hash
237 .as_deref()
238 .map(|s| {
239 B256::from_str(s).map_err(|e| {
240 CmdError::Decode(format!(
241 "server memo_hash `{s}` not a 0x-prefixed 32-byte hex: {e}"
242 ))
243 })
244 })
245 .transpose()?;
246
247 let review_window = review_window_from(¶ms)?;
250
251 let keystore_path = super::wallet_args::resolve_keystore_path(
253 args.keystore.as_deref(),
254 ctx.keystore_path.as_deref(),
255 );
256 let signer = super::wallet_args::load_signer_and_validate(
257 keystore_path.as_deref(),
258 args.wallet_password_file.as_deref(),
259 args.wallet_address
260 .as_deref()
261 .or(ctx.wallet_address.as_deref()),
262 "escrow approval",
263 )?;
264
265 let salt = B256::from(rand::random::<[u8; 32]>());
270 let escrow_id = compute_escrow_id(&EscrowIdParams {
271 poster: signer.address(),
272 worker,
273 token: token_address,
274 deposit,
275 platform_fee_amount: platform_fee,
276 platform: platform_wallet,
277 arbitrator,
278 salt,
279 });
280
281 let mut deadline_unix = server_deadline_or_abort(¶ms)?;
289 let mut signature_hex =
290 sign_distribution(&signer, &domain, escrow_id, U256::from(deadline_unix))?;
291
292 let open_calldata = open_calldata(
295 &OpenFields {
296 token: token_address,
297 deposit,
298 worker,
299 platform_fee,
300 platform: platform_wallet,
301 arbitrator,
302 salt,
303 },
304 memo_hash_opt,
305 review_window,
306 );
307
308 let (rpc_url, _via_proxy) = if let Some(ref url) = args.rpc_url {
315 validate_override_rpc_url(
316 url,
317 network_policy_for_chain_id(chain_id_u64),
318 ctx.allow_custom_endpoints,
319 )?;
320 (url.clone(), false)
321 } else {
322 let cfg = client.fetch_network_config().await.map_err(|e| {
323 CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
324 })?;
325 let (_name, entry) = cfg.entry_by_chain_id(params.chain_id).map_err(|e| {
326 CmdError::Server(format!(
327 "deployment at {} does not advertise chain_id={}: {e}",
328 ctx.base_url(),
329 params.chain_id
330 ))
331 })?;
332 if !is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
336 return Err(CmdError::Server(format!(
337 "deployment at {} returned rpc_url {:?} for chain_id={}, \
338 which is not on the same host. Refusing to route RPC \
339 traffic off-host.",
340 ctx.base_url(),
341 entry.rpc_url,
342 params.chain_id,
343 )));
344 }
345 (entry.rpc_url.clone(), true)
346 };
347
348 if ctx.dry_run {
349 return Ok(Envelope::success(
350 ctx.environment,
351 ctx.dry_run,
352 json!({
353 "action": "would_sign_escrow",
354 "bid_id": bid_id.to_string(),
355 "task_id": params.task_id.to_string(),
356 "escrow_id": format!("{escrow_id:#x}"),
357 "arbitrator": format!("{arbitrator:#x}"),
358 "salt": format!("{salt:#x}"),
359 "deadline": deadline_unix,
360 "signature": signature_hex,
361 "open_calldata": format!("0x{}", hex::encode(&open_calldata)),
362 "memo_hash": params.memo_hash,
363 "rpc_url": rpc_url,
364 "domain": {
365 "chain_id": chain_id_u64,
366 "verifying_contract": format!("{verifying_contract:#x}"),
367 },
368 }),
369 ));
370 }
371
372 let http = ctx.rpc_http_client(&client, &rpc_url);
373 let rpc = TempoRpcClient::new(http, rpc_url);
374 let default_timeout = crate::tempo_session::default_receipt_timeout_for_chain_id(chain_id_u64);
375 let receipt_timeout =
376 super::resolve_duration(args.receipt_timeout, ctx.receipt_timeout, default_timeout);
377 let session =
378 crate::tempo_session::TempoSession::new(signer, keystore_path, rpc, receipt_timeout);
379
380 let total_required = deposit
385 .checked_add(platform_fee)
386 .ok_or_else(|| CmdError::Decode("deposit + platform_fee overflow U256".into()))?;
387
388 let mut approval_tx_hex: Option<String> = None;
389 if !args.skip_allowance_check {
390 let balance = session
391 .erc20_balance_of(token_address, session.address())
392 .await?;
393 if balance < total_required {
394 return Err(CmdError::Usage(format!(
395 "poster balance {balance} < required {total_required} (deposit {deposit} + fee {platform_fee}) on token {token_address:#x}"
396 )));
397 }
398 approval_tx_hex = session
399 .ensure_allowance(token_address, task_escrow, total_required)
400 .await?
401 .map(|h| format!("{h:#x}"));
402 }
403
404 let voucher_tx = session
406 .send_transaction_and_wait(
407 task_escrow,
408 open_calldata,
409 "open",
410 Some(" — finalize aborted"),
411 )
412 .await?;
413 let voucher_hex = format!("{voucher_tx:#x}");
414
415 let mut attempts = 0u8;
422 let resp = loop {
423 let deadline_i64 = i64::try_from(deadline_unix)
427 .map_err(|_| CmdError::Decode(format!("deadline {deadline_unix} exceeds i64 range")))?;
428 let body = BidEscrowFinalizeRequest {
429 voucher: voucher_hex.clone(),
430 poster_approval_signature: signature_hex.clone(),
431 poster_approval_deadline: BidEscrowFinalizeRequestPosterApprovalDeadline::Integer(
432 deadline_i64,
433 ),
434 memo_hash: params.memo_hash.clone(),
435 };
436 match client.inner().finalize_bid_escrow(&bid_id, &body).await {
437 Ok(r) => break r.into_inner(),
438 Err(e) => {
439 let mapped = map_api_error(e).await;
440 if attempts == 0 && is_deadline_below_minimum(&mapped) {
441 attempts += 1;
442 let fresh = fetch_params(&client, &bid_id).await?;
443 deadline_unix = server_deadline_or_abort(&fresh)?;
444 signature_hex = sign_distribution(
445 session.signer(),
446 &domain,
447 escrow_id,
448 U256::from(deadline_unix),
449 )?;
450 continue;
451 }
452 return Err(mapped.into());
453 }
454 }
455 };
456
457 Ok(Envelope::success(
458 ctx.environment,
459 ctx.dry_run,
460 json!({
461 "bid_id": resp.bid_id,
462 "task_id": resp.task_id,
463 "status": resp.status,
464 "task_status": resp.task_status,
465 "escrow_id": format!("{escrow_id:#x}"),
466 "voucher_tx_hash": voucher_hex,
467 "approval_tx_hash": approval_tx_hex,
468 "deadline": deadline_unix,
469 }),
470 ))
471}
472
473async fn fetch_params(
477 client: &TaskFastClient,
478 bid_id: &Uuid,
479) -> Result<BidEscrowParamsResponse, taskfast_client::Error> {
480 match client
481 .inner()
482 .get_bid_escrow_params(bid_id, Some(GetBidEscrowParamsReviewClock::X1))
483 .await
484 {
485 Ok(v) => Ok(v.into_inner()),
486 Err(e) => Err(map_api_error(e).await),
487 }
488}
489
490const MAX_REVIEW_WINDOW_SECONDS: i64 = (1 << 53) - 1;
493
494fn review_window_from(params: &BidEscrowParamsResponse) -> Result<Option<U256>, CmdError> {
497 match params.review_window_seconds {
498 None => Ok(None),
499 Some(s) if (1..=MAX_REVIEW_WINDOW_SECONDS).contains(&s) => Ok(Some(U256::from(s))),
500 Some(s) => Err(CmdError::Validation {
501 code: "invalid_review_window".into(),
502 message: format!(
503 "server review_window_seconds={s} must be a positive integer \
504 (at most {MAX_REVIEW_WINDOW_SECONDS}); refusing to open the escrow"
505 ),
506 }),
507 }
508}
509
510mod review_abi {
513 alloy_sol_types::sol! {
514 function openWithReview(
515 address token,
516 uint256 deposit,
517 address worker,
518 uint256 platformFeeAmount,
519 address platform,
520 address arbitrator,
521 bytes32 salt,
522 uint256 reviewWindow,
523 bytes32 memoHash
524 ) external returns (bytes32);
525 }
526}
527
528struct OpenFields {
529 token: Address,
530 deposit: U256,
531 worker: Address,
532 platform_fee: U256,
533 platform: Address,
534 arbitrator: Address,
535 salt: B256,
536}
537
538fn open_calldata(f: &OpenFields, memo: Option<B256>, review_window: Option<U256>) -> Bytes {
542 if let Some(window) = review_window {
543 return review_abi::openWithReviewCall {
544 token: f.token,
545 deposit: f.deposit,
546 worker: f.worker,
547 platformFeeAmount: f.platform_fee,
548 platform: f.platform,
549 arbitrator: f.arbitrator,
550 salt: f.salt,
551 reviewWindow: window,
552 memoHash: memo.unwrap_or_default(),
553 }
554 .abi_encode()
555 .into();
556 }
557 if let Some(memo_hash) = memo {
558 TaskEscrow::openWithMemoCall {
559 token: f.token,
560 deposit: f.deposit,
561 worker: f.worker,
562 platformFeeAmount: f.platform_fee,
563 platform: f.platform,
564 arbitrator: f.arbitrator,
565 salt: f.salt,
566 memoHash: memo_hash,
567 }
568 .abi_encode()
569 .into()
570 } else {
571 TaskEscrow::openCall {
572 token: f.token,
573 deposit: f.deposit,
574 worker: f.worker,
575 platformFeeAmount: f.platform_fee,
576 platform: f.platform,
577 arbitrator: f.arbitrator,
578 salt: f.salt,
579 }
580 .abi_encode()
581 .into()
582 }
583}
584
585fn server_deadline_or_abort(params: &BidEscrowParamsResponse) -> Result<u64, CmdError> {
592 let deadline = u64::try_from(params.poster_approval_deadline).map_err(|_| {
593 CmdError::Decode(format!(
594 "server poster_approval_deadline={} is negative",
595 params.poster_approval_deadline
596 ))
597 })?;
598 let min_lifetime = u64::try_from(params.poster_approval_min_lifetime).map_err(|_| {
599 CmdError::Decode(format!(
600 "server poster_approval_min_lifetime={} is negative",
601 params.poster_approval_min_lifetime
602 ))
603 })?;
604 let now = u64::try_from(jiff::Timestamp::now().as_second())
605 .map_err(|_| CmdError::Decode("system clock before epoch".into()))?;
606 let remaining = deadline.saturating_sub(now);
607 if remaining < min_lifetime {
608 return Err(CmdError::Validation {
609 code: "deadline_below_minimum".into(),
610 message: format!(
611 "server-issued deadline has {remaining}s remaining, below the \
612 {min_lifetime}s minimum — aborting rather than sign an approval the \
613 server will reject. Re-run once the server re-issues a deadline."
614 ),
615 });
616 }
617 Ok(deadline)
618}
619
620fn is_deadline_below_minimum(err: &taskfast_client::Error) -> bool {
623 matches!(
624 err,
625 taskfast_client::Error::Validation { code, .. } if code == "deadline_below_minimum"
626 )
627}
628
629fn decimal_to_u256(s: &str, decimals: u8) -> Result<U256, CmdError> {
633 let trimmed = s.trim();
634 if trimmed.is_empty() {
635 return Err(CmdError::Decode("empty decimal amount".into()));
636 }
637 if trimmed.starts_with('-') {
638 return Err(CmdError::Decode(format!(
639 "negative amount `{s}` disallowed"
640 )));
641 }
642 let (whole, frac) = match trimmed.split_once('.') {
643 Some((w, f)) => (w, f),
644 None => (trimmed, ""),
645 };
646 let frac_len = frac.len();
647 if frac_len > decimals as usize {
648 return Err(CmdError::Decode(format!(
649 "amount `{s}` has {frac_len} fractional digits but token has only {decimals}"
650 )));
651 }
652 let mut combined = String::with_capacity(whole.len() + decimals as usize);
653 combined.push_str(whole);
654 combined.push_str(frac);
655 for _ in 0..(decimals as usize - frac_len) {
656 combined.push('0');
657 }
658 let stripped = combined.trim_start_matches('0');
660 let digits = if stripped.is_empty() { "0" } else { stripped };
661 U256::from_str_radix(digits, 10)
662 .map_err(|e| CmdError::Decode(format!("amount `{s}` not parseable as integer: {e}")))
663}
664
665#[cfg(test)]
666mod tests {
667 use super::*;
668 use taskfast_chains::tempo::TEMPO_MAINNET_CHAIN_ID;
669
670 fn default_receipt_timeout(chain_id: i64) -> Duration {
671 match u64::try_from(chain_id) {
672 Ok(id) => crate::tempo_session::default_receipt_timeout_for_chain_id(id),
673 _ => crate::tempo_session::DEFAULT_RECEIPT_TIMEOUT_TESTNET,
674 }
675 }
676
677 #[test]
678 fn decimal_to_u256_scales_basic() {
679 assert_eq!(
680 decimal_to_u256("75.00", 6).unwrap(),
681 U256::from(75_000_000u64)
682 );
683 assert_eq!(decimal_to_u256("75", 6).unwrap(), U256::from(75_000_000u64));
684 assert_eq!(decimal_to_u256("0.5", 6).unwrap(), U256::from(500_000u64));
685 assert_eq!(decimal_to_u256("0", 6).unwrap(), U256::ZERO);
686 }
687
688 #[test]
689 fn decimal_to_u256_rejects_excess_fractional_digits() {
690 let err = decimal_to_u256("1.1234567", 6).expect_err("7 > 6 must fail");
691 matches!(err, CmdError::Decode(_));
692 }
693
694 #[test]
695 fn decimal_to_u256_rejects_negative() {
696 let err = decimal_to_u256("-1.00", 6).expect_err("negative must fail");
697 matches!(err, CmdError::Decode(_));
698 }
699
700 #[test]
701 fn chain_id_constants_match_tempo_protocol() {
702 use taskfast_chains::tempo::TEMPO_TESTNET_CHAIN_ID;
703 assert_eq!(TEMPO_MAINNET_CHAIN_ID, 4_217);
707 assert_eq!(TEMPO_TESTNET_CHAIN_ID, 42_431);
708 }
709
710 #[test]
711 fn default_receipt_timeout_mainnet_is_three_minutes() {
712 assert_eq!(default_receipt_timeout(4_217), Duration::from_mins(3));
713 }
714
715 #[test]
716 fn default_receipt_timeout_testnet_is_one_minute() {
717 assert_eq!(default_receipt_timeout(42_431), Duration::from_mins(1));
718 }
719
720 #[test]
721 fn default_receipt_timeout_unknown_chain_falls_back_to_testnet_budget() {
722 assert_eq!(default_receipt_timeout(31_337), Duration::from_mins(1));
724 }
725
726 #[test]
727 fn deadline_below_minimum_detects_only_that_code() {
728 assert!(is_deadline_below_minimum(
729 &taskfast_client::Error::Validation {
730 code: "deadline_below_minimum".into(),
731 message: "x".into(),
732 }
733 ));
734 assert!(!is_deadline_below_minimum(
735 &taskfast_client::Error::Validation {
736 code: "validation_error".into(),
737 message: "x".into(),
738 }
739 ));
740 assert!(!is_deadline_below_minimum(&taskfast_client::Error::Server(
741 "deadline_below_minimum".into()
742 )));
743 }
744
745 fn fields() -> OpenFields {
746 OpenFields {
747 token: Address::repeat_byte(1),
748 deposit: U256::from(75_000_000u64),
749 worker: Address::repeat_byte(3),
750 platform_fee: U256::from(3_750_000u64),
751 platform: Address::repeat_byte(4),
752 arbitrator: Address::repeat_byte(5),
753 salt: B256::repeat_byte(9),
754 }
755 }
756
757 #[test]
758 fn open_with_review_selector_is_pinned() {
759 use alloy_primitives::keccak256;
760 let sig = "openWithReview(address,uint256,address,uint256,address,address,bytes32,uint256,bytes32)";
761 assert_eq!(
762 review_abi::openWithReviewCall::SELECTOR,
763 keccak256(sig)[..4]
764 );
765 assert_eq!(
766 review_abi::openWithReviewCall::SELECTOR,
767 [0xf1, 0xe3, 0x2b, 0xb8]
768 );
769 }
770
771 #[test]
772 fn legacy_calldata_is_byte_identical_without_window() {
773 let f = fields();
774 let memo = B256::repeat_byte(0x11);
775 let open = TaskEscrow::openCall {
776 token: f.token,
777 deposit: f.deposit,
778 worker: f.worker,
779 platformFeeAmount: f.platform_fee,
780 platform: f.platform,
781 arbitrator: f.arbitrator,
782 salt: f.salt,
783 }
784 .abi_encode();
785 let with_memo = TaskEscrow::openWithMemoCall {
786 token: f.token,
787 deposit: f.deposit,
788 worker: f.worker,
789 platformFeeAmount: f.platform_fee,
790 platform: f.platform,
791 arbitrator: f.arbitrator,
792 salt: f.salt,
793 memoHash: memo,
794 }
795 .abi_encode();
796 assert_eq!(open_calldata(&f, None, None).to_vec(), open);
797 assert_eq!(open_calldata(&f, Some(memo), None).to_vec(), with_memo);
798 }
799
800 #[test]
801 fn review_calldata_layout_matches_browser_encoding() {
802 let f = fields();
803 let memo = B256::repeat_byte(0x11);
804 let cd = open_calldata(&f, Some(memo), Some(U256::from(86_400u64)));
805 assert_eq!(cd[..4], [0xf1, 0xe3, 0x2b, 0xb8]);
806 assert_eq!(cd.len(), 4 + 32 * 9);
807 assert_eq!(&cd[4 + 32 * 6..4 + 32 * 7], f.salt.as_slice());
808 assert_eq!(
809 U256::from_be_slice(&cd[4 + 32 * 7..4 + 32 * 8]),
810 U256::from(86_400u64)
811 );
812 assert_eq!(&cd[4 + 32 * 8..], memo.as_slice());
813 let no_memo = open_calldata(&f, None, Some(U256::from(1u64)));
814 assert_eq!(&no_memo[4 + 32 * 8..], B256::ZERO.as_slice());
815 }
816}