use crate::{Identifier, NetworkName};
use core::fmt;
use leo_span::{Span, Symbol};
use serde::{Deserialize, Serialize};
use snarkvm::{
console::program::ProgramID,
prelude::{CanaryV0, MainnetV0, Network, Result, TestnetV0},
};
use std::str::FromStr;
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct ProgramId {
pub name: Identifier,
pub network: Identifier,
}
impl ProgramId {
pub fn span(&self) -> Span {
Span::new(self.name.span.lo, self.network.span.hi)
}
pub fn as_symbol(&self) -> Symbol {
Symbol::intern(&self.to_string())
}
pub fn from_str_with_network(string: &str, network: NetworkName) -> Result<Self> {
match network {
NetworkName::MainnetV0 => ProgramID::<MainnetV0>::from_str(string).map(|id| (&id).into()),
NetworkName::TestnetV0 => ProgramID::<TestnetV0>::from_str(string).map(|id| (&id).into()),
NetworkName::CanaryV0 => ProgramID::<CanaryV0>::from_str(string).map(|id| (&id).into()),
}
}
pub fn to_address_string(&self, network: NetworkName) -> Result<String> {
match network {
NetworkName::MainnetV0 => {
ProgramID::<MainnetV0>::from_str(&self.to_string())?.to_address().map(|addr| addr.to_string())
}
NetworkName::TestnetV0 => {
ProgramID::<TestnetV0>::from_str(&self.to_string())?.to_address().map(|addr| addr.to_string())
}
NetworkName::CanaryV0 => {
ProgramID::<CanaryV0>::from_str(&self.to_string())?.to_address().map(|addr| addr.to_string())
}
}
}
}
impl fmt::Display for ProgramId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.{}", self.name, self.network)
}
}
impl<N: Network> From<&ProgramID<N>> for ProgramId {
fn from(program: &ProgramID<N>) -> Self {
Self { name: Identifier::from(program.name()), network: Identifier::from(program.network()) }
}
}
impl From<Identifier> for ProgramId {
fn from(name: Identifier) -> Self {
Self {
name,
network: Identifier { name: Symbol::intern("aleo"), span: Default::default(), id: Default::default() },
}
}
}