Skip to main content

taskfast_cli/cmd/
escalate.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast escalate` — the poster's on-chain dispute path (taskfast#2044).
3//!
4//! After a Tier 1 or Tier 2 remedy fails, the dispute moves to the poster's own
5//! wallet: TaskFast holds no key that can sign `dispute(bytes32)`.
6//!
7//!  - `escalate reject-remedy <task_id>` → `POST /tasks/{id}/dispute/reject-remedy`
8//!    moves a dispute with a failed remedy to "awaiting the poster's signature".
9//!  - `escalate sign <task_id>` → `GET /tasks/{id}/dispute/signing-params`, then
10//!    signs and broadcasts `ArbitratedEscrow.dispute(escrowId)` from the poster's
11//!    keystore. Every value comes from the server; the CLI computes none.
12//!
13//! The dispute counts as signed only when the server's reconciler sees the
14//! finalized `EscrowDisputed` log, so output says "submitted", never "disputed".
15//! The CLI never compares its own clock with `escalation_deadline`: with
16//! `lapse_pending` true it warns and still sends, because the server accepts a
17//! signature until it records the lapse.
18//!
19//! Refuse-to-sign guards (all before any transaction; signing safety is the
20//! CLI's one unique job, so these deliberately do not trust the server blindly):
21//!  1. keystore address ≠ a non-nil `poster_wallet_address`;
22//!  2. `chain_id` ≠ the configured network's chain id, or ≠ the RPC node's;
23//!  3. `task_escrow_contract` / `escrow_id` malformed, or the contract is zero;
24//!  4. keystore address ≠ `--wallet-address` / configured wallet address.
25//!
26//! `--dry-run` runs guards 1–4 except the node check (it opens no RPC).
27//!
28//! `escalate timeout-resolve <task_id>` is the worker's fallback when the
29//! arbitrator never rules: once `disputedAt + DISPUTE_TIMEOUT` (120 days) has
30//! passed on a `Disputed` escrow, anyone may send `timeoutResolveDispute`.
31//! Inputs are the task's own `escrow_id` + `settlement_domain` (party-gated, so
32//! the worker can read them; venue-scoped, so a zone escrow is addressed
33//! correctly, gh#111) and the chain itself: escrow state, `disputedAt`,
34//! `DISPUTE_TIMEOUT` and the latest block time, which is what the contract
35//! compares, never the local clock. It refuses, sending nothing, on a wrong
36//! chain, a non-`Disputed` escrow, or a deadline still ahead. `--dry-run` makes
37//! read-only RPC calls so it can evaluate those refusals. The CLI does not say
38//! who gets paid (the contract decides by who raised the dispute) and writes
39//! nothing to the server: the reconciler mirrors the `EscrowDisputeTimedOut` log.
40
41use std::path::PathBuf;
42use std::str::FromStr;
43use std::time::Duration;
44
45use alloy_primitives::{Address, Bytes, B256};
46use clap::Parser;
47use serde_json::json;
48use uuid::Uuid;
49
50use super::{
51    is_proxy_rpc_url, network_policy_for_chain_id, validate_override_rpc_url, CmdError, CmdResult,
52    Ctx,
53};
54use crate::envelope::{Envelope, SecurityWarning};
55
56use taskfast_agent::chain::{
57    decode_escrow_state, decode_u256, dispute_calldata, dispute_timeout_calldata,
58    disputed_at_calldata, get_escrow_calldata, timeout_resolve_calldata, ESCROW_STATE_DISPUTED,
59};
60use taskfast_agent::tempo_rpc::TempoRpcClient;
61use taskfast_client::map_api_error;
62
63#[derive(Debug, clap::Subcommand)]
64pub enum Command {
65    /// Poster: reject a failed remedy; the dispute then awaits your on-chain signature.
66    RejectRemedy(RejectRemedyArgs),
67    /// Poster: sign + broadcast `dispute(escrowId)` from your own wallet.
68    Sign(SignArgs),
69    /// Worker: after the 120-day dispute timeout, sign + broadcast `timeoutResolveDispute(escrowId)`.
70    TimeoutResolve(TimeoutResolveArgs),
71}
72
73#[derive(Debug, Parser)]
74pub struct RejectRemedyArgs {
75    /// Task UUID. Caller must be the task's poster.
76    pub task_id: String,
77}
78
79#[derive(Debug, Parser)]
80pub struct SignArgs {
81    /// Task UUID. The dispute must be awaiting the poster's signature.
82    pub task_id: String,
83
84    /// Keystore reference (same form as `taskfast escrow sign`).
85    #[arg(long, env = "TEMPO_KEY_SOURCE")]
86    pub keystore: Option<String>,
87
88    /// Path to keystore password file.
89    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
90    pub wallet_password_file: Option<PathBuf>,
91
92    /// Poster wallet address preflight (0x-prefixed): fail if the keystore differs.
93    #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
94    pub wallet_address: Option<String>,
95
96    /// Tempo RPC override. Defaults to the deployment's authenticated proxy
97    /// for the configured network (`GET /config/network`).
98    #[arg(long, env = "TEMPO_RPC_URL")]
99    pub rpc_url: Option<String>,
100
101    /// Receipt-polling ceiling — human duration (`3min`, `90s`).
102    #[arg(
103        long,
104        env = "TASKFAST_RECEIPT_TIMEOUT",
105        value_parser = humantime::parse_duration,
106    )]
107    pub receipt_timeout: Option<Duration>,
108}
109
110/// Same wallet/RPC flags as [`SignArgs`]; the task must be one you are a party to.
111#[derive(Debug, Parser)]
112pub struct TimeoutResolveArgs {
113    /// Task UUID. The task's escrow must be `Disputed` on chain.
114    pub task_id: String,
115
116    /// Keystore reference (same form as `taskfast escrow sign`).
117    #[arg(long, env = "TEMPO_KEY_SOURCE")]
118    pub keystore: Option<String>,
119
120    /// Path to keystore password file.
121    #[arg(long, env = "TASKFAST_WALLET_PASSWORD_FILE")]
122    pub wallet_password_file: Option<PathBuf>,
123
124    /// Wallet address preflight (0x-prefixed): fail if the keystore differs.
125    #[arg(long, env = "TEMPO_WALLET_ADDRESS")]
126    pub wallet_address: Option<String>,
127
128    /// Tempo RPC override. Defaults to the deployment's authenticated proxy
129    /// for the configured network (`GET /config/network`).
130    #[arg(long, env = "TEMPO_RPC_URL")]
131    pub rpc_url: Option<String>,
132
133    /// Receipt-polling ceiling — human duration (`3min`, `90s`).
134    #[arg(
135        long,
136        env = "TASKFAST_RECEIPT_TIMEOUT",
137        value_parser = humantime::parse_duration,
138    )]
139    pub receipt_timeout: Option<Duration>,
140}
141
142pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
143    match cmd {
144        Command::RejectRemedy(a) => reject_remedy(ctx, a).await,
145        Command::Sign(a) => sign(ctx, a).await,
146        Command::TimeoutResolve(a) => timeout_resolve(ctx, a).await,
147    }
148}
149
150fn parse_task_id(raw: &str) -> Result<Uuid, CmdError> {
151    Uuid::parse_str(raw).map_err(|e| CmdError::Usage(format!("task id must be a UUID: {e}")))
152}
153
154/// One-line next step per server refusal. Hints only; the server's code and
155/// text stay in the error so orchestrators can still branch on the code.
156fn hint(code: &str) -> Option<&'static str> {
157    Some(match code {
158        "onchain_dispute_disabled" => "on-chain dispute signing is not enabled on this deployment",
159        "remedy_not_rejectable" => "no failed remedy can be rejected on this dispute right now",
160        "dispute_not_awaiting_signature" => {
161            "the dispute is absent, already resolved, or not awaiting your signature; run `taskfast dispute <task_id>`"
162        }
163        "escrow_already_disputed" => "the escrow is already disputed on chain; nothing to sign",
164        "escrow_not_held" => "the escrow is not held, so it cannot be disputed",
165        _ => return None,
166    })
167}
168
169/// Map a server error, appending the action hint for the known refusal codes.
170fn refusal(err: taskfast_client::Error) -> CmdError {
171    match err {
172        taskfast_client::Error::Validation { code, message } => match hint(&code) {
173            Some(h) => CmdError::Validation {
174                message: format!("{message} → {h}"),
175                code,
176            },
177            None => CmdError::Validation { code, message },
178        },
179        // The shared 5xx mapper keeps only the message, not the server's error
180        // code, so this is a hint (our inference), never a `code` value.
181        taskfast_client::Error::Server(m) if m.contains("503") => CmdError::Server(format!(
182            "{m} → hint: on this endpoint a 503 normally means the escrow target is \
183             unavailable (escrow_target_unavailable); retry later"
184        )),
185        other => other.into(),
186    }
187}
188
189async fn reject_remedy(ctx: &Ctx, args: RejectRemedyArgs) -> CmdResult {
190    let task_id = parse_task_id(&args.task_id)?;
191    if ctx.dry_run {
192        return Ok(Envelope::success(
193            ctx.environment,
194            ctx.dry_run,
195            json!({ "action": "would_reject_remedy", "task_id": task_id.to_string() }),
196        ));
197    }
198    let client = ctx.client()?;
199    let resp = match client.inner().reject_remedy(&task_id).await {
200        Ok(v) => v.into_inner(),
201        Err(e) => return Err(refusal(map_api_error(e).await)),
202    };
203    Ok(Envelope::success(
204        ctx.environment,
205        ctx.dry_run,
206        json!({
207            "task_id": resp.task_id,
208            "phase": resp.phase,
209            "escalation_deadline": resp.escalation_deadline,
210        }),
211    ))
212}
213
214fn missing(field: &str) -> CmdError {
215    CmdError::Decode(format!("signing-params response omitted `{field}`"))
216}
217
218async fn sign(ctx: &Ctx, args: SignArgs) -> CmdResult {
219    let task_id = parse_task_id(&args.task_id)?;
220    let client = ctx.client()?;
221
222    // 1. Server-derived params. Nothing below is computed locally.
223    let params = match client.inner().get_dispute_signing_params(&task_id).await {
224        Ok(v) => v.into_inner(),
225        Err(e) => return Err(refusal(map_api_error(e).await)),
226    };
227    let chain_id = params.chain_id.ok_or_else(|| missing("chain_id"))?;
228    let chain_id_u64 = u64::try_from(chain_id)
229        .map_err(|_| CmdError::Decode(format!("signing-params chain_id={chain_id} is negative")))?;
230    let raw_contract = params
231        .task_escrow_contract
232        .as_deref()
233        .ok_or_else(|| missing("task_escrow_contract"))?;
234    let raw_escrow_id = params
235        .escrow_id
236        .as_deref()
237        .ok_or_else(|| missing("escrow_id"))?;
238
239    // Guard 3: well-formed target; the zero address is never a real escrow.
240    let contract: Address = raw_contract.parse().map_err(|e| {
241        CmdError::Decode(format!(
242            "server task_escrow_contract `{raw_contract}` not a valid EVM address: {e}"
243        ))
244    })?;
245    if contract == Address::ZERO {
246        return Err(CmdError::Decode(
247            "server returned the zero address as task_escrow_contract; refusing to sign".into(),
248        ));
249    }
250    let escrow_id = B256::from_str(raw_escrow_id).map_err(|e| {
251        CmdError::Decode(format!(
252            "server escrow_id `{raw_escrow_id}` not a 0x-prefixed 32-byte hex: {e}"
253        ))
254    })?;
255
256    // 2. Signer + guards 4 and 1.
257    let keystore_path = super::wallet_args::resolve_keystore_path(
258        args.keystore.as_deref(),
259        ctx.keystore_path.as_deref(),
260    );
261    let signer = super::wallet_args::load_signer_and_validate(
262        keystore_path.as_deref(),
263        args.wallet_password_file.as_deref(),
264        args.wallet_address
265            .as_deref()
266            .or(ctx.wallet_address.as_deref()),
267        "escrow dispute",
268    )?;
269    let mut warnings: Vec<SecurityWarning> = Vec::new();
270    match params.poster_wallet_address.as_deref() {
271        Some(poster) => {
272            let poster_addr: Address = poster.parse().map_err(|e| {
273                CmdError::Decode(format!(
274                    "server poster_wallet_address `{poster}` not a valid EVM address: {e}"
275                ))
276            })?;
277            if poster_addr != signer.address() {
278                return Err(CmdError::Usage(format!(
279                    "keystore address {:#x} is not the escrow's poster_wallet_address {poster}; \
280                     connect the wallet that funded this escrow",
281                    signer.address()
282                )));
283            }
284        }
285        None => warnings.push(SecurityWarning {
286            code: "poster_wallet_unknown",
287            message: "server sent no poster_wallet_address (older escrow); the contract still \
288                      reverts if this wallet is not the poster"
289                .into(),
290        }),
291    }
292    if params.lapse_pending == Some(true) {
293        warnings.push(SecurityWarning {
294            code: "lapse_pending",
295            message: format!(
296                "the signing deadline ({}) has passed; the server still accepts a signature \
297                 until it records the lapse, which completes the task in the worker's favor",
298                params
299                    .escalation_deadline
300                    .map_or_else(|| "unknown".to_string(), |d| d.to_rfc3339())
301            ),
302        });
303    }
304
305    // 3. Guard 2 (configured network) + RPC URL.
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 network = ctx.environment.network();
310    let entry = cfg.entry(network.as_str()).map_err(|e| {
311        CmdError::Server(format!(
312            "deployment at {} does not advertise network `{}`: {e}",
313            ctx.base_url(),
314            network.as_str()
315        ))
316    })?;
317    if entry.chain_id != chain_id {
318        return Err(CmdError::Validation {
319            code: "chain_id_mismatch".into(),
320            message: format!(
321                "signing-params chain_id={chain_id} but the configured network `{}` is chain_id={}; refusing to sign",
322                network.as_str(),
323                entry.chain_id
324            ),
325        });
326    }
327    let rpc_url = if let Some(ref url) = args.rpc_url {
328        validate_override_rpc_url(
329            url,
330            network_policy_for_chain_id(chain_id_u64),
331            ctx.allow_custom_endpoints,
332        )?;
333        url.clone()
334    } else {
335        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={chain_id}, which is not on \
338                 the same host. Refusing to route RPC traffic off-host.",
339                ctx.base_url(),
340                entry.rpc_url,
341            )));
342        }
343        entry.rpc_url.clone()
344    };
345
346    let signer_address = signer.address();
347    let calldata: Bytes = dispute_calldata(escrow_id).into();
348    let common = |action: &str| {
349        json!({
350            "action": action,
351            "task_id": task_id.to_string(),
352            "escrow_id": format!("{escrow_id:#x}"),
353            "to": format!("{contract:#x}"),
354            "chain_id": chain_id,
355            "from": format!("{:#x}", signer_address),
356            "calldata": format!("0x{}", hex::encode(&calldata)),
357            "lapse_pending": params.lapse_pending,
358            "escalation_deadline": params.escalation_deadline,
359        })
360    };
361
362    if ctx.dry_run {
363        return Ok(
364            Envelope::success(ctx.environment, ctx.dry_run, common("would_submit_dispute"))
365                .with_warnings(warnings),
366        );
367    }
368
369    // 4. Live: guard 2 against the node, then send.
370    let http = ctx.rpc_http_client(&client, &rpc_url);
371    let rpc = TempoRpcClient::new(http, rpc_url.clone());
372    let node_chain = rpc
373        .chain_id()
374        .await
375        .map_err(|e| CmdError::Server(format!("eth_chainId from {rpc_url}: {e}")))?;
376    if node_chain != chain_id_u64 {
377        return Err(CmdError::Validation {
378            code: "chain_id_mismatch".into(),
379            message: format!(
380                "RPC node reports chain_id={node_chain} but signing-params say {chain_id}; refusing to sign"
381            ),
382        });
383    }
384    let receipt_timeout = super::resolve_duration(
385        args.receipt_timeout,
386        ctx.receipt_timeout,
387        crate::tempo_session::default_receipt_timeout_for_chain_id(chain_id_u64),
388    );
389    let session =
390        crate::tempo_session::TempoSession::new(signer, keystore_path, rpc, receipt_timeout);
391    let tx = session
392        .send_transaction_and_wait(
393            contract,
394            calldata.clone(),
395            "dispute",
396            Some(
397                " (Unauthorized: not the poster's wallet; InvalidState: the escrow can no longer be disputed)",
398            ),
399        )
400        .await?;
401    let mut data = common("dispute_submitted");
402    data["tx_hash"] = json!(format!("{tx:#x}"));
403    data["note"] = json!(
404        "submitted; the dispute counts as signed once TaskFast observes the finalized \
405         EscrowDisputed log"
406    );
407    Ok(Envelope::success(ctx.environment, ctx.dry_run, data).with_warnings(warnings))
408}
409
410fn chain_read_err(what: &str, e: impl std::fmt::Display) -> CmdError {
411    CmdError::Server(format!("chain read `{what}` failed: {e}"))
412}
413
414async fn timeout_resolve(ctx: &Ctx, args: TimeoutResolveArgs) -> CmdResult {
415    let task_id = parse_task_id(&args.task_id)?;
416    let client = ctx.client()?;
417
418    // 1. The task's own escrow id + venue domain (party-gated: null for non-parties).
419    let task = match client.inner().get_task(&task_id).await {
420        Ok(v) => v.into_inner(),
421        Err(e) => return Err(refusal(map_api_error(e).await)),
422    };
423    let raw_escrow_id = task
424        .escrow_id
425        .as_ref()
426        .map(|e| e.to_string())
427        .ok_or_else(|| CmdError::Validation {
428            code: "escrow_not_initialized".into(),
429            message: "task has no escrow_id (escrow not initialized, or you are not a party \
430                      to this task); nothing to resolve"
431                .into(),
432        })?;
433    // No readiness fallback: the global domain is the L1 venue, wrong for a zone task.
434    let domain = task
435        .settlement_domain
436        .as_ref()
437        .ok_or_else(|| CmdError::Validation {
438            code: "settlement_domain_unavailable".into(),
439            message: "task has no settlement_domain (venue unresolvable or suspended); \
440                      refusing to guess the escrow contract"
441                .into(),
442        })?;
443    let chain_id = domain.chain_id;
444    let chain_id_u64 = u64::try_from(chain_id).map_err(|_| {
445        CmdError::Decode(format!("settlement_domain chain_id={chain_id} is negative"))
446    })?;
447    let raw_contract = domain.verifying_contract.to_string();
448    let contract: Address = raw_contract.parse().map_err(|e| {
449        CmdError::Decode(format!(
450            "settlement_domain verifying_contract `{raw_contract}` not a valid EVM address: {e}"
451        ))
452    })?;
453    if contract == Address::ZERO {
454        return Err(CmdError::Decode(
455            "server returned the zero address as verifying_contract; refusing to send".into(),
456        ));
457    }
458    let escrow_id = B256::from_str(&raw_escrow_id).map_err(|e| {
459        CmdError::Decode(format!(
460            "server escrow_id `{raw_escrow_id}` not a 0x-prefixed 32-byte hex: {e}"
461        ))
462    })?;
463
464    // 2. Signer + wallet-address preflight. Any wallet may send this call, so
465    //    there is no "must be the worker" guard.
466    let keystore_path = super::wallet_args::resolve_keystore_path(
467        args.keystore.as_deref(),
468        ctx.keystore_path.as_deref(),
469    );
470    let signer = super::wallet_args::load_signer_and_validate(
471        keystore_path.as_deref(),
472        args.wallet_password_file.as_deref(),
473        args.wallet_address
474            .as_deref()
475            .or(ctx.wallet_address.as_deref()),
476        "escrow timeout-resolve",
477    )?;
478
479    // 3. Chain id vs the configured network, then RPC url.
480    let cfg = client.fetch_network_config().await.map_err(|e| {
481        CmdError::Server(format!("fetch network config from {}: {e}", ctx.base_url()))
482    })?;
483    let network = ctx.environment.network();
484    let entry = cfg.entry(network.as_str()).map_err(|e| {
485        CmdError::Server(format!(
486            "deployment at {} does not advertise network `{}`: {e}",
487            ctx.base_url(),
488            network.as_str()
489        ))
490    })?;
491    if entry.chain_id != chain_id {
492        return Err(CmdError::Validation {
493            code: "chain_id_mismatch".into(),
494            message: format!(
495                "task settlement_domain chain_id={chain_id} but the configured network `{}` is chain_id={}; refusing to send",
496                network.as_str(),
497                entry.chain_id
498            ),
499        });
500    }
501    let rpc_url = if let Some(ref url) = args.rpc_url {
502        validate_override_rpc_url(
503            url,
504            network_policy_for_chain_id(chain_id_u64),
505            ctx.allow_custom_endpoints,
506        )?;
507        url.clone()
508    } else {
509        if !is_proxy_rpc_url(&entry.rpc_url, ctx.base_url()) {
510            return Err(CmdError::Server(format!(
511                "deployment at {} returned rpc_url {:?} for chain_id={chain_id}, which is not on \
512                 the same host. Refusing to route RPC traffic off-host.",
513                ctx.base_url(),
514                entry.rpc_url,
515            )));
516        }
517        entry.rpc_url.clone()
518    };
519
520    // 4. Chain reads (also under --dry-run: read-only). Node chain id first, so
521    //    a wrong node is never trusted for the state reads below.
522    let http = ctx.rpc_http_client(&client, &rpc_url);
523    let rpc = TempoRpcClient::new(http, rpc_url.clone());
524    let node_chain = rpc
525        .chain_id()
526        .await
527        .map_err(|e| CmdError::Server(format!("eth_chainId from {rpc_url}: {e}")))?;
528    if node_chain != chain_id_u64 {
529        return Err(CmdError::Validation {
530            code: "chain_id_mismatch".into(),
531            message: format!(
532                "RPC node reports chain_id={node_chain} but the task's settlement_domain says {chain_id}; refusing to send"
533            ),
534        });
535    }
536    let read = |what: &'static str, data: Vec<u8>| {
537        let rpc = &rpc;
538        async move {
539            rpc.eth_call(contract, &data.into())
540                .await
541                .map_err(|e| chain_read_err(what, e))
542        }
543    };
544    let state = decode_escrow_state(&read("getEscrow", get_escrow_calldata(escrow_id)).await?)
545        .map_err(|e| chain_read_err("getEscrow", e))?;
546    if state != ESCROW_STATE_DISPUTED {
547        return Err(CmdError::Validation {
548            code: "escrow_not_disputed".into(),
549            message: format!(
550                "escrow state on chain is {state} (Open=1, PendingRefund=2, Completed=3, \
551                 Refunded=4, Disputed=5); only a Disputed escrow can time out"
552            ),
553        });
554    }
555    let disputed_at = decode_u256(&read("disputedAt", disputed_at_calldata(escrow_id)).await?)
556        .map_err(|e| chain_read_err("disputedAt", e))?;
557    let timeout = decode_u256(&read("DISPUTE_TIMEOUT", dispute_timeout_calldata()).await?)
558        .map_err(|e| chain_read_err("DISPUTE_TIMEOUT", e))?;
559    if disputed_at.is_zero() {
560        return Err(CmdError::Decode(
561            "escrow is Disputed but disputedAt is 0; refusing to send".into(),
562        ));
563    }
564    let eligible_at = disputed_at.saturating_add(timeout);
565    // The contract compares block.timestamp, so we compare the latest block's.
566    let block = rpc
567        .raw_call("eth_getBlockByNumber", json!(["latest", false]))
568        .await
569        .map_err(|e| chain_read_err("eth_getBlockByNumber", e))?;
570    let now = block["timestamp"]
571        .as_str()
572        .and_then(|t| alloy_primitives::U256::from_str(t).ok())
573        .ok_or_else(|| CmdError::Decode("latest block has no readable timestamp".into()))?;
574    if now < eligible_at {
575        let at = i64::try_from(eligible_at)
576            .ok()
577            .and_then(|s| chrono::DateTime::from_timestamp(s, 0))
578            .map_or_else(|| eligible_at.to_string(), |d| d.to_rfc3339());
579        return Err(CmdError::Validation {
580            code: "dispute_timeout_not_elapsed".into(),
581            message: format!(
582                "the dispute timeout has not elapsed on chain: eligible at {at} \
583                 ({} s of chain time remaining); nothing sent",
584                eligible_at - now
585            ),
586        });
587    }
588
589    let signer_address = signer.address();
590    let calldata: Bytes = timeout_resolve_calldata(escrow_id).into();
591    let common = |action: &str| {
592        json!({
593            "action": action,
594            "task_id": task_id.to_string(),
595            "escrow_id": format!("{escrow_id:#x}"),
596            "to": format!("{contract:#x}"),
597            "chain_id": chain_id,
598            "from": format!("{:#x}", signer_address),
599            "calldata": format!("0x{}", hex::encode(&calldata)),
600            "disputed_at": disputed_at.to_string(),
601            "eligible_at": eligible_at.to_string(),
602        })
603    };
604    if ctx.dry_run {
605        return Ok(Envelope::success(
606            ctx.environment,
607            ctx.dry_run,
608            common("would_submit_timeout_resolve"),
609        ));
610    }
611
612    // 5. Send.
613    let receipt_timeout = super::resolve_duration(
614        args.receipt_timeout,
615        ctx.receipt_timeout,
616        crate::tempo_session::default_receipt_timeout_for_chain_id(chain_id_u64),
617    );
618    let session =
619        crate::tempo_session::TempoSession::new(signer, keystore_path, rpc, receipt_timeout);
620    let tx = session
621        .send_transaction_and_wait(
622            contract,
623            calldata.clone(),
624            "timeout-resolve",
625            Some(
626                " (InvalidState: the escrow is no longer Disputed; DisputeTimeoutNotElapsed: the chain clock is behind)",
627            ),
628        )
629        .await?;
630    let mut data = common("timeout_resolve_submitted");
631    data["tx_hash"] = json!(format!("{tx:#x}"));
632    data["note"] = json!(
633        "submitted; the outcome counts once TaskFast observes the finalized \
634         EscrowDisputeTimedOut log. Who is paid is decided by the contract, not predicted here"
635    );
636    Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
637}