bitski_chain_models/
networks.rs

1use crate::chains;
2
3#[derive(Clone, Debug, Hash, PartialEq, Eq)]
4pub struct Network {
5    pub rpc_url: String,
6    pub chain_id: u64,
7}
8
9impl TryFrom<&str> for Network {
10    type Error = anyhow::Error;
11
12    fn try_from(value: &str) -> Result<Self, Self::Error> {
13        let chain = match value {
14            "mainnet" => {
15                return Ok(Network {
16                    rpc_url: "https://api.bitski.com/v1/web3/mainnet".to_owned(),
17                    chain_id: 1,
18                })
19            }
20            // remap to the short name since 'goerli' isn't in the list
21            "goerli" => chains::chain_from_str("gor"),
22            _ => chains::chain_from_str(value),
23        }?;
24
25        Ok(Network {
26            rpc_url: format!("https://api.bitski.com/v1/web3/{}", chain.chain_id),
27            chain_id: chain.chain_id,
28        })
29    }
30}
31
32#[test]
33fn test_chain_name_try_from() {
34    let n = Network::try_from("goerli").expect("could not get goerli chain");
35    assert_eq!(n.chain_id, 5);
36
37    let n = Network::try_from("mainnet").expect("could not get mainnet chain");
38    assert_eq!(n.chain_id, 1);
39
40    let n = Network::try_from("polygon").expect("could not get polygon chain");
41    assert_eq!(n.chain_id, 137);
42}