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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//  __________________________________________________________________________________________________
// |    Author: 	k3rn3lpanic
// |    Description: 	Defines the types used in the contract and implements some traits for converting
// |    them into byte arrays, or into JSON strings (and vice versa).
// |__________________________________________________________________________________________________

extern crate alloc;
use core::fmt::Display;

use alloc::{
    borrow::ToOwned,
    boxed::Box,
    collections::BTreeSet,
    format,
    string::{String, ToString},
    vec::Vec,
};
use casper_contract::contract_api::runtime::blake2b;
use casper_types::{
    account::AccountHash,
    bytesrepr::{Error, FromBytes, ToBytes},
    CLTyped,
};
/// Hash-len of the metadata, its blake2b so it would be 32 bytes
const METADATA_HASH_LENGTH: usize = 32;

/// Holds the hash of the metadata
pub struct MetadataHash(pub [u8; METADATA_HASH_LENGTH]);

impl AsStrized for MetadataHash {
    fn as_string(&self) -> String {
        base16::encode_lower(&self.0)
    }
}
/// This struct is used to store publish requests
pub struct PublishRequest {
    pub holder_id: u64,
    pub amount: u64,
    pub producer: AccountHash,
    pub publisher: AccountHash,
}
/// Metadata of the NFT, including name, uri, checksum, price and comission
pub struct NftMetadata {
    pub name: String,
    pub token_uri: String,
    pub checksum: String,
    pub price: u64,
    pub comission: u64,
}
/// NFTHolder : an amount and a token_id which identifies an NFT
pub struct NFTHolder {
    pub amount: u64,
    pub token_id: u64,
}

/// This struct is used to store the approved NFTs (approved to publish)
pub struct ApprovedNFT {
    pub holder_id: u64,
    pub amount: u64,
    pub owneraccount: AccountHash,
    pub publisheraccount: AccountHash,
    pub token_id: u64,
}

/// a simple wrapper for a set of u64
pub struct U64list {
    pub list: BTreeSet<u64>,
}

impl ToBytes for NftMetadata {
    fn to_bytes(&self) -> Result<Vec<u8>, casper_types::bytesrepr::Error> {
        let mut result = Vec::new();
        result.append(&mut self.name.to_bytes()?);
        result.append(&mut self.token_uri.to_bytes()?);
        result.append(&mut self.checksum.to_bytes()?);
        result.append(&mut self.price.to_bytes()?);
        result.append(&mut self.comission.to_bytes()?);
        Ok(result)
    }
    fn into_bytes(self) -> Result<Vec<u8>, casper_types::bytesrepr::Error>
    where
        Self: Sized,
    {
        self.to_bytes()
    }
    fn serialized_length(&self) -> usize {
        self.name.serialized_length()
            + self.token_uri.serialized_length()
            + self.checksum.serialized_length()
            + self.price.serialized_length()
            + self.comission.serialized_length()
    }
}

impl CLTyped for NftMetadata {
    fn cl_type() -> casper_types::CLType {
        casper_types::CLType::Any
    }
}

impl FromBytes for NftMetadata {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), casper_types::bytesrepr::Error> {
        let (name, rem) = FromBytes::from_bytes(bytes)?;
        let (token_uri, rem) = FromBytes::from_bytes(rem)?;
        let (checksum, rem) = FromBytes::from_bytes(rem)?;
        let (price, rem) = FromBytes::from_bytes(rem)?;
        let (comission, rem) = FromBytes::from_bytes(rem)?;
        Ok((
            NftMetadata {
                name,
                token_uri,
                checksum,
                price,
                comission,
            },
            rem,
        ))
    }
    fn from_vec(bytes: Vec<u8>) -> Result<(Self, Vec<u8>), casper_types::bytesrepr::Error> {
        Self::from_bytes(bytes.as_slice()).map(|(x, remainder)| (x, Vec::from(remainder)))
    }
}

impl NftMetadata {
    pub fn get_hash(&self) -> MetadataHash {
        return MetadataHash(blake2b(
            (self.name.as_str().to_owned()
                + self.token_uri.as_str()
                + self.checksum.as_str()
                + self.comission.to_string().as_str())
            .as_bytes(),
        ));
    }
    pub fn new(
        name: String,
        token_uri: String,
        checksum: String,
        price: u64,
        comission: u64,
    ) -> Self {
        NftMetadata {
            name,
            token_uri,
            checksum,
            price,
            comission,
        }
    }
    pub fn to_json(&self) -> String {
        format!("{{\"name\":\"{}\",\"token_uri\":\"{}\",\"checksum\":\"{}\",\"price\":\"{}\",\"comission\":\"{}\"}}",self.name,self.token_uri,self.checksum,self.price,self.comission)
    }
    pub fn from_json(json: String, price: u64, comission: u64) -> Result<Self, Error> {
        let split = json.split('\"');
        //TODO: use another functionality to get the name, token_uri and checksum from the json (this one depends on the index of the split)
        let mut name = String::new();
        let mut token_uri = String::new();
        let mut checksum = String::new();
        for (i, s) in split.enumerate() {
            if i == 3 {
                name = s.to_owned();
            }
            if i == 7 {
                token_uri = s.to_owned();
            }
            if i == 11 {
                checksum = s.to_owned();
            }
        }
        Ok(NftMetadata::new(
            name, token_uri, checksum, price, comission,
        ))
    }
}
impl Display for NftMetadata {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "{},{},{},{},{}",
            self.name, self.token_uri, self.checksum, self.price, self.comission
        )
    }
}

impl ToBytes for NFTHolder {
    fn to_bytes(&self) -> Result<Vec<u8>, casper_types::bytesrepr::Error> {
        let mut result = Vec::new();
        result.append(&mut self.amount.to_bytes()?);
        result.append(&mut self.token_id.to_bytes()?);
        Ok(result)
    }
    fn into_bytes(self) -> Result<Vec<u8>, casper_types::bytesrepr::Error>
    where
        Self: Sized,
    {
        self.to_bytes()
    }
    fn serialized_length(&self) -> usize {
        self.amount.serialized_length() + self.token_id.serialized_length()
    }
}

impl FromBytes for NFTHolder {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), casper_types::bytesrepr::Error> {
        let (amount, rem) = FromBytes::from_bytes(bytes)?;
        let (token_id, rem) = FromBytes::from_bytes(rem)?;
        Ok((NFTHolder { amount, token_id }, rem))
    }
    fn from_vec(bytes: Vec<u8>) -> Result<(Self, Vec<u8>), casper_types::bytesrepr::Error> {
        Self::from_bytes(bytes.as_slice()).map(|(x, remainder)| (x, Vec::from(remainder)))
    }
}

impl CLTyped for NFTHolder {
    fn cl_type() -> casper_types::CLType {
        casper_types::CLType::ByteArray(4u32)
    }
}

impl NFTHolder {
    pub fn new(amount: u64, token_id: u64) -> Self {
        NFTHolder { amount, token_id }
    }
}

impl Display for NFTHolder {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "{{\"amount\":\"{}\",\"token_id\":\"{}\"}}",
            self.amount, self.token_id
        )
    }
}

impl ToBytes for ApprovedNFT {
    fn to_bytes(&self) -> Result<Vec<u8>, casper_types::bytesrepr::Error> {
        let mut result = Vec::new();
        result.append(&mut self.holder_id.to_bytes()?);
        result.append(&mut self.amount.to_bytes()?);
        result.append(&mut self.owneraccount.to_bytes()?);
        result.append(&mut self.publisheraccount.to_bytes()?);
        result.append(&mut self.token_id.to_bytes()?);
        Ok(result)
    }
    fn into_bytes(self) -> Result<Vec<u8>, casper_types::bytesrepr::Error>
    where
        Self: Sized,
    {
        self.to_bytes()
    }
    fn serialized_length(&self) -> usize {
        self.holder_id.serialized_length()
            + self.amount.serialized_length()
            + self.owneraccount.serialized_length()
            + self.publisheraccount.serialized_length()
            + self.token_id.serialized_length()
    }
}

impl FromBytes for ApprovedNFT {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), casper_types::bytesrepr::Error> {
        let (holder_id, rem) = FromBytes::from_bytes(bytes)?;
        let (amount, rem) = FromBytes::from_bytes(rem)?;
        let (owneraccount, rem) = FromBytes::from_bytes(rem)?;
        let (publisheraccount, rem) = FromBytes::from_bytes(rem)?;
        let (token_id, rem) = FromBytes::from_bytes(rem)?;
        Ok((
            ApprovedNFT {
                holder_id,
                amount,
                owneraccount,
                publisheraccount,
                token_id,
            },
            rem,
        ))
    }
    fn from_vec(bytes: Vec<u8>) -> Result<(Self, Vec<u8>), casper_types::bytesrepr::Error> {
        Self::from_bytes(bytes.as_slice()).map(|(x, remainder)| (x, Vec::from(remainder)))
    }
}
impl CLTyped for ApprovedNFT {
    fn cl_type() -> casper_types::CLType {
        casper_types::CLType::Any
    }
}

impl ApprovedNFT {
    pub fn new(
        holder_id: u64,
        amount: u64,
        owneraccount: AccountHash,
        publisheraccount: AccountHash,
        token_id: u64,
    ) -> Self {
        ApprovedNFT {
            holder_id,
            amount,
            owneraccount,
            publisheraccount,
            token_id,
        }
    }
}
impl ToBytes for U64list {
    fn to_bytes(&self) -> Result<Vec<u8>, casper_types::bytesrepr::Error> {
        let mut result = Vec::new();
        result.append(&mut self.list.to_bytes()?);
        Ok(result)
    }
    fn into_bytes(self) -> Result<Vec<u8>, casper_types::bytesrepr::Error>
    where
        Self: Sized,
    {
        self.to_bytes()
    }
    fn serialized_length(&self) -> usize {
        self.list.serialized_length()
    }
}
impl FromBytes for U64list {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), casper_types::bytesrepr::Error> {
        let (list, rem) = FromBytes::from_bytes(bytes)?;
        Ok((U64list { list }, rem))
    }
    fn from_vec(bytes: Vec<u8>) -> Result<(Self, Vec<u8>), casper_types::bytesrepr::Error> {
        Self::from_bytes(bytes.as_slice()).map(|(x, remainder)| (x, Vec::from(remainder)))
    }
}
impl CLTyped for U64list {
    fn cl_type() -> casper_types::CLType {
        casper_types::CLType::List(Box::new(casper_types::CLType::U64))
    }
}
impl U64list {
    pub fn new() -> Self {
        U64list {
            list: BTreeSet::new(),
        }
    }
    pub fn remove(&mut self, value: u64) -> u64 {
        self.list.remove(&value);
        value
    }
    pub fn add(&mut self, value: u64) {
        self.list.insert(value);
    }
    pub fn contains(self, value: u64) -> bool {
        self.list.contains(&value)
    }
}
impl Default for U64list {
    fn default() -> Self {
        Self::new()
    }
}

impl ToBytes for PublishRequest {
    fn to_bytes(&self) -> Result<Vec<u8>, casper_types::bytesrepr::Error> {
        let mut result = Vec::new();
        result.append(&mut self.holder_id.to_bytes()?);
        result.append(&mut self.amount.to_bytes()?);
        result.append(&mut self.producer.to_bytes()?);
        result.append(&mut self.publisher.to_bytes()?);
        Ok(result)
    }
    fn into_bytes(self) -> Result<Vec<u8>, casper_types::bytesrepr::Error>
    where
        Self: Sized,
    {
        self.to_bytes()
    }
    fn serialized_length(&self) -> usize {
        self.holder_id.serialized_length()
            + self.amount.serialized_length()
            + self.producer.serialized_length()
            + self.publisher.serialized_length()
    }
}
impl FromBytes for PublishRequest {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), casper_types::bytesrepr::Error> {
        let (holder_id, rem) = FromBytes::from_bytes(bytes)?;
        let (amount, rem) = FromBytes::from_bytes(rem)?;
        let (producer, rem) = FromBytes::from_bytes(rem)?;
        let (publisher, rem) = FromBytes::from_bytes(rem)?;
        Ok((
            PublishRequest {
                holder_id,
                amount,
                producer,
                publisher,
            },
            rem,
        ))
    }
    fn from_vec(bytes: Vec<u8>) -> Result<(Self, Vec<u8>), casper_types::bytesrepr::Error> {
        Self::from_bytes(bytes.as_slice()).map(|(x, remainder)| (x, Vec::from(remainder)))
    }
}
impl CLTyped for PublishRequest {
    fn cl_type() -> casper_types::CLType {
        casper_types::CLType::ByteArray(20u32)
    }
}

impl PublishRequest {
    pub fn new(holder_id: u64, amount: u64, producer: AccountHash, publisher: AccountHash) -> Self {
        PublishRequest {
            holder_id,
            amount,
            producer,
            publisher,
        }
    }
}

/// Converts the given Strign to the type, used to convert hex encoded string to accounthash
pub trait FromStringize {
    fn from_string(string: String) -> Self;
}
impl FromStringize for AccountHash {
    fn from_string(string: String) -> Self {
        AccountHash::from_formatted_str(format!("account-hash-{}", string).as_str()).unwrap()
    }
}
/// Converts the given object to String, Its used to convert the AccountHash to base16 encoded string
pub trait AsStrized {
    fn as_string(&self) -> String;
}
impl AsStrized for AccountHash {
    fn as_string(&self) -> String {
        base16::encode_lower(&self.0)
    }
}