Skip to main content

quai_browser/
receipt_wait.rs

1//! Browser/worker receipt polling with owned timers and explicit attempt bounds.
2use crate::{BrowserError, BrowserWaitConfig};
3use quai_primitives::{Hash32, Zone};
4use quai_provider::{ConfirmedReceipt, Inclusion, Provider, ProviderError, ReceiptConfirmation};
5use quai_rpc::Transport;
6use std::{cell::Cell, future::Future, task::Poll};
7use wasm_bindgen::prelude::*;
8
9#[wasm_bindgen(module = "/src/timer.js")]
10extern "C" {
11    #[wasm_bindgen(catch, js_name = monotonicNow)]
12    pub(crate) fn now() -> Result<f64, JsValue>;
13    #[wasm_bindgen(catch, js_name = newTimer)]
14    fn new_timer(milliseconds: u32) -> Result<JsValue, JsValue>;
15    #[wasm_bindgen(catch, js_name = waitTimer)]
16    async fn wait_timer(handle: &JsValue) -> Result<JsValue, JsValue>;
17    #[wasm_bindgen(js_name = closeTimer)]
18    fn close_timer(handle: &JsValue);
19}
20pub(crate) struct Timer(JsValue);
21impl Timer {
22    pub(crate) fn new(ms: u32) -> Result<Self, BrowserError> {
23        new_timer(ms)
24            .map(Self)
25            .map_err(|_| BrowserError::InvalidConfig)
26    }
27    pub(crate) async fn wait(&self) -> Result<(), BrowserError> {
28        let elapsed = wait_timer(&self.0)
29            .await
30            .map_err(|_| BrowserError::InvalidResult)?;
31        if elapsed.as_bool() != Some(true) {
32            return Err(BrowserError::InvalidResult);
33        }
34        Ok(())
35    }
36}
37impl Drop for Timer {
38    fn drop(&mut self) {
39        close_timer(&self.0);
40    }
41}
42/// Wait failure never cancels a transaction or authorizes releasing its claims.
43#[derive(Debug, thiserror::Error)]
44#[non_exhaustive]
45pub enum BrowserReceiptWaitError {
46    /// Invalid limits are rejected before timers and provider I/O.
47    #[error("invalid browser transaction wait limits")]
48    InvalidConfig,
49    /// Deadline expired, including time spent awaiting RPCs. Information below is
50    /// from completed polls only; a cancelled partial poll contributes no inclusion.
51    #[error("browser transaction wait timed out for {transaction_hash}")]
52    Timeout {
53        /// Transaction still eligible for later observation.
54        transaction_hash: Hash32,
55        /// Most recent completed poll's inclusion, possibly reorged away.
56        last_completed_inclusion: Option<Inclusion>,
57        /// Number of fully completed observations.
58        polls_completed: u32,
59    },
60    /// Explicit observation budget exhausted, with no rejection inference.
61    #[error("browser transaction observation budget exhausted for {transaction_hash}")]
62    PollLimit {
63        /// Watched transaction.
64        transaction_hash: Hash32,
65        /// Most recent completed poll's inclusion, possibly reorged away.
66        last_completed_inclusion: Option<Inclusion>,
67        /// Number of fully completed observations.
68        polls_completed: u32,
69    },
70    /// A typed provider read failed; no implicit retry or submission is performed.
71    #[error("browser transaction observation failed for {transaction_hash}: {source}")]
72    Provider {
73        /// Watched transaction.
74        transaction_hash: Hash32,
75        /// Read error, without raw browser/provider objects.
76        #[source]
77        source: ProviderError,
78    },
79    /// Required worker/window clock or timer failed. No wall-clock fallback.
80    #[error("browser transaction wait runtime unavailable")]
81    Runtime,
82}
83/// Wait using portable confirmation checks and window/worker monotonic timers.
84/// At most two timers are held; drop clears them and drops the active read future.
85/// Non-Send transports are supported. The deadline covers RPCs and polling delays;
86/// delayed background callbacks cannot return success after observed clock expiry.
87/// Browser scheduling is not real-time and confirmations do not prove finality.
88/// Execution-failed receipts remain explicit successful *observations*.
89pub async fn wait_for_receipt<T: Transport>(
90    provider: &Provider<T>,
91    zone: Zone,
92    transaction_hash: Hash32,
93    config: BrowserWaitConfig,
94) -> Result<ConfirmedReceipt, BrowserReceiptWaitError> {
95    wait_for_observation(
96        transaction_hash,
97        config,
98        ReceiptPoll {
99            provider,
100            zone,
101            transaction_hash,
102            confirmations: config.confirmations,
103        },
104    )
105    .await
106}
107pub(crate) enum WaitObservation<R> {
108    Ready(R),
109    Pending {
110        inclusion: Option<Inclusion>,
111        immediate: bool,
112    },
113}
114pub(crate) trait WaitPoll {
115    type Output;
116    async fn poll(&mut self) -> Result<WaitObservation<Self::Output>, ProviderError>;
117}
118struct ReceiptPoll<'a, T> {
119    provider: &'a Provider<T>,
120    zone: Zone,
121    transaction_hash: Hash32,
122    confirmations: u64,
123}
124impl<T: Transport> WaitPoll for ReceiptPoll<'_, T> {
125    type Output = ConfirmedReceipt;
126    async fn poll(&mut self) -> Result<WaitObservation<Self::Output>, ProviderError> {
127        Ok(
128            match self
129                .provider
130                .observe_receipt_confirmation(self.zone, self.transaction_hash, self.confirmations)
131                .await?
132            {
133                ReceiptConfirmation::Confirmed(receipt) => WaitObservation::Ready(*receipt),
134                ReceiptConfirmation::Pending {
135                    last_observed_inclusion,
136                } => WaitObservation::Pending {
137                    inclusion: last_observed_inclusion,
138                    immediate: false,
139                },
140            },
141        )
142    }
143}
144pub(crate) async fn wait_for_observation<P: WaitPoll>(
145    transaction_hash: Hash32,
146    config: BrowserWaitConfig,
147    mut observer: P,
148) -> Result<P::Output, BrowserReceiptWaitError> {
149    config
150        .validate()
151        .map_err(|_| BrowserReceiptWaitError::InvalidConfig)?;
152    let started = now().map_err(|_| BrowserReceiptWaitError::Runtime)?;
153    let timer = Timer::new(config.timeout_ms).map_err(|_| BrowserReceiptWaitError::Runtime)?;
154    let mut deadline = std::pin::pin!(timer.wait());
155    let last = Cell::new(None);
156    let polls = Cell::new(0u32);
157    let timeout = || BrowserReceiptWaitError::Timeout {
158        transaction_hash,
159        last_completed_inclusion: last.get(),
160        polls_completed: polls.get(),
161    };
162    let expired = || {
163        now()
164            .map(|value| value - started >= f64::from(config.timeout_ms))
165            .map_err(|_| BrowserReceiptWaitError::Runtime)
166    };
167    let work = async {
168        loop {
169            if expired()? {
170                return Err(timeout());
171            }
172            let observation = observer.poll().await;
173            if expired()? {
174                return Err(timeout());
175            }
176            let observation = observation.map_err(|source| BrowserReceiptWaitError::Provider {
177                transaction_hash,
178                source,
179            })?;
180            polls.set(polls.get() + 1);
181            let immediate = match observation {
182                WaitObservation::Ready(result) => return Ok(result),
183                WaitObservation::Pending {
184                    inclusion,
185                    immediate,
186                } => {
187                    last.set(inclusion);
188                    immediate
189                }
190            };
191            if polls.get() >= config.max_polls {
192                return Err(BrowserReceiptWaitError::PollLimit {
193                    transaction_hash,
194                    last_completed_inclusion: last.get(),
195                    polls_completed: polls.get(),
196                });
197            }
198            if immediate {
199                continue;
200            }
201            Timer::new(config.poll_interval_ms)
202                .map_err(|_| BrowserReceiptWaitError::Runtime)?
203                .wait()
204                .await
205                .map_err(|_| BrowserReceiptWaitError::Runtime)?;
206        }
207    };
208    let mut work = std::pin::pin!(work);
209    std::future::poll_fn(|cx| {
210        match expired() {
211            Ok(true) => return Poll::Ready(Err(timeout())),
212            Err(e) => return Poll::Ready(Err(e)),
213            Ok(false) => {}
214        }
215        if let Poll::Ready(result) = deadline.as_mut().poll(cx) {
216            return Poll::Ready(Err(if result.is_ok() {
217                timeout()
218            } else {
219                BrowserReceiptWaitError::Runtime
220            }));
221        }
222        work.as_mut().poll(cx)
223    })
224    .await
225}