Skip to main content

quai_browser/
browser.rs

1use crate::{BrowserConfig, BrowserError, decode_response, encode, read_method};
2use quai_crypto::{RecoverableSignature, hash_message};
3use quai_primitives::{QuaiAddress, Shard};
4use quai_rpc::{Endpoint, RemoteError, RpcError, Transport, U256, parse_quantity};
5use serde_json::{Value, json};
6use std::{cell::Cell, fmt, rc::Rc};
7use wasm_bindgen::prelude::*;
8mod submission;
9mod wallet_send;
10pub use submission::InjectedSubmissionTransport;
11pub use wallet_send::{
12    WalletSendAcknowledgement, WalletSendError, WalletSendIdentity, WalletSendObservation,
13};
14
15#[wasm_bindgen(module = "/src/bridge.js")]
16extern "C" {
17    #[wasm_bindgen(catch, js_name = watchProvider)]
18    fn watch_provider(provider: &JsValue) -> Result<JsValue, JsValue>;
19    #[wasm_bindgen(js_name = providerRevision)]
20    fn provider_revision(watch: &JsValue) -> u32;
21    #[wasm_bindgen(js_name = providerEventsSupported)]
22    fn provider_events_supported(watch: &JsValue) -> bool;
23    #[wasm_bindgen(js_name = providerChanged)]
24    fn provider_changed(watch: &JsValue, revision: u32) -> bool;
25    #[wasm_bindgen(js_name = closeProviderWatch)]
26    fn close_provider_watch(watch: &JsValue);
27    #[wasm_bindgen(catch, js_name = newAbort)]
28    fn new_abort() -> Result<JsValue, JsValue>;
29    #[wasm_bindgen(js_name = abort)]
30    fn abort_js(controller: &JsValue);
31    #[wasm_bindgen(js_name = errorKind)]
32    fn error_kind(error: &JsValue) -> String;
33    #[wasm_bindgen(js_name = errorCode)]
34    fn error_code(error: &JsValue) -> f64;
35    #[wasm_bindgen(catch, js_name = validateProvider)]
36    fn validate_provider(provider: &JsValue) -> Result<bool, JsValue>;
37    #[wasm_bindgen(catch, js_name = fetchJson)]
38    async fn fetch_json(
39        url: &str,
40        body: &str,
41        controller: &JsValue,
42        timeout: u32,
43        max_bytes: usize,
44    ) -> Result<JsValue, JsValue>;
45    #[wasm_bindgen(catch, js_name = injectedJson)]
46    async fn injected_json(
47        provider: &JsValue,
48        payload: &str,
49        controller: &JsValue,
50        timeout: u32,
51        max_bytes: usize,
52    ) -> Result<JsValue, JsValue>;
53    #[wasm_bindgen(catch, js_name = randomBytes)]
54    fn random_bytes(length: usize) -> Result<js_sys::Uint8Array, JsValue>;
55}
56struct ProviderWatch(JsValue);
57impl Drop for ProviderWatch {
58    fn drop(&mut self) {
59        close_provider_watch(&self.0);
60    }
61}
62struct AbortGuard(JsValue);
63impl AbortGuard {
64    fn new() -> Result<Self, BrowserError> {
65        new_abort()
66            .map(Self)
67            .map_err(|_| BrowserError::InvalidConfig)
68    }
69}
70impl Drop for AbortGuard {
71    fn drop(&mut self) {
72        abort_js(&self.0);
73    }
74}
75struct Permit(Rc<Cell<usize>>);
76impl Drop for Permit {
77    fn drop(&mut self) {
78        self.0.set(self.0.get() - 1);
79    }
80}
81fn permit(active: &Rc<Cell<usize>>, max: usize) -> Result<Permit, BrowserError> {
82    if active.get() >= max {
83        return Err(BrowserError::Busy);
84    }
85    active.set(active.get() + 1);
86    Ok(Permit(active.clone()))
87}
88fn convert(error: JsValue) -> BrowserError {
89    let code = error_code(&error) as i64;
90    match error_kind(&error).as_str() {
91        "timeout" => RpcError::Timeout.into(),
92        "response_size" => RpcError::ResponseTooLarge.into(),
93        "invalid" => BrowserError::InvalidResult,
94        "http" => RpcError::HttpStatus(code as u16).into(),
95        "provider" => BrowserError::Provider(code),
96        "entropy" => BrowserError::EntropyUnavailable,
97        _ => RpcError::Transport.into(),
98    }
99}
100fn rpc_error(error: BrowserError) -> RpcError {
101    match error {
102        BrowserError::Rpc(error) => error,
103        BrowserError::Provider(code) => RpcError::Remote(RemoteError {
104            code,
105            message: String::new(),
106            data: None,
107        }),
108        BrowserError::InvalidResult => RpcError::InvalidResponse("invalid browser result"),
109        BrowserError::ChainMismatch => RpcError::InvalidResponse("injected chain ID mismatch"),
110        BrowserError::Busy => RpcError::AtCapacity,
111        BrowserError::ContextChanged => {
112            RpcError::InvalidResponse("injected provider context changed")
113        }
114        _ => RpcError::InvalidConfig,
115    }
116}
117fn result_string(value: JsValue) -> Result<String, BrowserError> {
118    value.as_string().ok_or(BrowserError::InvalidResult)
119}
120fn request_valid(method: &str, params: &Value) -> bool {
121    !method.is_empty()
122        && method.len() <= 128
123        && method
124            .bytes()
125            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.'))
126        && (params.is_array() || params.is_object())
127}
128
129/// Browser Fetch transport with streaming response limits, CORS and credential omission.
130///
131/// Clones share concurrency/ID limits. Dropping the request aborts its Fetch controller;
132/// completion or cancellation does not prove whether a remote write was accepted.
133#[derive(Clone)]
134pub struct BrowserFetchTransport {
135    config: BrowserConfig,
136    active: Rc<Cell<usize>>,
137    next_id: Rc<Cell<u64>>,
138}
139impl fmt::Debug for BrowserFetchTransport {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        f.debug_struct("BrowserFetchTransport")
142            .field("config", &self.config)
143            .finish_non_exhaustive()
144    }
145}
146impl BrowserFetchTransport {
147    /// Construct without network access. Available in windows and dedicated workers.
148    pub fn new(config: BrowserConfig) -> Result<Self, BrowserError> {
149        config.validate()?;
150        Ok(Self {
151            config,
152            active: Rc::new(Cell::new(0)),
153            next_id: Rc::new(Cell::new(1)),
154        })
155    }
156    /// Execute one explicit RPC call; never retries or follows redirects.
157    pub async fn send(
158        &self,
159        endpoint: &Endpoint,
160        method: &str,
161        params: Value,
162    ) -> Result<Value, BrowserError> {
163        if !matches!(endpoint.scheme(), "http" | "https") || !request_valid(method, &params) {
164            return Err(BrowserError::InvalidConfig);
165        }
166        let _permit = permit(&self.active, self.config.max_in_flight)?;
167        let id = self.next_id.get();
168        if id > 9_007_199_254_740_991 {
169            return Err(RpcError::RequestIdExhausted.into());
170        }
171        self.next_id.set(id + 1);
172        let body = encode(
173            &json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}),
174            self.config.max_request_bytes,
175        )?;
176        let guard = AbortGuard::new()?;
177        let result = fetch_json(
178            endpoint.as_str(),
179            &body,
180            &guard.0,
181            self.config.request_timeout_ms,
182            self.config.max_response_bytes,
183        )
184        .await
185        .map_err(convert)?;
186        let result = result_string(result)?;
187        Ok(decode_response(result.as_bytes(), id)?)
188    }
189}
190impl Transport for BrowserFetchTransport {
191    async fn request(
192        &self,
193        endpoint: &Endpoint,
194        method: &str,
195        params: Value,
196    ) -> Result<Value, RpcError> {
197        self.send(endpoint, method, params).await.map_err(rpc_error)
198    }
199}
200
201/// Explicit adapter for an application-selected Quai EIP-1193 provider object.
202///
203/// The configured endpoint is an exact routing identity, not a fetched URL. The
204/// encoded shard is included in every request as in pinned quais.js. Construction
205/// never requests accounts or signatures. Generic Transport is read-only; explicit
206/// methods are the only route to supported permission-sensitive wallet requests.
207#[derive(Clone)]
208pub struct InjectedProvider {
209    provider: JsValue,
210    watch: Rc<ProviderWatch>,
211    endpoint: Endpoint,
212    shard: Shard,
213    expected_chain: U256,
214    config: BrowserConfig,
215    active: Rc<Cell<usize>>,
216}
217impl fmt::Debug for InjectedProvider {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        f.debug_struct("InjectedProvider")
220            .field("endpoint", &self.endpoint)
221            .field("shard", &self.shard)
222            .field("expected_chain", &self.expected_chain)
223            .finish_non_exhaustive()
224    }
225}
226impl InjectedProvider {
227    /// Bind an explicitly selected JS provider, endpoint identity, shard and expected chain.
228    /// No global provider discovery or wallet prompt occurs.
229    pub fn new(
230        provider: JsValue,
231        endpoint: Endpoint,
232        shard: Shard,
233        expected_chain: U256,
234        config: BrowserConfig,
235    ) -> Result<Self, BrowserError> {
236        config.validate()?;
237        if !validate_provider(&provider).map_err(|_| BrowserError::InvalidConfig)? {
238            return Err(BrowserError::InvalidConfig);
239        }
240        let watch = Rc::new(ProviderWatch(watch_provider(&provider).map_err(convert)?));
241        Ok(Self {
242            provider,
243            watch,
244            endpoint,
245            shard,
246            expected_chain,
247            config,
248            active: Rc::new(Cell::new(0)),
249        })
250    }
251    /// Monotonic account/chain/disconnect revision shared by adapter clones.
252    /// Applications can invalidate displayed balances and cached authorization on change.
253    pub fn context_revision(&self) -> u32 {
254        provider_revision(&self.watch.0)
255    }
256    /// Whether this provider exposes removable EIP-1193 event listeners.
257    pub fn monitors_context_events(&self) -> bool {
258        provider_events_supported(&self.watch.0)
259    }
260    async fn verify_context(
261        &self,
262        revision: u32,
263        account: Option<QuaiAddress>,
264    ) -> Result<(), BrowserError> {
265        if provider_changed(&self.watch.0, revision) {
266            return Err(BrowserError::ContextChanged);
267        }
268        if !self.monitors_context_events() {
269            // Request-only providers cannot report transient changes. Recheck their
270            // current chain and exposed account before releasing a result.
271            self.check_chain().await?;
272            if let Some(account) = account
273                && !Self::accounts_from(self.raw("quai_accounts", json!([])).await?)?
274                    .contains(&account)
275            {
276                return Err(BrowserError::AccountUnavailable);
277            }
278        }
279        if provider_changed(&self.watch.0, revision) {
280            return Err(BrowserError::ContextChanged);
281        }
282        Ok(())
283    }
284    async fn raw(&self, method: &str, params: Value) -> Result<Value, BrowserError> {
285        let _permit = permit(&self.active, self.config.max_in_flight)?;
286        let payload = encode(
287            &json!({"method":method,"params":params,"shard":self.shard.encoded()}),
288            self.config.max_request_bytes,
289        )?;
290        let guard = AbortGuard::new()?;
291        let result = injected_json(
292            &self.provider,
293            &payload,
294            &guard.0,
295            self.config.request_timeout_ms,
296            self.config.max_response_bytes,
297        )
298        .await
299        .map_err(convert)?;
300        serde_json::from_str(&result_string(result)?).map_err(|_| BrowserError::InvalidResult)
301    }
302    async fn check_chain(&self) -> Result<Value, BrowserError> {
303        let value = self.raw("quai_chainId", json!([])).await?;
304        let chain = value
305            .as_str()
306            .ok_or(BrowserError::InvalidResult)
307            .and_then(|value| parse_quantity(value).map_err(|_| BrowserError::InvalidResult))?;
308        if chain != self.expected_chain {
309            return Err(BrowserError::ChainMismatch);
310        }
311        Ok(value)
312    }
313    /// Read through the fixed injected wallet after a fresh chain check.
314    /// Account/signing/sending permission methods cannot pass this allowlist.
315    pub async fn read(
316        &self,
317        endpoint: &Endpoint,
318        method: &str,
319        params: Value,
320    ) -> Result<Value, BrowserError> {
321        if endpoint != &self.endpoint || !request_valid(method, &params) {
322            return Err(BrowserError::InvalidConfig);
323        }
324        if !read_method(method) {
325            return Err(BrowserError::AuthorizationRequired);
326        }
327        let revision = self.context_revision();
328        let chain = self.check_chain().await?;
329        if method == "quai_chainId" {
330            if provider_changed(&self.watch.0, revision) {
331                return Err(BrowserError::ContextChanged);
332            }
333            return Ok(chain);
334        }
335        let result = self.raw(method, params).await?;
336        self.verify_context(revision, None).await?;
337        Ok(result)
338    }
339    fn accounts_from(value: Value) -> Result<Vec<QuaiAddress>, BrowserError> {
340        let values = value
341            .as_array()
342            .filter(|values| values.len() <= 1024)
343            .ok_or(BrowserError::InvalidResult)?;
344        let mut accounts = Vec::with_capacity(values.len());
345        for value in values {
346            let address = value
347                .as_str()
348                .ok_or(BrowserError::InvalidResult)?
349                .parse::<QuaiAddress>()
350                .map_err(|_| BrowserError::InvalidResult)?;
351            if accounts.contains(&address) {
352                return Err(BrowserError::InvalidResult);
353            }
354            accounts.push(address)
355        }
356        Ok(accounts)
357    }
358    /// Request wallet account access explicitly. Call only in the application's user-approved flow.
359    /// User rejection preserves numeric EIP-1193 code 4001. No retry occurs.
360    pub async fn request_accounts(&self) -> Result<Vec<QuaiAddress>, BrowserError> {
361        self.check_chain().await?;
362        let accounts = Self::accounts_from(self.raw("quai_requestAccounts", json!([])).await?)?;
363        self.check_chain().await?;
364        Ok(accounts)
365    }
366    /// Read accounts already exposed by the wallet; never requests additional permission.
367    pub async fn accounts(&self) -> Result<Vec<QuaiAddress>, BrowserError> {
368        let revision = self.context_revision();
369        self.check_chain().await?;
370        let accounts = Self::accounts_from(self.raw("quai_accounts", json!([])).await?)?;
371        self.verify_context(revision, None).await?;
372        Ok(accounts)
373    }
374    /// Explicitly ask the wallet to sign these bytes with personal_sign.
375    ///
376    /// Checks the configured chain, account exposure and sender zone before calling.
377    /// Recovers the exact message signature and requires the requested account.
378    /// Dropping this future cannot dismiss or revoke
379    /// a wallet approval already presented by the injected provider.
380    pub async fn personal_sign(
381        &self,
382        address: QuaiAddress,
383        message: &[u8],
384    ) -> Result<[u8; 65], BrowserError> {
385        if self.shard != Shard::Zone(address.zone())
386            || message.len() > self.config.max_request_bytes / 2
387        {
388            return Err(BrowserError::InvalidConfig);
389        }
390        let revision = self.context_revision();
391        self.check_chain().await?;
392        if !Self::accounts_from(self.raw("quai_accounts", json!([])).await?)?.contains(&address) {
393            return Err(BrowserError::AccountUnavailable);
394        }
395        let mut hex = String::with_capacity(2 + message.len() * 2);
396        hex.push_str("0x");
397        const DIGITS: &[u8] = b"0123456789abcdef";
398        for byte in message {
399            hex.push(DIGITS[(byte >> 4) as usize] as char);
400            hex.push(DIGITS[(byte & 15) as usize] as char)
401        }
402        if provider_changed(&self.watch.0, revision) {
403            return Err(BrowserError::ContextChanged);
404        }
405        let value = self
406            .raw(
407                "personal_sign",
408                json!([hex, address.to_string().to_ascii_lowercase()]),
409            )
410            .await?;
411        self.verify_context(revision, Some(address)).await?;
412        Self::verified_signature(value, address, &hash_message(message))
413    }
414    /// Explicitly request EIP-712 v4 signing after domain, chain and account checks.
415    /// The immutable document determines both the serialized request and recovered
416    /// signature hash. No implicit permission request or automatic retry occurs.
417    pub async fn sign_typed_data(
418        &self,
419        address: QuaiAddress,
420        data: &quai_signer::TypedData,
421        policy: quai_signer::DomainPolicy,
422    ) -> Result<[u8; 65], BrowserError> {
423        if self.shard != Shard::Zone(address.zone()) {
424            return Err(BrowserError::InvalidConfig);
425        }
426        policy
427            .validate(data, self.expected_chain)
428            .map_err(|_| BrowserError::ChainMismatch)?;
429        let document = data
430            .to_rpc_json()
431            .map_err(|_| BrowserError::InvalidResult)?;
432        let revision = self.context_revision();
433        self.check_chain().await?;
434        if !Self::accounts_from(self.raw("quai_accounts", json!([])).await?)?.contains(&address) {
435            return Err(BrowserError::AccountUnavailable);
436        }
437        if provider_changed(&self.watch.0, revision) {
438            return Err(BrowserError::ContextChanged);
439        }
440        let result = self
441            .raw(
442                "quai_signTypedData_v4",
443                json!([address.to_string().to_ascii_lowercase(), document]),
444            )
445            .await?;
446        self.verify_context(revision, Some(address)).await?;
447        Self::verified_signature(result, address, data.signing_hash().bytes())
448    }
449    fn verified_signature(
450        value: Value,
451        address: QuaiAddress,
452        digest: &[u8; 32],
453    ) -> Result<[u8; 65], BrowserError> {
454        let encoded = value
455            .as_str()
456            .filter(|s| {
457                s.len() == 132
458                    && s.starts_with("0x")
459                    && s.as_bytes()[2..].iter().all(u8::is_ascii_hexdigit)
460            })
461            .ok_or(BrowserError::InvalidResult)?;
462        let mut signature = [0; 65];
463        for (index, byte) in signature.iter_mut().enumerate() {
464            *byte = u8::from_str_radix(&encoded[2 + index * 2..4 + index * 2], 16)
465                .map_err(|_| BrowserError::InvalidResult)?;
466        }
467        let parsed = RecoverableSignature::from_quais_bytes(&signature)
468            .map_err(|_| BrowserError::InvalidResult)?;
469        let recovered = parsed
470            .recover_prehash(digest)
471            .map_err(|_| BrowserError::InvalidResult)?;
472        if recovered.address() != address.address() {
473            return Err(BrowserError::InvalidResult);
474        }
475        Ok(signature)
476    }
477
478    fn transaction_params(
479        &self,
480        address: QuaiAddress,
481        transaction: &quai_consensus::QuaiTransaction,
482        method: &str,
483    ) -> Result<Value, BrowserError> {
484        if transaction.chain_id != self.expected_chain || transaction.chain_id == U256::ZERO {
485            return Err(BrowserError::ChainMismatch);
486        }
487        if self.shard != Shard::Zone(address.zone()) {
488            return Err(BrowserError::InvalidConfig);
489        }
490        transaction
491            .unsigned_bytes()
492            .map_err(|_| BrowserError::InvalidConfig)?;
493        let access_list: Vec<_> = transaction.access_list.iter().map(|entry| {
494            json!({"address":entry.address.to_string(),"storageKeys":entry.storage_keys.iter().map(ToString::to_string).collect::<Vec<_>>()})
495        }).collect();
496        let mut rpc = json!({
497            "type":"0x0", "chainId":format!("{:#x}",transaction.chain_id),
498            "from":address.to_string().to_ascii_lowercase(),
499            "nonce":format!("{:#x}",transaction.nonce),
500            "value":format!("{:#x}",transaction.value),
501            "gas":format!("{:#x}",transaction.gas_limit),
502            "gasPrice":format!("{:#x}",transaction.gas_price),
503            "data":quai_primitives::hexlify(&transaction.data).map_err(|_|BrowserError::InvalidConfig)?,
504            "accessList":access_list,
505        });
506        if let Some(to) = transaction.to {
507            rpc["to"] = json!(to.to_string().to_ascii_lowercase());
508        }
509        let params = json!([rpc]);
510        // Check the exact outgoing envelope before even passive wallet reads.
511        encode(
512            &json!({"method":method,"params":params,"shard":self.shard.encoded()}),
513            self.config.max_request_bytes,
514        )?;
515        Ok(params)
516    }
517    /// Explicitly request signing of an exact, fully populated type-0 Quai
518    /// transaction. Does not estimate, fill fields, request accounts or broadcast.
519    /// Canonical returned protobuf must recover the requested exposed account
520    /// and match every unsigned field, including ordered access-list entries.
521    /// Dropping the future cannot retract an already displayed wallet approval.
522    pub async fn sign_quai_transaction(
523        &self,
524        address: QuaiAddress,
525        transaction: &quai_consensus::QuaiTransaction,
526    ) -> Result<quai_consensus::SignedQuaiTransaction, BrowserError> {
527        let params = self.transaction_params(address, transaction, "quai_signTransaction")?;
528        let revision = self.context_revision();
529        self.check_chain().await?;
530        if !Self::accounts_from(self.raw("quai_accounts", json!([])).await?)?.contains(&address) {
531            return Err(BrowserError::AccountUnavailable);
532        }
533        if provider_changed(&self.watch.0, revision) {
534            return Err(BrowserError::ContextChanged);
535        }
536        let value = self.raw("quai_signTransaction", params).await?;
537        self.verify_context(revision, Some(address)).await?;
538        let bytes = value
539            .as_str()
540            .ok_or(BrowserError::InvalidResult)
541            .and_then(|text| {
542                quai_primitives::get_bytes(text).map_err(|_| BrowserError::InvalidResult)
543            })?;
544        let signed = quai_consensus::SignedQuaiTransaction::decode(&bytes)
545            .map_err(|_| BrowserError::InvalidResult)?;
546        if signed.from() != address || signed.transaction() != transaction {
547            return Err(BrowserError::InvalidResult);
548        }
549        Ok(signed)
550    }
551}
552impl Transport for InjectedProvider {
553    async fn request(
554        &self,
555        endpoint: &Endpoint,
556        method: &str,
557        params: Value,
558    ) -> Result<Value, RpcError> {
559        self.read(endpoint, method, params).await.map_err(rpc_error)
560    }
561}
562
563/// Fill at most 65,536 bytes using secure-context Web Crypto, with no fallback PRNG.
564/// No wallet key storage or generation is performed automatically.
565pub fn fill_random(destination: &mut [u8]) -> Result<(), BrowserError> {
566    if destination.len() > 65_536 {
567        return Err(BrowserError::EntropyUnavailable);
568    }
569    let bytes = random_bytes(destination.len()).map_err(|_| BrowserError::EntropyUnavailable)?;
570    if bytes.length() as usize != destination.len() {
571        return Err(BrowserError::EntropyUnavailable);
572    }
573    bytes.copy_to(destination);
574    Ok(())
575}