foundry_test_utils/
rpc.rs

1//! RPC API keys utilities.
2
3use foundry_config::{
4    NamedChain::{
5        self, Arbitrum, Base, BinanceSmartChainTestnet, Celo, Mainnet, Optimism, Polygon, Sepolia,
6    },
7    RpcEndpointUrl, RpcEndpoints,
8};
9use rand::seq::SliceRandom;
10use std::{
11    env,
12    sync::{
13        LazyLock,
14        atomic::{AtomicUsize, Ordering},
15    },
16};
17
18macro_rules! shuffled_list {
19    ($name:ident, $e:expr $(,)?) => {
20        static $name: LazyLock<ShuffledList<&'static str>> =
21            LazyLock::new(|| ShuffledList::new($e));
22    };
23}
24
25struct ShuffledList<T> {
26    list: Vec<T>,
27    index: AtomicUsize,
28}
29
30impl<T> ShuffledList<T> {
31    fn new(mut list: Vec<T>) -> Self {
32        assert!(!list.is_empty());
33        list.shuffle(&mut rand::rng());
34        Self { list, index: AtomicUsize::new(0) }
35    }
36
37    fn next(&self) -> &T {
38        let index = self.index.fetch_add(1, Ordering::Relaxed);
39        &self.list[index % self.list.len()]
40    }
41}
42
43shuffled_list!(
44    HTTP_ARCHIVE_DOMAINS,
45    vec![
46        //
47        "reth-ethereum.ithaca.xyz/rpc",
48    ],
49);
50shuffled_list!(
51    HTTP_DOMAINS,
52    vec![
53        //
54        "reth-ethereum.ithaca.xyz/rpc",
55        // "reth-ethereum-full.ithaca.xyz/rpc",
56    ],
57);
58shuffled_list!(
59    WS_ARCHIVE_DOMAINS,
60    vec![
61        //
62        "reth-ethereum.ithaca.xyz/ws",
63    ],
64);
65shuffled_list!(
66    WS_DOMAINS,
67    vec![
68        //
69        "reth-ethereum.ithaca.xyz/ws",
70        // "reth-ethereum-full.ithaca.xyz/ws",
71    ],
72);
73
74// List of general purpose DRPC keys to rotate through
75shuffled_list!(
76    DRPC_KEYS,
77    vec![
78        "Agc9NK9-6UzYh-vQDDM80Tv0A5UnBkUR8I3qssvAG40d",
79        "AjUPUPonSEInt2CZ_7A-ai3hMyxxBlsR8I4EssvAG40d",
80    ],
81);
82
83// List of etherscan keys.
84shuffled_list!(
85    ETHERSCAN_KEYS,
86    vec![
87        "MCAUM7WPE9XP5UQMZPCKIBUJHPM1C24FP6",
88        "JW6RWCG2C5QF8TANH4KC7AYIF1CX7RB5D1",
89        "ZSMDY6BI2H55MBE3G9CUUQT4XYUDBB6ZSK",
90        "4FYHTY429IXYMJNS4TITKDMUKW5QRYDX61",
91        "QYKNT5RHASZ7PGQE68FNQWH99IXVTVVD2I",
92        "VXMQ117UN58Y4RHWUB8K1UGCEA7UQEWK55",
93        "C7I2G4JTA5EPYS42Z8IZFEIMQNI5GXIJEV",
94        "A15KZUMZXXCK1P25Y1VP1WGIVBBHIZDS74",
95        "3IA6ASNQXN8WKN7PNFX7T72S9YG56X9FPG",
96    ],
97);
98
99/// the RPC endpoints used during tests
100pub fn rpc_endpoints() -> RpcEndpoints {
101    RpcEndpoints::new([
102        ("mainnet", RpcEndpointUrl::Url(next_http_archive_rpc_url())),
103        ("mainnet2", RpcEndpointUrl::Url(next_http_archive_rpc_url())),
104        ("sepolia", RpcEndpointUrl::Url(next_rpc_endpoint(NamedChain::Sepolia))),
105        ("optimism", RpcEndpointUrl::Url(next_rpc_endpoint(NamedChain::Optimism))),
106        ("arbitrum", RpcEndpointUrl::Url(next_rpc_endpoint(NamedChain::Arbitrum))),
107        ("polygon", RpcEndpointUrl::Url(next_rpc_endpoint(NamedChain::Polygon))),
108        ("bsc", RpcEndpointUrl::Url(next_rpc_endpoint(NamedChain::BinanceSmartChain))),
109        ("avaxTestnet", RpcEndpointUrl::Url("https://api.avax-test.network/ext/bc/C/rpc".into())),
110        ("moonbeam", RpcEndpointUrl::Url("https://moonbeam-rpc.publicnode.com".into())),
111        ("rpcEnvAlias", RpcEndpointUrl::Env("${RPC_ENV_ALIAS}".into())),
112    ])
113}
114
115/// Returns the next _mainnet_ rpc URL in inline
116///
117/// This will rotate all available rpc endpoints
118pub fn next_http_rpc_endpoint() -> String {
119    next_rpc_endpoint(NamedChain::Mainnet)
120}
121
122/// Returns the next _mainnet_ rpc URL in inline
123///
124/// This will rotate all available rpc endpoints
125pub fn next_ws_rpc_endpoint() -> String {
126    next_ws_endpoint(NamedChain::Mainnet)
127}
128
129/// Returns the next HTTP RPC URL.
130pub fn next_rpc_endpoint(chain: NamedChain) -> String {
131    next_url(false, chain)
132}
133
134/// Returns the next WS RPC URL.
135pub fn next_ws_endpoint(chain: NamedChain) -> String {
136    next_url(true, chain)
137}
138
139/// Returns a websocket URL that has access to archive state
140pub fn next_http_archive_rpc_url() -> String {
141    next_archive_url(false)
142}
143
144/// Returns an HTTP URL that has access to archive state
145pub fn next_ws_archive_rpc_url() -> String {
146    next_archive_url(true)
147}
148
149/// Returns a URL that has access to archive state.
150fn next_archive_url(is_ws: bool) -> String {
151    let domain = if is_ws { &WS_ARCHIVE_DOMAINS } else { &HTTP_ARCHIVE_DOMAINS }.next();
152    let url = if is_ws { format!("wss://{domain}") } else { format!("https://{domain}") };
153    test_debug!("next_archive_url(is_ws={is_ws}) = {}", debug_url(&url));
154    url
155}
156
157/// Returns the next etherscan api key.
158pub fn next_etherscan_api_key() -> String {
159    let mut key = env::var("ETHERSCAN_KEY").unwrap_or_default();
160    if key.is_empty() {
161        key = ETHERSCAN_KEYS.next().to_string();
162    }
163    test_debug!("next_etherscan_api_key() = {}...", &key[..6]);
164    key
165}
166
167fn next_url(is_ws: bool, chain: NamedChain) -> String {
168    let url = next_url_inner(is_ws, chain);
169    test_debug!("next_url(is_ws={is_ws}, chain={chain:?}) = {}", debug_url(&url));
170    url
171}
172
173fn next_url_inner(is_ws: bool, chain: NamedChain) -> String {
174    if matches!(chain, Base) {
175        return "https://mainnet.base.org".to_string();
176    }
177
178    if matches!(chain, Optimism) {
179        return "https://mainnet.optimism.io".to_string();
180    }
181
182    if matches!(chain, BinanceSmartChainTestnet) {
183        return "https://bsc-testnet-rpc.publicnode.com".to_string();
184    }
185
186    if matches!(chain, Celo) {
187        return "https://celo.drpc.org".to_string();
188    }
189
190    if matches!(chain, Sepolia) {
191        let rpc_url = env::var("ETH_SEPOLIA_RPC").unwrap_or_default();
192        if !rpc_url.is_empty() {
193            return rpc_url;
194        }
195    }
196
197    if matches!(chain, Arbitrum) {
198        let rpc_url = env::var("ARBITRUM_RPC").unwrap_or_default();
199        if !rpc_url.is_empty() {
200            return rpc_url;
201        }
202    }
203
204    let reth_works = true;
205    let domain = if reth_works && matches!(chain, Mainnet) {
206        *(if is_ws { &WS_DOMAINS } else { &HTTP_DOMAINS }).next()
207    } else {
208        // DRPC for other networks used in tests.
209        let key = DRPC_KEYS.next();
210        let network = match chain {
211            Mainnet => "ethereum",
212            Polygon => "polygon",
213            Arbitrum => "arbitrum",
214            Sepolia => "sepolia",
215            _ => "",
216        };
217        &format!("lb.drpc.org/ogrpc?network={network}&dkey={key}")
218    };
219
220    if is_ws { format!("wss://{domain}") } else { format!("https://{domain}") }
221}
222
223/// Basic redaction for debugging RPC URLs.
224fn debug_url(url: &str) -> impl std::fmt::Display + '_ {
225    let url = reqwest::Url::parse(url).unwrap();
226    format!(
227        "{scheme}://{host}{path}",
228        scheme = url.scheme(),
229        host = url.host_str().unwrap(),
230        path = url.path().get(..8).unwrap_or(url.path()),
231    )
232}
233
234#[cfg(test)]
235#[expect(clippy::disallowed_macros)]
236mod tests {
237    use super::*;
238    use alloy_primitives::address;
239    use foundry_config::Chain;
240
241    #[tokio::test]
242    #[ignore = "run manually"]
243    async fn test_etherscan_keys() {
244        let address = address!("0xdAC17F958D2ee523a2206206994597C13D831ec7");
245        let mut first_abi = None;
246        let mut failed = Vec::new();
247        for (i, &key) in ETHERSCAN_KEYS.list.iter().enumerate() {
248            println!("trying key {i} ({key})");
249
250            let client = foundry_block_explorers::Client::builder()
251                .chain(Chain::mainnet())
252                .unwrap()
253                .with_api_key(key)
254                .build()
255                .unwrap();
256
257            let mut fail = |e: &str| {
258                eprintln!("key {i} ({key}) failed: {e}");
259                failed.push(key);
260            };
261
262            let abi = match client.contract_abi(address).await {
263                Ok(abi) => abi,
264                Err(e) => {
265                    fail(&e.to_string());
266                    continue;
267                }
268            };
269
270            if let Some(first_abi) = &first_abi {
271                if abi != *first_abi {
272                    fail("abi mismatch");
273                }
274            } else {
275                first_abi = Some(abi);
276            }
277        }
278        if !failed.is_empty() {
279            panic!("failed keys: {failed:#?}");
280        }
281    }
282}