Skip to main content

quai_provider/
code_wait.rs

1//! Bounded runtime-code appearance checks when a deployment transaction is unknown.
2use crate::{BlockTag, ContractCodeObservation, Provider, ProviderError};
3use quai_primitives::{Hash32, QuaiAddress};
4use quai_rpc::Transport;
5
6/// Explicit account and trusted network/runtime constraints, with no deployment hash.
7#[derive(Clone, Copy, Debug)]
8#[non_exhaustive]
9pub struct ContractCodeTarget {
10    /// Account whose code should appear.
11    pub address: QuaiAddress,
12    /// Required nonzero genesis identity, rechecked in every observation.
13    pub genesis: Hash32,
14    /// Optional expected runtime Keccak; mismatched nonempty code fails immediately.
15    pub expected_runtime: Option<Hash32>,
16}
17impl ContractCodeTarget {
18    /// Code expected at `address` on the `genesis` network, optionally exact.
19    pub const fn new(
20        address: QuaiAddress,
21        genesis: Hash32,
22        expected_runtime: Option<Hash32>,
23    ) -> Self {
24        Self {
25            address,
26            genesis,
27            expected_runtime,
28        }
29    }
30}
31impl ContractCodeTarget {
32    /// One bounded code observation. Empty code or changed canonical anchors
33    /// return None; other failures stop. Nonempty code must satisfy the target.
34    /// Appearance is not authenticated finality, ABI/proxy semantics or execution proof.
35    pub async fn observe<T: Transport>(
36        &self,
37        provider: &Provider<T>,
38    ) -> Result<Option<ContractCodeObservation>, ProviderError> {
39        if self.genesis == Hash32::ZERO {
40            return Err(ProviderError::InvalidRequest("zero code target genesis"));
41        }
42        let observation = match provider
43            .observe_contract_codes(
44                self.genesis,
45                &[(self.address, self.expected_runtime)],
46                BlockTag::Latest,
47            )
48            .await
49        {
50            Err(ProviderError::ObservationChanged) => return Ok(None),
51            other => other?.remove(0),
52        };
53        if observation.code.bytes.bytes().is_empty() {
54            return Ok(None);
55        }
56        if observation.code.matches_expected == Some(false) {
57            return Err(ProviderError::InvalidResult(
58                "contract runtime code mismatch",
59            ));
60        }
61        Ok(Some(observation))
62    }
63}
64/// Portable millisecond limits for code-appearance waiting, without a misleading
65/// confirmation-depth setting. At most 100,000 completed observations.
66#[derive(Clone, Copy, Debug)]
67#[non_exhaustive]
68pub struct CodeWaitConfig {
69    /// Overall deadline, 1..=i32::MAX milliseconds, including RPCs and delays.
70    pub timeout_ms: u32,
71    /// Positive interval, no longer than the timeout.
72    pub poll_interval_ms: u32,
73    /// Independent limit of 1..100000 completed observations.
74    pub max_polls: u32,
75}
76impl CodeWaitConfig {
77    /// Every limit is required: there is deliberately no default.
78    pub const fn new(timeout_ms: u32, poll_interval_ms: u32, max_polls: u32) -> Self {
79        Self {
80            timeout_ms,
81            poll_interval_ms,
82            max_polls,
83        }
84    }
85    /// Replace `timeout_ms`.
86    pub const fn with_timeout_ms(mut self, timeout_ms: u32) -> Self {
87        self.timeout_ms = timeout_ms;
88        self
89    }
90    /// Replace `poll_interval_ms`.
91    pub const fn with_poll_interval_ms(mut self, poll_interval_ms: u32) -> Self {
92        self.poll_interval_ms = poll_interval_ms;
93        self
94    }
95    /// Replace `max_polls`.
96    pub const fn with_max_polls(mut self, max_polls: u32) -> Self {
97        self.max_polls = max_polls;
98        self
99    }
100    /// Validate before timers or I/O on both native and browser runtimes.
101    pub fn validate(self) -> Result<(), CodeWaitError> {
102        if self.timeout_ms == 0
103            || self.timeout_ms > i32::MAX as u32
104            || self.poll_interval_ms == 0
105            || self.poll_interval_ms > self.timeout_ms
106            || !(1..=100_000).contains(&self.max_polls)
107        {
108            return Err(CodeWaitError::InvalidConfig);
109        }
110        Ok(())
111    }
112}
113/// Waiting errors do not undo deployments, change bindings or authorize transactions.
114#[derive(Debug, thiserror::Error)]
115#[non_exhaustive]
116pub enum CodeWaitError {
117    /// Invalid limits or zero expected genesis; no I/O occurs.
118    #[error("invalid contract code wait configuration")]
119    InvalidConfig,
120    /// Observable deadline expired, including time in a stalled read.
121    #[error("timed out waiting for contract code at {address}")]
122    Timeout {
123        /// Watched account.
124        address: QuaiAddress,
125        /// Fully completed observations; a cancelled partial poll does not count.
126        polls_completed: u32,
127    },
128    /// Configured observation count exhausted; absence is not a terminal conclusion.
129    #[error("contract code observation budget exhausted at {address}")]
130    PollLimit {
131        /// Watched account.
132        address: QuaiAddress,
133        /// Fully completed observations.
134        polls_completed: u32,
135    },
136    /// Source error or mismatched identity/code, with no automatic retry.
137    #[error(transparent)]
138    Provider(#[from] ProviderError),
139    /// Browser monotonic timer infrastructure failed.
140    #[error("contract code wait timer failed")]
141    Runtime,
142}
143#[cfg(all(feature = "polling", not(target_arch = "wasm32")))]
144impl<T: Transport> Provider<T> {
145    /// Wait for nonempty, rechecked code without knowing a deployment transaction.
146    /// Overall time and completed polls are bounded. Drop cancels active reads;
147    /// source errors stop, and no transaction is submitted or considered final.
148    pub async fn wait_for_contract_code(
149        &self,
150        target: ContractCodeTarget,
151        config: CodeWaitConfig,
152    ) -> Result<ContractCodeObservation, CodeWaitError> {
153        use std::time::Duration;
154        config.validate()?;
155        if target.genesis == Hash32::ZERO {
156            return Err(CodeWaitError::InvalidConfig);
157        }
158        let deadline = tokio::time::Instant::now()
159            .checked_add(Duration::from_millis(u64::from(config.timeout_ms)))
160            .ok_or(CodeWaitError::InvalidConfig)?;
161        let mut polls = 0;
162        let work = async {
163            loop {
164                let result = target.observe(self).await;
165                if tokio::time::Instant::now() >= deadline {
166                    return Err(CodeWaitError::Timeout {
167                        address: target.address,
168                        polls_completed: polls,
169                    });
170                }
171                let result = result?;
172                polls += 1;
173                if let Some(code) = result {
174                    return Ok(code);
175                }
176                if polls >= config.max_polls {
177                    return Err(CodeWaitError::PollLimit {
178                        address: target.address,
179                        polls_completed: polls,
180                    });
181                }
182                tokio::time::sleep(Duration::from_millis(u64::from(config.poll_interval_ms))).await;
183            }
184        };
185        match tokio::time::timeout_at(deadline, work).await {
186            Ok(result) => result,
187            Err(_) => Err(CodeWaitError::Timeout {
188                address: target.address,
189                polls_completed: polls,
190            }),
191        }
192    }
193}