erpc-sdk 0.11.0

Async multi-network Rust SDK for ERPC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
//! Async Rust client for ERPC JSON-RPC, subscriptions, price, account, usage,
//! and Cloud APIs.

mod account;
mod arbitrum;
mod arc;
mod avalanche;
mod base;
mod bitcoin;
mod bridge;
mod bridge_local;
mod bsc;
mod cloud;
mod config;
pub mod dex_catalog;
mod error;
mod ethereum;
mod generated;
mod hyperliquid;
mod kaia;
mod monad;
mod near;
mod optimism;
mod polygon;
mod price;
mod rest;
mod robinhood;
mod rpc;
mod solana;
mod soneium;
mod subscriptions;
mod sui;
mod sui_grpc_web;
mod sui_proto;
mod swap;
pub mod token_catalog;
pub mod token_rankings;
mod tron;
mod usage;

pub use account::{AccountClient, ErpcPlan, TokenBalance};
pub use arbitrum::{ARBITRUM_RPC_METHODS, ArbitrumClient, ArbitrumRpcClient};
pub use arc::{ARC_RPC_METHODS, ArcClient, ArcRpcClient};
pub use avalanche::{
    AVALANCHE_AVAX_METHODS, AVALANCHE_INDEX_METHODS, AVALANCHE_INFO_METHODS,
    AVALANCHE_P_CHAIN_METHODS, AVALANCHE_PROPOSER_VM_METHODS, AVALANCHE_X_CHAIN_METHODS,
    AvalancheAvaxClient, AvalancheClient, AvalancheIndexClient, AvalancheIndexRpcClient,
    AvalancheInfoClient, AvalanchePChainClient, AvalancheProposerVmClient, AvalancheXChainClient,
};
pub use base::{BASE_RPC_METHODS, BaseClient, BaseRpcClient};
pub use bitcoin::{BITCOIN_RPC_METHODS, BitcoinClient, BitcoinRpcClient};
pub use bridge::{
    BridgeClient, BridgeError, BridgeErrorCode, BridgeResult, MayanEvmUnsignedTransaction,
    MayanSolanaUnsignedTransaction, MayanSwiftV2Allowance, MayanSwiftV2BridgeClient,
    MayanSwiftV2BridgeConfig, MayanSwiftV2Build, MayanSwiftV2BuildRequest, MayanSwiftV2BuildResult,
    MayanSwiftV2BuildUnsignedRequest, MayanSwiftV2BuildValidation, MayanSwiftV2LocalBuildConfig,
    MayanSwiftV2Quote, MayanSwiftV2QuoteRequest, MayanSwiftV2QuoteResult, MayanSwiftV2SourceSwap,
    MayanSwiftV2Status, MayanSwiftV2StatusRequest, MayanSwiftV2StatusResult,
    MayanSwiftV2UnsignedTransaction, create_mayan_swift_v2_bridge_client,
};
pub use bridge_local::{
    MayanSwiftV2LocalBuild, MayanSwiftV2LocalBuildRequest, MayanSwiftV2LocalBuildValidation,
    MayanSwiftV2LocalConstruction, MayanSwiftV2LocalContext, MayanSwiftV2LocalEvmRpcEvidence,
    MayanSwiftV2LocalSolanaRpcEvidence, MayanSwiftV2LocalSolanaRpcLookupTableEvidence,
    MayanSwiftV2LocalSourceRpcEvidence, MayanSwiftV2LocalSourceSwapInstruction,
    MayanSwiftV2LocalSourceSwapInstructionAccount, MayanSwiftV2LocalSourceSwapPlan,
    MayanSwiftV2SourceSwapPlan,
};
pub use bsc::{BSC_RPC_METHODS, BscClient, BscRpcClient};
pub use cloud::{
    CloudCatalogClient, CloudCredit, CloudCreditAlertLevel, CloudCreditClient, CloudOffering,
    CloudOfferingBilling, CloudOfferingCompute, CloudOfferingComputeTenancy, CloudOfferingSolana,
    CloudOfferingSolanaTransport, CloudResource, CloudResourceBillingStatus, CloudResourceKind,
    CloudResourceMode, CloudResourceStatus, CloudResourceStatusBilling, CloudResourcesClient,
    ErpcCloudClient, ErpcCloudClientConfig,
};
pub use config::{
    DEFAULT_ACCOUNT_ENDPOINT, DEFAULT_ARBITRUM_ENDPOINT, DEFAULT_ARC_ENDPOINT,
    DEFAULT_AVALANCHE_ENDPOINT, DEFAULT_BASE_ENDPOINT, DEFAULT_BSC_ENDPOINT, DEFAULT_ENDPOINT,
    DEFAULT_HYPERLIQUID_ENDPOINT, DEFAULT_KAIA_ENDPOINT, DEFAULT_MONAD_ENDPOINT,
    DEFAULT_NEAR_ENDPOINT, DEFAULT_OPTIMISM_ENDPOINT, DEFAULT_POLYGON_ENDPOINT,
    DEFAULT_ROBINHOOD_ENDPOINT, DEFAULT_SONEIUM_ENDPOINT, DEFAULT_SUI_ENDPOINT, DEFAULT_TIMEOUT,
    DEFAULT_TRON_ENDPOINT, DEFAULT_USER_ENDPOINT, ErpcClientConfig, RpcEndpointConfig,
    SuiGrpcWebEndpointConfig,
};
pub use dex_catalog::{
    DEX_ALIASES, DEX_CATALOG_AS_OF_DATE, DEX_CATALOG_CONTENT_DIGEST, DEX_CATALOG_VERSION,
    DEX_CHAIN_IDS, DEX_DEPLOYMENTS, DexAlias, DexChainId, DexDeployment,
    ListPoolDefinitionsOptions, NATIVE_WRAP_DEFINITIONS, NativeWrapDefinition, POOL_DEFINITIONS,
    PoolAdapter, PoolDefinition, dexes, find_pool_definition_by_address,
    find_pool_definitions_by_pair, get_dex_deployment, get_native_wrap_definition,
    get_pool_definition, list_pool_definitions, pools,
};
pub use error::{ErpcError, ErpcErrorCode, JsonRpcErrorObject, Result};
pub use ethereum::{
    ETHEREUM_RPC_METHODS, ETHEREUM_SUBSCRIPTION_METHODS, EthereumClient, EthereumRpcClient,
    EthereumSubscriptions,
};
pub use hyperliquid::{HYPERLIQUID_RPC_METHODS, HyperliquidClient, HyperliquidRpcClient};
pub use kaia::{KAIA_RPC_METHODS, KaiaClient, KaiaRpcClient};
pub use monad::{MONAD_RPC_METHODS, MonadClient, MonadRpcClient};
pub use near::{
    NEAR_RPC_METHODS, NearAccountView, NearBlockHeader, NearBlockId, NearBlockReference,
    NearBlockView, NearClient, NearFinality, NearNodeVersion, NearRpcClient, NearStatus,
    NearSyncInfo,
};
pub use optimism::{OPTIMISM_RPC_METHODS, OptimismClient, OptimismRpcClient};
pub use polygon::{POLYGON_RPC_METHODS, PolygonClient, PolygonRpcClient};
pub use price::{
    BinaryUpdate, ParsedPriceMetadata, ParsedPriceUpdate, ParsedPublisherStakeCaps, PriceAssetType,
    PriceClient, PriceEncoding, PriceFeedMetadata, PricePoint, PriceStream, PriceStreamEvent,
    PriceStreamOptions, PriceUpdateOptions, PriceUpdateResponse, PublisherStakeCap,
    PublisherStakeCapsResponse,
};
pub use robinhood::{ROBINHOOD_RPC_METHODS, RobinhoodClient, RobinhoodRpcClient};
pub use rpc::{
    HttpJsonRpcTransport, HttpTransportConfig, JsonRpcId, PendingRpcBatchRequest,
    PendingRpcRequest, RequestOptions, RpcBatchCall, RpcNamespace,
};
pub use solana::{
    AddressTransaction, AddressTransactionPage, AddressTransactionsOptions, AddressTransfer,
    AddressTransferDirection, AddressTransferFilters, AddressTransferPage, AddressTransferType,
    AddressTransfersOptions, AnalyticsTimeBound, AssetBatchRequest, AssetListRequest, AssetRequest,
    EpochSummary, IndexedAsset, IndexedAssetList, IndexedAssetProof, LeaderSlot, LeaderSlotsResult,
    NumericFilter, PingMeasurement, PriorityFeeEstimate, ProgramStatsBucket, ProgramStatsOptions,
    SOLANA_ANALYTICS_METHODS, SOLANA_DAS_METHODS, SOLANA_ENHANCED_SUBSCRIPTION_METHODS,
    SOLANA_HISTORY_METHODS, SOLANA_LEADER_METHODS, SOLANA_RPC_METHODS, SlotStatsOptions,
    SlotStatsRow, SolanaAnalyticsClient, SolanaClient, SolanaCommitment, SolanaContext,
    SolanaContextResult, SolanaDasClient, SolanaEncoding, SolanaHistoryClient, SolanaLeaderClient,
    SolanaRpcClient, SolanaSubscriptions, TopProgramRow, TopProgramsOptions, TpsBucket,
    TpsTimeseriesOptions, ValidatorInformation, ValidatorsInformationOptions,
    ValidatorsInformationResult,
};
pub use soneium::{SONEIUM_RPC_METHODS, SoneiumClient, SoneiumRpcClient};
pub use subscriptions::{RpcNotification, RpcSubscription, SubscriptionId};
pub use sui::{
    PendingSuiGrpcWebRequest, SUI_GRPC_WEB_CONTENT_TYPE, SUI_GRPC_WEB_METHODS, SuiBalance,
    SuiClient, SuiGrpcWebClient, SuiObjectSummary, SuiServiceInfo,
};
pub use swap::{
    EvmBlockSnapshot, EvmUnsignedTransaction, ExactInputQuoteRequest, ExactInputQuoteResult,
    ExactInputSwapPathEntry, ExactInputSwapPreparation, ExactInputSwapRequest,
    ExactInputSwapSimulation, PrepareExactInputSwapRequest, PrepareExactInputSwapResult, QuoteFee,
    SimulateExactInputSwapResult, SwapAllowance, SwapClient, SwapExecutionError,
    SwapExecutionErrorCode, SwapExecutionResult, SwapFreshness, SwapPathEntry, SwapPreparation,
    SwapQuoteError, SwapQuoteErrorCode, SwapQuoteRequest, SwapResult, SwapSimulation,
};
pub use token_catalog::{
    TOKEN_ALIASES, TOKEN_ASSETS, TOKEN_CATALOG_AS_OF_DATE, TOKEN_CATALOG_CONTENT_DIGEST,
    TOKEN_CATALOG_VERSION, TOKEN_CHAIN_IDS, TOKEN_DEPLOYMENTS, TokenAlias, TokenAsset,
    TokenChainId, TokenDeployment, TokenRepresentationKind, TokenStandard, TokenStatus,
    find_token_deployment_by_address, find_token_deployments_by_symbol,
    get_native_token_deployment, get_token_asset, get_token_deployment, list_token_deployments,
    token_chain_ids, tokens,
};
pub use token_rankings::{
    TOKEN_RANKINGS, TOKEN_RANKINGS_AS_OF, TOKEN_RANKINGS_CONTENT_DIGEST, TOKEN_RANKINGS_COVERAGE,
    TOKEN_RANKINGS_METADATA, TOKEN_RANKINGS_METRIC, TOKEN_RANKINGS_SCHEMA_VERSION,
    TOKEN_RANKINGS_SOURCE_IDS, TOKEN_RANKINGS_STATUS, TokenRanking, TokenRankingCoverage,
    TokenRankingMetadata, list_token_rankings,
};
pub use tokio_util::sync::CancellationToken;
pub use tron::{TRON_RPC_METHODS, TronClient, TronRpcClient};
pub use usage::{
    MonthlyApiKeyChainUsage, MonthlyApiKeyMethodUsage, MonthlyApiKeyUsage, MonthlyApiKeyUsageEntry,
    MonthlyApiKeyUsageParams, UsageClient,
};

use std::sync::Arc;

use config::{ResolvedErpcClientConfig, ResolvedRpcEndpoint, endpoint_with_path, websocket_url};
use rest::RestTransport;
use subscriptions::WebSocketJsonRpcTransport;

fn legacy_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    endpoint: url::Url,
    client: &reqwest::Client,
    namespace: &str,
) -> Arc<HttpJsonRpcTransport> {
    if let Some(api_key) = &resolved.api_key {
        Arc::new(HttpJsonRpcTransport::new(HttpTransportConfig {
            api_key: api_key.clone(),
            endpoint,
            headers: resolved.headers.clone(),
            max_batch_size: 256,
            timeout: resolved.timeout,
            client: client.clone(),
        }))
    } else {
        Arc::new(HttpJsonRpcTransport::unavailable(
            namespace,
            resolved.timeout,
            client.clone(),
        ))
    }
}

fn direct_rpc_transport(
    endpoint: &ResolvedRpcEndpoint,
    client: &reqwest::Client,
    namespace: &str,
    timeout: std::time::Duration,
) -> Arc<HttpJsonRpcTransport> {
    Arc::new(HttpJsonRpcTransport::new_direct(
        endpoint.http_url.clone(),
        endpoint.headers.clone(),
        endpoint.redaction_secrets.clone(),
        256,
        timeout,
        client.clone(),
        namespace,
    ))
}

fn bitcoin_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Result<Arc<HttpJsonRpcTransport>> {
    if let Some(endpoint) = &resolved.bitcoin_rpc {
        return Ok(Arc::new(HttpJsonRpcTransport::new_direct_bitcoin(
            endpoint.http_url.clone(),
            endpoint.headers.clone(),
            endpoint.redaction_secrets.clone(),
            resolved.timeout,
            direct_client.clone(),
            "bitcoin.rpc",
        )));
    }
    if let Some(api_key) = &resolved.api_key {
        return Ok(Arc::new(HttpJsonRpcTransport::new_bitcoin(
            api_key.clone(),
            endpoint_with_path(&resolved.endpoint, "/bitcoin"),
            resolved.headers.clone(),
            resolved.timeout,
            direct_client.clone(),
        )?));
    }
    Ok(Arc::new(HttpJsonRpcTransport::unavailable(
        "bitcoin.rpc",
        resolved.timeout,
        client.clone(),
    )))
}

fn base_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Arc<HttpJsonRpcTransport> {
    if let Some(endpoint) = &resolved.base_rpc {
        return direct_rpc_transport(endpoint, direct_client, "base.rpc", resolved.timeout);
    }
    legacy_rpc_transport(resolved, resolved.base_endpoint.clone(), client, "base.rpc")
}

fn arbitrum_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Arc<HttpJsonRpcTransport> {
    if let Some(endpoint) = &resolved.arbitrum_rpc {
        return direct_rpc_transport(endpoint, direct_client, "arbitrum.rpc", resolved.timeout);
    }
    legacy_rpc_transport(
        resolved,
        resolved.arbitrum_endpoint.clone(),
        client,
        "arbitrum.rpc",
    )
}

fn polygon_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Arc<HttpJsonRpcTransport> {
    if let Some(endpoint) = &resolved.polygon_rpc {
        return direct_rpc_transport(endpoint, direct_client, "polygon.rpc", resolved.timeout);
    }
    legacy_rpc_transport(
        resolved,
        resolved.polygon_endpoint.clone(),
        client,
        "polygon.rpc",
    )
}

fn bsc_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Arc<HttpJsonRpcTransport> {
    if let Some(endpoint) = &resolved.bsc_rpc {
        return direct_rpc_transport(endpoint, direct_client, "bsc.rpc", resolved.timeout);
    }
    legacy_rpc_transport(resolved, resolved.bsc_endpoint.clone(), client, "bsc.rpc")
}

fn optimism_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Arc<HttpJsonRpcTransport> {
    if let Some(endpoint) = &resolved.optimism_rpc {
        return direct_rpc_transport(endpoint, direct_client, "optimism.rpc", resolved.timeout);
    }
    legacy_rpc_transport(
        resolved,
        resolved.optimism_endpoint.clone(),
        client,
        "optimism.rpc",
    )
}

fn kaia_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Arc<HttpJsonRpcTransport> {
    if let Some(endpoint) = &resolved.kaia_rpc {
        return direct_rpc_transport(endpoint, direct_client, "kaia.rpc", resolved.timeout);
    }
    legacy_rpc_transport(resolved, resolved.kaia_endpoint.clone(), client, "kaia.rpc")
}

fn soneium_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Arc<HttpJsonRpcTransport> {
    if let Some(endpoint) = &resolved.soneium_rpc {
        return direct_rpc_transport(endpoint, direct_client, "soneium.rpc", resolved.timeout);
    }
    legacy_rpc_transport(
        resolved,
        resolved.soneium_endpoint.clone(),
        client,
        "soneium.rpc",
    )
}

fn monad_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Arc<HttpJsonRpcTransport> {
    if let Some(endpoint) = &resolved.monad_rpc {
        return direct_rpc_transport(endpoint, direct_client, "monad.rpc", resolved.timeout);
    }
    legacy_rpc_transport(
        resolved,
        resolved.monad_endpoint.clone(),
        client,
        "monad.rpc",
    )
}

fn hyperliquid_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Arc<HttpJsonRpcTransport> {
    if let Some(endpoint) = &resolved.hyperliquid_rpc {
        return direct_rpc_transport(endpoint, direct_client, "hyperliquid.rpc", resolved.timeout);
    }
    legacy_rpc_transport(
        resolved,
        resolved.hyperliquid_endpoint.clone(),
        client,
        "hyperliquid.rpc",
    )
}

fn arc_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Arc<HttpJsonRpcTransport> {
    if let Some(endpoint) = &resolved.arc_rpc {
        return direct_rpc_transport(endpoint, direct_client, "arc.rpc", resolved.timeout);
    }
    legacy_rpc_transport(resolved, resolved.arc_endpoint.clone(), client, "arc.rpc")
}

fn robinhood_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Arc<HttpJsonRpcTransport> {
    if let Some(endpoint) = &resolved.robinhood_rpc {
        return direct_rpc_transport(endpoint, direct_client, "robinhood.rpc", resolved.timeout);
    }
    legacy_rpc_transport(
        resolved,
        resolved.robinhood_endpoint.clone(),
        client,
        "robinhood.rpc",
    )
}

fn near_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Arc<HttpJsonRpcTransport> {
    if let Some(endpoint) = &resolved.near_rpc {
        return direct_rpc_transport(endpoint, direct_client, "near.rpc", resolved.timeout);
    }
    legacy_rpc_transport(resolved, resolved.near_endpoint.clone(), client, "near.rpc")
}

fn tron_rpc_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Arc<HttpJsonRpcTransport> {
    if let Some(endpoint) = &resolved.tron_rpc {
        return direct_rpc_transport(endpoint, direct_client, "tron.rpc", resolved.timeout);
    }
    legacy_rpc_transport(resolved, resolved.tron_endpoint.clone(), client, "tron.rpc")
}

fn sui_grpc_web_transport(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
    direct_client: &reqwest::Client,
) -> Result<Arc<sui_grpc_web::SuiGrpcWebTransport>> {
    if let Some(endpoint) = &resolved.sui_grpc_web {
        return Ok(Arc::new(sui_grpc_web::SuiGrpcWebTransport::new_direct(
            endpoint.base_url.clone(),
            endpoint.headers.clone(),
            resolved.timeout,
            direct_client.clone(),
        )));
    }
    if let Some(api_key) = &resolved.api_key {
        return Ok(Arc::new(sui_grpc_web::SuiGrpcWebTransport::new_hosted(
            api_key.clone(),
            resolved.sui_endpoint.clone(),
            resolved.headers.clone(),
            resolved.timeout,
            direct_client.clone(),
        )?));
    }
    Ok(Arc::new(sui_grpc_web::SuiGrpcWebTransport::unavailable(
        resolved.timeout,
        client.clone(),
    )))
}

fn websocket_transport(
    resolved: &ResolvedErpcClientConfig,
    direct: Option<&ResolvedRpcEndpoint>,
    legacy_endpoint: &url::Url,
    legacy_path: &str,
    namespace: &str,
) -> Result<Arc<WebSocketJsonRpcTransport>> {
    if let Some(endpoint) = direct {
        return Ok(if let Some(websocket_url) = &endpoint.websocket_url {
            Arc::new(WebSocketJsonRpcTransport::new_direct(
                websocket_url.clone(),
                endpoint.redaction_secrets.clone(),
                resolved.timeout,
                namespace,
            ))
        } else {
            Arc::new(WebSocketJsonRpcTransport::unavailable(
                namespace,
                resolved.timeout,
            ))
        });
    }
    if let Some(api_key) = &resolved.api_key {
        return Ok(Arc::new(WebSocketJsonRpcTransport::new(
            websocket_url(legacy_endpoint, api_key, legacy_path)?,
            resolved.timeout,
        )));
    }
    Ok(Arc::new(WebSocketJsonRpcTransport::unavailable(
        namespace,
        resolved.timeout,
    )))
}

fn avalanche_index_transports(
    resolved: &ResolvedErpcClientConfig,
    client: &reqwest::Client,
) -> avalanche::AvalancheIndexTransports {
    let index_transport = |path| {
        legacy_rpc_transport(
            resolved,
            endpoint_with_path(&resolved.avalanche_endpoint, path),
            client,
            "avalanche.index",
        )
    };
    avalanche::AvalancheIndexTransports {
        c_chain_blocks: index_transport("/ava/ext/index/C/block"),
        p_chain_blocks: index_transport("/ava/ext/index/P/block"),
        x_chain_blocks: index_transport("/ava/ext/index/X/block"),
        x_chain_transactions: index_transport("/ava/ext/index/X/tx"),
    }
}

/// A configured ERPC client containing all public service clients.
#[derive(Clone)]
pub struct ErpcClient {
    /// Account and token balance API.
    pub account: AccountClient,
    /// Arbitrum One read-only HTTP JSON-RPC.
    pub arbitrum: ArbitrumClient,
    /// Avalanche C-Chain, native-chain, Index API, and subscriptions.
    pub avalanche: AvalancheClient,
    /// BNB Smart Chain mainnet read-only HTTP JSON-RPC.
    pub bsc: BscClient,
    /// Arc mainnet read-only HTTP JSON-RPC.
    pub arc: ArcClient,
    /// Base read-only HTTP JSON-RPC.
    pub base: BaseClient,
    /// Bitcoin Core HTTP JSON-RPC.
    pub bitcoin: BitcoinClient,
    /// Standard Ethereum JSON-RPC and subscriptions.
    pub ethereum: EthereumClient,
    /// Price feed REST and streaming API.
    pub price: PriceClient,
    /// Kaia mainnet read-only HTTP JSON-RPC.
    pub kaia: KaiaClient,
    /// Hyperliquid `HyperEVM` mainnet read-only HTTP JSON-RPC.
    pub hyperliquid: HyperliquidClient,
    /// Monad mainnet read-only HTTP JSON-RPC.
    pub monad: MonadClient,
    /// OP Mainnet read-only HTTP JSON-RPC.
    pub optimism: OptimismClient,
    /// Robinhood Chain Public Mainnet read-only HTTP JSON-RPC.
    pub robinhood: RobinhoodClient,
    /// Standard and extended Solana JSON-RPC and subscriptions.
    pub solana: SolanaClient,
    /// Polygon `PoS` mainnet read-only HTTP JSON-RPC.
    pub polygon: PolygonClient,
    /// Soneium mainnet read-only HTTP JSON-RPC.
    pub soneium: SoneiumClient,
    /// RPC-backed exact-input DEX quote client.
    pub swap: SwapClient,
    /// Monthly API key usage API.
    pub usage: UsageClient,
    /// NEAR mainnet read-only HTTP JSON-RPC.
    pub near: NearClient,
    /// TRON mainnet read-only HTTP JSON-RPC.
    pub tron: TronClient,
    /// Sui mainnet read-only binary gRPC-Web.
    pub sui: SuiClient,
}

impl ErpcClient {
    /// Creates a client after validating all configuration.
    #[allow(clippy::too_many_lines)]
    pub fn new(config: ErpcClientConfig) -> Result<Self> {
        let resolved = ResolvedErpcClientConfig::try_from(config)?;
        let http = ResolvedErpcClientConfig::http_client()?;
        let direct_http = ResolvedErpcClientConfig::direct_http_client()?;
        let base_transport = base_rpc_transport(&resolved, &http, &direct_http);
        let arbitrum_transport = arbitrum_rpc_transport(&resolved, &http, &direct_http);
        let polygon_transport = polygon_rpc_transport(&resolved, &http, &direct_http);
        let bsc_transport = bsc_rpc_transport(&resolved, &http, &direct_http);
        let optimism_transport = optimism_rpc_transport(&resolved, &http, &direct_http);
        let kaia_transport = kaia_rpc_transport(&resolved, &http, &direct_http);
        let soneium_transport = soneium_rpc_transport(&resolved, &http, &direct_http);
        let monad_transport = monad_rpc_transport(&resolved, &http, &direct_http);
        let hyperliquid_transport = hyperliquid_rpc_transport(&resolved, &http, &direct_http);
        let arc_transport = arc_rpc_transport(&resolved, &http, &direct_http);
        let robinhood_transport = robinhood_rpc_transport(&resolved, &http, &direct_http);
        let near_transport = near_rpc_transport(&resolved, &http, &direct_http);
        let tron_transport = tron_rpc_transport(&resolved, &http, &direct_http);
        let sui_transport = sui_grpc_web_transport(&resolved, &http, &direct_http)?;
        let bitcoin_transport = bitcoin_rpc_transport(&resolved, &http, &direct_http)?;
        let solana_transport = resolved.solana_rpc.as_ref().map_or_else(
            || legacy_rpc_transport(&resolved, resolved.endpoint.clone(), &http, "solana.rpc"),
            |endpoint| direct_rpc_transport(endpoint, &direct_http, "solana.rpc", resolved.timeout),
        );
        let ethereum_transport = resolved.ethereum_rpc.as_ref().map_or_else(
            || {
                legacy_rpc_transport(
                    &resolved,
                    endpoint_with_path(&resolved.endpoint, "/eth"),
                    &http,
                    "ethereum.rpc",
                )
            },
            |endpoint| {
                direct_rpc_transport(endpoint, &direct_http, "ethereum.rpc", resolved.timeout)
            },
        );
        let avalanche_c_transport = resolved.avalanche_c_rpc.as_ref().map_or_else(
            || {
                legacy_rpc_transport(
                    &resolved,
                    endpoint_with_path(&resolved.avalanche_endpoint, "/ava"),
                    &http,
                    "avalanche.rpc",
                )
            },
            |endpoint| {
                direct_rpc_transport(endpoint, &direct_http, "avalanche.rpc", resolved.timeout)
            },
        );
        let avalanche_native_transport = legacy_rpc_transport(
            &resolved,
            endpoint_with_path(&resolved.avalanche_endpoint, "/ava"),
            &http,
            "avalanche.native",
        );
        let avalanche_index = avalanche_index_transports(&resolved, &http);
        let solana_ws = websocket_transport(
            &resolved,
            resolved.solana_rpc.as_ref(),
            &resolved.endpoint,
            "",
            "solana.subscriptions",
        )?;
        let ethereum_ws = websocket_transport(
            &resolved,
            resolved.ethereum_rpc.as_ref(),
            &resolved.endpoint,
            "/eth",
            "ethereum.subscriptions",
        )?;
        let avalanche_ws = websocket_transport(
            &resolved,
            resolved.avalanche_c_rpc.as_ref(),
            &resolved.avalanche_endpoint,
            "/ava-ws",
            "avalanche.subscriptions",
        )?;
        let (shared_rest, account_rest, user_rest) = if let Some(api_key) = &resolved.api_key {
            (
                RestTransport::new(
                    api_key.clone(),
                    resolved.endpoint.clone(),
                    resolved.headers.clone(),
                    resolved.timeout,
                    http.clone(),
                ),
                RestTransport::new(
                    api_key.clone(),
                    resolved.account_endpoint.clone(),
                    resolved.headers.clone(),
                    resolved.timeout,
                    http.clone(),
                ),
                RestTransport::new(
                    api_key.clone(),
                    resolved.user_endpoint.clone(),
                    resolved.headers.clone(),
                    resolved.timeout,
                    http.clone(),
                ),
            )
        } else {
            (
                RestTransport::unavailable("price", resolved.timeout, http.clone()),
                RestTransport::unavailable("account", resolved.timeout, http.clone()),
                RestTransport::unavailable("usage", resolved.timeout, http.clone()),
            )
        };
        let swap = SwapClient::new(
            Arc::clone(&ethereum_transport),
            Arc::clone(&avalanche_c_transport),
        );

        Ok(Self {
            account: AccountClient::new(account_rest),
            arbitrum: ArbitrumClient::new(arbitrum_transport),
            avalanche: AvalancheClient::new(
                &avalanche_c_transport,
                avalanche_native_transport,
                avalanche_ws,
                avalanche_index,
            ),
            bsc: BscClient::new(bsc_transport),
            arc: ArcClient::new(arc_transport),
            base: BaseClient::new(base_transport),
            bitcoin: BitcoinClient::new(bitcoin_transport),
            ethereum: EthereumClient::new(ethereum_transport, ethereum_ws),
            price: PriceClient::new(shared_rest),
            kaia: KaiaClient::new(kaia_transport),
            hyperliquid: HyperliquidClient::new(hyperliquid_transport),
            monad: MonadClient::new(monad_transport),
            optimism: OptimismClient::new(optimism_transport),
            robinhood: RobinhoodClient::new(robinhood_transport),
            solana: SolanaClient::new(solana_transport, solana_ws),
            polygon: PolygonClient::new(polygon_transport),
            soneium: SoneiumClient::new(soneium_transport),
            swap,
            usage: UsageClient::new(user_rest),
            near: NearClient::new(near_transport),
            tron: TronClient::new(tron_transport),
            sui: SuiClient::new(sui_transport),
        })
    }

    /// Builds a test client with a private deterministic swap clock.
    #[cfg(test)]
    pub(crate) fn new_with_swap_clock(
        config: ErpcClientConfig,
        clock: fn() -> u64,
    ) -> Result<Self> {
        let mut client = Self::new(config)?;
        client.swap = client.swap.with_clock(clock);
        Ok(client)
    }

    /// Closes all subscription connections. HTTP clients need no explicit close.
    pub async fn close(&self) {
        self.solana.subscriptions.close().await;
        self.ethereum.subscriptions.close().await;
        self.avalanche.subscriptions.close().await;
    }
}