sos_core/
identity.rs

1//! Public identity information.
2use crate::AccountId;
3use crate::Error;
4use serde::{Deserialize, Serialize};
5use std::{fmt, str::FromStr};
6
7/// Public account identity information.
8#[typeshare::typeshare]
9#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, Hash)]
10pub struct PublicIdentity {
11    /// Account identifier.
12    account_id: AccountId,
13    /// Label for the account.
14    ///
15    /// This is the name given to the identity vault.
16    label: String,
17}
18
19impl PublicIdentity {
20    /// Create new account information.
21    pub fn new(account_id: AccountId, label: String) -> Self {
22        Self { account_id, label }
23    }
24
25    /// Get the account identifier.
26    pub fn account_id(&self) -> &AccountId {
27        &self.account_id
28    }
29
30    /// Get the label of this account.
31    pub fn label(&self) -> &str {
32        &self.label
33    }
34
35    /// Set the account label.
36    pub fn set_label(&mut self, label: String) {
37        self.label = label;
38    }
39}
40
41impl From<&PublicIdentity> for AccountRef {
42    fn from(value: &PublicIdentity) -> Self {
43        AccountRef::Id(*value.account_id())
44    }
45}
46
47impl From<PublicIdentity> for AccountRef {
48    fn from(value: PublicIdentity) -> Self {
49        (&value).into()
50    }
51}
52
53/// Reference to an account using an address or a named label.
54#[derive(Debug, Clone)]
55pub enum AccountRef {
56    /// Account identifier.
57    Id(AccountId),
58    /// Account label.
59    Name(String),
60}
61
62impl fmt::Display for AccountRef {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        match self {
65            Self::Id(id) => write!(f, "{}", id),
66            Self::Name(name) => write!(f, "{}", name),
67        }
68    }
69}
70
71impl FromStr for AccountRef {
72    type Err = Error;
73    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
74        if let Ok(id) = s.parse::<AccountId>() {
75            Ok(Self::Id(id))
76        } else {
77            Ok(Self::Name(s.to_string()))
78        }
79    }
80}