Skip to main content

defuse_token_id/
nep245.rs

1use std::{fmt, str::FromStr};
2
3use near_account_id::AccountId;
4
5use crate::{TokenIdType, error::TokenIdError};
6
7#[cfg_attr(any(feature = "arbitrary", test), derive(::arbitrary::Arbitrary))]
8#[cfg_attr(
9    feature = "borsh",
10    derive(::borsh::BorshSerialize, ::borsh::BorshDeserialize),
11    cfg_attr(feature = "borsh-schema", derive(::borsh::BorshSchema))
12)]
13#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct Nep245TokenId {
15    pub contract_id: AccountId,
16
17    pub mt_token_id: String,
18}
19
20impl Nep245TokenId {
21    pub fn new(contract_id: impl Into<AccountId>, mt_token_id: impl Into<String>) -> Self {
22        Self {
23            contract_id: contract_id.into(),
24            mt_token_id: mt_token_id.into(),
25        }
26    }
27}
28
29impl std::fmt::Debug for Nep245TokenId {
30    #[inline]
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        write!(f, "{}:{}", self.contract_id, self.mt_token_id)
33    }
34}
35
36impl std::fmt::Display for Nep245TokenId {
37    #[inline]
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        fmt::Debug::fmt(&self, f)
40    }
41}
42
43impl FromStr for Nep245TokenId {
44    type Err = TokenIdError;
45
46    fn from_str(data: &str) -> Result<Self, Self::Err> {
47        let (contract_id, token_id) = data
48            .split_once(':')
49            .ok_or(strum::ParseError::VariantNotFound)?;
50        Ok(Self::new(contract_id.parse::<AccountId>()?, token_id))
51    }
52}
53
54impl From<&Nep245TokenId> for TokenIdType {
55    #[inline]
56    fn from(_: &Nep245TokenId) -> Self {
57        Self::Nep245
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    use defuse_test_utils::random::make_arbitrary;
66    use rstest::rstest;
67
68    #[rstest]
69    #[trace]
70    fn display_from_str_roundtrip(#[from(make_arbitrary)] token_id: Nep245TokenId) {
71        let s = token_id.to_string();
72        let got: Nep245TokenId = s.parse().unwrap();
73        assert_eq!(got, token_id);
74    }
75}