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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
use super::*;

use crate::types::*;
use frame_support::{sp_io::hashing::blake2_256, traits::tokens::nonfungibles::Inspect};
use frame_system::pallet_prelude::*;
use scale_info::prelude::string::String;

use pallet_rbac::types::*;

use frame_support::{pallet_prelude::*, traits::EnsureOriginWithArg, PalletId};
use scale_info::prelude::vec;
// use frame_support::traits::OriginTrait;
use sp_runtime::{sp_std::vec::Vec, traits::AccountIdConversion, Permill};
// use sp_runtime::traits::StaticLookup;

impl<T: Config> Pallet<T> {
  pub fn u32_to_instance_id(input: u32) -> T::ItemId
  where
    <T as pallet_uniques::Config>::ItemId: From<u32>,
  {
    T::ItemId::from(input)
  }

  pub fn u32_to_class_id(input: u32) -> T::CollectionId
  where
    <T as pallet_uniques::Config>::CollectionId: From<u32>,
  {
    T::CollectionId::from(input)
  }

  pub fn bytes_to_u32(input: Vec<u8>) -> u32 {
    u32::from_ne_bytes(input.try_into().unwrap())
  }

  pub fn percent_to_permill(input: u32) -> Permill {
    Permill::from_percent(input)
  }

  pub fn permill_to_percent(input: Permill) -> u32 {
    input.deconstruct() as u32
  }

  pub fn bytes_to_string(input: Vec<u8>) -> String {
    let mut s = String::default();
    for x in input {
      //let c: char = x.into();
      s.push(x as char);
    }
    s
  }

  pub fn account_id_to_lookup_source(
    account_id: &T::AccountId,
  ) -> <T::Lookup as sp_runtime::traits::StaticLookup>::Source {
    <T::Lookup as sp_runtime::traits::StaticLookup>::unlookup(account_id.clone())
  }

  pub fn dummy_description() -> CollectionDescription<T> {
    CollectionDescription::<T>::try_from(b"dummy description".to_vec()).unwrap()
  }

  pub fn dummy_attributes() -> Vec<(AttributeKey<T>, AttributeValue<T>)> {
    vec![(
      AttributeKey::<T>::try_from(b"dummy key".encode())
        .expect("Error on encoding key to BoundedVec"),
      AttributeValue::<T>::try_from(b"dummy value".encode())
        .expect("Error on encoding value to BoundedVec"),
    )]
  }

  /// Helper function for printing purposes
  pub fn get_nft_attribute(
    class_id: &T::CollectionId,
    instance_id: &T::ItemId,
    key: &[u8],
  ) -> AttributeValue<T> {
    if let Some(a) = pallet_uniques::Pallet::<T>::attribute(class_id, instance_id, key) {
      return BoundedVec::<u8, T::ValueLimit>::try_from(a)
        .expect("Error on converting the attribute to BoundedVec");
    }
    BoundedVec::<u8, T::ValueLimit>::default()
  }

  pub fn admin_of(class_id: &T::CollectionId, instance_id: &T::ItemId) -> Option<T::AccountId> {
    pallet_uniques::Pallet::<T>::owner(*class_id, *instance_id)
  }

  pub fn is_frozen(collection_id: &T::CollectionId, instance_id: &T::ItemId) -> bool {
    let frunique: FruniqueData<T> =
      <FruniqueInfo<T>>::try_get(&collection_id, &instance_id).unwrap();

    frunique.frozen
  }

  pub fn collection_exists(class_id: &T::CollectionId) -> bool {
    if let Some(_owner) = pallet_uniques::Pallet::<T>::collection_owner(*class_id) {
      return true;
    }
    false
  }

  pub fn instance_exists(class_id: &T::CollectionId, instance_id: &T::ItemId) -> bool {
    if let Some(_owner) = pallet_uniques::Pallet::<T>::owner(*class_id, *instance_id) {
      return true;
    }
    false
  }

  // helper to initialize the roles for the RBAC module
  pub fn do_initial_setup() -> DispatchResult {
    let pallet: IdOrVec = Self::pallet_id();

    let owner_role_ids =
      T::Rbac::create_and_set_roles(pallet.clone(), FruniqueRole::get_owner_roles())?;

    for owner_role in owner_role_ids {
      T::Rbac::create_and_set_permissions(
        pallet.clone(),
        owner_role,
        Permission::owner_permissions(),
      )?;
    }

    let admin_role_ids =
      T::Rbac::create_and_set_roles(pallet.clone(), FruniqueRole::get_admin_roles())?;

    for admin_role in admin_role_ids {
      T::Rbac::create_and_set_permissions(
        pallet.clone(),
        admin_role,
        Permission::admin_permissions(),
      )?;
    }

    let collaborator_role_ids =
      T::Rbac::create_and_set_roles(pallet.clone(), FruniqueRole::get_collaborator_roles())?;

    for collaborator_role in collaborator_role_ids {
      T::Rbac::create_and_set_permissions(
        pallet.clone(),
        collaborator_role,
        Permission::collaborator_permissions(),
      )?;
    }

    let collector_role_ids =
      T::Rbac::create_and_set_roles(pallet.clone(), FruniqueRole::get_collector_roles())?;

    for collector_role in collector_role_ids {
      T::Rbac::create_and_set_permissions(
        pallet.clone(),
        collector_role,
        Permission::collector_permissions(),
      )?;
    }

    let holder_role_ids =
      T::Rbac::create_and_set_roles(pallet.clone(), FruniqueRole::get_holder_roles())?;

    for holder_role in holder_role_ids {
      T::Rbac::create_and_set_permissions(
        pallet.clone(),
        holder_role,
        Permission::holder_permissions(),
      )?;
    }

    Ok(())
  }

  // Helper function to set an attribute to a given NFT
  pub fn set_attribute(
    origin: OriginFor<T>,
    class_id: &T::CollectionId,
    instance_id: T::ItemId,
    key: AttributeKey<T>,
    value: AttributeValue<T>,
  ) -> DispatchResult {
    pallet_uniques::Pallet::<T>::set_attribute(origin, *class_id, Some(instance_id), key, value)?;
    Ok(())
  }

  // Helper function to mint a new NFT
  pub fn do_mint(
    collection: T::CollectionId,
    owner: T::AccountId,
    metadata: CollectionDescription<T>,
    attributes: Option<Attributes<T>>,
  ) -> DispatchResult
  where
    <T as pallet_uniques::Config>::ItemId: From<u32>,
  {
    let nex_item: ItemId = <NextFrunique<T>>::try_get(collection).unwrap_or(0);
    <NextFrunique<T>>::insert(collection, nex_item + 1);

    let item = Self::u32_to_instance_id(nex_item);
    pallet_uniques::Pallet::<T>::do_mint(collection, item, owner, |_| Ok(()))?;

    pallet_uniques::Pallet::<T>::set_metadata(
      frame_system::RawOrigin::Root.into(),
      collection,
      item.clone(),
      metadata,
      false,
    )?;

    if let Some(attributes) = attributes {
      for (key, value) in attributes {
        pallet_uniques::Pallet::<T>::set_attribute(
          frame_system::RawOrigin::Root.into(),
          collection,
          Some(item),
          key,
          value,
        )?;
      }
    }

    Ok(())
  }

  pub fn do_freeze(class_id: &T::CollectionId, instance_id: T::ItemId) -> DispatchResult {
    <FruniqueInfo<T>>::try_mutate::<_, _, _, DispatchError, _>(
      class_id,
      instance_id,
      |frunique_data| -> DispatchResult {
        let frunique = frunique_data.as_mut().ok_or(Error::<T>::FruniqueNotFound)?;
        frunique.frozen = true;
        Ok(())
      },
    )?;
    Ok(())
  }

  pub fn do_thaw(class_id: &T::CollectionId, instance_id: T::ItemId) -> DispatchResult {
    <FruniqueInfo<T>>::try_mutate::<_, _, _, DispatchError, _>(
      class_id,
      instance_id,
      |frunique_data| -> DispatchResult {
        let frunique = frunique_data.as_mut().ok_or(Error::<T>::FruniqueNotFound)?;
        frunique.frozen = false;
        Ok(())
      },
    )?;
    Ok(())
  }

  pub fn burn(
    origin: OriginFor<T>,
    class_id: &T::CollectionId,
    instance_id: T::ItemId,
  ) -> DispatchResult {
    let admin = Self::admin_of(class_id, &instance_id);
    ensure!(admin.is_some(), "Instance is not owned by anyone");

    pallet_uniques::Pallet::<T>::burn(
      origin,
      *class_id,
      instance_id,
      Some(Self::account_id_to_lookup_source(&admin.unwrap())),
    )?;
    Ok(())
  }

  /// Helper function to create a new collection
  /// Creates a collection and updates its metadata if needed.
  pub fn do_create_collection(
    origin: OriginFor<T>,
    metadata: CollectionDescription<T>,
    admin: T::AccountId,
  ) -> Result<T::CollectionId, DispatchError>
  where
    <T as pallet_uniques::Config>::CollectionId: From<u32>,
  {
    let next_collection: u32 = Self::next_collection();
    let class_id = Self::u32_to_class_id(next_collection);

    let owner = T::CreateOrigin::ensure_origin(origin.clone(), &class_id)?;

    let scope_id = class_id.using_encoded(blake2_256);
    T::Rbac::create_scope(Self::pallet_id(), scope_id)?;

    Self::insert_auth_in_frunique_collection(owner.clone(), class_id, FruniqueRole::Owner)?;

    pallet_uniques::Pallet::<T>::do_create_collection(
      class_id,
      owner.clone(),
      admin.clone(),
      T::CollectionDeposit::get(),
      false,
      pallet_uniques::Event::Created { collection: class_id, creator: admin.clone(), owner },
    )?;

    pallet_uniques::Pallet::<T>::set_collection_metadata(
      origin,
      class_id.clone(),
      metadata,
      false,
    )?;

    <NextCollection<T>>::put(Self::next_collection() + 1);

    Ok(class_id)
  }

  // Create a new NFT for a given collection
  pub fn do_spawn(
    collection: T::CollectionId,
    owner: T::AccountId,
    metadata: CollectionDescription<T>,
    attributes: Option<Attributes<T>>,
    parent_info: Option<ParentInfo<T>>,
  ) -> DispatchResult
  where
    <T as pallet_uniques::Config>::ItemId: From<u32>,
  {
    ensure!(Self::collection_exists(&collection), Error::<T>::CollectionNotFound);

    let nex_item: ItemId = <NextFrunique<T>>::try_get(collection).unwrap_or(0);
    let item = Self::u32_to_instance_id(nex_item);

    Self::do_mint(collection, owner.clone(), metadata.clone(), attributes)?;

    if let Some(ref parent_info) = parent_info {
      return Self::do_nft_division(collection, item, metadata, parent_info, owner);
    }

    let frunique_data = FruniqueData {
      metadata,
      weight: Self::percent_to_permill(100),
      parent: None,
      children: None,
      verified: false,
      frozen: false,
      redeemed: false,
      spawned_by: Some(owner.clone()),
      verified_by: None,
    };

    <FruniqueInfo<T>>::insert(collection, item, frunique_data);
    <FruniqueRoots<T>>::insert(collection, item, true);

    Ok(())
  }

  // Takes cares of the division of the NFT
  pub fn do_nft_division(
    collection: T::CollectionId,
    item: T::ItemId,
    metadata: CollectionDescription<T>,
    parent_info: &ParentInfo<T>,
    user: T::AccountId,
  ) -> DispatchResult
  where
    <T as pallet_uniques::Config>::ItemId: From<u32>,
  {
    ensure!(Self::collection_exists(&parent_info.collection_id), Error::<T>::CollectionNotFound);
    ensure!(
      Self::instance_exists(&parent_info.collection_id, &parent_info.parent_id),
      Error::<T>::FruniqueNotFound
    );

    let frunique_parent: FruniqueData<T> =
      <FruniqueInfo<T>>::try_get(&parent_info.collection_id, &parent_info.parent_id).unwrap();

    ensure!(!frunique_parent.frozen, Error::<T>::ParentFrozen);
    ensure!(!frunique_parent.redeemed, Error::<T>::ParentAlreadyRedeemed);

    let child_percentage: Permill = parent_info.parent_weight * frunique_parent.weight;

    let parent_data: ParentInfo<T> = ParentInfo {
      collection_id: parent_info.collection_id,
      parent_id: parent_info.parent_id,
      parent_weight: child_percentage,
      is_hierarchical: parent_info.is_hierarchical,
    };

    let frunique_data: FruniqueData<T> = FruniqueData {
      metadata,
      weight: Self::percent_to_permill(100),
      parent: Some(parent_data),
      children: None,
      verified: false,
      frozen: false,
      redeemed: false,
      spawned_by: Some(user.clone()),
      verified_by: None,
    };

    <FruniqueInfo<T>>::insert(collection, item, frunique_data);

    let frunique_child: ChildInfo<T> = ChildInfo {
      collection_id: collection,
      child_id: item,
      weight_inherited: child_percentage,
      is_hierarchical: parent_info.is_hierarchical,
    };

    <FruniqueInfo<T>>::try_mutate::<_, _, _, DispatchError, _>(
      parent_info.collection_id,
      parent_info.parent_id,
      |frunique_data| -> DispatchResult {
        let frunique = frunique_data.as_mut().ok_or(Error::<T>::FruniqueNotFound)?;
        match frunique.children.as_mut() {
          Some(children) => children
            .try_push(frunique_child)
            .map_err(|_| Error::<T>::MaxNumberOfChildrenReached)?,
          None => {
            let child = frunique.children.get_or_insert(Children::default());
            child
              .try_push(frunique_child)
              .map_err(|_| Error::<T>::MaxNumberOfChildrenReached)?;
          },
        }
        frunique.weight = frunique.weight - child_percentage;
        Ok(())
      },
    )?;

    Ok(())
  }

  pub fn do_redeem(collection: T::CollectionId, item: T::ItemId) -> DispatchResult
  where
    <T as pallet_uniques::Config>::ItemId: From<u32>,
  {
    ensure!(Self::collection_exists(&collection), Error::<T>::CollectionNotFound);
    ensure!(Self::instance_exists(&collection, &item), Error::<T>::FruniqueNotFound);

    let frunique_data: FruniqueData<T> = <FruniqueInfo<T>>::try_get(collection, item).unwrap();

    ensure!(!frunique_data.frozen, Error::<T>::FruniqueFrozen);
    ensure!(!frunique_data.redeemed, Error::<T>::FruniqueAlreadyRedeemed);

    <FruniqueInfo<T>>::try_mutate::<_, _, _, DispatchError, _>(
      collection,
      item,
      |frunique_data| -> DispatchResult {
        let frunique = frunique_data.as_mut().ok_or(Error::<T>::FruniqueNotFound)?;
        frunique.redeemed = true;
        frunique.frozen = true;

        Ok(())
      },
    )?;

    <FruniqueRedeemed<T>>::insert(collection, item, true);

    Ok(())
  }

  pub fn get_nft_metadata(
    collection: T::CollectionId,
    item: T::ItemId,
  ) -> CollectionDescription<T> {
    let frunique_data = <FruniqueInfo<T>>::try_get(collection, item).unwrap();
    frunique_data.metadata
  }

  /// Helper functions to interact with the RBAC module
  pub fn pallet_id() -> IdOrVec {
    IdOrVec::Vec(Self::module_name().as_bytes().to_vec())
  }

  // Helper function to get the pallet account as a AccountId
  pub fn pallet_account() -> T::AccountId {
    let pallet_name = Self::module_name().as_bytes().to_vec();
    let pallet_account_name: [u8; 8] = pallet_name.as_slice().try_into().unwrap_or(*b"frunique");
    let pallet_id = PalletId(pallet_account_name);
    pallet_id.try_into_account().unwrap()
  }

  // Helper add RBAC roles for collections
  pub fn insert_auth_in_frunique_collection(
    user: T::AccountId,
    class_id: T::CollectionId,
    role: FruniqueRole,
  ) -> DispatchResult {
    T::Rbac::assign_role_to_user(
      user,
      Self::pallet_id(),
      &class_id.using_encoded(blake2_256),
      role.id(),
    )?;

    Ok(())
  }

  // Helper function to remove RBAC roles for collections
  pub fn remove_auth_from_frunique_collection(
    user: T::AccountId,
    class_id: T::CollectionId,
    role: FruniqueRole,
  ) -> DispatchResult {
    T::Rbac::remove_role_from_user(
      user,
      Self::pallet_id(),
      &class_id.using_encoded(blake2_256),
      role.id(),
    )?;

    Ok(())
  }

  // Helper function to check if a user has a specific role in a collection
  pub fn is_authorized(
    user: T::AccountId,
    collection_id: T::CollectionId,
    permission: Permission,
  ) -> DispatchResult {
    let scope_id = collection_id.using_encoded(blake2_256);
    <T as pallet::Config>::Rbac::is_authorized(user, Self::pallet_id(), &scope_id, &permission.id())
  }
}