1use 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 "reth-ethereum.ithaca.xyz/rpc",
48 ],
49);
50shuffled_list!(
51 HTTP_DOMAINS,
52 vec![
53 "reth-ethereum.ithaca.xyz/rpc",
55 ],
57);
58shuffled_list!(
59 WS_ARCHIVE_DOMAINS,
60 vec![
61 "reth-ethereum.ithaca.xyz/ws",
63 ],
64);
65shuffled_list!(
66 WS_DOMAINS,
67 vec![
68 "reth-ethereum.ithaca.xyz/ws",
70 ],
72);
73
74shuffled_list!(
76 DRPC_KEYS,
77 vec![
78 "Agc9NK9-6UzYh-vQDDM80Tv0A5UnBkUR8I3qssvAG40d",
79 "AjUPUPonSEInt2CZ_7A-ai3hMyxxBlsR8I4EssvAG40d",
80 ],
81);
82
83shuffled_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
99pub 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
115pub fn next_http_rpc_endpoint() -> String {
119 next_rpc_endpoint(NamedChain::Mainnet)
120}
121
122pub fn next_ws_rpc_endpoint() -> String {
126 next_ws_endpoint(NamedChain::Mainnet)
127}
128
129pub fn next_rpc_endpoint(chain: NamedChain) -> String {
131 next_url(false, chain)
132}
133
134pub fn next_ws_endpoint(chain: NamedChain) -> String {
136 next_url(true, chain)
137}
138
139pub fn next_http_archive_rpc_url() -> String {
141 next_archive_url(false)
142}
143
144pub fn next_ws_archive_rpc_url() -> String {
146 next_archive_url(true)
147}
148
149fn 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
157pub 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, Arbitrum) {
191 let rpc_url = env::var("ARBITRUM_RPC").unwrap_or_default();
192 if !rpc_url.is_empty() {
193 return rpc_url;
194 }
195 }
196
197 let reth_works = true;
198 let domain = if reth_works && matches!(chain, Mainnet) {
199 *(if is_ws { &WS_DOMAINS } else { &HTTP_DOMAINS }).next()
200 } else {
201 let key = DRPC_KEYS.next();
203 let network = match chain {
204 Mainnet => "ethereum",
205 Polygon => "polygon",
206 Arbitrum => "arbitrum",
207 Sepolia => "sepolia",
208 _ => "",
209 };
210 &format!("lb.drpc.org/ogrpc?network={network}&dkey={key}")
211 };
212
213 if is_ws { format!("wss://{domain}") } else { format!("https://{domain}") }
214}
215
216fn debug_url(url: &str) -> impl std::fmt::Display + '_ {
218 let url = reqwest::Url::parse(url).unwrap();
219 format!(
220 "{scheme}://{host}{path}",
221 scheme = url.scheme(),
222 host = url.host_str().unwrap(),
223 path = url.path().get(..8).unwrap_or(url.path()),
224 )
225}
226
227#[cfg(test)]
228#[expect(clippy::disallowed_macros)]
229mod tests {
230 use super::*;
231 use alloy_primitives::address;
232 use foundry_config::Chain;
233
234 #[tokio::test]
235 #[ignore = "run manually"]
236 async fn test_etherscan_keys() {
237 let address = address!("0xdAC17F958D2ee523a2206206994597C13D831ec7");
238 let mut first_abi = None;
239 let mut failed = Vec::new();
240 for (i, &key) in ETHERSCAN_KEYS.list.iter().enumerate() {
241 println!("trying key {i} ({key})");
242
243 let client = foundry_block_explorers::Client::builder()
244 .chain(Chain::mainnet())
245 .unwrap()
246 .with_api_key(key)
247 .build()
248 .unwrap();
249
250 let mut fail = |e: &str| {
251 eprintln!("key {i} ({key}) failed: {e}");
252 failed.push(key);
253 };
254
255 let abi = match client.contract_abi(address).await {
256 Ok(abi) => abi,
257 Err(e) => {
258 fail(&e.to_string());
259 continue;
260 }
261 };
262
263 if let Some(first_abi) = &first_abi {
264 if abi != *first_abi {
265 fail("abi mismatch");
266 }
267 } else {
268 first_abi = Some(abi);
269 }
270 }
271 if !failed.is_empty() {
272 panic!("failed keys: {failed:#?}");
273 }
274 }
275}