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