quai_provider/
code_wait.rs1use crate::{BlockTag, ContractCodeObservation, Provider, ProviderError};
3use quai_primitives::{Hash32, QuaiAddress};
4use quai_rpc::Transport;
5
6#[derive(Clone, Copy, Debug)]
8#[non_exhaustive]
9pub struct ContractCodeTarget {
10 pub address: QuaiAddress,
12 pub genesis: Hash32,
14 pub expected_runtime: Option<Hash32>,
16}
17impl ContractCodeTarget {
18 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 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#[derive(Clone, Copy, Debug)]
67#[non_exhaustive]
68pub struct CodeWaitConfig {
69 pub timeout_ms: u32,
71 pub poll_interval_ms: u32,
73 pub max_polls: u32,
75}
76impl CodeWaitConfig {
77 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 pub const fn with_timeout_ms(mut self, timeout_ms: u32) -> Self {
87 self.timeout_ms = timeout_ms;
88 self
89 }
90 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 pub const fn with_max_polls(mut self, max_polls: u32) -> Self {
97 self.max_polls = max_polls;
98 self
99 }
100 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#[derive(Debug, thiserror::Error)]
115#[non_exhaustive]
116pub enum CodeWaitError {
117 #[error("invalid contract code wait configuration")]
119 InvalidConfig,
120 #[error("timed out waiting for contract code at {address}")]
122 Timeout {
123 address: QuaiAddress,
125 polls_completed: u32,
127 },
128 #[error("contract code observation budget exhausted at {address}")]
130 PollLimit {
131 address: QuaiAddress,
133 polls_completed: u32,
135 },
136 #[error(transparent)]
138 Provider(#[from] ProviderError),
139 #[error("contract code wait timer failed")]
141 Runtime,
142}
143#[cfg(all(feature = "polling", not(target_arch = "wasm32")))]
144impl<T: Transport> Provider<T> {
145 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}