1use 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;
45pub 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
82pub enum BlockTag {
83 Latest,
85 Pending,
87 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#[derive(Debug, Error)]
103#[non_exhaustive]
104pub enum ProviderError {
105 #[error("canonical replay history unavailable; restore an older checkpoint explicitly")]
107 ReplayHistoryUnavailable,
108 #[error("invalid RPC request: {0}")]
110 InvalidRequest(&'static str),
111 #[error("exact Qi conversion fee estimation is not qualified for this node API")]
113 ConversionFeeEstimationUnavailable,
114 #[error("block number exceeds the node's signed 64-bit range")]
116 BlockNumberOutOfRange,
117 #[error(transparent)]
119 Route(#[from] RouteError),
120 #[error(transparent)]
122 Rpc(#[from] RpcError),
123 #[error(transparent)]
125 Quantity(#[from] QuantityError),
126 #[error("chain ID mismatch: expected {expected}, received {actual}")]
128 ChainMismatch {
129 expected: U256,
131 actual: U256,
133 },
134 #[error("network genesis mismatch")]
137 GenesisMismatch,
138 #[error("canonical observation changed during the request")]
140 ObservationChanged,
141 #[error("state anchor is older than required")]
144 StaleAnchor,
145 #[error("another node disputes the state anchor")]
150 AnchorDisputed,
151 #[error("invalid RPC result: {0}")]
153 InvalidResult(&'static str),
154 #[error(transparent)]
157 Proof(#[from] state_proof::ProofError),
158 #[error(transparent)]
160 Header(#[from] header_hash::HeaderHashError),
161}
162
163impl ProviderError {
164 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#[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 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 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 pub fn expected_chain_id(&self) -> U256 {
229 self.expected_chain_id
230 }
231
232 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 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 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 pub async fn block_number(&self, shard: Shard) -> Result<U256, ProviderError> {
306 quantity(self.read(shard, "quai_blockNumber", json!([])).await?)
307 }
308
309 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 pub async fn latest_header(&self, zone: Zone) -> Result<Option<ZoneHeader>, ProviderError> {
324 self.zone_header(zone, BlockTag::Latest).await
325 }
326
327 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 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 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 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 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 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 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 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 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 pub async fn gas_price(&self, zone: Zone) -> Result<U256, ProviderError> {
511 quantity(self.read(zone.into(), "quai_gasPrice", json!([])).await?)
512 }
513
514 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 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 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 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 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 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 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 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 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 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#[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 pub fn parse_outpoints(value: Value) -> Result<Vec<AddressOutpoint>, ProviderError> {
766 crate::types::parse_outpoints(value)
767 }
768
769 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 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}