1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
//! Defines Non-Fungible Token Transfer (ICS-721) token types.
use core::fmt::{self, Display};
use core::str::FromStr;

use http::Uri;
use ibc_core::primitives::prelude::*;
#[cfg(feature = "serde")]
use ibc_core::primitives::serializers;

use crate::data::Data;
use crate::error::NftTransferError;

/// Token ID for an NFT
#[cfg_attr(
    feature = "parity-scale-codec",
    derive(
        parity_scale_codec::Encode,
        parity_scale_codec::Decode,
        scale_info::TypeInfo
    )
)]
#[cfg_attr(
    feature = "borsh",
    derive(borsh::BorshSerialize, borsh::BorshDeserialize)
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct TokenId(String);

impl AsRef<str> for TokenId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Display for TokenId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for TokenId {
    type Err = NftTransferError;

    fn from_str(token_id: &str) -> Result<Self, Self::Err> {
        if token_id.trim().is_empty() {
            Err(NftTransferError::InvalidTokenId)
        } else {
            Ok(Self(token_id.to_string()))
        }
    }
}

#[cfg_attr(
    feature = "parity-scale-codec",
    derive(
        parity_scale_codec::Encode,
        parity_scale_codec::Decode,
        scale_info::TypeInfo
    )
)]
#[cfg_attr(
    feature = "borsh",
    derive(borsh::BorshSerialize, borsh::BorshDeserialize)
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TokenIds(pub Vec<TokenId>);

impl TokenIds {
    pub fn as_ref(&self) -> Vec<&TokenId> {
        self.0.iter().collect()
    }
}

impl Display for TokenIds {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            self.0
                .iter()
                .map(|t| t.to_string())
                .collect::<Vec<String>>()
                .join(",")
        )
    }
}

impl TryFrom<Vec<String>> for TokenIds {
    type Error = NftTransferError;

    fn try_from(token_ids: Vec<String>) -> Result<Self, Self::Error> {
        if token_ids.is_empty() {
            return Err(NftTransferError::NoTokenId);
        }
        let ids: Result<Vec<TokenId>, _> = token_ids.iter().map(|t| t.parse()).collect();
        let mut ids = ids?;
        ids.sort();
        ids.dedup();
        if ids.len() != token_ids.len() {
            return Err(NftTransferError::DuplicatedTokenIds);
        }
        Ok(Self(ids))
    }
}

/// Token URI for an NFT
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TokenUri(
    #[cfg_attr(feature = "serde", serde(with = "serializers"))]
    #[cfg_attr(feature = "schema", schemars(with = "String"))]
    Uri,
);

#[cfg(feature = "borsh")]
impl borsh::BorshSerialize for TokenUri {
    fn serialize<W: borsh::maybestd::io::Write>(
        &self,
        writer: &mut W,
    ) -> borsh::maybestd::io::Result<()> {
        borsh::BorshSerialize::serialize(&self.to_string(), writer)
    }
}

#[cfg(feature = "borsh")]
impl borsh::BorshDeserialize for TokenUri {
    fn deserialize_reader<R: borsh::maybestd::io::Read>(
        reader: &mut R,
    ) -> borsh::maybestd::io::Result<Self> {
        let uri = String::deserialize_reader(reader)?;
        Ok(TokenUri::from_str(&uri).map_err(|_| borsh::maybestd::io::ErrorKind::Other)?)
    }
}

#[cfg(feature = "parity-scale-codec")]
impl parity_scale_codec::Encode for TokenUri {
    fn encode_to<T: parity_scale_codec::Output + ?Sized>(&self, writer: &mut T) {
        self.to_string().encode_to(writer);
    }
}

#[cfg(feature = "parity-scale-codec")]
impl parity_scale_codec::Decode for TokenUri {
    fn decode<I: parity_scale_codec::Input>(
        input: &mut I,
    ) -> Result<Self, parity_scale_codec::Error> {
        let uri = String::decode(input)?;
        TokenUri::from_str(&uri).map_err(|_| parity_scale_codec::Error::from("from str error"))
    }
}

#[cfg(feature = "parity-scale-codec")]
impl scale_info::TypeInfo for TokenUri {
    type Identity = Self;

    fn type_info() -> scale_info::Type {
        scale_info::Type::builder()
            .path(scale_info::Path::new("TokenUri", module_path!()))
            .composite(
                scale_info::build::Fields::unnamed()
                    .field(|f| f.ty::<String>().type_name("String")),
            )
    }
}

impl Display for TokenUri {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for TokenUri {
    type Err = NftTransferError;

    fn from_str(token_uri: &str) -> Result<Self, Self::Err> {
        match Uri::from_str(token_uri) {
            Ok(uri) => Ok(Self(uri)),
            Err(err) => Err(NftTransferError::InvalidUri {
                uri: token_uri.to_string(),
                validation_error: err,
            }),
        }
    }
}

/// Token data for an NFT
#[cfg_attr(
    feature = "parity-scale-codec",
    derive(
        parity_scale_codec::Encode,
        parity_scale_codec::Decode,
        scale_info::TypeInfo
    )
)]
#[cfg_attr(
    feature = "borsh",
    derive(borsh::BorshSerialize, borsh::BorshDeserialize)
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq, derive_more::AsRef)]
pub struct TokenData(Data);

impl Display for TokenData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for TokenData {
    type Err = NftTransferError;

    fn from_str(token_data: &str) -> Result<Self, Self::Err> {
        let data = Data::from_str(token_data)?;
        Ok(Self(data))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(feature = "serde")]
    #[test]
    fn test_serde_json_roundtrip() {
        fn serde_roundtrip(token_uri: TokenUri) {
            let serialized =
                serde_json::to_string(&token_uri).expect("failed to serialize TokenUri");
            let deserialized = serde_json::from_str::<TokenUri>(&serialized)
                .expect("failed to deserialize TokenUri");

            assert_eq!(deserialized, token_uri);
        }

        let uri = "/foo/bar?baz".parse::<Uri>().unwrap();
        serde_roundtrip(TokenUri(uri));

        let uri = "https://www.rust-lang.org/install.html"
            .parse::<Uri>()
            .unwrap();
        serde_roundtrip(TokenUri(uri));
    }

    #[cfg(feature = "borsh")]
    #[test]
    fn test_borsh_roundtrip() {
        fn borsh_roundtrip(token_uri: TokenUri) {
            use borsh::{BorshDeserialize, BorshSerialize};

            let token_uri_bytes = token_uri.try_to_vec().unwrap();
            let res = TokenUri::try_from_slice(&token_uri_bytes).unwrap();

            assert_eq!(token_uri, res);
        }

        let uri = "/foo/bar?baz".parse::<Uri>().unwrap();
        borsh_roundtrip(TokenUri(uri));

        let uri = "https://www.rust-lang.org/install.html"
            .parse::<Uri>()
            .unwrap();
        borsh_roundtrip(TokenUri(uri));
    }
}