Skip to main content

erpc_sdk/
config.rs

1use std::{fmt, str::FromStr, time::Duration};
2
3use percent_encoding::percent_decode_str;
4use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
5use url::Url;
6
7use crate::{ErpcError, Result};
8
9/// Default JSON-RPC and price endpoint.
10pub const DEFAULT_ENDPOINT: &str = "https://edge.erpc.global";
11/// Default Avalanche JSON-RPC endpoint.
12pub const DEFAULT_AVALANCHE_ENDPOINT: &str = "https://ava-rpc.erpc.global";
13/// Default account endpoint.
14pub const DEFAULT_ACCOUNT_ENDPOINT: &str = "https://solana-rpc.erpc.global";
15/// Default user and Cloud endpoint.
16pub const DEFAULT_USER_ENDPOINT: &str = "https://user-api.erpc.global";
17/// Default Base JSON-RPC endpoint.
18pub const DEFAULT_BASE_ENDPOINT: &str = "https://base.erpc.global";
19/// Default Arbitrum One JSON-RPC endpoint.
20pub const DEFAULT_ARBITRUM_ENDPOINT: &str = "https://arbitrum.erpc.global";
21/// Default Polygon `PoS` mainnet JSON-RPC endpoint.
22pub const DEFAULT_POLYGON_ENDPOINT: &str = "https://polygon.erpc.global";
23/// Default BNB Smart Chain mainnet JSON-RPC endpoint.
24pub const DEFAULT_BSC_ENDPOINT: &str = "https://bsc.erpc.global";
25/// Default OP Mainnet JSON-RPC endpoint.
26pub const DEFAULT_OPTIMISM_ENDPOINT: &str = "https://optimism.erpc.global";
27/// Default Kaia mainnet JSON-RPC endpoint.
28pub const DEFAULT_KAIA_ENDPOINT: &str = "https://kaia.erpc.global";
29/// Default Soneium mainnet JSON-RPC endpoint.
30pub const DEFAULT_SONEIUM_ENDPOINT: &str = "https://soneium.erpc.global";
31/// Default Monad mainnet JSON-RPC endpoint.
32pub const DEFAULT_MONAD_ENDPOINT: &str = "https://monad.erpc.global";
33/// Default Hyperliquid `HyperEVM` mainnet JSON-RPC endpoint.
34pub const DEFAULT_HYPERLIQUID_ENDPOINT: &str = "https://hyperliquid.erpc.global";
35/// Default Arc mainnet JSON-RPC endpoint.
36pub const DEFAULT_ARC_ENDPOINT: &str = "https://arc.erpc.global";
37/// Default Robinhood Chain Public Mainnet JSON-RPC endpoint.
38pub const DEFAULT_ROBINHOOD_ENDPOINT: &str = "https://robinhood.erpc.global";
39/// Default NEAR mainnet JSON-RPC endpoint.
40pub const DEFAULT_NEAR_ENDPOINT: &str = "https://near.erpc.global";
41/// Default TRON mainnet JSON-RPC endpoint.
42pub const DEFAULT_TRON_ENDPOINT: &str = "https://tron.erpc.global";
43/// Default Sui mainnet binary gRPC-Web endpoint.
44pub const DEFAULT_SUI_ENDPOINT: &str = "https://sui.erpc.global";
45/// Default request and connection-establishment timeout.
46pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
47
48/// Configuration for one caller-owned JSON-RPC endpoint.
49///
50/// The HTTP URL is the complete request target. Its path and query are
51/// preserved exactly and no eRPC route or API-key query parameter is added.
52/// A WebSocket URL, when supplied, is independent from the HTTP URL.
53#[derive(Clone)]
54pub struct RpcEndpointConfig {
55    /// Complete HTTP(S) JSON-RPC request target.
56    pub http_url: String,
57    /// Optional complete WS(S) subscription target.
58    pub websocket_url: Option<String>,
59    /// Headers scoped to this endpoint's HTTP JSON-RPC requests only.
60    pub headers: Vec<(String, String)>,
61}
62
63impl fmt::Debug for RpcEndpointConfig {
64    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65        formatter
66            .debug_struct("RpcEndpointConfig")
67            .field("http_url", &debug_endpoint(&self.http_url))
68            .field(
69                "websocket_url",
70                &self.websocket_url.as_deref().map(debug_endpoint),
71            )
72            .field(
73                "header_names",
74                &self
75                    .headers
76                    .iter()
77                    .map(|(name, _)| name)
78                    .collect::<Vec<_>>(),
79            )
80            .finish()
81    }
82}
83
84impl RpcEndpointConfig {
85    /// Starts an endpoint configuration with a complete HTTP(S) URL.
86    #[must_use]
87    pub fn new(http_url: impl Into<String>) -> Self {
88        Self {
89            http_url: http_url.into(),
90            websocket_url: None,
91            headers: Vec::new(),
92        }
93    }
94
95    /// Replaces the complete HTTP(S) request target.
96    #[must_use]
97    pub fn with_http_url(mut self, http_url: impl Into<String>) -> Self {
98        self.http_url = http_url.into();
99        self
100    }
101
102    /// Sets the independent complete WS(S) subscription target.
103    #[must_use]
104    pub fn with_websocket_url(mut self, websocket_url: impl Into<String>) -> Self {
105        self.websocket_url = Some(websocket_url.into());
106        self
107    }
108
109    /// Sets the independent complete WS(S) subscription target.
110    #[must_use]
111    pub fn with_websocket(self, websocket_url: impl Into<String>) -> Self {
112        self.with_websocket_url(websocket_url)
113    }
114
115    /// Adds an HTTP header scoped to this endpoint.
116    #[must_use]
117    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
118        self.headers.push((name.into(), value.into()));
119        self
120    }
121
122    /// Replaces the endpoint-scoped headers.
123    #[must_use]
124    pub fn with_headers<I, N, V>(mut self, headers: I) -> Self
125    where
126        I: IntoIterator<Item = (N, V)>,
127        N: Into<String>,
128        V: Into<String>,
129    {
130        self.headers = headers
131            .into_iter()
132            .map(|(name, value)| (name.into(), value.into()))
133            .collect();
134        self
135    }
136}
137
138impl From<&str> for RpcEndpointConfig {
139    fn from(http_url: &str) -> Self {
140        Self::new(http_url)
141    }
142}
143
144impl From<String> for RpcEndpointConfig {
145    fn from(http_url: String) -> Self {
146        Self::new(http_url)
147    }
148}
149
150impl Default for RpcEndpointConfig {
151    fn default() -> Self {
152        Self::new("")
153    }
154}
155
156/// Configuration for one caller-owned binary Sui gRPC-Web endpoint.
157///
158/// The URL is a base prefix. Each supported Sui method is appended to it at
159/// request time while preserving its encoded path and query string.
160#[derive(Clone)]
161pub struct SuiGrpcWebEndpointConfig {
162    /// Base HTTP(S) URL for the caller-owned binary gRPC-Web service.
163    pub base_url: String,
164    /// Headers scoped to this Sui endpoint only.
165    pub headers: Vec<(String, String)>,
166}
167
168impl fmt::Debug for SuiGrpcWebEndpointConfig {
169    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
170        formatter
171            .debug_struct("SuiGrpcWebEndpointConfig")
172            .field("origin", &debug_origin(&self.base_url))
173            .field(
174                "header_names",
175                &self
176                    .headers
177                    .iter()
178                    .map(|(name, _)| name)
179                    .collect::<Vec<_>>(),
180            )
181            .finish()
182    }
183}
184
185impl SuiGrpcWebEndpointConfig {
186    /// Starts a Sui configuration with a base HTTP(S) URL.
187    #[must_use]
188    pub fn new(base_url: impl Into<String>) -> Self {
189        Self {
190            base_url: base_url.into(),
191            headers: Vec::new(),
192        }
193    }
194
195    /// Replaces the base HTTP(S) URL.
196    #[must_use]
197    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
198        self.base_url = base_url.into();
199        self
200    }
201
202    /// Adds a header scoped to this Sui endpoint.
203    #[must_use]
204    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
205        self.headers.push((name.into(), value.into()));
206        self
207    }
208
209    /// Replaces the endpoint-scoped headers.
210    #[must_use]
211    pub fn with_headers<I, N, V>(mut self, headers: I) -> Self
212    where
213        I: IntoIterator<Item = (N, V)>,
214        N: Into<String>,
215        V: Into<String>,
216    {
217        self.headers = headers
218            .into_iter()
219            .map(|(name, value)| (name.into(), value.into()))
220            .collect();
221        self
222    }
223}
224
225impl From<&str> for SuiGrpcWebEndpointConfig {
226    fn from(base_url: &str) -> Self {
227        Self::new(base_url)
228    }
229}
230
231impl From<String> for SuiGrpcWebEndpointConfig {
232    fn from(base_url: String) -> Self {
233        Self::new(base_url)
234    }
235}
236
237/// Configuration used to create an [`crate::ErpcClient`].
238#[derive(Clone)]
239pub struct ErpcClientConfig {
240    /// ERPC API key. It is held in memory and omitted from debug output.
241    api_key: String,
242    /// Optional JSON-RPC and price endpoint override.
243    pub endpoint: String,
244    /// Optional Avalanche endpoint override.
245    pub avalanche_endpoint: String,
246    /// Optional account endpoint override.
247    pub account_endpoint: String,
248    /// Optional user endpoint override.
249    pub user_endpoint: String,
250    /// Extra request headers.
251    pub headers: Vec<(String, String)>,
252    /// Request timeout.
253    pub timeout: Duration,
254    /// Optional caller-owned Solana JSON-RPC endpoint.
255    pub solana_rpc: Option<RpcEndpointConfig>,
256    /// Optional caller-owned Ethereum JSON-RPC endpoint.
257    pub ethereum_rpc: Option<RpcEndpointConfig>,
258    /// Optional caller-owned Avalanche C-Chain JSON-RPC endpoint.
259    pub avalanche_c_rpc: Option<RpcEndpointConfig>,
260    /// Optional caller-owned Bitcoin JSON-RPC endpoint.
261    pub bitcoin_rpc: Option<RpcEndpointConfig>,
262    /// Hosted Base JSON-RPC endpoint override.
263    pub base_endpoint: String,
264    /// Optional caller-owned Base JSON-RPC endpoint.
265    pub base_rpc: Option<RpcEndpointConfig>,
266    /// Hosted Arbitrum One JSON-RPC endpoint override.
267    pub arbitrum_endpoint: String,
268    /// Optional caller-owned Arbitrum One JSON-RPC endpoint.
269    pub arbitrum_rpc: Option<RpcEndpointConfig>,
270    /// Hosted Polygon `PoS` mainnet JSON-RPC endpoint override.
271    pub polygon_endpoint: String,
272    /// Optional caller-owned Polygon `PoS` mainnet JSON-RPC endpoint.
273    pub polygon_rpc: Option<RpcEndpointConfig>,
274    /// Hosted BNB Smart Chain mainnet JSON-RPC endpoint override.
275    pub bsc_endpoint: String,
276    /// Optional caller-owned BNB Smart Chain mainnet JSON-RPC endpoint.
277    pub bsc_rpc: Option<RpcEndpointConfig>,
278    /// Hosted OP Mainnet JSON-RPC endpoint override.
279    pub optimism_endpoint: String,
280    /// Optional caller-owned OP Mainnet JSON-RPC endpoint.
281    pub optimism_rpc: Option<RpcEndpointConfig>,
282    /// Hosted Kaia mainnet JSON-RPC endpoint override.
283    pub kaia_endpoint: String,
284    /// Optional caller-owned Kaia mainnet JSON-RPC endpoint.
285    pub kaia_rpc: Option<RpcEndpointConfig>,
286    /// Hosted Soneium mainnet JSON-RPC endpoint override.
287    pub soneium_endpoint: String,
288    /// Optional caller-owned Soneium mainnet JSON-RPC endpoint.
289    pub soneium_rpc: Option<RpcEndpointConfig>,
290    /// Hosted Monad mainnet JSON-RPC endpoint override.
291    pub monad_endpoint: String,
292    /// Optional caller-owned Monad mainnet JSON-RPC endpoint.
293    pub monad_rpc: Option<RpcEndpointConfig>,
294    /// Hosted Hyperliquid `HyperEVM` mainnet JSON-RPC endpoint override.
295    pub hyperliquid_endpoint: String,
296    /// Optional caller-owned Hyperliquid `HyperEVM` mainnet JSON-RPC endpoint.
297    pub hyperliquid_rpc: Option<RpcEndpointConfig>,
298    /// Hosted Arc mainnet JSON-RPC endpoint override.
299    pub arc_endpoint: String,
300    /// Optional caller-owned Arc mainnet JSON-RPC endpoint.
301    pub arc_rpc: Option<RpcEndpointConfig>,
302    /// Hosted Robinhood Chain Public Mainnet JSON-RPC endpoint override.
303    pub robinhood_endpoint: String,
304    /// Optional caller-owned Robinhood Chain Public Mainnet JSON-RPC endpoint.
305    pub robinhood_rpc: Option<RpcEndpointConfig>,
306    /// Hosted NEAR mainnet endpoint override.
307    pub near_endpoint: String,
308    /// Optional caller-owned NEAR JSON-RPC endpoint.
309    pub near_rpc: Option<RpcEndpointConfig>,
310    /// Hosted TRON mainnet endpoint override.
311    pub tron_endpoint: String,
312    /// Optional caller-owned TRON JSON-RPC endpoint.
313    pub tron_rpc: Option<RpcEndpointConfig>,
314    /// Hosted Sui binary gRPC-Web endpoint override.
315    pub sui_endpoint: String,
316    /// Optional caller-owned Sui binary gRPC-Web endpoint.
317    pub sui_grpc_web: Option<SuiGrpcWebEndpointConfig>,
318}
319
320impl fmt::Debug for ErpcClientConfig {
321    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
322        formatter
323            .debug_struct("ErpcClientConfig")
324            .field("api_key", &"[REDACTED]")
325            .field("endpoint", &debug_endpoint(&self.endpoint))
326            .field(
327                "avalanche_endpoint",
328                &debug_endpoint(&self.avalanche_endpoint),
329            )
330            .field("account_endpoint", &debug_endpoint(&self.account_endpoint))
331            .field("user_endpoint", &debug_endpoint(&self.user_endpoint))
332            .field("solana_rpc", &self.solana_rpc)
333            .field("ethereum_rpc", &self.ethereum_rpc)
334            .field("avalanche_c_rpc", &self.avalanche_c_rpc)
335            .field("bitcoin_rpc", &self.bitcoin_rpc)
336            .field("base_endpoint", &debug_origin(&self.base_endpoint))
337            .field("base_rpc", &self.base_rpc.as_ref().map(BaseRpcDebug))
338            .field("arbitrum_endpoint", &debug_origin(&self.arbitrum_endpoint))
339            .field(
340                "arbitrum_rpc",
341                &self.arbitrum_rpc.as_ref().map(ArbitrumRpcDebug),
342            )
343            .field("polygon_endpoint", &debug_origin(&self.polygon_endpoint))
344            .field(
345                "polygon_rpc",
346                &self.polygon_rpc.as_ref().map(PolygonRpcDebug),
347            )
348            .field("bsc_endpoint", &debug_origin(&self.bsc_endpoint))
349            .field("bsc_rpc", &self.bsc_rpc.as_ref().map(BscRpcDebug))
350            .field("optimism_endpoint", &debug_origin(&self.optimism_endpoint))
351            .field(
352                "optimism_rpc",
353                &self.optimism_rpc.as_ref().map(OptimismRpcDebug),
354            )
355            .field("kaia_endpoint", &debug_origin(&self.kaia_endpoint))
356            .field("kaia_rpc", &self.kaia_rpc.as_ref().map(KaiaRpcDebug))
357            .field("soneium_endpoint", &debug_origin(&self.soneium_endpoint))
358            .field(
359                "soneium_rpc",
360                &self.soneium_rpc.as_ref().map(SoneiumRpcDebug),
361            )
362            .field("monad_endpoint", &debug_origin(&self.monad_endpoint))
363            .field("monad_rpc", &self.monad_rpc.as_ref().map(MonadRpcDebug))
364            .field(
365                "hyperliquid_endpoint",
366                &debug_origin(&self.hyperliquid_endpoint),
367            )
368            .field(
369                "hyperliquid_rpc",
370                &self.hyperliquid_rpc.as_ref().map(HyperliquidRpcDebug),
371            )
372            .field("arc_endpoint", &debug_origin(&self.arc_endpoint))
373            .field("arc_rpc", &self.arc_rpc.as_ref().map(ArcRpcDebug))
374            .field(
375                "robinhood_endpoint",
376                &debug_origin(&self.robinhood_endpoint),
377            )
378            .field(
379                "robinhood_rpc",
380                &self.robinhood_rpc.as_ref().map(RobinhoodRpcDebug),
381            )
382            .field("near_endpoint", &debug_origin(&self.near_endpoint))
383            .field("near_rpc", &self.near_rpc.as_ref().map(NearRpcDebug))
384            .field("tron_endpoint", &debug_origin(&self.tron_endpoint))
385            .field("tron_rpc", &self.tron_rpc.as_ref().map(TronRpcDebug))
386            .field("sui_endpoint", &debug_origin(&self.sui_endpoint))
387            .field("sui_grpc_web", &self.sui_grpc_web)
388            .field(
389                "header_names",
390                &self
391                    .headers
392                    .iter()
393                    .map(|(name, _)| name)
394                    .collect::<Vec<_>>(),
395            )
396            .field("timeout", &self.timeout)
397            .finish()
398    }
399}
400
401impl ErpcClientConfig {
402    /// Starts a configuration with production endpoints and a 30-second timeout.
403    #[must_use]
404    pub fn new(api_key: impl Into<String>) -> Self {
405        Self {
406            api_key: api_key.into(),
407            endpoint: DEFAULT_ENDPOINT.to_owned(),
408            avalanche_endpoint: DEFAULT_AVALANCHE_ENDPOINT.to_owned(),
409            account_endpoint: DEFAULT_ACCOUNT_ENDPOINT.to_owned(),
410            user_endpoint: DEFAULT_USER_ENDPOINT.to_owned(),
411            headers: Vec::new(),
412            timeout: DEFAULT_TIMEOUT,
413            solana_rpc: None,
414            ethereum_rpc: None,
415            avalanche_c_rpc: None,
416            bitcoin_rpc: None,
417            base_endpoint: DEFAULT_BASE_ENDPOINT.to_owned(),
418            base_rpc: None,
419            arbitrum_endpoint: DEFAULT_ARBITRUM_ENDPOINT.to_owned(),
420            arbitrum_rpc: None,
421            polygon_endpoint: DEFAULT_POLYGON_ENDPOINT.to_owned(),
422            polygon_rpc: None,
423            bsc_endpoint: DEFAULT_BSC_ENDPOINT.to_owned(),
424            bsc_rpc: None,
425            optimism_endpoint: DEFAULT_OPTIMISM_ENDPOINT.to_owned(),
426            optimism_rpc: None,
427            kaia_endpoint: DEFAULT_KAIA_ENDPOINT.to_owned(),
428            kaia_rpc: None,
429            soneium_endpoint: DEFAULT_SONEIUM_ENDPOINT.to_owned(),
430            soneium_rpc: None,
431            monad_endpoint: DEFAULT_MONAD_ENDPOINT.to_owned(),
432            monad_rpc: None,
433            hyperliquid_endpoint: DEFAULT_HYPERLIQUID_ENDPOINT.to_owned(),
434            hyperliquid_rpc: None,
435            arc_endpoint: DEFAULT_ARC_ENDPOINT.to_owned(),
436            arc_rpc: None,
437            robinhood_endpoint: DEFAULT_ROBINHOOD_ENDPOINT.to_owned(),
438            robinhood_rpc: None,
439            near_endpoint: DEFAULT_NEAR_ENDPOINT.to_owned(),
440            near_rpc: None,
441            tron_endpoint: DEFAULT_TRON_ENDPOINT.to_owned(),
442            tron_rpc: None,
443            sui_endpoint: DEFAULT_SUI_ENDPOINT.to_owned(),
444            sui_grpc_web: None,
445        }
446    }
447
448    /// Starts a keyless configuration for one or more direct RPC endpoints.
449    ///
450    /// Construction succeeds before an override is attached so callers can
451    /// build a configuration fluently. [`crate::ErpcClient::new`] rejects it
452    /// when no valid direct endpoint is configured.
453    #[must_use]
454    pub fn for_rpc() -> Self {
455        Self::new(String::new())
456    }
457
458    /// Returns the API key without placing it in debug output.
459    #[must_use]
460    pub fn api_key(&self) -> &str {
461        &self.api_key
462    }
463
464    /// Overrides the JSON-RPC and price endpoint.
465    #[must_use]
466    pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
467        self.endpoint = endpoint.into();
468        self
469    }
470
471    /// Overrides the Avalanche endpoint.
472    #[must_use]
473    pub fn with_avalanche_endpoint(mut self, endpoint: impl Into<String>) -> Self {
474        self.avalanche_endpoint = endpoint.into();
475        self
476    }
477
478    /// Overrides the account endpoint.
479    #[must_use]
480    pub fn with_account_endpoint(mut self, endpoint: impl Into<String>) -> Self {
481        self.account_endpoint = endpoint.into();
482        self
483    }
484
485    /// Overrides the user endpoint.
486    #[must_use]
487    pub fn with_user_endpoint(mut self, endpoint: impl Into<String>) -> Self {
488        self.user_endpoint = endpoint.into();
489        self
490    }
491
492    /// Adds an HTTP header after construction-time validation.
493    #[must_use]
494    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
495        self.headers.push((name.into(), value.into()));
496        self
497    }
498
499    /// Overrides the request timeout.
500    #[must_use]
501    pub const fn with_timeout(mut self, timeout: Duration) -> Self {
502        self.timeout = timeout;
503        self
504    }
505
506    /// Selects a caller-owned Solana JSON-RPC endpoint.
507    #[must_use]
508    pub fn with_solana_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
509        self.solana_rpc = Some(endpoint.into());
510        self
511    }
512
513    /// Selects a caller-owned Ethereum JSON-RPC endpoint.
514    #[must_use]
515    pub fn with_ethereum_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
516        self.ethereum_rpc = Some(endpoint.into());
517        self
518    }
519
520    /// Selects a caller-owned Avalanche C-Chain JSON-RPC endpoint.
521    #[must_use]
522    pub fn with_avalanche_c_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
523        self.avalanche_c_rpc = Some(endpoint.into());
524        self
525    }
526
527    /// Selects a caller-owned Avalanche C-Chain JSON-RPC endpoint.
528    #[must_use]
529    pub fn with_avalanche_rpc(self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
530        self.with_avalanche_c_rpc(endpoint)
531    }
532
533    /// Selects a caller-owned Bitcoin JSON-RPC endpoint.
534    #[must_use]
535    pub fn with_bitcoin_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
536        self.bitcoin_rpc = Some(endpoint.into());
537        self
538    }
539
540    /// Overrides the hosted Base JSON-RPC endpoint.
541    #[must_use]
542    pub fn with_base_endpoint(mut self, endpoint: impl Into<String>) -> Self {
543        self.base_endpoint = endpoint.into();
544        self
545    }
546
547    /// Selects a caller-owned Base JSON-RPC endpoint.
548    #[must_use]
549    pub fn with_base_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
550        self.base_rpc = Some(endpoint.into());
551        self
552    }
553
554    /// Overrides the hosted Arbitrum One JSON-RPC endpoint.
555    #[must_use]
556    pub fn with_arbitrum_endpoint(mut self, endpoint: impl Into<String>) -> Self {
557        self.arbitrum_endpoint = endpoint.into();
558        self
559    }
560
561    /// Selects a caller-owned Arbitrum One JSON-RPC endpoint.
562    #[must_use]
563    pub fn with_arbitrum_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
564        self.arbitrum_rpc = Some(endpoint.into());
565        self
566    }
567
568    /// Overrides the hosted Polygon `PoS` mainnet JSON-RPC endpoint.
569    #[must_use]
570    pub fn with_polygon_endpoint(mut self, endpoint: impl Into<String>) -> Self {
571        self.polygon_endpoint = endpoint.into();
572        self
573    }
574
575    /// Selects a caller-owned Polygon `PoS` mainnet JSON-RPC endpoint.
576    #[must_use]
577    pub fn with_polygon_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
578        self.polygon_rpc = Some(endpoint.into());
579        self
580    }
581
582    /// Overrides the hosted BNB Smart Chain mainnet JSON-RPC endpoint.
583    #[must_use]
584    pub fn with_bsc_endpoint(mut self, endpoint: impl Into<String>) -> Self {
585        self.bsc_endpoint = endpoint.into();
586        self
587    }
588
589    /// Selects a caller-owned BNB Smart Chain mainnet JSON-RPC endpoint.
590    #[must_use]
591    pub fn with_bsc_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
592        self.bsc_rpc = Some(endpoint.into());
593        self
594    }
595
596    /// Overrides the hosted OP Mainnet JSON-RPC endpoint.
597    #[must_use]
598    pub fn with_optimism_endpoint(mut self, endpoint: impl Into<String>) -> Self {
599        self.optimism_endpoint = endpoint.into();
600        self
601    }
602
603    /// Selects a caller-owned OP Mainnet JSON-RPC endpoint.
604    #[must_use]
605    pub fn with_optimism_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
606        self.optimism_rpc = Some(endpoint.into());
607        self
608    }
609
610    /// Overrides the hosted Kaia mainnet JSON-RPC endpoint.
611    #[must_use]
612    pub fn with_kaia_endpoint(mut self, endpoint: impl Into<String>) -> Self {
613        self.kaia_endpoint = endpoint.into();
614        self
615    }
616
617    /// Selects a caller-owned Kaia mainnet JSON-RPC endpoint.
618    #[must_use]
619    pub fn with_kaia_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
620        self.kaia_rpc = Some(endpoint.into());
621        self
622    }
623
624    /// Overrides the hosted Soneium mainnet JSON-RPC endpoint.
625    #[must_use]
626    pub fn with_soneium_endpoint(mut self, endpoint: impl Into<String>) -> Self {
627        self.soneium_endpoint = endpoint.into();
628        self
629    }
630
631    /// Selects a caller-owned Soneium mainnet JSON-RPC endpoint.
632    #[must_use]
633    pub fn with_soneium_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
634        self.soneium_rpc = Some(endpoint.into());
635        self
636    }
637
638    /// Overrides the hosted Monad mainnet JSON-RPC endpoint.
639    #[must_use]
640    pub fn with_monad_endpoint(mut self, endpoint: impl Into<String>) -> Self {
641        self.monad_endpoint = endpoint.into();
642        self
643    }
644
645    /// Selects a caller-owned Monad mainnet JSON-RPC endpoint.
646    #[must_use]
647    pub fn with_monad_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
648        self.monad_rpc = Some(endpoint.into());
649        self
650    }
651
652    /// Overrides the hosted Hyperliquid `HyperEVM` mainnet JSON-RPC endpoint.
653    #[must_use]
654    pub fn with_hyperliquid_endpoint(mut self, endpoint: impl Into<String>) -> Self {
655        self.hyperliquid_endpoint = endpoint.into();
656        self
657    }
658
659    /// Selects a caller-owned Hyperliquid `HyperEVM` mainnet JSON-RPC endpoint.
660    #[must_use]
661    pub fn with_hyperliquid_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
662        self.hyperliquid_rpc = Some(endpoint.into());
663        self
664    }
665
666    /// Overrides the hosted Arc mainnet JSON-RPC endpoint.
667    #[must_use]
668    pub fn with_arc_endpoint(mut self, endpoint: impl Into<String>) -> Self {
669        self.arc_endpoint = endpoint.into();
670        self
671    }
672
673    /// Selects a caller-owned Arc mainnet JSON-RPC endpoint.
674    #[must_use]
675    pub fn with_arc_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
676        self.arc_rpc = Some(endpoint.into());
677        self
678    }
679
680    /// Overrides the hosted Robinhood Chain Public Mainnet JSON-RPC endpoint.
681    #[must_use]
682    pub fn with_robinhood_endpoint(mut self, endpoint: impl Into<String>) -> Self {
683        self.robinhood_endpoint = endpoint.into();
684        self
685    }
686
687    /// Selects a caller-owned Robinhood Chain Public Mainnet JSON-RPC endpoint.
688    #[must_use]
689    pub fn with_robinhood_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
690        self.robinhood_rpc = Some(endpoint.into());
691        self
692    }
693
694    /// Overrides the hosted NEAR endpoint.
695    #[must_use]
696    pub fn with_near_endpoint(mut self, endpoint: impl Into<String>) -> Self {
697        self.near_endpoint = endpoint.into();
698        self
699    }
700
701    /// Selects a caller-owned NEAR JSON-RPC endpoint.
702    #[must_use]
703    pub fn with_near_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
704        self.near_rpc = Some(endpoint.into());
705        self
706    }
707
708    /// Overrides the hosted TRON endpoint.
709    #[must_use]
710    pub fn with_tron_endpoint(mut self, endpoint: impl Into<String>) -> Self {
711        self.tron_endpoint = endpoint.into();
712        self
713    }
714
715    /// Selects a caller-owned TRON JSON-RPC endpoint.
716    #[must_use]
717    pub fn with_tron_rpc(mut self, endpoint: impl Into<RpcEndpointConfig>) -> Self {
718        self.tron_rpc = Some(endpoint.into());
719        self
720    }
721
722    /// Overrides the hosted Sui binary gRPC-Web endpoint.
723    #[must_use]
724    pub fn with_sui_endpoint(mut self, endpoint: impl Into<String>) -> Self {
725        self.sui_endpoint = endpoint.into();
726        self
727    }
728
729    /// Selects a caller-owned Sui binary gRPC-Web endpoint.
730    #[must_use]
731    pub fn with_sui_grpc_web(mut self, endpoint: impl Into<SuiGrpcWebEndpointConfig>) -> Self {
732        self.sui_grpc_web = Some(endpoint.into());
733        self
734    }
735}
736
737pub(crate) struct ResolvedRpcEndpoint {
738    pub http_url: Url,
739    pub websocket_url: Option<Url>,
740    pub headers: HeaderMap,
741    pub redaction_secrets: Vec<String>,
742}
743
744pub(crate) struct ResolvedErpcClientConfig {
745    pub api_key: Option<String>,
746    pub endpoint: Url,
747    pub avalanche_endpoint: Url,
748    pub account_endpoint: Url,
749    pub user_endpoint: Url,
750    pub headers: HeaderMap,
751    pub timeout: Duration,
752    pub solana_rpc: Option<ResolvedRpcEndpoint>,
753    pub ethereum_rpc: Option<ResolvedRpcEndpoint>,
754    pub avalanche_c_rpc: Option<ResolvedRpcEndpoint>,
755    pub bitcoin_rpc: Option<ResolvedRpcEndpoint>,
756    pub base_endpoint: Url,
757    pub base_rpc: Option<ResolvedRpcEndpoint>,
758    pub arbitrum_endpoint: Url,
759    pub arbitrum_rpc: Option<ResolvedRpcEndpoint>,
760    pub polygon_endpoint: Url,
761    pub polygon_rpc: Option<ResolvedRpcEndpoint>,
762    pub bsc_endpoint: Url,
763    pub bsc_rpc: Option<ResolvedRpcEndpoint>,
764    pub optimism_endpoint: Url,
765    pub optimism_rpc: Option<ResolvedRpcEndpoint>,
766    pub kaia_endpoint: Url,
767    pub kaia_rpc: Option<ResolvedRpcEndpoint>,
768    pub soneium_endpoint: Url,
769    pub soneium_rpc: Option<ResolvedRpcEndpoint>,
770    pub monad_endpoint: Url,
771    pub monad_rpc: Option<ResolvedRpcEndpoint>,
772    pub hyperliquid_endpoint: Url,
773    pub hyperliquid_rpc: Option<ResolvedRpcEndpoint>,
774    pub arc_endpoint: Url,
775    pub arc_rpc: Option<ResolvedRpcEndpoint>,
776    pub robinhood_endpoint: Url,
777    pub robinhood_rpc: Option<ResolvedRpcEndpoint>,
778    pub near_endpoint: Url,
779    pub near_rpc: Option<ResolvedRpcEndpoint>,
780    pub tron_endpoint: Url,
781    pub tron_rpc: Option<ResolvedRpcEndpoint>,
782    pub sui_endpoint: Url,
783    pub sui_grpc_web: Option<ResolvedSuiGrpcWebEndpoint>,
784}
785
786pub(crate) struct ResolvedSuiGrpcWebEndpoint {
787    pub base_url: Url,
788    pub headers: HeaderMap,
789}
790
791impl TryFrom<ErpcClientConfig> for ResolvedErpcClientConfig {
792    type Error = ErpcError;
793
794    #[allow(clippy::too_many_lines)]
795    fn try_from(config: ErpcClientConfig) -> Result<Self> {
796        let api_key = config.api_key.trim().to_owned();
797        if api_key.is_empty()
798            && config.solana_rpc.is_none()
799            && config.ethereum_rpc.is_none()
800            && config.avalanche_c_rpc.is_none()
801            && config.bitcoin_rpc.is_none()
802            && config.base_rpc.is_none()
803            && config.arbitrum_rpc.is_none()
804            && config.polygon_rpc.is_none()
805            && config.bsc_rpc.is_none()
806            && config.optimism_rpc.is_none()
807            && config.kaia_rpc.is_none()
808            && config.soneium_rpc.is_none()
809            && config.monad_rpc.is_none()
810            && config.hyperliquid_rpc.is_none()
811            && config.arc_rpc.is_none()
812            && config.robinhood_rpc.is_none()
813            && config.near_rpc.is_none()
814            && config.tron_rpc.is_none()
815            && config.sui_grpc_web.is_none()
816        {
817            return Err(ErpcError::Config("api_key must not be empty".to_owned()));
818        }
819        if config.timeout.is_zero() {
820            return Err(ErpcError::Config("timeout must be positive".to_owned()));
821        }
822        let headers = parse_headers(&config.headers)?;
823        let solana_rpc = config
824            .solana_rpc
825            .as_ref()
826            .map(resolve_rpc_endpoint)
827            .transpose()?;
828        let ethereum_rpc = config
829            .ethereum_rpc
830            .as_ref()
831            .map(resolve_rpc_endpoint)
832            .transpose()?;
833        let avalanche_rpc = config
834            .avalanche_c_rpc
835            .as_ref()
836            .map(resolve_rpc_endpoint)
837            .transpose()?;
838        let bitcoin_rpc = config
839            .bitcoin_rpc
840            .as_ref()
841            .map(resolve_bitcoin_rpc_endpoint)
842            .transpose()?;
843        let base_rpc = config
844            .base_rpc
845            .as_ref()
846            .map(resolve_base_rpc_endpoint)
847            .transpose()?;
848        let arbitrum_rpc = config
849            .arbitrum_rpc
850            .as_ref()
851            .map(resolve_arbitrum_rpc_endpoint)
852            .transpose()?;
853        let polygon_rpc = config
854            .polygon_rpc
855            .as_ref()
856            .map(resolve_polygon_rpc_endpoint)
857            .transpose()?;
858        let bsc_rpc = config
859            .bsc_rpc
860            .as_ref()
861            .map(resolve_bsc_rpc_endpoint)
862            .transpose()?;
863        let optimism_rpc = config
864            .optimism_rpc
865            .as_ref()
866            .map(resolve_optimism_rpc_endpoint)
867            .transpose()?;
868        let kaia_rpc = config
869            .kaia_rpc
870            .as_ref()
871            .map(resolve_kaia_rpc_endpoint)
872            .transpose()?;
873        let soneium_rpc = config
874            .soneium_rpc
875            .as_ref()
876            .map(resolve_soneium_rpc_endpoint)
877            .transpose()?;
878        let monad_rpc = config
879            .monad_rpc
880            .as_ref()
881            .map(resolve_monad_rpc_endpoint)
882            .transpose()?;
883        let hyperliquid_rpc = config
884            .hyperliquid_rpc
885            .as_ref()
886            .map(resolve_hyperliquid_rpc_endpoint)
887            .transpose()?;
888        let arc_rpc = config
889            .arc_rpc
890            .as_ref()
891            .map(resolve_arc_rpc_endpoint)
892            .transpose()?;
893        let robinhood_rpc = config
894            .robinhood_rpc
895            .as_ref()
896            .map(resolve_robinhood_rpc_endpoint)
897            .transpose()?;
898        let near_rpc = config
899            .near_rpc
900            .as_ref()
901            .map(resolve_near_rpc_endpoint)
902            .transpose()?;
903        let tron_rpc = config
904            .tron_rpc
905            .as_ref()
906            .map(resolve_tron_rpc_endpoint)
907            .transpose()?;
908        let sui_grpc_web = config
909            .sui_grpc_web
910            .as_ref()
911            .map(resolve_sui_grpc_web_endpoint)
912            .transpose()?;
913        Ok(Self {
914            api_key: (!api_key.is_empty()).then_some(api_key),
915            endpoint: endpoint(&config.endpoint, false)?,
916            avalanche_endpoint: endpoint(&config.avalanche_endpoint, false)?,
917            account_endpoint: endpoint(&config.account_endpoint, false)?,
918            user_endpoint: endpoint(&config.user_endpoint, false)?,
919            headers,
920            timeout: config.timeout,
921            solana_rpc,
922            ethereum_rpc,
923            avalanche_c_rpc: avalanche_rpc,
924            bitcoin_rpc,
925            base_endpoint: endpoint(&config.base_endpoint, false)?,
926            base_rpc,
927            arbitrum_endpoint: endpoint(&config.arbitrum_endpoint, false)?,
928            arbitrum_rpc,
929            polygon_endpoint: endpoint(&config.polygon_endpoint, false)?,
930            polygon_rpc,
931            bsc_endpoint: endpoint(&config.bsc_endpoint, false)?,
932            bsc_rpc,
933            optimism_endpoint: endpoint(&config.optimism_endpoint, false)?,
934            optimism_rpc,
935            kaia_endpoint: endpoint(&config.kaia_endpoint, false)?,
936            kaia_rpc,
937            soneium_endpoint: endpoint(&config.soneium_endpoint, false)?,
938            soneium_rpc,
939            monad_endpoint: endpoint(&config.monad_endpoint, false)?,
940            monad_rpc,
941            hyperliquid_endpoint: endpoint(&config.hyperliquid_endpoint, false)?,
942            hyperliquid_rpc,
943            arc_endpoint: endpoint(&config.arc_endpoint, false)?,
944            arc_rpc,
945            robinhood_endpoint: endpoint(&config.robinhood_endpoint, false)?,
946            robinhood_rpc,
947            near_endpoint: endpoint(&config.near_endpoint, false)?,
948            near_rpc,
949            tron_endpoint: endpoint(&config.tron_endpoint, false)?,
950            tron_rpc,
951            sui_endpoint: resolve_sui_hosted_endpoint(&config.sui_endpoint)?,
952            sui_grpc_web,
953        })
954    }
955}
956
957impl ResolvedErpcClientConfig {
958    pub fn http_client() -> Result<reqwest::Client> {
959        reqwest::Client::builder()
960            .build()
961            .map_err(|_| ErpcError::Config("unable to create HTTP client".to_owned()))
962    }
963
964    pub fn direct_http_client() -> Result<reqwest::Client> {
965        reqwest::Client::builder()
966            .redirect(reqwest::redirect::Policy::none())
967            .build()
968            .map_err(|_| ErpcError::Config("unable to create direct HTTP client".to_owned()))
969    }
970}
971
972pub(crate) fn endpoint(value: &str, local_http_only: bool) -> Result<Url> {
973    let mut url = Url::parse(value)
974        .map_err(|_| ErpcError::Config("endpoint must be an absolute HTTP(S) URL".to_owned()))?;
975    let local = matches!(url.host_str(), Some("127.0.0.1" | "::1" | "localhost"));
976    let allowed =
977        url.scheme() == "https" || (url.scheme() == "http" && (!local_http_only || local));
978    if !allowed {
979        let message = if local_http_only {
980            "endpoint must use HTTPS except on localhost"
981        } else {
982            "endpoint must use HTTP or HTTPS"
983        };
984        return Err(ErpcError::Config(message.to_owned()));
985    }
986    url.set_query(None);
987    url.set_fragment(None);
988    let normalized = url.path().trim_end_matches('/').to_owned();
989    url.set_path(if normalized.is_empty() {
990        "/"
991    } else {
992        &normalized
993    });
994    Ok(url)
995}
996
997fn resolve_sui_hosted_endpoint(value: &str) -> Result<Url> {
998    let parsed = Url::parse(value).map_err(|_| {
999        ErpcError::Config("Sui hosted endpoint must be an absolute HTTP(S) URL".to_owned())
1000    })?;
1001    if has_normalized_userinfo(value, &parsed) {
1002        return Err(ErpcError::Config(
1003            "Sui hosted endpoint must not contain userinfo".to_owned(),
1004        ));
1005    }
1006    if parsed.fragment().is_some() {
1007        return Err(ErpcError::Config(
1008            "Sui hosted endpoint must not contain a fragment".to_owned(),
1009        ));
1010    }
1011    endpoint(value, false)
1012}
1013
1014fn resolve_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1015    let http_url = direct_http_endpoint(&config.http_url)?;
1016    let websocket_url = config
1017        .websocket_url
1018        .as_deref()
1019        .map(direct_websocket_endpoint)
1020        .transpose()?;
1021    let headers = parse_headers(&config.headers)?;
1022    let mut redaction_secrets = redaction_secrets_for_raw_headers(&config.headers);
1023    collect_query_values(&http_url, &mut redaction_secrets);
1024    if let Some(websocket_url) = &websocket_url {
1025        collect_query_values(websocket_url, &mut redaction_secrets);
1026    }
1027    Ok(ResolvedRpcEndpoint {
1028        http_url,
1029        websocket_url,
1030        headers,
1031        redaction_secrets,
1032    })
1033}
1034
1035fn resolve_bitcoin_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1036    if config.websocket_url.is_some() {
1037        return Err(ErpcError::Config(
1038            "bitcoin RPC is HTTP-only; websocket_url is not supported".to_owned(),
1039        ));
1040    }
1041    resolve_rpc_endpoint(config)
1042}
1043
1044fn resolve_base_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1045    if config.websocket_url.is_some() {
1046        return Err(ErpcError::Config(
1047            "base RPC is HTTP-only; websocket_url is not supported".to_owned(),
1048        ));
1049    }
1050    let mut endpoint = resolve_rpc_endpoint(config)?;
1051    collect_path_values(&endpoint.http_url, &mut endpoint.redaction_secrets);
1052    Ok(endpoint)
1053}
1054
1055fn resolve_arbitrum_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1056    if config.websocket_url.is_some() {
1057        return Err(ErpcError::Config(
1058            "Arbitrum RPC is HTTP-only; websocket_url is not supported".to_owned(),
1059        ));
1060    }
1061    let mut endpoint = resolve_rpc_endpoint(config)?;
1062    collect_path_values(&endpoint.http_url, &mut endpoint.redaction_secrets);
1063    Ok(endpoint)
1064}
1065
1066fn resolve_polygon_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1067    if config.websocket_url.is_some() {
1068        return Err(ErpcError::Config(
1069            "Polygon RPC is HTTP-only; websocket_url is not supported".to_owned(),
1070        ));
1071    }
1072    let mut endpoint = resolve_rpc_endpoint(config)?;
1073    collect_path_values(&endpoint.http_url, &mut endpoint.redaction_secrets);
1074    Ok(endpoint)
1075}
1076
1077fn resolve_bsc_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1078    if config.websocket_url.is_some() {
1079        return Err(ErpcError::Config(
1080            "BSC RPC is HTTP-only; websocket_url is not supported".to_owned(),
1081        ));
1082    }
1083    let mut endpoint = resolve_rpc_endpoint(config)?;
1084    collect_path_values(&endpoint.http_url, &mut endpoint.redaction_secrets);
1085    Ok(endpoint)
1086}
1087
1088fn resolve_optimism_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1089    if config.websocket_url.is_some() {
1090        return Err(ErpcError::Config(
1091            "Optimism RPC is HTTP-only; websocket_url is not supported".to_owned(),
1092        ));
1093    }
1094    let mut endpoint = resolve_rpc_endpoint(config)?;
1095    collect_path_values(&endpoint.http_url, &mut endpoint.redaction_secrets);
1096    Ok(endpoint)
1097}
1098
1099fn resolve_kaia_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1100    if config.websocket_url.is_some() {
1101        return Err(ErpcError::Config(
1102            "Kaia RPC is HTTP-only; websocket_url is not supported".to_owned(),
1103        ));
1104    }
1105    let mut endpoint = resolve_rpc_endpoint(config)?;
1106    collect_path_values(&endpoint.http_url, &mut endpoint.redaction_secrets);
1107    Ok(endpoint)
1108}
1109
1110fn resolve_soneium_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1111    if config.websocket_url.is_some() {
1112        return Err(ErpcError::Config(
1113            "Soneium RPC is HTTP-only; websocket_url is not supported".to_owned(),
1114        ));
1115    }
1116    let mut endpoint = resolve_rpc_endpoint(config)?;
1117    collect_path_values(&endpoint.http_url, &mut endpoint.redaction_secrets);
1118    Ok(endpoint)
1119}
1120
1121fn resolve_monad_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1122    if config.websocket_url.is_some() {
1123        return Err(ErpcError::Config(
1124            "Monad RPC is HTTP-only; websocket_url is not supported".to_owned(),
1125        ));
1126    }
1127    let mut endpoint = resolve_rpc_endpoint(config)?;
1128    collect_path_values(&endpoint.http_url, &mut endpoint.redaction_secrets);
1129    Ok(endpoint)
1130}
1131
1132fn resolve_hyperliquid_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1133    if config.websocket_url.is_some() {
1134        return Err(ErpcError::Config(
1135            "Hyperliquid RPC is HTTP-only; websocket_url is not supported".to_owned(),
1136        ));
1137    }
1138    let mut endpoint = resolve_rpc_endpoint(config)?;
1139    collect_path_values(&endpoint.http_url, &mut endpoint.redaction_secrets);
1140    Ok(endpoint)
1141}
1142
1143fn resolve_arc_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1144    if config.websocket_url.is_some() {
1145        return Err(ErpcError::Config(
1146            "Arc RPC is HTTP-only; websocket_url is not supported".to_owned(),
1147        ));
1148    }
1149    let mut endpoint = resolve_rpc_endpoint(config)?;
1150    collect_path_values(&endpoint.http_url, &mut endpoint.redaction_secrets);
1151    Ok(endpoint)
1152}
1153
1154fn resolve_robinhood_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1155    if config.websocket_url.is_some() {
1156        return Err(ErpcError::Config(
1157            "Robinhood RPC is HTTP-only; websocket_url is not supported".to_owned(),
1158        ));
1159    }
1160    let mut endpoint = resolve_rpc_endpoint(config)?;
1161    collect_path_values(&endpoint.http_url, &mut endpoint.redaction_secrets);
1162    Ok(endpoint)
1163}
1164
1165fn resolve_near_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1166    if config.websocket_url.is_some() {
1167        return Err(ErpcError::Config(
1168            "NEAR RPC is HTTP-only; websocket_url is not supported".to_owned(),
1169        ));
1170    }
1171    let mut endpoint = resolve_rpc_endpoint(config)?;
1172    collect_path_values(&endpoint.http_url, &mut endpoint.redaction_secrets);
1173    Ok(endpoint)
1174}
1175
1176fn resolve_tron_rpc_endpoint(config: &RpcEndpointConfig) -> Result<ResolvedRpcEndpoint> {
1177    if config.websocket_url.is_some() {
1178        return Err(ErpcError::Config(
1179            "TRON RPC is HTTP-only; websocket_url is not supported".to_owned(),
1180        ));
1181    }
1182    let mut endpoint = resolve_rpc_endpoint(config)?;
1183    collect_path_values(&endpoint.http_url, &mut endpoint.redaction_secrets);
1184    Ok(endpoint)
1185}
1186
1187fn resolve_sui_grpc_web_endpoint(
1188    config: &SuiGrpcWebEndpointConfig,
1189) -> Result<ResolvedSuiGrpcWebEndpoint> {
1190    let base_url = direct_sui_endpoint(&config.base_url)?;
1191    let headers = parse_headers(&config.headers)?;
1192    Ok(ResolvedSuiGrpcWebEndpoint { base_url, headers })
1193}
1194
1195fn parse_headers(values: &[(String, String)]) -> Result<HeaderMap> {
1196    let mut headers = HeaderMap::new();
1197    for (name, value) in values {
1198        let name = HeaderName::from_str(name)
1199            .map_err(|_| ErpcError::Config("header name is invalid".to_owned()))?;
1200        let value = HeaderValue::from_str(value)
1201            .map_err(|_| ErpcError::Config("header value is invalid".to_owned()))?;
1202        headers.insert(name, value);
1203    }
1204    Ok(headers)
1205}
1206
1207fn direct_http_endpoint(value: &str) -> Result<Url> {
1208    direct_endpoint(value, false)
1209        .map_err(|_| ErpcError::Config("rpc http_url must be an absolute HTTP(S) URL".to_owned()))
1210}
1211
1212fn direct_sui_endpoint(value: &str) -> Result<Url> {
1213    direct_endpoint(value, false).map_err(|_| {
1214        ErpcError::Config("Sui gRPC-Web base_url must be an absolute HTTP(S) URL".to_owned())
1215    })
1216}
1217
1218fn direct_websocket_endpoint(value: &str) -> Result<Url> {
1219    direct_endpoint(value, true).map_err(|_| {
1220        ErpcError::Config("rpc websocket_url must be an absolute WS(S) URL".to_owned())
1221    })
1222}
1223
1224fn direct_endpoint(value: &str, websocket: bool) -> Result<Url> {
1225    let value = value.trim();
1226    let Some(scheme_end) = value.find("://") else {
1227        return Err(ErpcError::Config(
1228            "direct endpoint is missing an authority".to_owned(),
1229        ));
1230    };
1231    let authority = &value[scheme_end + 3..];
1232    let authority_end = authority.find(['/', '?', '#']).unwrap_or(authority.len());
1233    let authority = &authority[..authority_end];
1234    if authority.is_empty() || authority.contains('@') || value.contains('#') {
1235        return Err(ErpcError::Config(
1236            "direct endpoint authority is invalid".to_owned(),
1237        ));
1238    }
1239    let url = Url::parse(value)
1240        .map_err(|_| ErpcError::Config("direct endpoint is invalid".to_owned()))?;
1241    let allowed = if websocket {
1242        matches!(url.scheme(), "ws" | "wss")
1243    } else {
1244        matches!(url.scheme(), "http" | "https")
1245    };
1246    if !allowed || url.host_str().is_none() {
1247        return Err(ErpcError::Config(
1248            "direct endpoint scheme or authority is invalid".to_owned(),
1249        ));
1250    }
1251    if has_normalized_userinfo(value, &url) {
1252        return Err(ErpcError::Config(
1253            "direct endpoint authority is invalid".to_owned(),
1254        ));
1255    }
1256    Ok(url)
1257}
1258
1259fn has_normalized_userinfo(value: &str, url: &Url) -> bool {
1260    if !url.username().is_empty() || url.password().is_some() {
1261        return true;
1262    }
1263    let special_scheme = matches!(url.scheme(), "http" | "https" | "ws" | "wss");
1264    let mut normalized = String::with_capacity(value.len());
1265    for character in value.trim().chars() {
1266        match character {
1267            '\t' | '\n' | '\r' => {}
1268            '\\' if special_scheme => normalized.push('/'),
1269            character => normalized.push(character),
1270        }
1271    }
1272    let Some(scheme_end) = normalized.find(':') else {
1273        return false;
1274    };
1275    let authority = normalized[scheme_end + 1..].trim_start_matches('/');
1276    let authority_end = authority.find(['/', '?', '#']).unwrap_or(authority.len());
1277    authority[..authority_end].contains('@')
1278}
1279
1280fn collect_query_values(url: &Url, secrets: &mut Vec<String>) {
1281    if let Some(query) = url.query() {
1282        for component in query.split('&') {
1283            let raw_value = component
1284                .split_once('=')
1285                .map_or(component, |(_, value)| value);
1286            if !raw_value.is_empty() && !secrets.contains(&raw_value.to_owned()) {
1287                secrets.push(raw_value.to_owned());
1288            }
1289        }
1290    }
1291    for (_, value) in url.query_pairs() {
1292        let value = value.into_owned();
1293        if !value.is_empty() && !secrets.contains(&value) {
1294            secrets.push(value);
1295        }
1296    }
1297}
1298
1299fn collect_path_values(url: &Url, secrets: &mut Vec<String>) {
1300    for component in url
1301        .path()
1302        .split('/')
1303        .filter(|component| !component.is_empty())
1304    {
1305        if !secrets.contains(&component.to_owned()) {
1306            secrets.push(component.to_owned());
1307        }
1308        if let Ok(decoded) = percent_decode_str(component).decode_utf8() {
1309            let decoded = decoded.into_owned();
1310            if !decoded.is_empty() && !secrets.contains(&decoded) {
1311                secrets.push(decoded);
1312            }
1313        }
1314    }
1315}
1316
1317pub(crate) fn redaction_secrets_for_headers(headers: &HeaderMap) -> Vec<String> {
1318    let mut secrets = Vec::new();
1319    for (name, value) in headers {
1320        let Ok(value) = value.to_str() else { continue };
1321        add_header_redaction_secrets(&mut secrets, name.as_str(), value);
1322    }
1323    secrets
1324}
1325
1326fn redaction_secrets_for_raw_headers(headers: &[(String, String)]) -> Vec<String> {
1327    let mut secrets = Vec::new();
1328    for (name, value) in headers {
1329        add_header_redaction_secrets(&mut secrets, name, value);
1330    }
1331    secrets
1332}
1333
1334fn add_header_redaction_secrets(secrets: &mut Vec<String>, name: &str, value: &str) {
1335    let value = value.trim();
1336    if value.is_empty() {
1337        return;
1338    }
1339    for candidate in [
1340        value.to_owned(),
1341        format!("{name}: {value}"),
1342        format!("{name}:{value}"),
1343        format!("{name}={value}"),
1344    ] {
1345        if !secrets.contains(&candidate) {
1346            secrets.push(candidate);
1347        }
1348    }
1349    let mut parts = value.splitn(2, char::is_whitespace);
1350    let scheme = parts.next().unwrap_or_default();
1351    if !matches!(scheme.to_ascii_lowercase().as_str(), "bearer" | "basic") {
1352        return;
1353    }
1354    let Some(component) = parts
1355        .next()
1356        .map(str::trim)
1357        .filter(|value| !value.is_empty())
1358    else {
1359        return;
1360    };
1361    if !secrets.iter().any(|secret| secret == component) {
1362        secrets.push(component.to_owned());
1363    }
1364    if !scheme.eq_ignore_ascii_case("basic") {
1365        return;
1366    }
1367    let Some(decoded) = decode_base64(component).and_then(|bytes| String::from_utf8(bytes).ok())
1368    else {
1369        return;
1370    };
1371    if !secrets.iter().any(|secret| secret == &decoded) {
1372        secrets.push(decoded.clone());
1373    }
1374    if let Some((username, password)) = decoded.split_once(':') {
1375        for value in [username, password] {
1376            if !value.is_empty() && !secrets.iter().any(|secret| secret == value) {
1377                secrets.push(value.to_owned());
1378            }
1379        }
1380    }
1381}
1382
1383fn decode_base64(value: &str) -> Option<Vec<u8>> {
1384    if value.is_empty() {
1385        return None;
1386    }
1387    let mut output = Vec::new();
1388    let mut accumulator = 0_u32;
1389    let mut bits = 0_u8;
1390    let mut padding = false;
1391    let mut padding_count = 0_usize;
1392    let mut data_count = 0_usize;
1393    for byte in value.bytes() {
1394        if byte == b'=' {
1395            padding = true;
1396            padding_count += 1;
1397            if padding_count > 2 {
1398                return None;
1399            }
1400            continue;
1401        }
1402        if padding {
1403            return None;
1404        }
1405        data_count += 1;
1406        let digit = match byte {
1407            b'A'..=b'Z' => byte - b'A',
1408            b'a'..=b'z' => byte - b'a' + 26,
1409            b'0'..=b'9' => byte - b'0' + 52,
1410            b'+' => 62,
1411            b'/' => 63,
1412            _ => return None,
1413        };
1414        accumulator = (accumulator << 6) | u32::from(digit);
1415        bits += 6;
1416        while bits >= 8 {
1417            bits -= 8;
1418            let byte = (accumulator >> bits) & 0xff;
1419            output.push(u8::try_from(byte).ok()?);
1420            if bits == 0 {
1421                accumulator = 0;
1422            } else {
1423                accumulator &= (1_u32 << bits) - 1;
1424            }
1425        }
1426    }
1427    if data_count == 0 || data_count % 4 == 1 {
1428        return None;
1429    }
1430    if padding_count > 0
1431        && ((data_count + padding_count) % 4 != 0 || 4 - (data_count % 4) != padding_count)
1432    {
1433        return None;
1434    }
1435    if bits > 0 && accumulator & ((1_u32 << bits) - 1) != 0 {
1436        return None;
1437    }
1438    Some(output)
1439}
1440
1441fn debug_endpoint(value: &str) -> String {
1442    let Ok(mut url) = Url::parse(value) else {
1443        return "[REDACTED]".to_owned();
1444    };
1445    url.set_query(None);
1446    url.set_fragment(None);
1447    let _ = url.set_username("");
1448    let _ = url.set_password(None);
1449    url.to_string()
1450}
1451
1452fn debug_origin(value: &str) -> String {
1453    let Ok(mut url) = Url::parse(value) else {
1454        return "[REDACTED]".to_owned();
1455    };
1456    url.set_path("/");
1457    url.set_query(None);
1458    url.set_fragment(None);
1459    let _ = url.set_username("");
1460    let _ = url.set_password(None);
1461    url.to_string()
1462}
1463
1464struct BaseRpcDebug<'a>(&'a RpcEndpointConfig);
1465
1466impl fmt::Debug for BaseRpcDebug<'_> {
1467    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1468        formatter
1469            .debug_struct("BaseRpcEndpointConfig")
1470            .field("origin", &debug_origin(&self.0.http_url))
1471            .field("has_websocket_url", &self.0.websocket_url.is_some())
1472            .field(
1473                "header_names",
1474                &self
1475                    .0
1476                    .headers
1477                    .iter()
1478                    .map(|(name, _)| name)
1479                    .collect::<Vec<_>>(),
1480            )
1481            .finish()
1482    }
1483}
1484
1485struct ArbitrumRpcDebug<'a>(&'a RpcEndpointConfig);
1486
1487impl fmt::Debug for ArbitrumRpcDebug<'_> {
1488    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1489        formatter
1490            .debug_struct("ArbitrumRpcEndpointConfig")
1491            .field("origin", &debug_origin(&self.0.http_url))
1492            .field("has_websocket_url", &self.0.websocket_url.is_some())
1493            .field(
1494                "header_names",
1495                &self
1496                    .0
1497                    .headers
1498                    .iter()
1499                    .map(|(name, _)| name)
1500                    .collect::<Vec<_>>(),
1501            )
1502            .finish()
1503    }
1504}
1505
1506struct PolygonRpcDebug<'a>(&'a RpcEndpointConfig);
1507
1508impl fmt::Debug for PolygonRpcDebug<'_> {
1509    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1510        formatter
1511            .debug_struct("PolygonRpcEndpointConfig")
1512            .field("origin", &debug_origin(&self.0.http_url))
1513            .field("has_websocket_url", &self.0.websocket_url.is_some())
1514            .field(
1515                "header_names",
1516                &self
1517                    .0
1518                    .headers
1519                    .iter()
1520                    .map(|(name, _)| name)
1521                    .collect::<Vec<_>>(),
1522            )
1523            .finish()
1524    }
1525}
1526
1527struct BscRpcDebug<'a>(&'a RpcEndpointConfig);
1528
1529impl fmt::Debug for BscRpcDebug<'_> {
1530    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1531        formatter
1532            .debug_struct("BscRpcEndpointConfig")
1533            .field("origin", &debug_origin(&self.0.http_url))
1534            .field("has_websocket_url", &self.0.websocket_url.is_some())
1535            .field(
1536                "header_names",
1537                &self
1538                    .0
1539                    .headers
1540                    .iter()
1541                    .map(|(name, _)| name)
1542                    .collect::<Vec<_>>(),
1543            )
1544            .finish()
1545    }
1546}
1547
1548struct OptimismRpcDebug<'a>(&'a RpcEndpointConfig);
1549
1550impl fmt::Debug for OptimismRpcDebug<'_> {
1551    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1552        formatter
1553            .debug_struct("OptimismRpcEndpointConfig")
1554            .field("origin", &debug_origin(&self.0.http_url))
1555            .field("has_websocket_url", &self.0.websocket_url.is_some())
1556            .field(
1557                "header_names",
1558                &self
1559                    .0
1560                    .headers
1561                    .iter()
1562                    .map(|(name, _)| name)
1563                    .collect::<Vec<_>>(),
1564            )
1565            .finish()
1566    }
1567}
1568
1569struct KaiaRpcDebug<'a>(&'a RpcEndpointConfig);
1570
1571impl fmt::Debug for KaiaRpcDebug<'_> {
1572    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1573        formatter
1574            .debug_struct("KaiaRpcEndpointConfig")
1575            .field("origin", &debug_origin(&self.0.http_url))
1576            .field("has_websocket_url", &self.0.websocket_url.is_some())
1577            .field(
1578                "header_names",
1579                &self
1580                    .0
1581                    .headers
1582                    .iter()
1583                    .map(|(name, _)| name)
1584                    .collect::<Vec<_>>(),
1585            )
1586            .finish()
1587    }
1588}
1589
1590struct SoneiumRpcDebug<'a>(&'a RpcEndpointConfig);
1591
1592impl fmt::Debug for SoneiumRpcDebug<'_> {
1593    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1594        formatter
1595            .debug_struct("SoneiumRpcEndpointConfig")
1596            .field("origin", &debug_origin(&self.0.http_url))
1597            .field("has_websocket_url", &self.0.websocket_url.is_some())
1598            .field(
1599                "header_names",
1600                &self
1601                    .0
1602                    .headers
1603                    .iter()
1604                    .map(|(name, _)| name)
1605                    .collect::<Vec<_>>(),
1606            )
1607            .finish()
1608    }
1609}
1610
1611struct MonadRpcDebug<'a>(&'a RpcEndpointConfig);
1612
1613impl fmt::Debug for MonadRpcDebug<'_> {
1614    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1615        formatter
1616            .debug_struct("MonadRpcEndpointConfig")
1617            .field("origin", &debug_origin(&self.0.http_url))
1618            .field("has_websocket_url", &self.0.websocket_url.is_some())
1619            .field(
1620                "header_names",
1621                &self
1622                    .0
1623                    .headers
1624                    .iter()
1625                    .map(|(name, _)| name)
1626                    .collect::<Vec<_>>(),
1627            )
1628            .finish()
1629    }
1630}
1631
1632struct HyperliquidRpcDebug<'a>(&'a RpcEndpointConfig);
1633
1634impl fmt::Debug for HyperliquidRpcDebug<'_> {
1635    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1636        formatter
1637            .debug_struct("HyperliquidRpcEndpointConfig")
1638            .field("origin", &debug_origin(&self.0.http_url))
1639            .field("has_websocket_url", &self.0.websocket_url.is_some())
1640            .field(
1641                "header_names",
1642                &self
1643                    .0
1644                    .headers
1645                    .iter()
1646                    .map(|(name, _)| name)
1647                    .collect::<Vec<_>>(),
1648            )
1649            .finish()
1650    }
1651}
1652
1653struct ArcRpcDebug<'a>(&'a RpcEndpointConfig);
1654
1655impl fmt::Debug for ArcRpcDebug<'_> {
1656    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1657        formatter
1658            .debug_struct("ArcRpcEndpointConfig")
1659            .field("origin", &debug_origin(&self.0.http_url))
1660            .field("has_websocket_url", &self.0.websocket_url.is_some())
1661            .field(
1662                "header_names",
1663                &self
1664                    .0
1665                    .headers
1666                    .iter()
1667                    .map(|(name, _)| name)
1668                    .collect::<Vec<_>>(),
1669            )
1670            .finish()
1671    }
1672}
1673
1674struct RobinhoodRpcDebug<'a>(&'a RpcEndpointConfig);
1675
1676impl fmt::Debug for RobinhoodRpcDebug<'_> {
1677    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1678        formatter
1679            .debug_struct("RobinhoodRpcEndpointConfig")
1680            .field("origin", &debug_origin(&self.0.http_url))
1681            .field("has_websocket_url", &self.0.websocket_url.is_some())
1682            .field(
1683                "header_names",
1684                &self
1685                    .0
1686                    .headers
1687                    .iter()
1688                    .map(|(name, _)| name)
1689                    .collect::<Vec<_>>(),
1690            )
1691            .finish()
1692    }
1693}
1694
1695struct NearRpcDebug<'a>(&'a RpcEndpointConfig);
1696
1697impl fmt::Debug for NearRpcDebug<'_> {
1698    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1699        formatter
1700            .debug_struct("NearRpcEndpointConfig")
1701            .field("origin", &debug_origin(&self.0.http_url))
1702            .field("has_websocket_url", &self.0.websocket_url.is_some())
1703            .field(
1704                "header_names",
1705                &self
1706                    .0
1707                    .headers
1708                    .iter()
1709                    .map(|(name, _)| name)
1710                    .collect::<Vec<_>>(),
1711            )
1712            .finish()
1713    }
1714}
1715
1716struct TronRpcDebug<'a>(&'a RpcEndpointConfig);
1717
1718impl fmt::Debug for TronRpcDebug<'_> {
1719    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1720        formatter
1721            .debug_struct("TronRpcEndpointConfig")
1722            .field("origin", &debug_origin(&self.0.http_url))
1723            .field("has_websocket_url", &self.0.websocket_url.is_some())
1724            .field(
1725                "header_names",
1726                &self
1727                    .0
1728                    .headers
1729                    .iter()
1730                    .map(|(name, _)| name)
1731                    .collect::<Vec<_>>(),
1732            )
1733            .finish()
1734    }
1735}
1736
1737pub(crate) fn endpoint_with_path(endpoint: &Url, path: &str) -> Url {
1738    let mut url = endpoint.clone();
1739    let base = endpoint.path().trim_end_matches('/');
1740    let path = path.trim_start_matches('/');
1741    url.set_path(&format!("{base}/{path}"));
1742    url
1743}
1744
1745pub(crate) fn websocket_url(endpoint: &Url, api_key: &str, path: &str) -> Result<Url> {
1746    let mut url = endpoint_with_path(endpoint, path);
1747    let scheme = if url.scheme() == "https" { "wss" } else { "ws" };
1748    url.set_scheme(scheme)
1749        .map_err(|()| ErpcError::Config("unable to create WebSocket URL".to_owned()))?;
1750    url.query_pairs_mut().append_pair("api-key", api_key);
1751    Ok(url)
1752}