Skip to main content

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