leo_ast/common/
program_id.rs1use crate::{Identifier, NetworkName};
18
19use core::fmt;
20use leo_span::{Span, Symbol};
21use serde::{Deserialize, Serialize};
22use snarkvm::{
23 console::program::ProgramID,
24 prelude::{CanaryV0, MainnetV0, Network, Result, TestnetV0},
25};
26use std::str::FromStr;
27
28#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
30pub struct ProgramId {
31 pub name: Identifier,
33 pub network: Identifier,
35}
36
37impl ProgramId {
38 pub fn span(&self) -> Span {
39 Span::new(self.name.span.lo, self.network.span.hi)
40 }
41
42 pub fn as_symbol(&self) -> Symbol {
43 Symbol::intern(&self.to_string())
44 }
45
46 pub fn from_str_with_network(string: &str, network: NetworkName) -> Result<Self> {
48 match network {
49 NetworkName::MainnetV0 => ProgramID::<MainnetV0>::from_str(string).map(|id| (&id).into()),
50 NetworkName::TestnetV0 => ProgramID::<TestnetV0>::from_str(string).map(|id| (&id).into()),
51 NetworkName::CanaryV0 => ProgramID::<CanaryV0>::from_str(string).map(|id| (&id).into()),
52 }
53 }
54
55 pub fn to_address_string(&self, network: NetworkName) -> Result<String> {
57 match network {
58 NetworkName::MainnetV0 => {
59 ProgramID::<MainnetV0>::from_str(&self.to_string())?.to_address().map(|addr| addr.to_string())
60 }
61 NetworkName::TestnetV0 => {
62 ProgramID::<TestnetV0>::from_str(&self.to_string())?.to_address().map(|addr| addr.to_string())
63 }
64 NetworkName::CanaryV0 => {
65 ProgramID::<CanaryV0>::from_str(&self.to_string())?.to_address().map(|addr| addr.to_string())
66 }
67 }
68 }
69}
70
71impl fmt::Display for ProgramId {
72 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
73 write!(f, "{}.{}", self.name, self.network)
74 }
75}
76
77impl<N: Network> From<&ProgramID<N>> for ProgramId {
78 fn from(program: &ProgramID<N>) -> Self {
79 Self { name: Identifier::from(program.name()), network: Identifier::from(program.network()) }
80 }
81}
82
83impl From<Identifier> for ProgramId {
84 fn from(name: Identifier) -> Self {
85 Self {
86 name,
87 network: Identifier { name: Symbol::intern("aleo"), span: Default::default(), id: Default::default() },
88 }
89 }
90}