Skip to main content

quai_browser/
lib.rs

1//! Native-independent browser boundaries plus wasm-only Fetch and injected Quai adapters.
2//!
3//! Browser APIs require an application-selected endpoint/provider. Construction performs no
4//! network requests and never prompts for accounts. Heavy derivation and persistent wallet
5//! storage remain separate worker/storage responsibilities.
6#[cfg(any(target_arch = "wasm32", test))]
7use quai_rpc::RemoteError;
8use quai_rpc::RpcError;
9#[cfg(any(target_arch = "wasm32", test))]
10use serde::Deserialize;
11#[cfg(any(target_arch = "wasm32", test))]
12use serde_json::Value;
13
14#[cfg(target_arch = "wasm32")]
15mod browser;
16#[cfg(target_arch = "wasm32")]
17mod resource;
18#[cfg(target_arch = "wasm32")]
19pub use browser::{
20    BrowserFetchTransport, InjectedProvider, InjectedSubmissionTransport,
21    WalletSendAcknowledgement, WalletSendError, WalletSendIdentity, WalletSendObservation,
22    fill_random,
23};
24#[cfg(target_arch = "wasm32")]
25pub use quai_signer::{DomainPolicy, TypedData};
26#[cfg(target_arch = "wasm32")]
27pub use resource::BrowserResourceFetch;
28
29/// Browser resource limits. Concurrent calls fail fast when capacity is exhausted.
30#[derive(Clone, Copy, Debug)]
31#[non_exhaustive]
32pub struct BrowserConfig {
33    /// Total request wait deadline in milliseconds; browser suspension can delay timers.
34    pub request_timeout_ms: u32,
35    /// Maximum serialized outgoing JSON bytes.
36    pub max_request_bytes: usize,
37    /// Maximum streamed response or serialized injected result bytes.
38    pub max_response_bytes: usize,
39    /// Maximum active operations across all clones; no unbounded waiting queue.
40    pub max_in_flight: usize,
41}
42impl BrowserConfig {
43    /// Replace `request_timeout_ms`.
44    pub const fn with_request_timeout_ms(mut self, request_timeout_ms: u32) -> Self {
45        self.request_timeout_ms = request_timeout_ms;
46        self
47    }
48    /// Replace `max_request_bytes`.
49    pub const fn with_max_request_bytes(mut self, max_request_bytes: usize) -> Self {
50        self.max_request_bytes = max_request_bytes;
51        self
52    }
53    /// Replace `max_response_bytes`.
54    pub const fn with_max_response_bytes(mut self, max_response_bytes: usize) -> Self {
55        self.max_response_bytes = max_response_bytes;
56        self
57    }
58    /// Replace `max_in_flight`.
59    pub const fn with_max_in_flight(mut self, max_in_flight: usize) -> Self {
60        self.max_in_flight = max_in_flight;
61        self
62    }
63}
64impl Default for BrowserConfig {
65    fn default() -> Self {
66        Self {
67            request_timeout_ms: 10_000,
68            max_request_bytes: 1024 * 1024,
69            max_response_bytes: 2 * 1024 * 1024,
70            max_in_flight: 8,
71        }
72    }
73}
74impl BrowserConfig {
75    /// Validate limits without touching browser globals or the network.
76    pub fn validate(&self) -> Result<(), BrowserError> {
77        if self.request_timeout_ms == 0
78            || self.request_timeout_ms > i32::MAX as u32
79            || self.max_request_bytes == 0
80            || self.max_request_bytes > 16 * 1024 * 1024
81            || self.max_response_bytes == 0
82            || self.max_response_bytes > 16 * 1024 * 1024
83            || self.max_in_flight == 0
84            || self.max_in_flight > 128
85            || self
86                .max_response_bytes
87                .checked_mul(self.max_in_flight)
88                .is_none_or(|n| n > 128 * 1024 * 1024)
89        {
90            return Err(BrowserError::InvalidConfig);
91        }
92        Ok(())
93    }
94}
95
96/// Sanitized browser failures. No provider strings, payloads, keys or URLs are retained.
97#[derive(Debug, thiserror::Error)]
98#[non_exhaustive]
99pub enum BrowserError {
100    /// IndexedDB open/transaction/schema/quota failure; no remote text is retained.
101    #[error("browser snapshot storage failed")]
102    Storage,
103    /// A concurrent writer or stale tab changed the snapshot revision.
104    #[error("browser snapshot revision conflict")]
105    StorageConflict,
106    /// Configuration or endpoint does not match this adapter.
107    #[error("invalid browser adapter configuration")]
108    InvalidConfig,
109    /// A configured concurrent-operation limit was reached.
110    #[error("browser adapter concurrency limit reached")]
111    Busy,
112    /// Permission-sensitive RPC must use an explicit wallet API.
113    #[error("method requires an explicit supported wallet operation")]
114    AuthorizationRequired,
115    /// The injected wallet reports another network.
116    #[error("injected provider chain ID mismatch")]
117    ChainMismatch,
118    /// Accounts, chain or connection changed while an operation was awaiting the wallet.
119    #[error("injected provider context changed during request")]
120    ContextChanged,
121    /// Wallet result or message/address request has an invalid shape.
122    #[error("invalid injected provider result or request")]
123    InvalidResult,
124    /// The specified account is not currently exposed by the wallet.
125    #[error("account is not authorized by the injected wallet")]
126    AccountUnavailable,
127    /// Numeric EIP-1193 failure, including 4001 user rejection and 4200 unsupported method.
128    #[error("injected provider rejected request (code {0})")]
129    Provider(i64),
130    /// Web Crypto entropy is unavailable or the request exceeds its 65,536-byte limit.
131    #[error("secure browser entropy unavailable")]
132    EntropyUnavailable,
133    /// Bounded RPC/transport error.
134    #[error(transparent)]
135    Rpc(#[from] RpcError),
136}
137
138#[cfg(any(target_arch = "wasm32", test))]
139fn read_method(method: &str) -> bool {
140    matches!(
141        method,
142        "quai_chainId"
143            | "quai_blockNumber"
144            | "quai_getBalance"
145            | "quai_getTransactionCount"
146            | "quai_gasPrice"
147            | "quai_estimateGas"
148            | "quai_getCode"
149            | "quai_getStorageAt"
150            | "quai_call"
151            | "quai_getTransactionByHash"
152            | "quai_getTransactionReceipt"
153            | "quai_getOutpointsByAddress"
154            | "quai_estimateFeeForQi"
155            | "quai_getHeaderByNumber"
156            | "quai_getHeaderByHash"
157            | "quai_getBlockByNumber"
158            | "quai_getBlockByHash"
159            | "quai_getLogs"
160            | "quai_listRunningChains"
161            | "quai_getOutpointDeltasForAddressesInRange"
162            | "quai_getLatestUTXOSetSize"
163            | "quai_qiToQuai"
164            | "quai_quaiToQi"
165            | "quai_calculateConversionAmount"
166            | "quai_getWrappedQiDeposit"
167            | "quai_getLockedBalance"
168            | "quai_createAccessList"
169            | "quai_getPendingHeader"
170            | "quai_getProtocolExpansionNumber"
171            | "txpool_status"
172            | "txpool_content"
173            | "txpool_inspect"
174            | "quai_accounts"
175    )
176}
177
178#[cfg(any(target_arch = "wasm32", test))]
179fn encode(value: &Value, max: usize) -> Result<String, RpcError> {
180    use std::io::Write;
181    struct Writer {
182        bytes: Vec<u8>,
183        max: usize,
184    }
185    impl Write for Writer {
186        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
187            if bytes.len() > self.max - self.bytes.len() {
188                return Err(std::io::Error::other("request limit"));
189            }
190            self.bytes.extend_from_slice(bytes);
191            Ok(bytes.len())
192        }
193        fn flush(&mut self) -> std::io::Result<()> {
194            Ok(())
195        }
196    }
197    let mut writer = Writer {
198        bytes: Vec::new(),
199        max,
200    };
201    serde_json::to_writer(&mut writer, value).map_err(|_| RpcError::RequestTooLarge)?;
202    String::from_utf8(writer.bytes).map_err(|_| RpcError::InvalidConfig)
203}
204
205#[cfg(any(target_arch = "wasm32", test))]
206fn decode_response(bytes: &[u8], expected_id: u64) -> Result<Value, RpcError> {
207    #[derive(Default)]
208    enum Slot {
209        #[default]
210        Absent,
211        Present(Value),
212    }
213    fn slot<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Slot, D::Error> {
214        Value::deserialize(d).map(Slot::Present)
215    }
216    #[derive(Deserialize)]
217    struct Envelope {
218        jsonrpc: String,
219        id: u64,
220        #[serde(default, deserialize_with = "slot")]
221        result: Slot,
222        #[serde(default, deserialize_with = "slot")]
223        error: Slot,
224    }
225    let envelope: Envelope = serde_json::from_slice(bytes)
226        .map_err(|_| RpcError::InvalidResponse("malformed envelope"))?;
227    if envelope.jsonrpc != "2.0" || envelope.id != expected_id {
228        return Err(RpcError::InvalidResponse(
229            "protocol version or request ID mismatch",
230        ));
231    }
232    match (envelope.result, envelope.error) {
233        (Slot::Present(result), Slot::Absent) => Ok(result),
234        (Slot::Absent, Slot::Present(error)) => Err(RpcError::Remote(
235            serde_json::from_value::<RemoteError>(error)
236                .map_err(|_| RpcError::InvalidResponse("malformed error"))?,
237        )),
238        _ => Err(RpcError::InvalidResponse(
239            "expected exactly one result or error",
240        )),
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247    #[test]
248    fn config_and_authorization_boundaries() {
249        BrowserConfig::default().validate().unwrap();
250        assert!(
251            BrowserConfig {
252                max_in_flight: 0,
253                ..Default::default()
254            }
255            .validate()
256            .is_err()
257        );
258        assert!(
259            BrowserConfig {
260                max_response_bytes: 16 * 1024 * 1024,
261                max_in_flight: 128,
262                ..Default::default()
263            }
264            .validate()
265            .is_err()
266        );
267        for method in [
268            "quai_sendRawTransaction",
269            "quai_sendTransaction",
270            "quai_requestAccounts",
271            "personal_sign",
272            "quai_signTypedData_v4",
273            "wallet_switchEthereumChain",
274        ] {
275            assert!(!read_method(method));
276        }
277        assert!(read_method("quai_getHeaderByNumber"));
278    }
279    #[test]
280    fn bounded_encoding_and_strict_response_envelopes() {
281        assert!(matches!(
282            encode(&serde_json::json!(["abcdef"]), 3),
283            Err(RpcError::RequestTooLarge)
284        ));
285        assert_eq!(
286            decode_response(br#"{"jsonrpc":"2.0","id":1,"result":null}"#, 1).unwrap(),
287            Value::Null
288        );
289        for value in [
290            br#"{"jsonrpc":"2.0","id":2,"result":null}"#.as_slice(),
291            br#"{"jsonrpc":"2.0","id":1,"id":1,"result":null}"#,
292            br#"{"jsonrpc":"2.0","id":1,"result":null,"error":null}"#,
293        ] {
294            assert!(decode_response(value, 1).is_err());
295        }
296    }
297}
298
299#[cfg(target_arch = "wasm32")]
300mod storage;
301#[cfg(target_arch = "wasm32")]
302pub use storage::{
303    BrowserSnapshot, BrowserSnapshotStore, BrowserSnapshotUpdate, BrowserStorageScope,
304    compare_exchange_snapshots,
305};
306
307/// Browser WebSocket request and notification resource limits.
308#[derive(Clone, Copy, Debug)]
309#[non_exhaustive]
310pub struct BrowserSocketConfig {
311    /// Request size, response size, deadline and shared concurrency limits.
312    pub rpc: BrowserConfig,
313    /// Active plus pending subscriptions, 1..=128.
314    pub max_subscriptions: usize,
315    /// Queued notifications per subscription, 1..=1024.
316    pub max_notifications: usize,
317    /// Total queued UTF-8 notification bytes across the session, at most 128 MiB.
318    pub max_queued_bytes: usize,
319}
320impl BrowserSocketConfig {
321    /// Replace `rpc`.
322    pub const fn with_rpc(mut self, rpc: BrowserConfig) -> Self {
323        self.rpc = rpc;
324        self
325    }
326    /// Replace `max_subscriptions`.
327    pub const fn with_max_subscriptions(mut self, max_subscriptions: usize) -> Self {
328        self.max_subscriptions = max_subscriptions;
329        self
330    }
331    /// Replace `max_notifications`.
332    pub const fn with_max_notifications(mut self, max_notifications: usize) -> Self {
333        self.max_notifications = max_notifications;
334        self
335    }
336    /// Replace `max_queued_bytes`.
337    pub const fn with_max_queued_bytes(mut self, max_queued_bytes: usize) -> Self {
338        self.max_queued_bytes = max_queued_bytes;
339        self
340    }
341}
342impl Default for BrowserSocketConfig {
343    fn default() -> Self {
344        Self {
345            rpc: BrowserConfig::default(),
346            max_subscriptions: 16,
347            max_notifications: 64,
348            max_queued_bytes: 8 * 1024 * 1024,
349        }
350    }
351}
352impl BrowserSocketConfig {
353    /// Validate without opening a socket or accessing browser globals.
354    pub fn validate(&self) -> Result<(), BrowserError> {
355        self.rpc.validate()?;
356        if self
357            .rpc
358            .max_request_bytes
359            .checked_mul(self.rpc.max_in_flight)
360            .is_none_or(|n| n > 128 * 1024 * 1024)
361            || self
362                .rpc
363                .max_response_bytes
364                .checked_mul(self.max_subscriptions)
365                .is_none_or(|n| n > 128 * 1024 * 1024)
366            || !(1..=128).contains(&self.max_subscriptions)
367            || !(1..=1024).contains(&self.max_notifications)
368            || !(1..=128 * 1024 * 1024).contains(&self.max_queued_bytes)
369        {
370            return Err(BrowserError::InvalidConfig);
371        }
372        Ok(())
373    }
374}
375#[cfg(target_arch = "wasm32")]
376mod code_wait;
377#[cfg(target_arch = "wasm32")]
378pub use code_wait::wait_for_contract_code;
379#[cfg(target_arch = "wasm32")]
380mod transaction_wait;
381#[cfg(target_arch = "wasm32")]
382pub use transaction_wait::{BrowserTransactionWaitError, wait_for_transaction};
383#[cfg(target_arch = "wasm32")]
384mod account_wait;
385#[cfg(target_arch = "wasm32")]
386mod receipt_wait;
387#[cfg(target_arch = "wasm32")]
388pub use account_wait::{BrowserAccountWaitError, wait_for_account_transaction};
389#[cfg(target_arch = "wasm32")]
390mod socket;
391#[cfg(target_arch = "wasm32")]
392pub use receipt_wait::{BrowserReceiptWaitError, wait_for_receipt};
393#[cfg(target_arch = "wasm32")]
394pub use socket::{BrowserSubscription, BrowserWebSocketTransport};
395
396/// Explicit browser transaction-wait limits. Milliseconds must be positive and fit a
397/// browser timer; polling attempts are independently bounded. No implicit defaults.
398#[derive(Clone, Copy, Debug)]
399#[non_exhaustive]
400pub struct BrowserWaitConfig {
401    /// Required positive observed depth, including the containing block.
402    pub confirmations: u64,
403    /// Overall observable monotonic timeout, including RPCs and polling delays.
404    pub timeout_ms: u32,
405    /// Delay between incomplete observations, no longer than the timeout.
406    pub poll_interval_ms: u32,
407    /// At most 100,000 completed observations; zero is invalid.
408    pub max_polls: u32,
409}
410impl BrowserWaitConfig {
411    /// Every limit is required: there is deliberately no default.
412    pub const fn new(
413        confirmations: u64,
414        timeout_ms: u32,
415        poll_interval_ms: u32,
416        max_polls: u32,
417    ) -> Self {
418        Self {
419            confirmations,
420            timeout_ms,
421            poll_interval_ms,
422            max_polls,
423        }
424    }
425    /// Replace `confirmations`.
426    pub const fn with_confirmations(mut self, confirmations: u64) -> Self {
427        self.confirmations = confirmations;
428        self
429    }
430    /// Replace `timeout_ms`.
431    pub const fn with_timeout_ms(mut self, timeout_ms: u32) -> Self {
432        self.timeout_ms = timeout_ms;
433        self
434    }
435    /// Replace `poll_interval_ms`.
436    pub const fn with_poll_interval_ms(mut self, poll_interval_ms: u32) -> Self {
437        self.poll_interval_ms = poll_interval_ms;
438        self
439    }
440    /// Replace `max_polls`.
441    pub const fn with_max_polls(mut self, max_polls: u32) -> Self {
442        self.max_polls = max_polls;
443        self
444    }
445}
446impl BrowserWaitConfig {
447    /// Validate before allocating timers or performing provider I/O.
448    pub fn validate(&self) -> Result<(), BrowserError> {
449        if self.confirmations == 0
450            || self.timeout_ms == 0
451            || self.timeout_ms > i32::MAX as u32
452            || self.poll_interval_ms == 0
453            || self.poll_interval_ms > self.timeout_ms
454            || !(1..=100_000).contains(&self.max_polls)
455        {
456            return Err(BrowserError::InvalidConfig);
457        }
458        Ok(())
459    }
460}
461
462#[cfg(test)]
463mod socket_config_tests {
464    use super::*;
465    #[test]
466    fn socket_limits_bound_outgoing_buffers_and_notification_state() {
467        let mut config = BrowserSocketConfig::default();
468        config.validate().unwrap();
469        config.rpc.max_request_bytes = 16 * 1024 * 1024;
470        config.rpc.max_response_bytes = 1;
471        config.rpc.max_in_flight = 128;
472        assert!(config.validate().is_err());
473        config.rpc.max_in_flight = 8;
474        config.validate().unwrap();
475        for (subscriptions, notifications, bytes) in [
476            (0, 1, 1),
477            (129, 1, 1),
478            (1, 0, 1),
479            (1, 1025, 1),
480            (1, 1, 0),
481            (1, 1, usize::MAX),
482        ] {
483            config.max_subscriptions = subscriptions;
484            config.max_notifications = notifications;
485            config.max_queued_bytes = bytes;
486            assert!(config.validate().is_err());
487        }
488    }
489}