Skip to main content

erpc_sdk/
lib.rs

1//! Async Rust client for ERPC JSON-RPC, subscriptions, price, account, usage,
2//! and Cloud APIs.
3
4mod account;
5mod arbitrum;
6mod arc;
7mod avalanche;
8mod base;
9mod bitcoin;
10mod bridge;
11mod bridge_local;
12mod bsc;
13mod cloud;
14mod config;
15pub mod dex_catalog;
16mod error;
17mod ethereum;
18mod generated;
19mod hyperliquid;
20mod kaia;
21mod monad;
22mod near;
23mod optimism;
24mod polygon;
25mod price;
26mod rest;
27mod robinhood;
28mod rpc;
29mod solana;
30mod soneium;
31mod subscriptions;
32mod sui;
33mod sui_grpc_web;
34mod sui_proto;
35mod swap;
36pub mod token_catalog;
37pub mod token_rankings;
38mod tron;
39mod usage;
40
41pub use account::{AccountClient, ErpcPlan, TokenBalance};
42pub use arbitrum::{ARBITRUM_RPC_METHODS, ArbitrumClient, ArbitrumRpcClient};
43pub use arc::{ARC_RPC_METHODS, ArcClient, ArcRpcClient};
44pub use avalanche::{
45    AVALANCHE_AVAX_METHODS, AVALANCHE_INDEX_METHODS, AVALANCHE_INFO_METHODS,
46    AVALANCHE_P_CHAIN_METHODS, AVALANCHE_PROPOSER_VM_METHODS, AVALANCHE_X_CHAIN_METHODS,
47    AvalancheAvaxClient, AvalancheClient, AvalancheIndexClient, AvalancheIndexRpcClient,
48    AvalancheInfoClient, AvalanchePChainClient, AvalancheProposerVmClient, AvalancheXChainClient,
49};
50pub use base::{BASE_RPC_METHODS, BaseClient, BaseRpcClient};
51pub use bitcoin::{BITCOIN_RPC_METHODS, BitcoinClient, BitcoinRpcClient};
52pub use bridge::{
53    BridgeClient, BridgeError, BridgeErrorCode, BridgeResult, MayanEvmUnsignedTransaction,
54    MayanSolanaUnsignedTransaction, MayanSwiftV2Allowance, MayanSwiftV2BridgeClient,
55    MayanSwiftV2BridgeConfig, MayanSwiftV2Build, MayanSwiftV2BuildRequest, MayanSwiftV2BuildResult,
56    MayanSwiftV2BuildUnsignedRequest, MayanSwiftV2BuildValidation, MayanSwiftV2LocalBuildConfig,
57    MayanSwiftV2Quote, MayanSwiftV2QuoteRequest, MayanSwiftV2QuoteResult, MayanSwiftV2SourceSwap,
58    MayanSwiftV2Status, MayanSwiftV2StatusRequest, MayanSwiftV2StatusResult,
59    MayanSwiftV2UnsignedTransaction, create_mayan_swift_v2_bridge_client,
60};
61pub use bridge_local::{
62    MayanSwiftV2LocalBuild, MayanSwiftV2LocalBuildRequest, MayanSwiftV2LocalBuildValidation,
63    MayanSwiftV2LocalConstruction, MayanSwiftV2LocalContext, MayanSwiftV2LocalEvmRpcEvidence,
64    MayanSwiftV2LocalSolanaRpcEvidence, MayanSwiftV2LocalSolanaRpcLookupTableEvidence,
65    MayanSwiftV2LocalSourceRpcEvidence, MayanSwiftV2LocalSourceSwapInstruction,
66    MayanSwiftV2LocalSourceSwapInstructionAccount, MayanSwiftV2LocalSourceSwapPlan,
67    MayanSwiftV2SourceSwapPlan,
68};
69pub use bsc::{BSC_RPC_METHODS, BscClient, BscRpcClient};
70pub use cloud::{
71    CloudCatalogClient, CloudCredit, CloudCreditAlertLevel, CloudCreditClient, CloudOffering,
72    CloudOfferingBilling, CloudOfferingCompute, CloudOfferingComputeTenancy, CloudOfferingSolana,
73    CloudOfferingSolanaTransport, CloudResource, CloudResourceBillingStatus, CloudResourceKind,
74    CloudResourceMode, CloudResourceStatus, CloudResourceStatusBilling, CloudResourcesClient,
75    ErpcCloudClient, ErpcCloudClientConfig,
76};
77pub use config::{
78    DEFAULT_ACCOUNT_ENDPOINT, DEFAULT_ARBITRUM_ENDPOINT, DEFAULT_ARC_ENDPOINT,
79    DEFAULT_AVALANCHE_ENDPOINT, DEFAULT_BASE_ENDPOINT, DEFAULT_BSC_ENDPOINT, DEFAULT_ENDPOINT,
80    DEFAULT_HYPERLIQUID_ENDPOINT, DEFAULT_KAIA_ENDPOINT, DEFAULT_MONAD_ENDPOINT,
81    DEFAULT_NEAR_ENDPOINT, DEFAULT_OPTIMISM_ENDPOINT, DEFAULT_POLYGON_ENDPOINT,
82    DEFAULT_ROBINHOOD_ENDPOINT, DEFAULT_SONEIUM_ENDPOINT, DEFAULT_SUI_ENDPOINT, DEFAULT_TIMEOUT,
83    DEFAULT_TRON_ENDPOINT, DEFAULT_USER_ENDPOINT, ErpcClientConfig, RpcEndpointConfig,
84    SuiGrpcWebEndpointConfig,
85};
86pub use dex_catalog::{
87    DEX_ALIASES, DEX_CATALOG_AS_OF_DATE, DEX_CATALOG_CONTENT_DIGEST, DEX_CATALOG_VERSION,
88    DEX_CHAIN_IDS, DEX_DEPLOYMENTS, DexAlias, DexChainId, DexDeployment,
89    ListPoolDefinitionsOptions, NATIVE_WRAP_DEFINITIONS, NativeWrapDefinition, POOL_DEFINITIONS,
90    PoolAdapter, PoolDefinition, dexes, find_pool_definition_by_address,
91    find_pool_definitions_by_pair, get_dex_deployment, get_native_wrap_definition,
92    get_pool_definition, list_pool_definitions, pools,
93};
94pub use error::{ErpcError, ErpcErrorCode, JsonRpcErrorObject, Result};
95pub use ethereum::{
96    ETHEREUM_RPC_METHODS, ETHEREUM_SUBSCRIPTION_METHODS, EthereumClient, EthereumRpcClient,
97    EthereumSubscriptions,
98};
99pub use hyperliquid::{HYPERLIQUID_RPC_METHODS, HyperliquidClient, HyperliquidRpcClient};
100pub use kaia::{KAIA_RPC_METHODS, KaiaClient, KaiaRpcClient};
101pub use monad::{MONAD_RPC_METHODS, MonadClient, MonadRpcClient};
102pub use near::{
103    NEAR_RPC_METHODS, NearAccountView, NearBlockHeader, NearBlockId, NearBlockReference,
104    NearBlockView, NearClient, NearFinality, NearNodeVersion, NearRpcClient, NearStatus,
105    NearSyncInfo,
106};
107pub use optimism::{OPTIMISM_RPC_METHODS, OptimismClient, OptimismRpcClient};
108pub use polygon::{POLYGON_RPC_METHODS, PolygonClient, PolygonRpcClient};
109pub use price::{
110    BinaryUpdate, ParsedPriceMetadata, ParsedPriceUpdate, ParsedPublisherStakeCaps, PriceAssetType,
111    PriceClient, PriceEncoding, PriceFeedMetadata, PricePoint, PriceStream, PriceStreamEvent,
112    PriceStreamOptions, PriceUpdateOptions, PriceUpdateResponse, PublisherStakeCap,
113    PublisherStakeCapsResponse,
114};
115pub use robinhood::{ROBINHOOD_RPC_METHODS, RobinhoodClient, RobinhoodRpcClient};
116pub use rpc::{
117    HttpJsonRpcTransport, HttpTransportConfig, JsonRpcId, PendingRpcBatchRequest,
118    PendingRpcRequest, RequestOptions, RpcBatchCall, RpcNamespace,
119};
120pub use solana::{
121    AddressTransaction, AddressTransactionPage, AddressTransactionsOptions, AddressTransfer,
122    AddressTransferDirection, AddressTransferFilters, AddressTransferPage, AddressTransferType,
123    AddressTransfersOptions, AnalyticsTimeBound, AssetBatchRequest, AssetListRequest, AssetRequest,
124    EpochSummary, IndexedAsset, IndexedAssetList, IndexedAssetProof, LeaderSlot, LeaderSlotsResult,
125    NumericFilter, PingMeasurement, PriorityFeeEstimate, ProgramStatsBucket, ProgramStatsOptions,
126    SOLANA_ANALYTICS_METHODS, SOLANA_DAS_METHODS, SOLANA_ENHANCED_SUBSCRIPTION_METHODS,
127    SOLANA_HISTORY_METHODS, SOLANA_LEADER_METHODS, SOLANA_RPC_METHODS, SlotStatsOptions,
128    SlotStatsRow, SolanaAnalyticsClient, SolanaClient, SolanaCommitment, SolanaContext,
129    SolanaContextResult, SolanaDasClient, SolanaEncoding, SolanaHistoryClient, SolanaLeaderClient,
130    SolanaRpcClient, SolanaSubscriptions, TopProgramRow, TopProgramsOptions, TpsBucket,
131    TpsTimeseriesOptions, ValidatorInformation, ValidatorsInformationOptions,
132    ValidatorsInformationResult,
133};
134pub use soneium::{SONEIUM_RPC_METHODS, SoneiumClient, SoneiumRpcClient};
135pub use subscriptions::{RpcNotification, RpcSubscription, SubscriptionId};
136pub use sui::{
137    PendingSuiGrpcWebRequest, SUI_GRPC_WEB_CONTENT_TYPE, SUI_GRPC_WEB_METHODS, SuiBalance,
138    SuiClient, SuiGrpcWebClient, SuiObjectSummary, SuiServiceInfo,
139};
140pub use swap::{
141    EvmBlockSnapshot, EvmUnsignedTransaction, ExactInputQuoteRequest, ExactInputQuoteResult,
142    ExactInputSwapPathEntry, ExactInputSwapPreparation, ExactInputSwapRequest,
143    ExactInputSwapSimulation, PrepareExactInputSwapRequest, PrepareExactInputSwapResult, QuoteFee,
144    SimulateExactInputSwapResult, SwapAllowance, SwapClient, SwapExecutionError,
145    SwapExecutionErrorCode, SwapExecutionResult, SwapFreshness, SwapPathEntry, SwapPreparation,
146    SwapQuoteError, SwapQuoteErrorCode, SwapQuoteRequest, SwapResult, SwapSimulation,
147};
148pub use token_catalog::{
149    TOKEN_ALIASES, TOKEN_ASSETS, TOKEN_CATALOG_AS_OF_DATE, TOKEN_CATALOG_CONTENT_DIGEST,
150    TOKEN_CATALOG_VERSION, TOKEN_CHAIN_IDS, TOKEN_DEPLOYMENTS, TokenAlias, TokenAsset,
151    TokenChainId, TokenDeployment, TokenRepresentationKind, TokenStandard, TokenStatus,
152    find_token_deployment_by_address, find_token_deployments_by_symbol,
153    get_native_token_deployment, get_token_asset, get_token_deployment, list_token_deployments,
154    token_chain_ids, tokens,
155};
156pub use token_rankings::{
157    TOKEN_RANKINGS, TOKEN_RANKINGS_AS_OF, TOKEN_RANKINGS_CONTENT_DIGEST, TOKEN_RANKINGS_COVERAGE,
158    TOKEN_RANKINGS_METADATA, TOKEN_RANKINGS_METRIC, TOKEN_RANKINGS_SCHEMA_VERSION,
159    TOKEN_RANKINGS_SOURCE_IDS, TOKEN_RANKINGS_STATUS, TokenRanking, TokenRankingCoverage,
160    TokenRankingMetadata, list_token_rankings,
161};
162pub use tokio_util::sync::CancellationToken;
163pub use tron::{TRON_RPC_METHODS, TronClient, TronRpcClient};
164pub use usage::{
165    MonthlyApiKeyChainUsage, MonthlyApiKeyMethodUsage, MonthlyApiKeyUsage, MonthlyApiKeyUsageEntry,
166    MonthlyApiKeyUsageParams, UsageClient,
167};
168
169use std::sync::Arc;
170
171use config::{ResolvedErpcClientConfig, ResolvedRpcEndpoint, endpoint_with_path, websocket_url};
172use rest::RestTransport;
173use subscriptions::WebSocketJsonRpcTransport;
174
175fn legacy_rpc_transport(
176    resolved: &ResolvedErpcClientConfig,
177    endpoint: url::Url,
178    client: &reqwest::Client,
179    namespace: &str,
180) -> Arc<HttpJsonRpcTransport> {
181    if let Some(api_key) = &resolved.api_key {
182        Arc::new(HttpJsonRpcTransport::new(HttpTransportConfig {
183            api_key: api_key.clone(),
184            endpoint,
185            headers: resolved.headers.clone(),
186            max_batch_size: 256,
187            timeout: resolved.timeout,
188            client: client.clone(),
189        }))
190    } else {
191        Arc::new(HttpJsonRpcTransport::unavailable(
192            namespace,
193            resolved.timeout,
194            client.clone(),
195        ))
196    }
197}
198
199fn direct_rpc_transport(
200    endpoint: &ResolvedRpcEndpoint,
201    client: &reqwest::Client,
202    namespace: &str,
203    timeout: std::time::Duration,
204) -> Arc<HttpJsonRpcTransport> {
205    Arc::new(HttpJsonRpcTransport::new_direct(
206        endpoint.http_url.clone(),
207        endpoint.headers.clone(),
208        endpoint.redaction_secrets.clone(),
209        256,
210        timeout,
211        client.clone(),
212        namespace,
213    ))
214}
215
216fn bitcoin_rpc_transport(
217    resolved: &ResolvedErpcClientConfig,
218    client: &reqwest::Client,
219    direct_client: &reqwest::Client,
220) -> Result<Arc<HttpJsonRpcTransport>> {
221    if let Some(endpoint) = &resolved.bitcoin_rpc {
222        return Ok(Arc::new(HttpJsonRpcTransport::new_direct_bitcoin(
223            endpoint.http_url.clone(),
224            endpoint.headers.clone(),
225            endpoint.redaction_secrets.clone(),
226            resolved.timeout,
227            direct_client.clone(),
228            "bitcoin.rpc",
229        )));
230    }
231    if let Some(api_key) = &resolved.api_key {
232        return Ok(Arc::new(HttpJsonRpcTransport::new_bitcoin(
233            api_key.clone(),
234            endpoint_with_path(&resolved.endpoint, "/bitcoin"),
235            resolved.headers.clone(),
236            resolved.timeout,
237            direct_client.clone(),
238        )?));
239    }
240    Ok(Arc::new(HttpJsonRpcTransport::unavailable(
241        "bitcoin.rpc",
242        resolved.timeout,
243        client.clone(),
244    )))
245}
246
247fn base_rpc_transport(
248    resolved: &ResolvedErpcClientConfig,
249    client: &reqwest::Client,
250    direct_client: &reqwest::Client,
251) -> Arc<HttpJsonRpcTransport> {
252    if let Some(endpoint) = &resolved.base_rpc {
253        return direct_rpc_transport(endpoint, direct_client, "base.rpc", resolved.timeout);
254    }
255    legacy_rpc_transport(resolved, resolved.base_endpoint.clone(), client, "base.rpc")
256}
257
258fn arbitrum_rpc_transport(
259    resolved: &ResolvedErpcClientConfig,
260    client: &reqwest::Client,
261    direct_client: &reqwest::Client,
262) -> Arc<HttpJsonRpcTransport> {
263    if let Some(endpoint) = &resolved.arbitrum_rpc {
264        return direct_rpc_transport(endpoint, direct_client, "arbitrum.rpc", resolved.timeout);
265    }
266    legacy_rpc_transport(
267        resolved,
268        resolved.arbitrum_endpoint.clone(),
269        client,
270        "arbitrum.rpc",
271    )
272}
273
274fn polygon_rpc_transport(
275    resolved: &ResolvedErpcClientConfig,
276    client: &reqwest::Client,
277    direct_client: &reqwest::Client,
278) -> Arc<HttpJsonRpcTransport> {
279    if let Some(endpoint) = &resolved.polygon_rpc {
280        return direct_rpc_transport(endpoint, direct_client, "polygon.rpc", resolved.timeout);
281    }
282    legacy_rpc_transport(
283        resolved,
284        resolved.polygon_endpoint.clone(),
285        client,
286        "polygon.rpc",
287    )
288}
289
290fn bsc_rpc_transport(
291    resolved: &ResolvedErpcClientConfig,
292    client: &reqwest::Client,
293    direct_client: &reqwest::Client,
294) -> Arc<HttpJsonRpcTransport> {
295    if let Some(endpoint) = &resolved.bsc_rpc {
296        return direct_rpc_transport(endpoint, direct_client, "bsc.rpc", resolved.timeout);
297    }
298    legacy_rpc_transport(resolved, resolved.bsc_endpoint.clone(), client, "bsc.rpc")
299}
300
301fn optimism_rpc_transport(
302    resolved: &ResolvedErpcClientConfig,
303    client: &reqwest::Client,
304    direct_client: &reqwest::Client,
305) -> Arc<HttpJsonRpcTransport> {
306    if let Some(endpoint) = &resolved.optimism_rpc {
307        return direct_rpc_transport(endpoint, direct_client, "optimism.rpc", resolved.timeout);
308    }
309    legacy_rpc_transport(
310        resolved,
311        resolved.optimism_endpoint.clone(),
312        client,
313        "optimism.rpc",
314    )
315}
316
317fn kaia_rpc_transport(
318    resolved: &ResolvedErpcClientConfig,
319    client: &reqwest::Client,
320    direct_client: &reqwest::Client,
321) -> Arc<HttpJsonRpcTransport> {
322    if let Some(endpoint) = &resolved.kaia_rpc {
323        return direct_rpc_transport(endpoint, direct_client, "kaia.rpc", resolved.timeout);
324    }
325    legacy_rpc_transport(resolved, resolved.kaia_endpoint.clone(), client, "kaia.rpc")
326}
327
328fn soneium_rpc_transport(
329    resolved: &ResolvedErpcClientConfig,
330    client: &reqwest::Client,
331    direct_client: &reqwest::Client,
332) -> Arc<HttpJsonRpcTransport> {
333    if let Some(endpoint) = &resolved.soneium_rpc {
334        return direct_rpc_transport(endpoint, direct_client, "soneium.rpc", resolved.timeout);
335    }
336    legacy_rpc_transport(
337        resolved,
338        resolved.soneium_endpoint.clone(),
339        client,
340        "soneium.rpc",
341    )
342}
343
344fn monad_rpc_transport(
345    resolved: &ResolvedErpcClientConfig,
346    client: &reqwest::Client,
347    direct_client: &reqwest::Client,
348) -> Arc<HttpJsonRpcTransport> {
349    if let Some(endpoint) = &resolved.monad_rpc {
350        return direct_rpc_transport(endpoint, direct_client, "monad.rpc", resolved.timeout);
351    }
352    legacy_rpc_transport(
353        resolved,
354        resolved.monad_endpoint.clone(),
355        client,
356        "monad.rpc",
357    )
358}
359
360fn hyperliquid_rpc_transport(
361    resolved: &ResolvedErpcClientConfig,
362    client: &reqwest::Client,
363    direct_client: &reqwest::Client,
364) -> Arc<HttpJsonRpcTransport> {
365    if let Some(endpoint) = &resolved.hyperliquid_rpc {
366        return direct_rpc_transport(endpoint, direct_client, "hyperliquid.rpc", resolved.timeout);
367    }
368    legacy_rpc_transport(
369        resolved,
370        resolved.hyperliquid_endpoint.clone(),
371        client,
372        "hyperliquid.rpc",
373    )
374}
375
376fn arc_rpc_transport(
377    resolved: &ResolvedErpcClientConfig,
378    client: &reqwest::Client,
379    direct_client: &reqwest::Client,
380) -> Arc<HttpJsonRpcTransport> {
381    if let Some(endpoint) = &resolved.arc_rpc {
382        return direct_rpc_transport(endpoint, direct_client, "arc.rpc", resolved.timeout);
383    }
384    legacy_rpc_transport(resolved, resolved.arc_endpoint.clone(), client, "arc.rpc")
385}
386
387fn robinhood_rpc_transport(
388    resolved: &ResolvedErpcClientConfig,
389    client: &reqwest::Client,
390    direct_client: &reqwest::Client,
391) -> Arc<HttpJsonRpcTransport> {
392    if let Some(endpoint) = &resolved.robinhood_rpc {
393        return direct_rpc_transport(endpoint, direct_client, "robinhood.rpc", resolved.timeout);
394    }
395    legacy_rpc_transport(
396        resolved,
397        resolved.robinhood_endpoint.clone(),
398        client,
399        "robinhood.rpc",
400    )
401}
402
403fn near_rpc_transport(
404    resolved: &ResolvedErpcClientConfig,
405    client: &reqwest::Client,
406    direct_client: &reqwest::Client,
407) -> Arc<HttpJsonRpcTransport> {
408    if let Some(endpoint) = &resolved.near_rpc {
409        return direct_rpc_transport(endpoint, direct_client, "near.rpc", resolved.timeout);
410    }
411    legacy_rpc_transport(resolved, resolved.near_endpoint.clone(), client, "near.rpc")
412}
413
414fn tron_rpc_transport(
415    resolved: &ResolvedErpcClientConfig,
416    client: &reqwest::Client,
417    direct_client: &reqwest::Client,
418) -> Arc<HttpJsonRpcTransport> {
419    if let Some(endpoint) = &resolved.tron_rpc {
420        return direct_rpc_transport(endpoint, direct_client, "tron.rpc", resolved.timeout);
421    }
422    legacy_rpc_transport(resolved, resolved.tron_endpoint.clone(), client, "tron.rpc")
423}
424
425fn sui_grpc_web_transport(
426    resolved: &ResolvedErpcClientConfig,
427    client: &reqwest::Client,
428    direct_client: &reqwest::Client,
429) -> Result<Arc<sui_grpc_web::SuiGrpcWebTransport>> {
430    if let Some(endpoint) = &resolved.sui_grpc_web {
431        return Ok(Arc::new(sui_grpc_web::SuiGrpcWebTransport::new_direct(
432            endpoint.base_url.clone(),
433            endpoint.headers.clone(),
434            resolved.timeout,
435            direct_client.clone(),
436        )));
437    }
438    if let Some(api_key) = &resolved.api_key {
439        return Ok(Arc::new(sui_grpc_web::SuiGrpcWebTransport::new_hosted(
440            api_key.clone(),
441            resolved.sui_endpoint.clone(),
442            resolved.headers.clone(),
443            resolved.timeout,
444            direct_client.clone(),
445        )?));
446    }
447    Ok(Arc::new(sui_grpc_web::SuiGrpcWebTransport::unavailable(
448        resolved.timeout,
449        client.clone(),
450    )))
451}
452
453fn websocket_transport(
454    resolved: &ResolvedErpcClientConfig,
455    direct: Option<&ResolvedRpcEndpoint>,
456    legacy_endpoint: &url::Url,
457    legacy_path: &str,
458    namespace: &str,
459) -> Result<Arc<WebSocketJsonRpcTransport>> {
460    if let Some(endpoint) = direct {
461        return Ok(if let Some(websocket_url) = &endpoint.websocket_url {
462            Arc::new(WebSocketJsonRpcTransport::new_direct(
463                websocket_url.clone(),
464                endpoint.redaction_secrets.clone(),
465                resolved.timeout,
466                namespace,
467            ))
468        } else {
469            Arc::new(WebSocketJsonRpcTransport::unavailable(
470                namespace,
471                resolved.timeout,
472            ))
473        });
474    }
475    if let Some(api_key) = &resolved.api_key {
476        return Ok(Arc::new(WebSocketJsonRpcTransport::new(
477            websocket_url(legacy_endpoint, api_key, legacy_path)?,
478            resolved.timeout,
479        )));
480    }
481    Ok(Arc::new(WebSocketJsonRpcTransport::unavailable(
482        namespace,
483        resolved.timeout,
484    )))
485}
486
487fn avalanche_index_transports(
488    resolved: &ResolvedErpcClientConfig,
489    client: &reqwest::Client,
490) -> avalanche::AvalancheIndexTransports {
491    let index_transport = |path| {
492        legacy_rpc_transport(
493            resolved,
494            endpoint_with_path(&resolved.avalanche_endpoint, path),
495            client,
496            "avalanche.index",
497        )
498    };
499    avalanche::AvalancheIndexTransports {
500        c_chain_blocks: index_transport("/ava/ext/index/C/block"),
501        p_chain_blocks: index_transport("/ava/ext/index/P/block"),
502        x_chain_blocks: index_transport("/ava/ext/index/X/block"),
503        x_chain_transactions: index_transport("/ava/ext/index/X/tx"),
504    }
505}
506
507/// A configured ERPC client containing all public service clients.
508#[derive(Clone)]
509pub struct ErpcClient {
510    /// Account and token balance API.
511    pub account: AccountClient,
512    /// Arbitrum One read-only HTTP JSON-RPC.
513    pub arbitrum: ArbitrumClient,
514    /// Avalanche C-Chain, native-chain, Index API, and subscriptions.
515    pub avalanche: AvalancheClient,
516    /// BNB Smart Chain mainnet read-only HTTP JSON-RPC.
517    pub bsc: BscClient,
518    /// Arc mainnet read-only HTTP JSON-RPC.
519    pub arc: ArcClient,
520    /// Base read-only HTTP JSON-RPC.
521    pub base: BaseClient,
522    /// Bitcoin Core HTTP JSON-RPC.
523    pub bitcoin: BitcoinClient,
524    /// Standard Ethereum JSON-RPC and subscriptions.
525    pub ethereum: EthereumClient,
526    /// Price feed REST and streaming API.
527    pub price: PriceClient,
528    /// Kaia mainnet read-only HTTP JSON-RPC.
529    pub kaia: KaiaClient,
530    /// Hyperliquid `HyperEVM` mainnet read-only HTTP JSON-RPC.
531    pub hyperliquid: HyperliquidClient,
532    /// Monad mainnet read-only HTTP JSON-RPC.
533    pub monad: MonadClient,
534    /// OP Mainnet read-only HTTP JSON-RPC.
535    pub optimism: OptimismClient,
536    /// Robinhood Chain Public Mainnet read-only HTTP JSON-RPC.
537    pub robinhood: RobinhoodClient,
538    /// Standard and extended Solana JSON-RPC and subscriptions.
539    pub solana: SolanaClient,
540    /// Polygon `PoS` mainnet read-only HTTP JSON-RPC.
541    pub polygon: PolygonClient,
542    /// Soneium mainnet read-only HTTP JSON-RPC.
543    pub soneium: SoneiumClient,
544    /// RPC-backed exact-input DEX quote client.
545    pub swap: SwapClient,
546    /// Monthly API key usage API.
547    pub usage: UsageClient,
548    /// NEAR mainnet read-only HTTP JSON-RPC.
549    pub near: NearClient,
550    /// TRON mainnet read-only HTTP JSON-RPC.
551    pub tron: TronClient,
552    /// Sui mainnet read-only binary gRPC-Web.
553    pub sui: SuiClient,
554}
555
556impl ErpcClient {
557    /// Creates a client after validating all configuration.
558    #[allow(clippy::too_many_lines)]
559    pub fn new(config: ErpcClientConfig) -> Result<Self> {
560        let resolved = ResolvedErpcClientConfig::try_from(config)?;
561        let http = ResolvedErpcClientConfig::http_client()?;
562        let direct_http = ResolvedErpcClientConfig::direct_http_client()?;
563        let base_transport = base_rpc_transport(&resolved, &http, &direct_http);
564        let arbitrum_transport = arbitrum_rpc_transport(&resolved, &http, &direct_http);
565        let polygon_transport = polygon_rpc_transport(&resolved, &http, &direct_http);
566        let bsc_transport = bsc_rpc_transport(&resolved, &http, &direct_http);
567        let optimism_transport = optimism_rpc_transport(&resolved, &http, &direct_http);
568        let kaia_transport = kaia_rpc_transport(&resolved, &http, &direct_http);
569        let soneium_transport = soneium_rpc_transport(&resolved, &http, &direct_http);
570        let monad_transport = monad_rpc_transport(&resolved, &http, &direct_http);
571        let hyperliquid_transport = hyperliquid_rpc_transport(&resolved, &http, &direct_http);
572        let arc_transport = arc_rpc_transport(&resolved, &http, &direct_http);
573        let robinhood_transport = robinhood_rpc_transport(&resolved, &http, &direct_http);
574        let near_transport = near_rpc_transport(&resolved, &http, &direct_http);
575        let tron_transport = tron_rpc_transport(&resolved, &http, &direct_http);
576        let sui_transport = sui_grpc_web_transport(&resolved, &http, &direct_http)?;
577        let bitcoin_transport = bitcoin_rpc_transport(&resolved, &http, &direct_http)?;
578        let solana_transport = resolved.solana_rpc.as_ref().map_or_else(
579            || legacy_rpc_transport(&resolved, resolved.endpoint.clone(), &http, "solana.rpc"),
580            |endpoint| direct_rpc_transport(endpoint, &direct_http, "solana.rpc", resolved.timeout),
581        );
582        let ethereum_transport = resolved.ethereum_rpc.as_ref().map_or_else(
583            || {
584                legacy_rpc_transport(
585                    &resolved,
586                    endpoint_with_path(&resolved.endpoint, "/eth"),
587                    &http,
588                    "ethereum.rpc",
589                )
590            },
591            |endpoint| {
592                direct_rpc_transport(endpoint, &direct_http, "ethereum.rpc", resolved.timeout)
593            },
594        );
595        let avalanche_c_transport = resolved.avalanche_c_rpc.as_ref().map_or_else(
596            || {
597                legacy_rpc_transport(
598                    &resolved,
599                    endpoint_with_path(&resolved.avalanche_endpoint, "/ava"),
600                    &http,
601                    "avalanche.rpc",
602                )
603            },
604            |endpoint| {
605                direct_rpc_transport(endpoint, &direct_http, "avalanche.rpc", resolved.timeout)
606            },
607        );
608        let avalanche_native_transport = legacy_rpc_transport(
609            &resolved,
610            endpoint_with_path(&resolved.avalanche_endpoint, "/ava"),
611            &http,
612            "avalanche.native",
613        );
614        let avalanche_index = avalanche_index_transports(&resolved, &http);
615        let solana_ws = websocket_transport(
616            &resolved,
617            resolved.solana_rpc.as_ref(),
618            &resolved.endpoint,
619            "",
620            "solana.subscriptions",
621        )?;
622        let ethereum_ws = websocket_transport(
623            &resolved,
624            resolved.ethereum_rpc.as_ref(),
625            &resolved.endpoint,
626            "/eth",
627            "ethereum.subscriptions",
628        )?;
629        let avalanche_ws = websocket_transport(
630            &resolved,
631            resolved.avalanche_c_rpc.as_ref(),
632            &resolved.avalanche_endpoint,
633            "/ava-ws",
634            "avalanche.subscriptions",
635        )?;
636        let (shared_rest, account_rest, user_rest) = if let Some(api_key) = &resolved.api_key {
637            (
638                RestTransport::new(
639                    api_key.clone(),
640                    resolved.endpoint.clone(),
641                    resolved.headers.clone(),
642                    resolved.timeout,
643                    http.clone(),
644                ),
645                RestTransport::new(
646                    api_key.clone(),
647                    resolved.account_endpoint.clone(),
648                    resolved.headers.clone(),
649                    resolved.timeout,
650                    http.clone(),
651                ),
652                RestTransport::new(
653                    api_key.clone(),
654                    resolved.user_endpoint.clone(),
655                    resolved.headers.clone(),
656                    resolved.timeout,
657                    http.clone(),
658                ),
659            )
660        } else {
661            (
662                RestTransport::unavailable("price", resolved.timeout, http.clone()),
663                RestTransport::unavailable("account", resolved.timeout, http.clone()),
664                RestTransport::unavailable("usage", resolved.timeout, http.clone()),
665            )
666        };
667        let swap = SwapClient::new(
668            Arc::clone(&ethereum_transport),
669            Arc::clone(&avalanche_c_transport),
670        );
671
672        Ok(Self {
673            account: AccountClient::new(account_rest),
674            arbitrum: ArbitrumClient::new(arbitrum_transport),
675            avalanche: AvalancheClient::new(
676                &avalanche_c_transport,
677                avalanche_native_transport,
678                avalanche_ws,
679                avalanche_index,
680            ),
681            bsc: BscClient::new(bsc_transport),
682            arc: ArcClient::new(arc_transport),
683            base: BaseClient::new(base_transport),
684            bitcoin: BitcoinClient::new(bitcoin_transport),
685            ethereum: EthereumClient::new(ethereum_transport, ethereum_ws),
686            price: PriceClient::new(shared_rest),
687            kaia: KaiaClient::new(kaia_transport),
688            hyperliquid: HyperliquidClient::new(hyperliquid_transport),
689            monad: MonadClient::new(monad_transport),
690            optimism: OptimismClient::new(optimism_transport),
691            robinhood: RobinhoodClient::new(robinhood_transport),
692            solana: SolanaClient::new(solana_transport, solana_ws),
693            polygon: PolygonClient::new(polygon_transport),
694            soneium: SoneiumClient::new(soneium_transport),
695            swap,
696            usage: UsageClient::new(user_rest),
697            near: NearClient::new(near_transport),
698            tron: TronClient::new(tron_transport),
699            sui: SuiClient::new(sui_transport),
700        })
701    }
702
703    /// Builds a test client with a private deterministic swap clock.
704    #[cfg(test)]
705    pub(crate) fn new_with_swap_clock(
706        config: ErpcClientConfig,
707        clock: fn() -> u64,
708    ) -> Result<Self> {
709        let mut client = Self::new(config)?;
710        client.swap = client.swap.with_clock(clock);
711        Ok(client)
712    }
713
714    /// Closes all subscription connections. HTTP clients need no explicit close.
715    pub async fn close(&self) {
716        self.solana.subscriptions.close().await;
717        self.ethereum.subscriptions.close().await;
718        self.avalanche.subscriptions.close().await;
719    }
720}