1use std::path::PathBuf;
24use std::str::FromStr;
25use std::time::Duration;
26
27use alloy_primitives::{Address, Bytes, B256, U256};
28use alloy_signer_local::PrivateKeySigner;
29use alloy_sol_types::SolCall;
30use clap::Parser;
31use serde_json::json;
32use uuid::Uuid;
33
34use super::{
35 is_proxy_rpc_url, network_policy_for_chain_id, validate_override_rpc_url, CmdError, CmdResult,
36 Ctx,
37};
38use crate::envelope::Envelope;
39
40use taskfast_agent::chain::{compute_escrow_id, EscrowIdParams, TaskEscrow};
41use taskfast_agent::tempo_rpc::TempoRpcClient;
42use taskfast_chains::tempo::{sign_distribution, DistributionDomain, SigningError};
43use taskfast_client::api::types::{
44 BidEscrowFinalizeRequest, BidEscrowFinalizeRequestPosterApprovalDeadline,
45 BidEscrowParamsResponse,
46};
47use taskfast_client::map_api_error;
48
49#[derive(Debug, clap::Subcommand)]
50pub enum Command {
51 Sign(SignArgs),
53}
54
55#[derive(Debug, Parser)]
56pub struct SignArgs {
57 pub bid_id: String,
60
61 #[arg(long, env = "TEMPO_KEY_SOURCE")]
63 pub keystore: Option<String>,
64
65 #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
67 pub wallet_password_file: Option<PathBuf>,
68
69 #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
72 pub wallet_address: Option<String>,
73
74 #[arg(long, env = "TEMPO_RPC_URL")]
78 pub rpc_url: Option<String>,
79
80 #[arg(long)]
83 pub skip_allowance_check: bool,
84
85 #[arg(
89 long,
90 env = "TASKFAST_RECEIPT_TIMEOUT",
91 value_parser = humantime::parse_duration,
92 )]
93 pub receipt_timeout: Option<Duration>,
94}
95
96pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
97 match cmd {
98 Command::Sign(a) => sign(ctx, a).await,
99 }
100}
101
102async fn sign(ctx: &Ctx, args: SignArgs) -> CmdResult {
103 let bid_id = Uuid::parse_str(&args.bid_id)
105 .map_err(|e| CmdError::Usage(format!("bid id must be a UUID: {e}")))?;
106
107 let client = ctx.client()?;
108
109 let params = match client.inner().get_bid_escrow_params(&bid_id).await {
111 Ok(v) => v.into_inner(),
112 Err(e) => {
113 let mapped = map_api_error(e).await;
114 if matches!(&mapped, taskfast_client::Error::Decode(_))
121 && mapped.to_string().contains("arbitrator_address")
122 {
123 return Err(CmdError::Validation {
124 code: "server_missing_arbitrator".into(),
125 message: "server omitted `arbitrator_address`; this deployment predates \
126 v2 arbitrated escrow — upgrade the server or use a CLI version \
127 that matches it"
128 .into(),
129 });
130 }
131 return Err(mapped.into());
132 }
133 };
134
135 let token_address: Address = params.token_address.parse().map_err(|e| {
144 CmdError::Decode(format!(
145 "server token_address `{}` not a valid EVM address: {e}",
146 params.token_address
147 ))
148 })?;
149 let task_escrow: Address = params.task_escrow_contract.parse().map_err(|e| {
150 CmdError::Decode(format!(
151 "server task_escrow_contract `{}` not a valid EVM address: {e}",
152 params.task_escrow_contract
153 ))
154 })?;
155 let worker: Address = params.worker_address.parse().map_err(|e| {
156 CmdError::Decode(format!(
157 "server worker_address `{}` not a valid EVM address: {e}",
158 params.worker_address
159 ))
160 })?;
161 let platform_wallet: Address = params.platform_wallet.parse().map_err(|e| {
162 CmdError::Decode(format!(
163 "server platform_wallet `{}` not a valid EVM address: {e}",
164 params.platform_wallet
165 ))
166 })?;
167 let arbitrator: Address = params.arbitrator_address.parse().map_err(|e| {
171 CmdError::Decode(format!(
172 "server arbitrator_address `{}` not a valid EVM address: {e}",
173 params.arbitrator_address
174 ))
175 })?;
176 if arbitrator == Address::ZERO {
180 return Err(CmdError::Decode(
181 "server returned a zero arbitrator_address; the v2 escrow open requires a \
182 pool arbitrator and would revert (arbitrator_not_in_pool)"
183 .to_string(),
184 ));
185 }
186
187 let chain_id_u64 = u64::try_from(params.chain_id).map_err(|_| {
192 CmdError::Decode(format!(
193 "escrow params chain_id={} is negative",
194 params.chain_id
195 ))
196 })?;
197 let verifying_contract = task_escrow;
198 let domain = DistributionDomain::new(chain_id_u64, verifying_contract);
199
200 let decimals = u8::try_from(params.decimals).map_err(|_| {
201 CmdError::Decode(format!(
202 "escrow params decimals={} out of u8 range",
203 params.decimals
204 ))
205 })?;
206 let deposit = decimal_to_u256(¶ms.amount, decimals)?;
207 let platform_fee = decimal_to_u256(¶ms.platform_fee_amount, decimals)?;
208
209 let memo_hash_opt: Option<B256> = params
212 .memo_hash
213 .as_deref()
214 .map(|s| {
215 B256::from_str(s).map_err(|e| {
216 CmdError::Decode(format!(
217 "server memo_hash `{s}` not a 0x-prefixed 32-byte hex: {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 "escrow approval",
235 )?;
236
237 let salt = B256::from(rand::random::<[u8; 32]>());
242 let escrow_id = compute_escrow_id(&EscrowIdParams {
243 poster: signer.address(),
244 worker,
245 token: token_address,
246 deposit,
247 platform_fee_amount: platform_fee,
248 platform: platform_wallet,
249 arbitrator,
250 salt,
251 });
252
253 let mut deadline_unix = server_deadline_or_abort(¶ms)?;
261 let mut signature_hex = sign_deadline(&signer, &domain, escrow_id, deadline_unix)?;
262
263 let open_calldata: Bytes = if let Some(memo_hash) = memo_hash_opt {
266 TaskEscrow::openWithMemoCall {
267 token: token_address,
268 deposit,
269 worker,
270 platformFeeAmount: platform_fee,
271 platform: platform_wallet,
272 arbitrator,
273 salt,
274 memoHash: memo_hash,
275 }
276 .abi_encode()
277 .into()
278 } else {
279 TaskEscrow::openCall {
280 token: token_address,
281 deposit,
282 worker,
283 platformFeeAmount: platform_fee,
284 platform: platform_wallet,
285 arbitrator,
286 salt,
287 }
288 .abi_encode()
289 .into()
290 };
291
292 let (rpc_url, _via_proxy) = if let Some(ref url) = args.rpc_url {
299 validate_override_rpc_url(
300 url,
301 network_policy_for_chain_id(chain_id_u64),
302 ctx.allow_custom_endpoints,
303 )?;
304 (url.clone(), false)
305 } else {
306 let cfg = client.fetch_network_config().await.map_err(|e| {
307 CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
308 })?;
309 let (_name, entry) = cfg.entry_by_chain_id(params.chain_id).map_err(|e| {
310 CmdError::Server(format!(
311 "deployment at {} does not advertise chain_id={}: {e}",
312 ctx.base_url(),
313 params.chain_id
314 ))
315 })?;
316 if !is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
320 return Err(CmdError::Server(format!(
321 "deployment at {} returned rpc_url {:?} for chain_id={}, \
322 which is not on the same host. Refusing to route RPC \
323 traffic off-host.",
324 ctx.base_url(),
325 entry.rpc_url,
326 params.chain_id,
327 )));
328 }
329 (entry.rpc_url.clone(), true)
330 };
331
332 if ctx.dry_run {
333 return Ok(Envelope::success(
334 ctx.environment,
335 ctx.dry_run,
336 json!({
337 "action": "would_sign_escrow",
338 "bid_id": bid_id.to_string(),
339 "task_id": params.task_id.to_string(),
340 "escrow_id": format!("{escrow_id:#x}"),
341 "arbitrator": format!("{arbitrator:#x}"),
342 "salt": format!("{salt:#x}"),
343 "deadline": deadline_unix,
344 "signature": signature_hex,
345 "open_calldata": format!("0x{}", hex::encode(&open_calldata)),
346 "memo_hash": params.memo_hash,
347 "rpc_url": rpc_url,
348 "domain": {
349 "chain_id": chain_id_u64,
350 "verifying_contract": format!("{verifying_contract:#x}"),
351 },
352 }),
353 ));
354 }
355
356 let http = ctx.rpc_http_client(&client, &rpc_url);
357 let rpc = TempoRpcClient::new(http, rpc_url);
358 let default_timeout = crate::tempo_session::default_receipt_timeout_for_chain_id(chain_id_u64);
359 let receipt_timeout =
360 super::resolve_duration(args.receipt_timeout, ctx.receipt_timeout, default_timeout);
361 let session =
362 crate::tempo_session::TempoSession::new(signer, keystore_path, rpc, receipt_timeout);
363
364 let total_required = deposit
369 .checked_add(platform_fee)
370 .ok_or_else(|| CmdError::Decode("deposit + platform_fee overflow U256".into()))?;
371
372 let mut approval_tx_hex: Option<String> = None;
373 if !args.skip_allowance_check {
374 let balance = session
375 .erc20_balance_of(token_address, session.address())
376 .await?;
377 if balance < total_required {
378 return Err(CmdError::Usage(format!(
379 "poster balance {balance} < required {total_required} (deposit {deposit} + fee {platform_fee}) on token {token_address:#x}"
380 )));
381 }
382 approval_tx_hex = session
383 .ensure_allowance(token_address, task_escrow, total_required)
384 .await?
385 .map(|h| format!("{h:#x}"));
386 }
387
388 let voucher_tx = session
390 .send_transaction_and_wait(
391 task_escrow,
392 open_calldata,
393 "open",
394 Some(" — finalize aborted"),
395 )
396 .await?;
397 let voucher_hex = format!("{voucher_tx:#x}");
398
399 let mut attempts = 0u8;
406 let resp = loop {
407 let deadline_i64 = deadline_unix
411 .map(|d| {
412 i64::try_from(d)
413 .map_err(|_| CmdError::Decode(format!("deadline {d} exceeds i64 range")))
414 })
415 .transpose()?;
416 let body = BidEscrowFinalizeRequest {
417 voucher: voucher_hex.clone(),
418 poster_approval_signature: signature_hex.clone(),
419 poster_approval_deadline: deadline_i64
420 .map(BidEscrowFinalizeRequestPosterApprovalDeadline::Integer),
421 memo_hash: params.memo_hash.clone(),
422 };
423 match client.inner().finalize_bid_escrow(&bid_id, &body).await {
424 Ok(r) => break r.into_inner(),
425 Err(e) => {
426 let mapped = map_api_error(e).await;
427 if attempts == 0 && is_deadline_below_minimum(&mapped) {
428 attempts += 1;
429 let fresh = match client.inner().get_bid_escrow_params(&bid_id).await {
430 Ok(v) => v.into_inner(),
431 Err(e) => return Err(map_api_error(e).await.into()),
432 };
433 deadline_unix = server_deadline_or_abort(&fresh)?;
434 signature_hex =
435 sign_deadline(session.signer(), &domain, escrow_id, deadline_unix)?;
436 continue;
437 }
438 return Err(mapped.into());
439 }
440 }
441 };
442
443 Ok(Envelope::success(
444 ctx.environment,
445 ctx.dry_run,
446 json!({
447 "bid_id": resp.bid_id,
448 "task_id": resp.task_id,
449 "status": resp.status,
450 "task_status": resp.task_status,
451 "escrow_id": format!("{escrow_id:#x}"),
452 "voucher_tx_hash": voucher_hex,
453 "approval_tx_hash": approval_tx_hex,
454 "deadline": deadline_unix,
455 }),
456 ))
457}
458
459fn server_deadline_or_abort(params: &BidEscrowParamsResponse) -> Result<Option<u64>, CmdError> {
470 let (deadline, min_lifetime) = match (
471 params.poster_approval_deadline,
472 params.poster_approval_min_lifetime,
473 ) {
474 (Some(d), Some(m)) => (d, m),
475 (None, None) if params.contract_version.as_deref() == Some("v3") => return Ok(None),
476 _ => {
477 return Err(CmdError::Validation {
478 code: "server_missing_approval_deadline".into(),
479 message: "server omitted `poster_approval_deadline`; this deployment predates \
480 the server-issued escrow deadline — upgrade the server or use a CLI \
481 version that matches it"
482 .into(),
483 })
484 }
485 };
486 let deadline = u64::try_from(deadline).map_err(|_| {
487 CmdError::Decode(format!(
488 "server poster_approval_deadline={deadline} is negative"
489 ))
490 })?;
491 let min_lifetime = u64::try_from(min_lifetime).map_err(|_| {
492 CmdError::Decode(format!(
493 "server poster_approval_min_lifetime={min_lifetime} is negative"
494 ))
495 })?;
496 let now = u64::try_from(chrono::Utc::now().timestamp())
497 .map_err(|_| CmdError::Decode("system clock before epoch".into()))?;
498 let remaining = deadline.saturating_sub(now);
499 if remaining < min_lifetime {
500 return Err(CmdError::Validation {
501 code: "deadline_below_minimum".into(),
502 message: format!(
503 "server-issued deadline has {remaining}s remaining, below the \
504 {min_lifetime}s minimum — aborting rather than sign an approval the \
505 server will reject. Re-run once the server re-issues a deadline."
506 ),
507 });
508 }
509 Ok(Some(deadline))
510}
511
512fn sign_deadline(
514 signer: &PrivateKeySigner,
515 domain: &DistributionDomain,
516 escrow_id: B256,
517 deadline: Option<u64>,
518) -> Result<Option<String>, SigningError> {
519 deadline
520 .map(|d| sign_distribution(signer, domain, escrow_id, U256::from(d)))
521 .transpose()
522}
523
524fn is_deadline_below_minimum(err: &taskfast_client::Error) -> bool {
527 matches!(
528 err,
529 taskfast_client::Error::Validation { code, .. } if code == "deadline_below_minimum"
530 )
531}
532
533fn decimal_to_u256(s: &str, decimals: u8) -> Result<U256, CmdError> {
537 let trimmed = s.trim();
538 if trimmed.is_empty() {
539 return Err(CmdError::Decode("empty decimal amount".into()));
540 }
541 if trimmed.starts_with('-') {
542 return Err(CmdError::Decode(format!(
543 "negative amount `{s}` disallowed"
544 )));
545 }
546 let (whole, frac) = match trimmed.split_once('.') {
547 Some((w, f)) => (w, f),
548 None => (trimmed, ""),
549 };
550 let frac_len = frac.len();
551 if frac_len > decimals as usize {
552 return Err(CmdError::Decode(format!(
553 "amount `{s}` has {frac_len} fractional digits but token has only {decimals}"
554 )));
555 }
556 let mut combined = String::with_capacity(whole.len() + decimals as usize);
557 combined.push_str(whole);
558 combined.push_str(frac);
559 for _ in 0..(decimals as usize - frac_len) {
560 combined.push('0');
561 }
562 let stripped = combined.trim_start_matches('0');
564 let digits = if stripped.is_empty() { "0" } else { stripped };
565 U256::from_str_radix(digits, 10)
566 .map_err(|e| CmdError::Decode(format!("amount `{s}` not parseable as integer: {e}")))
567}
568
569#[cfg(test)]
570mod tests {
571 use super::*;
572 use taskfast_chains::tempo::TEMPO_MAINNET_CHAIN_ID;
573
574 fn default_receipt_timeout(chain_id: i64) -> Duration {
575 match u64::try_from(chain_id) {
576 Ok(id) => crate::tempo_session::default_receipt_timeout_for_chain_id(id),
577 _ => crate::tempo_session::DEFAULT_RECEIPT_TIMEOUT_TESTNET,
578 }
579 }
580
581 #[test]
582 fn decimal_to_u256_scales_basic() {
583 assert_eq!(
584 decimal_to_u256("75.00", 6).unwrap(),
585 U256::from(75_000_000u64)
586 );
587 assert_eq!(decimal_to_u256("75", 6).unwrap(), U256::from(75_000_000u64));
588 assert_eq!(decimal_to_u256("0.5", 6).unwrap(), U256::from(500_000u64));
589 assert_eq!(decimal_to_u256("0", 6).unwrap(), U256::ZERO);
590 }
591
592 #[test]
593 fn decimal_to_u256_rejects_excess_fractional_digits() {
594 let err = decimal_to_u256("1.1234567", 6).expect_err("7 > 6 must fail");
595 matches!(err, CmdError::Decode(_));
596 }
597
598 #[test]
599 fn decimal_to_u256_rejects_negative() {
600 let err = decimal_to_u256("-1.00", 6).expect_err("negative must fail");
601 matches!(err, CmdError::Decode(_));
602 }
603
604 #[test]
605 fn chain_id_constants_match_tempo_protocol() {
606 use taskfast_chains::tempo::TEMPO_TESTNET_CHAIN_ID;
607 assert_eq!(TEMPO_MAINNET_CHAIN_ID, 4_217);
611 assert_eq!(TEMPO_TESTNET_CHAIN_ID, 42_431);
612 }
613
614 #[test]
615 fn default_receipt_timeout_mainnet_is_three_minutes() {
616 assert_eq!(default_receipt_timeout(4_217), Duration::from_mins(3));
617 }
618
619 #[test]
620 fn default_receipt_timeout_testnet_is_one_minute() {
621 assert_eq!(default_receipt_timeout(42_431), Duration::from_mins(1));
622 }
623
624 #[test]
625 fn default_receipt_timeout_unknown_chain_falls_back_to_testnet_budget() {
626 assert_eq!(default_receipt_timeout(31_337), Duration::from_mins(1));
628 }
629
630 #[test]
631 fn deadline_below_minimum_detects_only_that_code() {
632 assert!(is_deadline_below_minimum(
633 &taskfast_client::Error::Validation {
634 code: "deadline_below_minimum".into(),
635 message: "x".into(),
636 }
637 ));
638 assert!(!is_deadline_below_minimum(
639 &taskfast_client::Error::Validation {
640 code: "validation_error".into(),
641 message: "x".into(),
642 }
643 ));
644 assert!(!is_deadline_below_minimum(&taskfast_client::Error::Server(
645 "deadline_below_minimum".into()
646 )));
647 }
648}