Skip to main content

quai_provider/
lib.rs

1//! Typed provider with explicit routing, validated reads and signed transaction submission.
2use quai_primitives::{Hash32, QiAddress, QuaiAddress, Shard, Zone};
3use quai_rpc::{
4    Endpoint, QuantityError, RouteError, Routing, RpcError, Transport, U256, parse_quantity,
5};
6use serde_json::{Value, json};
7use thiserror::Error;
8
9mod network;
10pub use network::{FeeData, Network, NetworkError, NetworkMatch, NetworkRegistry};
11
12mod confirmation;
13mod transaction_confirmation;
14pub use confirmation::{ConfirmedReceipt, ReceiptConfirmation};
15pub use transaction_confirmation::{ConfirmedTransaction, TransactionConfirmation};
16mod account_replacement;
17pub use account_replacement::{
18    AccountNonceCandidate, AccountReplacementPoll, AccountReplacementScan,
19    AccountReplacementScanRequest, AccountReplacementTracker, ReplacementReason,
20};
21mod deployment;
22#[cfg(all(feature = "polling", not(target_arch = "wasm32")))]
23pub use deployment::DeploymentWaitError;
24pub use deployment::{DeploymentCode, DeploymentObservation, DeploymentReference};
25mod account_proof;
26mod code_wait;
27pub use account_proof::{
28    MAX_PROVEN_ACCOUNTS, MAX_PROVEN_SLOTS, ProvenAccount, ProvenSlot, StateAnchor,
29};
30mod anchored;
31mod contract_code;
32pub mod header_hash;
33pub mod state_proof;
34pub use code_wait::{CodeWaitConfig, CodeWaitError, ContractCodeTarget};
35pub use contract_code::{ContractCodeObservation, MAX_CONTRACT_CODE_TARGETS};
36mod blocks;
37pub use blocks::{
38    BlockHashes, BlockMetadata, BlockTransactionId, MinedBlock, OutboundBlockTransaction,
39};
40mod qi_credit;
41pub use qi_credit::QiCreditObservation;
42mod external_tracking;
43pub use external_tracking::{ExternalObservation, ExternalReference};
44mod account_rpc;
45/// Runtime-independent bounded local event registration and delivery.
46pub mod event_hub;
47pub use account_rpc::{AccessListEstimate, PoolInspection, PoolStatus, PoolTransaction};
48mod conversion_tracking;
49pub use conversion_tracking::{
50    BlockReference, ConversionEffect, ConversionObservation, ConversionOriginObservation,
51    ConversionReference, ConversionSpendability, EtxCorrelation, EtxExecutionObservation,
52    EtxScanRequest, EtxScanResult, LockedBalanceObservation, ScanCoverage, TransactionBlock,
53};
54mod head_tracker;
55mod logs;
56mod qi;
57pub use head_tracker::{HeadTracker, HeadUpdate, MAX_HEAD_STATE_BYTES};
58mod qi_special_fee;
59pub use qi_special_fee::{QiFeeProfile, QiFeeQuote, qi_special_gas};
60mod wallet_rpc;
61pub use logs::{LogFilter, LogRange, TopicMatch};
62pub use wallet_rpc::{
63    AccountState, ConversionEstimate, MAX_ACCOUNT_STATES, MAX_OUTPOINT_ADDRESSES, OutpointDeltas,
64};
65mod response_json;
66mod submission;
67mod types;
68#[cfg(all(feature = "polling", not(target_arch = "wasm32")))]
69mod wait;
70pub use submission::{BroadcastError, BroadcastResult};
71pub use types::{
72    AccessListItem, AddressOutpoint, CallRequest, EcdsaValues, Extensions, ExternalTransaction,
73    Inclusion, Log, MAX_RPC_DATA_BYTES, OutPoint, QiInput, QiOutput, QiTransaction,
74    QuaiTransaction, Receipt, ReceiptOutcome, RpcData, Transaction, TransactionDetails,
75    TransactionKind, ZoneHeader,
76};
77#[cfg(all(feature = "polling", not(target_arch = "wasm32")))]
78pub use wait::{WaitConfig, WaitError};
79
80/// A block selector supported by the initial account read methods.
81#[derive(Clone, Copy, Debug, Eq, PartialEq)]
82pub enum BlockTag {
83    /// The node's latest block.
84    Latest,
85    /// The node's pending state.
86    Pending,
87    /// An explicit block number. Values above `i64::MAX` are rejected before I/O.
88    Number(U256),
89}
90impl BlockTag {
91    fn rpc_value(self) -> Result<String, ProviderError> {
92        match self {
93            Self::Latest => Ok("latest".into()),
94            Self::Pending => Ok("pending".into()),
95            Self::Number(n) if n <= U256::from(i64::MAX as u64) => Ok(format!("{n:#x}")),
96            Self::Number(_) => Err(ProviderError::BlockNumberOutOfRange),
97        }
98    }
99}
100
101/// Provider failures without raw endpoint URLs or remote response bodies.
102#[derive(Debug, Error)]
103#[non_exhaustive]
104pub enum ProviderError {
105    /// Requested canonical replay predates retained anchors or source history.
106    #[error("canonical replay history unavailable; restore an older checkpoint explicitly")]
107    ReplayHistoryUnavailable,
108    /// A typed request violates the supported account simulation contract.
109    #[error("invalid RPC request: {0}")]
110    InvalidRequest(&'static str),
111    /// The pinned RPC estimator omits conversion data and cannot quote this exact envelope.
112    #[error("exact Qi conversion fee estimation is not qualified for this node API")]
113    ConversionFeeEstimationUnavailable,
114    /// go-quai block-number selectors are signed 64-bit values; longer hex may mean a hash.
115    #[error("block number exceeds the node's signed 64-bit range")]
116    BlockNumberOutOfRange,
117    /// No valid route exists for the requested shard.
118    #[error(transparent)]
119    Route(#[from] RouteError),
120    /// Transport or JSON-RPC protocol failure.
121    #[error(transparent)]
122    Rpc(#[from] RpcError),
123    /// An invalid or out-of-range unsigned quantity.
124    #[error(transparent)]
125    Quantity(#[from] QuantityError),
126    /// The endpoint identifies a different chain.
127    #[error("chain ID mismatch: expected {expected}, received {actual}")]
128    ChainMismatch {
129        /// Caller-configured chain identity.
130        expected: U256,
131        /// Identity reported by the endpoint.
132        actual: U256,
133    },
134    /// The endpoint's genesis is not the one the caller trusts: a different
135    /// network with the same chain ID.
136    #[error("network genesis mismatch")]
137    GenesisMismatch,
138    /// A canonical block anchor or parent link changed during a multi-request observation.
139    #[error("canonical observation changed during the request")]
140    ObservationChanged,
141    /// A state anchor is older than the caller's freshness bound. The node
142    /// lags, or served an old block: anchor again, or use another node.
143    #[error("state anchor is older than required")]
144    StaleAnchor,
145    /// Another node's header at the anchor's height has a different
146    /// `headerHash`. Near the head this is usually a race, so anchor a few
147    /// blocks deep; if it persists, the nodes disagree about the chain and
148    /// neither node's proofs are confirmed.
149    #[error("another node disputes the state anchor")]
150    AnchorDisputed,
151    /// A method result does not match its expected shape.
152    #[error("invalid RPC result: {0}")]
153    InvalidResult(&'static str),
154    /// A state proof the node returned does not verify, or contradicts the
155    /// values the node reported beside it.
156    #[error(transparent)]
157    Proof(#[from] state_proof::ProofError),
158    /// The header's hashes do not follow from its fields.
159    #[error(transparent)]
160    Header(#[from] header_hash::HeaderHashError),
161}
162
163impl ProviderError {
164    /// How to react to this failure; see [`quai_primitives::ErrorClass`].
165    pub fn class(&self) -> quai_primitives::ErrorClass {
166        use quai_primitives::ErrorClass;
167        match self {
168            Self::Rpc(error) => error.class(),
169            Self::ChainMismatch { .. } | Self::GenesisMismatch => ErrorClass::NetworkMismatch,
170            Self::ObservationChanged | Self::StaleAnchor | Self::AnchorDisputed => {
171                ErrorClass::Stale
172            }
173            Self::ReplayHistoryUnavailable
174            | Self::InvalidRequest(_)
175            | Self::ConversionFeeEstimationUnavailable
176            | Self::BlockNumberOutOfRange
177            | Self::Route(_)
178            | Self::Quantity(_)
179            | Self::InvalidResult(_)
180            | Self::Proof(_)
181            | Self::Header(_) => ErrorClass::Invalid,
182        }
183    }
184}
185
186/// A provider with a fixed routing table and an explicitly expected chain ID.
187///
188/// Every high-level read checks the target endpoint's chain ID first. This is a
189/// configuration check, not authentication or an atomic snapshot: a malicious
190/// endpoint can lie, and a load balancer can change backends between requests.
191/// Call `genesis_hash` and compare it with a trusted network scope when needed;
192/// fork validation is not implemented. Submission requires an immutable
193/// signed transaction and never retries automatically.
194#[derive(Clone, Debug)]
195pub struct Provider<T> {
196    transport: T,
197    routing: Routing,
198    expected_chain_id: U256,
199}
200
201impl<T: Transport> Provider<T> {
202    /// Construct without network access. Reads fail if the endpoint's chain ID differs.
203    pub fn new(transport: T, routing: Routing, expected_chain_id: U256) -> Self {
204        Self {
205            transport,
206            routing,
207            expected_chain_id,
208        }
209    }
210
211    /// Read and verify the chain ID at an explicitly configured shard.
212    pub async fn chain_id(&self, shard: Shard) -> Result<U256, ProviderError> {
213        let result = self
214            .transport
215            .request(self.routing.endpoint(shard)?, "quai_chainId", json!([]))
216            .await?;
217        let actual = quantity(result)?;
218        if actual != self.expected_chain_id {
219            return Err(ProviderError::ChainMismatch {
220                expected: self.expected_chain_id,
221                actual,
222            });
223        }
224        Ok(actual)
225    }
226
227    /// The expected chain ID this provider was constructed with.
228    pub fn expected_chain_id(&self) -> U256 {
229        self.expected_chain_id
230    }
231
232    /// Check an observed chain ID against the expected one.
233    fn check_chain_id(&self, observed: Value) -> Result<(), ProviderError> {
234        let actual = quantity(observed)?;
235        if actual != self.expected_chain_id {
236            return Err(ProviderError::ChainMismatch {
237                expected: self.expected_chain_id,
238                actual,
239            });
240        }
241        Ok(())
242    }
243
244    /// Read with the chain check preceding the call.
245    ///
246    /// Where the transport supports batching, the guard and the payload travel
247    /// as `[quai_chainId, method]` in one request instead of two sequential
248    /// round trips, so one backend answers both. It remains a configuration
249    /// check, not authentication: a malicious endpoint can answer the guard
250    /// truthfully and lie in the payload.
251    ///
252    /// Transports without batching return `None`, having sent nothing, and fall
253    /// back to the sequential form.
254    async fn read(
255        &self,
256        shard: Shard,
257        method: &str,
258        params: Value,
259    ) -> Result<Value, ProviderError> {
260        let endpoint = self.routing.endpoint(shard)?;
261        if let Some(batch) = self
262            .guarded_batch(endpoint, vec![(method, params.clone())])
263            .await
264        {
265            return Ok(batch?.pop().expect("checked count")?);
266        }
267        self.chain_id(shard).await?;
268        Ok(self.transport.request(endpoint, method, params).await?)
269    }
270
271    /// Send `calls` in one batch led by a chain-ID guard.
272    ///
273    /// `None` means the transport does not batch and sent nothing. The guard
274    /// must pass before any payload is returned, so a chain mismatch is never
275    /// reported as a successful read. Results keep the order of `calls`.
276    ///
277    /// There is no trailing guard. A batch is one request that one backend
278    /// answers, so nothing can change chains between its elements; and a
279    /// gateway that splits a batch across backends could route the payload
280    /// away from a guard at either end, so a second guard would not cover
281    /// that case either. It cost a third of every single read's calls, which
282    /// counts against a metered or rate-limited gateway.
283    async fn guarded_batch(
284        &self,
285        endpoint: &Endpoint,
286        calls: Vec<(&str, Value)>,
287    ) -> Option<Result<Vec<Result<Value, RpcError>>, ProviderError>> {
288        let count = calls.len();
289        let mut requests = Vec::with_capacity(count + 1);
290        requests.push(("quai_chainId", json!([])));
291        requests.extend(calls);
292        let batch = self.transport.request_batch(endpoint, requests).await?;
293        Some((|| {
294            let mut responses = batch?;
295            if responses.len() != count + 1 {
296                return Err(ProviderError::InvalidResult("batch response count"));
297            }
298            let leading = responses.remove(0);
299            self.check_chain_id(leading?)?;
300            Ok(responses)
301        })())
302    }
303
304    /// Read the latest block number for this shard, without narrowing to a machine integer.
305    pub async fn block_number(&self, shard: Shard) -> Result<U256, ProviderError> {
306        quantity(self.read(shard, "quai_blockNumber", json!([])).await?)
307    }
308
309    /// Read the network's root genesis identity through an explicitly routed zone.
310    ///
311    /// The pinned node returns a root-location header even on zone endpoints at
312    /// height zero. Validate its zero height, root location and zero parent, then
313    /// return its exact work-object hash. This validates the response shape; the
314    /// caller must compare the returned identity with its trusted network scope.
315    pub async fn genesis_hash(&self, zone: Zone) -> Result<Hash32, ProviderError> {
316        let value = self
317            .read(zone.into(), "quai_getHeaderByNumber", json!(["0x0"]))
318            .await?;
319        types::genesis_hash(value)
320    }
321
322    /// Read a latest zone header with explicit location validation. None means unavailable.
323    pub async fn latest_header(&self, zone: Zone) -> Result<Option<ZoneHeader>, ProviderError> {
324        self.zone_header(zone, BlockTag::Latest).await
325    }
326
327    /// Read a canonical-by-number zone header and validate the returned location and height.
328    pub async fn header_at(
329        &self,
330        zone: Zone,
331        number: u64,
332    ) -> Result<Option<ZoneHeader>, ProviderError> {
333        self.zone_header(zone, BlockTag::Number(U256::from(number)))
334            .await
335    }
336
337    async fn zone_header(
338        &self,
339        zone: Zone,
340        block: BlockTag,
341    ) -> Result<Option<ZoneHeader>, ProviderError> {
342        let selector = block.rpc_value()?;
343        let value = self
344            .read(zone.into(), "quai_getHeaderByNumber", json!([selector]))
345            .await?;
346        Self::parse_zone_header(value, zone, block)
347    }
348
349    /// Several zone headers in one round trip where the transport batches, in
350    /// order, each validated as [`Self::header_at`] and [`Self::latest_header`]
351    /// validate theirs. `None` means the node reported no header.
352    pub async fn headers(
353        &self,
354        zone: Zone,
355        blocks: &[BlockTag],
356    ) -> Result<Vec<Option<ZoneHeader>>, ProviderError> {
357        let values = self.header_values(zone, blocks).await.into_iter();
358        Self::parse_zone_headers(values, zone, blocks)
359    }
360
361    /// [`Self::headers`], read together with the network's genesis. `None` when
362    /// the genesis is not `genesis`: that is checked before any header is
363    /// parsed and before any header's RPC error is returned, so a wrong network
364    /// is reported as such rather than as a bad or missing header. Chain ID is
365    /// guarded on every read, as always.
366    pub async fn headers_on_network(
367        &self,
368        zone: Zone,
369        genesis: Hash32,
370        blocks: &[BlockTag],
371    ) -> Result<Option<Vec<Option<ZoneHeader>>>, ProviderError> {
372        let mut selectors = Vec::with_capacity(blocks.len() + 1);
373        selectors.push(BlockTag::Number(U256::ZERO));
374        selectors.extend_from_slice(blocks);
375        let mut values = self.header_values(zone, &selectors).await.into_iter();
376        let observed = values
377            .next()
378            .ok_or(ProviderError::InvalidResult("header batch count"))??;
379        if types::genesis_hash(observed)? != genesis {
380            return Ok(None);
381        }
382        Self::parse_zone_headers(values, zone, blocks).map(Some)
383    }
384
385    /// Parse raw header responses in order, each for the matching block.
386    fn parse_zone_headers(
387        values: impl Iterator<Item = Result<Value, ProviderError>>,
388        zone: Zone,
389        blocks: &[BlockTag],
390    ) -> Result<Vec<Option<ZoneHeader>>, ProviderError> {
391        let headers = values
392            .zip(blocks)
393            .map(|(value, block)| Self::parse_zone_header(value?, zone, *block))
394            .collect::<Result<Vec<_>, _>>()?;
395        if headers.len() != blocks.len() {
396            return Err(ProviderError::InvalidResult("header batch count"));
397        }
398        Ok(headers)
399    }
400
401    /// Several headers from one zone, in order, as raw responses: guarded
402    /// batches of up to `MAX_BATCH_CALLS - 1` where the transport batches,
403    /// otherwise one guarded read each. Parse each with `parse_zone_header`, or
404    /// `types::genesis_hash` for height zero.
405    ///
406    /// Reading stops at the first error, which is the last entry, so a caller
407    /// can check an earlier response, such as the genesis, before a later
408    /// failure decides the outcome.
409    pub(crate) async fn header_values(
410        &self,
411        zone: Zone,
412        blocks: &[BlockTag],
413    ) -> Vec<Result<Value, ProviderError>> {
414        let mut values = Vec::with_capacity(blocks.len());
415        if let Err(error) = self.read_header_values(zone, blocks, &mut values).await {
416            values.push(Err(error));
417        }
418        values
419    }
420
421    async fn read_header_values(
422        &self,
423        zone: Zone,
424        blocks: &[BlockTag],
425        values: &mut Vec<Result<Value, ProviderError>>,
426    ) -> Result<(), ProviderError> {
427        let endpoint = self.routing.endpoint(zone.into())?;
428        for page in blocks.chunks(quai_rpc::MAX_BATCH_CALLS - 1) {
429            let calls = page
430                .iter()
431                .map(|block| Ok(("quai_getHeaderByNumber", json!([block.rpc_value()?]))))
432                .collect::<Result<Vec<_>, ProviderError>>()?;
433            match self.guarded_batch(endpoint, calls).await {
434                Some(batch) => {
435                    for value in batch? {
436                        values.push(Ok(value?));
437                    }
438                }
439                // Nothing was sent, so read each block alone.
440                None => {
441                    for block in page {
442                        let params = json!([block.rpc_value()?]);
443                        values.push(Ok(self
444                            .read(zone.into(), "quai_getHeaderByNumber", params)
445                            .await?));
446                    }
447                }
448            }
449        }
450        Ok(())
451    }
452
453    /// Validate a header response's location and, for a numbered read, height.
454    pub(crate) fn parse_zone_header(
455        value: Value,
456        zone: Zone,
457        block: BlockTag,
458    ) -> Result<Option<ZoneHeader>, ProviderError> {
459        if value.is_null() {
460            return Ok(None);
461        }
462        let header = ZoneHeader::try_from(value)?;
463        if header.zone != zone {
464            return Err(ProviderError::InvalidResult("header zone mismatch"));
465        }
466        if let BlockTag::Number(number) = block
467            && number != U256::from(header.number)
468        {
469            return Err(ProviderError::InvalidResult("header number mismatch"));
470        }
471        Ok(Some(header))
472    }
473
474    /// Read a Quai account balance in base units, routed by the address's zone.
475    /// Qi UTXO balances require a separate API and cannot be passed here.
476    pub async fn balance(
477        &self,
478        address: QuaiAddress,
479        block: BlockTag,
480    ) -> Result<U256, ProviderError> {
481        let block = block.rpc_value()?;
482        quantity(
483            self.read(
484                Shard::Zone(address.zone()),
485                "quai_getBalance",
486                json!([address.to_string(), block]),
487            )
488            .await?,
489        )
490    }
491
492    /// Account nonce at a block or pending pool state; routed by the sender.
493    pub async fn transaction_count(
494        &self,
495        address: QuaiAddress,
496        block: BlockTag,
497    ) -> Result<u64, ProviderError> {
498        let block = block.rpc_value()?;
499        types::uint64(
500            self.read(
501                address.zone().into(),
502                "quai_getTransactionCount",
503                json!([address.to_string(), block]),
504            )
505            .await?,
506        )
507    }
508
509    /// Current node-recommended gas price for a zone; this is not a historical quote.
510    pub async fn gas_price(&self, zone: Zone) -> Result<U256, ProviderError> {
511        quantity(self.read(zone.into(), "quai_gasPrice", json!([])).await?)
512    }
513
514    /// [`Self::gas_price`], read together with the network's genesis in one
515    /// round trip where the transport batches. `None` when the genesis is not
516    /// `genesis`, decided before the price is parsed, so a wrong network is
517    /// reported as such. Both reads are address-free, so joining them discloses
518    /// nothing before the network is confirmed.
519    pub async fn gas_price_on_network(
520        &self,
521        zone: Zone,
522        genesis: Hash32,
523    ) -> Result<Option<U256>, ProviderError> {
524        let endpoint = self.routing.endpoint(zone.into())?;
525        let calls = vec![
526            ("quai_getHeaderByNumber", json!(["0x0"])),
527            ("quai_gasPrice", json!([])),
528        ];
529        let (observed, price) = match self.guarded_batch(endpoint, calls).await {
530            Some(batch) => {
531                let mut values = batch?.into_iter();
532                match (values.next(), values.next()) {
533                    (Some(observed), Some(price)) => (observed?, price),
534                    _ => return Err(ProviderError::InvalidResult("batch response count")),
535                }
536            }
537            // Nothing was sent: the genesis first, so a wrong network is never
538            // asked for anything else.
539            None => {
540                let observed = self
541                    .read(zone.into(), "quai_getHeaderByNumber", json!(["0x0"]))
542                    .await?;
543                if types::genesis_hash(observed)? != genesis {
544                    return Ok(None);
545                }
546                return self.gas_price(zone).await.map(Some);
547            }
548        };
549        if types::genesis_hash(observed)? != genesis {
550            return Ok(None);
551        }
552        Ok(Some(quantity(price?)?))
553    }
554
555    /// Read account/contract bytecode; empty code is a valid result.
556    pub async fn code(
557        &self,
558        address: QuaiAddress,
559        block: BlockTag,
560    ) -> Result<RpcData, ProviderError> {
561        let block = block.rpc_value()?;
562        types::data(
563            self.read(
564                address.zone().into(),
565                "quai_getCode",
566                json!([address.to_string(), block]),
567            )
568            .await?,
569        )
570    }
571
572    /// Read exactly one 32-byte storage word using a full-width unsigned slot index.
573    pub async fn storage_at(
574        &self,
575        address: QuaiAddress,
576        slot: U256,
577        block: BlockTag,
578    ) -> Result<Hash32, ProviderError> {
579        let block = block.rpc_value()?;
580        types::hash(
581            self.read(
582                address.zone().into(),
583                "quai_getStorageAt",
584                json!([address.to_string(), format!("{slot:#x}"), block]),
585            )
586            .await?,
587        )
588    }
589
590    /// Simulate an account transaction without submitting it. Remote reverts remain Rpc errors.
591    pub async fn call(
592        &self,
593        request: &CallRequest,
594        block: BlockTag,
595    ) -> Result<RpcData, ProviderError> {
596        let block = block.rpc_value()?;
597        let args = request.rpc_value()?;
598        types::data(
599            self.read(
600                request.from.zone().into(),
601                "quai_call",
602                json!([args, block]),
603            )
604            .await?,
605        )
606    }
607
608    /// Estimate account gas at an explicit selector; unlike JS, the node supports a second selector parameter.
609    /// Node simulation may replace a supplied nonce with state nonce. No fee or inclusion guarantee is implied.
610    pub async fn estimate_gas(
611        &self,
612        request: &CallRequest,
613        block: BlockTag,
614    ) -> Result<u64, ProviderError> {
615        let block = block.rpc_value()?;
616        let args = request.rpc_value()?;
617        types::uint64(
618            self.read(
619                request.from.zone().into(),
620                "quai_estimateGas",
621                json!([args, block]),
622            )
623            .await?,
624        )
625    }
626
627    /// Look up an included or pending transaction in an explicitly selected zone.
628    /// This does not infer a route from modified transaction-hash bytes.
629    pub async fn transaction(
630        &self,
631        zone: Zone,
632        hash: Hash32,
633    ) -> Result<Option<Transaction>, ProviderError> {
634        let value = self
635            .read(
636                zone.into(),
637                "quai_getTransactionByHash",
638                json!([hash.to_string()]),
639            )
640            .await?;
641        if value.is_null() {
642            return Ok(None);
643        }
644        let tx = Transaction::try_from(value)?;
645        if tx.hash != hash {
646            return Err(ProviderError::InvalidResult("transaction hash mismatch"));
647        }
648        let chain = match &tx.details {
649            TransactionDetails::Quai(tx) => Some(tx.chain_id),
650            TransactionDetails::Qi(tx) => Some(tx.chain_id),
651            TransactionDetails::External(_) => None,
652        };
653        if let Some(actual) = chain
654            && actual != self.expected_chain_id
655        {
656            return Err(ProviderError::ChainMismatch {
657                expected: self.expected_chain_id,
658                actual,
659            });
660        }
661        Ok(Some(tx))
662    }
663
664    /// Look up a receipt in an explicit zone; None is not evidence of rejection or finality.
665    pub async fn receipt(
666        &self,
667        zone: Zone,
668        hash: Hash32,
669    ) -> Result<Option<Receipt>, ProviderError> {
670        let value = self
671            .read(
672                zone.into(),
673                "quai_getTransactionReceipt",
674                json!([hash.to_string()]),
675            )
676            .await?;
677        if value.is_null() {
678            return Ok(None);
679        }
680        let receipt = Receipt::try_from(value)?;
681        if receipt.transaction_hash != hash {
682            return Err(ProviderError::InvalidResult(
683                "receipt transaction hash mismatch",
684            ));
685        }
686        Ok(Some(receipt))
687    }
688
689    /// Query current-head indexed Qi outputs. Empty results do not prove a complete index.
690    /// Returned outputs require independent maturity, expiry and ownership checks before spending.
691    pub async fn outpoints(
692        &self,
693        address: QiAddress,
694    ) -> Result<Vec<AddressOutpoint>, ProviderError> {
695        types::parse_outpoints(
696            self.read(
697                address.zone().into(),
698                "quai_getOutpointsByAddress",
699                json!([address.to_string()]),
700            )
701            .await?,
702        )
703    }
704
705    /// Read the Prime chain's advertised active zones without adding routes implicitly.
706    pub async fn running_zones(&self) -> Result<Vec<Zone>, ProviderError> {
707        let value = self
708            .read(Shard::Prime, "quai_listRunningChains", json!([]))
709            .await?;
710        let locations = value
711            .as_array()
712            .ok_or(ProviderError::InvalidResult("expected location array"))?;
713        if locations.len() > Zone::ALL.len() {
714            return Err(ProviderError::InvalidResult("too many locations"));
715        }
716        let mut zones = Vec::with_capacity(locations.len());
717        for location in locations {
718            let pair = location
719                .as_array()
720                .filter(|p| p.len() == 2)
721                .ok_or(ProviderError::InvalidResult("expected region/zone pair"))?;
722            let region = pair[0]
723                .as_u64()
724                .filter(|r| *r <= 2)
725                .ok_or(ProviderError::InvalidResult("unknown region"))?;
726            let index = pair[1]
727                .as_u64()
728                .filter(|z| *z <= 2)
729                .ok_or(ProviderError::InvalidResult("unknown zone"))?;
730            let zone = Zone::from_byte(((region << 4) | index) as u8)
731                .map_err(|_| ProviderError::InvalidResult("unknown zone"))?;
732            if zones.contains(&zone) {
733                return Err(ProviderError::InvalidResult("duplicate zone"));
734            }
735            zones.push(zone);
736        }
737        Ok(zones)
738    }
739}
740
741fn quantity(value: Value) -> Result<U256, ProviderError> {
742    let value = value
743        .as_str()
744        .ok_or(ProviderError::InvalidResult("expected hex quantity string"))?;
745    Ok(parse_quantity(value)?)
746}
747
748#[cfg(all(feature = "ws", not(target_arch = "wasm32")))]
749mod head_follower;
750#[cfg(all(feature = "ws", not(target_arch = "wasm32")))]
751pub use head_follower::{HeadFollowPolicy, WsHeadFollower};
752
753/// Internal response parsers exposed for fuzzing only.
754///
755/// Not public API: the `fuzzing` feature is off by default, these items are
756/// hidden from documentation, and their signatures may change without notice.
757#[cfg(feature = "fuzzing")]
758#[doc(hidden)]
759pub mod fuzz_internals {
760    use crate::{AddressOutpoint, BlockReference, MinedBlock, ProviderError};
761    use quai_primitives::{Hash32, QuaiAddress, Zone};
762    use serde_json::{Map, Value};
763
764    /// Parse a `quai_getOutpointsByAddress` result.
765    pub fn parse_outpoints(value: Value) -> Result<Vec<AddressOutpoint>, ProviderError> {
766        crate::types::parse_outpoints(value)
767    }
768
769    /// Validate a block response for a zone and selector.
770    pub fn block_fields(
771        value: Value,
772        zone: Zone,
773        selector: MinedBlock,
774    ) -> Result<(BlockReference, Hash32, Map<String, Value>), ProviderError> {
775        crate::blocks::block_fields(value, zone, selector)
776    }
777
778    /// Parse a `txpool_content` result for one zone.
779    pub fn pool_entries(
780        value: Value,
781        zone: Zone,
782        max_entries: usize,
783    ) -> Result<Vec<(bool, QuaiAddress, u64, Value)>, ProviderError> {
784        crate::account_rpc::pool_entries(value, zone, max_entries)
785    }
786}