use crate::abstractions::NetworkId;
#[derive(Debug, Clone)]
pub struct NetworkConfig {
pub name: String,
pub indexer_http: String,
pub node_ws: String,
pub proof_server_url: Option<String>,
pub proof_server_remote_url: Option<String>,
pub network_id: NetworkId,
pub chain_kind: String,
}
impl NetworkConfig {
#[must_use]
pub fn is_mainnet(&self) -> bool {
self.chain_kind.as_str() == "mainnet"
}
#[must_use]
pub fn is_fund_class(&self) -> bool {
matches!(self.chain_kind.as_str(), "mainnet" | "preprod")
}
}
pub const BLOCKFROST_PROJECT_ID_ENV: &str = "BLOCKFROST_PROJECT_ID";
const PROJECT_ID: &str = "project_id";
fn is_blockfrost(endpoint: &str) -> bool {
url::Url::parse(endpoint)
.is_ok_and(|u| u.host_str().is_some_and(|h| h.ends_with(".blockfrost.io")))
}
fn has_project_id(endpoint: &str) -> bool {
url::Url::parse(endpoint).is_ok_and(|u| u.query_pairs().any(|(k, _)| k == PROJECT_ID))
}
impl NetworkConfig {
#[must_use]
pub fn needs_project_id(&self) -> bool {
[&self.indexer_http, &self.node_ws]
.into_iter()
.any(|e| is_blockfrost(e) && !has_project_id(e))
}
pub fn with_project_id(mut self, project_id: &str) -> anyhow::Result<Self> {
for endpoint in [&mut self.indexer_http, &mut self.node_ws] {
if is_blockfrost(endpoint) && !has_project_id(endpoint) {
let mut url = url::Url::parse(endpoint)?;
url.query_pairs_mut().append_pair(PROJECT_ID, project_id);
*endpoint = url.to_string();
}
}
Ok(self)
}
pub fn authenticated_from_env(self) -> anyhow::Result<Self> {
self.authenticated_with(|name| std::env::var(name).ok())
}
fn authenticated_with(self, lookup: impl Fn(&str) -> Option<String>) -> anyhow::Result<Self> {
if !self.needs_project_id() {
return Ok(self);
}
let per_network = format!(
"{BLOCKFROST_PROJECT_ID_ENV}_{}",
self.name.to_ascii_uppercase().replace('-', "_")
);
let Some(project_id) = lookup(&per_network).or_else(|| lookup(BLOCKFROST_PROJECT_ID_ENV))
else {
anyhow::bail!(
"network `{}` is served by Blockfrost, which needs a project id: set \
{per_network} or {BLOCKFROST_PROJECT_ID_ENV} to a Blockfrost project id for this \
network (https://blockfrost.io)",
self.name
);
};
self.with_project_id(&project_id)
}
}
#[must_use]
pub fn network_id_for_chain_kind(chain_kind: &str, fallback: &str) -> NetworkId {
match chain_kind {
"mainnet" => NetworkId::MainNet,
"testnet" => NetworkId::TestNet,
"devnet" => NetworkId::DevNet,
"qanet" => NetworkId::QaNet,
"preview" => NetworkId::Preview,
"preprod" => NetworkId::PreProd,
"localdev" | "undeployed" => NetworkId::Undeployed,
other => NetworkId::from_label(if other.is_empty() { fallback } else { other }),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn blockfrost_endpoints_take_the_project_id_from_the_environment() {
let preprod = crate::session::presets::preprod();
assert!(preprod.needs_project_id());
let env = |name: &str| {
(name == "BLOCKFROST_PROJECT_ID_PREPROD").then(|| "nightpreprodX".to_owned())
};
let authed = preprod.authenticated_with(env).unwrap();
assert!(!authed.needs_project_id());
assert!(authed.indexer_http.ends_with("?project_id=nightpreprodX"));
assert!(authed.node_ws.ends_with("?project_id=nightpreprodX"));
}
#[test]
fn a_missing_project_id_names_the_variables_to_set() {
let err = crate::session::presets::mainnet()
.authenticated_with(|_| None)
.unwrap_err()
.to_string();
assert!(err.contains("BLOCKFROST_PROJECT_ID_MAINNET"), "{err}");
}
#[test]
fn self_hosted_endpoints_need_nothing() {
let local = crate::session::presets::localdev();
assert!(!local.needs_project_id());
assert_eq!(
local
.clone()
.authenticated_with(|_| None)
.unwrap()
.indexer_http,
local.indexer_http
);
}
#[test]
fn network_id_mapping_covers_known_chain_kinds() {
assert!(matches!(
network_id_for_chain_kind("mainnet", "n"),
NetworkId::MainNet
));
assert!(matches!(
network_id_for_chain_kind("testnet", "n"),
NetworkId::TestNet
));
assert!(matches!(
network_id_for_chain_kind("localdev", "n"),
NetworkId::Undeployed
));
assert!(matches!(
network_id_for_chain_kind("undeployed", "n"),
NetworkId::Undeployed
));
match network_id_for_chain_kind("acme-stage", "n") {
NetworkId::Custom(s) => assert_eq!(s, "acme-stage"),
other => panic!("expected Custom, got {other:?}"),
}
}
#[test]
fn is_mainnet_flags_only_mainnet() {
let mn = NetworkConfig {
name: "n".to_owned(),
indexer_http: String::new(),
node_ws: String::new(),
proof_server_url: None,
proof_server_remote_url: None,
network_id: NetworkId::MainNet,
chain_kind: "mainnet".to_owned(),
};
assert!(mn.is_mainnet());
let pp = NetworkConfig {
chain_kind: "preprod".to_owned(),
..mn.clone()
};
assert!(!pp.is_mainnet());
assert!(pp.is_fund_class());
let local = NetworkConfig {
chain_kind: "localdev".to_owned(),
..mn
};
assert!(!local.is_mainnet());
assert!(!local.is_fund_class());
}
#[test]
fn network_config_roundtrips_proof_server_url() {
let cfg = NetworkConfig {
name: "n".to_owned(),
indexer_http: String::new(),
node_ws: String::new(),
proof_server_url: Some("http://127.0.0.1:6300".to_owned()),
proof_server_remote_url: None,
network_id: NetworkId::Undeployed,
chain_kind: "localdev".to_owned(),
};
assert_eq!(
cfg.proof_server_url.as_deref(),
Some("http://127.0.0.1:6300")
);
}
}