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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
use super::*;
use crate::types::*;
use frame_support::pallet_prelude::*;
use frame_support::sp_io::hashing::blake2_256;
use frame_support::traits::Time;
use frame_system::pallet_prelude::*;
use frame_system::RawOrigin;
use pallet_rbac::types::*;
use scale_info::prelude::vec; // vec![] macro
use sp_runtime::sp_std::vec::Vec; // vec primitive
use sp_runtime::traits::StaticLookup;
use sp_runtime::Permill;

impl<T: Config> Pallet<T> {
  pub fn do_initial_setup() -> DispatchResult {
    let pallet_id = Self::pallet_id();
    let super_roles = vec![MarketplaceRole::Owner.to_vec(), MarketplaceRole::Admin.to_vec()];
    let super_role_ids =
      <T as pallet::Config>::Rbac::create_and_set_roles(pallet_id.clone(), super_roles)?;
    for super_role in super_role_ids {
      <T as pallet::Config>::Rbac::create_and_set_permissions(
        pallet_id.clone(),
        super_role,
        Permission::admin_permissions(),
      )?;
    }
    // participant role and permissions
    let participant_role_id = <T as pallet::Config>::Rbac::create_and_set_roles(
      pallet_id.clone(),
      [MarketplaceRole::Participant.to_vec()].to_vec(),
    )?;
    <T as pallet::Config>::Rbac::create_and_set_permissions(
      pallet_id.clone(),
      participant_role_id[0],
      Permission::participant_permissions(),
    )?;
    // appraiser role and permissions
    let _appraiser_role_id = <T as pallet::Config>::Rbac::create_and_set_roles(
      pallet_id.clone(),
      [MarketplaceRole::Appraiser.to_vec()].to_vec(),
    )?;
    // redemption specialist role and permissions
    let _redemption_role_id = <T as pallet::Config>::Rbac::create_and_set_roles(
      pallet_id,
      [MarketplaceRole::RedemptionSpecialist.to_vec()].to_vec(),
    )?;

    Self::deposit_event(Event::MarketplaceSetupCompleted);
    Ok(())
  }

  pub fn do_create_marketplace(
    origin: OriginFor<T>,
    admin: T::AccountId,
    marketplace: Marketplace<T>,
  ) -> DispatchResult {
    let owner = ensure_signed(origin.clone())?;
    // Gen market id
    let marketplace_id = marketplace.using_encoded(blake2_256);

    // ensure the generated id is unique
    ensure!(!<Marketplaces<T>>::contains_key(marketplace_id), Error::<T>::MarketplaceAlreadyExists);

    //Insert on marketplaces and marketplaces by auth
    <T as pallet::Config>::Rbac::create_scope(Self::pallet_id(), marketplace_id)?;
    Self::insert_in_auth_market_lists(owner.clone(), MarketplaceRole::Owner, marketplace_id)?;
    Self::insert_in_auth_market_lists(admin.clone(), MarketplaceRole::Admin, marketplace_id)?;
    <Marketplaces<T>>::insert(marketplace_id, marketplace);
    Self::deposit_event(Event::MarketplaceStored(owner, admin, marketplace_id));
    Ok(())
  }

  pub fn do_apply(
    applicant: T::AccountId,
    custodian: Option<T::AccountId>,
    marketplace_id: [u8; 32],
    application: Application<T>,
  ) -> DispatchResult {
    // marketplace exists?
    ensure!(<Marketplaces<T>>::contains_key(marketplace_id), Error::<T>::MarketplaceNotFound);
    // Ensure the user is not blocked
    ensure!(!Self::is_user_blocked(applicant.clone(), marketplace_id), Error::<T>::UserIsBlocked);
    // The user only can apply once by marketplace
    ensure!(
      !<ApplicationsByAccount<T>>::contains_key(applicant.clone(), marketplace_id),
      Error::<T>::AlreadyApplied
    );
    // Generate application Id
    let app_id = (marketplace_id, applicant.clone(), application.clone()).using_encoded(blake2_256);
    // Ensure another identical application doesnt exists
    ensure!(!<Applications<T>>::contains_key(app_id), Error::<T>::AlreadyApplied);

    if let Some(c) = custodian {
      // Ensure applicant and custodian arent the same
      ensure!(applicant.ne(&c), Error::<T>::ApplicantCannotBeCustodian);
      Self::insert_custodian(c, marketplace_id, applicant.clone())?;
    }

    Self::insert_in_applicants_lists(
      applicant.clone(),
      ApplicationStatus::default(),
      marketplace_id,
    )?;
    <ApplicationsByAccount<T>>::insert(applicant, marketplace_id, app_id);
    <Applications<T>>::insert(app_id, application);

    Self::deposit_event(Event::ApplicationStored(app_id, marketplace_id));
    Ok(())
  }

  pub fn do_invite(
    authority: T::AccountId,
    marketplace_id: [u8; 32],
    new_user: T::AccountId,
    fields: Fields<T>,
    custodian_fields: Option<CustodianFields<T>>,
  ) -> DispatchResult {
    ensure!(<Marketplaces<T>>::contains_key(marketplace_id), Error::<T>::MarketplaceNotFound);
    // Ensure the user is not blocked
    ensure!(!Self::is_user_blocked(new_user.clone(), marketplace_id), Error::<T>::UserIsBlocked);
    // The user only can apply once by marketplace
    ensure!(
      !<ApplicationsByAccount<T>>::contains_key(new_user.clone(), marketplace_id),
      Error::<T>::AlreadyApplied
    );
    // ensure the origin is owner or admin
    Self::is_authorized(authority.clone(), &marketplace_id, Permission::Enroll)?;

    let (custodian, fields) = Self::set_up_application(fields, custodian_fields);

    let application = Application::<T> {
      status: ApplicationStatus::default(),
      fields,
      feedback: BoundedVec::<u8, T::MaxFeedbackLen>::default(),
    };

    Self::do_apply(new_user.clone(), custodian, marketplace_id, application)?;

    Self::do_enroll(
      authority,
      marketplace_id,
      AccountOrApplication::Account(new_user),
      true,
      BoundedVec::<u8, T::MaxFeedbackLen>::try_from(
        b"User enrolled by the marketplace admin".to_vec(),
      )
      .unwrap(),
    )?;

    Ok(())
  }

  pub fn do_enroll(
    authority: T::AccountId,
    marketplace_id: [u8; 32],
    account_or_application: AccountOrApplication<T>,
    approved: bool,
    feedback: BoundedVec<u8, T::MaxFeedbackLen>,
  ) -> DispatchResult {
    // ensure the origin is owner or admin
    Self::is_authorized(authority, &marketplace_id, Permission::Enroll)?;
    let next_status = match approved {
      true => ApplicationStatus::Approved,
      false => ApplicationStatus::Rejected,
    };
    let applicant = match account_or_application.clone() {
      AccountOrApplication::Account(acc) => acc,
      AccountOrApplication::Application(application_id) => <ApplicationsByAccount<T>>::iter()
        .find_map(|(acc, m_id, app_id)| {
          if m_id == marketplace_id && app_id == application_id {
            return Some(acc);
          }
          None
        })
        .ok_or(Error::<T>::ApplicationNotFound)?,
    };
    // ensure the account is not blocked
    ensure!(!Self::is_user_blocked(applicant.clone(), marketplace_id), Error::<T>::UserIsBlocked);
    Self::change_applicant_status(applicant, marketplace_id, next_status, feedback)?;

    Self::deposit_event(Event::ApplicationProcessed(
      account_or_application,
      marketplace_id,
      next_status,
    ));
    Ok(())
  }

  pub fn do_authority(
    authority: T::AccountId,
    account: T::AccountId,
    authority_type: MarketplaceRole,
    marketplace_id: [u8; 32],
  ) -> DispatchResult {
    //ensure the origin is owner or admin
    //TODO: implement copy trait for MarketplaceAuthority & T::AccountId
    //Self::can_enroll(authority, marketplace_id)?;
    Self::is_authorized(authority, &marketplace_id, Permission::AddAuth)?;
    //ensure the account is not already an authority
    // handled by <T as pallet::Config>::Rbac::assign_role_to_user
    //ensure!(!Self::does_exist_authority(account.clone(), marketplace_id, authority_type), Error::<T>::AlreadyApplied);

    // ensure the account is not blocked
    ensure!(!Self::is_user_blocked(account.clone(), marketplace_id), Error::<T>::UserIsBlocked);
    match authority_type {
      MarketplaceRole::Owner => {
        ensure!(!Self::owner_exist(marketplace_id), Error::<T>::OnlyOneOwnerIsAllowed);
        Self::insert_in_auth_market_lists(account.clone(), authority_type, marketplace_id)?;
      },
      _ => {
        Self::insert_in_auth_market_lists(account.clone(), authority_type, marketplace_id)?;
      },
    }

    Self::deposit_event(Event::AuthorityAdded(account, authority_type));
    Ok(())
  }

  pub fn self_enroll(account: T::AccountId, marketplace_id: [u8; 32]) -> DispatchResult {
    //since users can self-enroll, the caller of this function must validate
    //that the user is indeed the owner of the address by using ensure_signed

    //ensure the account is not already in the marketplace
    ensure!(
      !Self::has_any_role(account.clone(), &marketplace_id),
      Error::<T>::UserAlreadyParticipant
    );

    // ensure the account is not blocked by the marketplace
    ensure!(!Self::is_user_blocked(account.clone(), marketplace_id), Error::<T>::UserIsBlocked);

    // ensure the marketplace exist
    ensure!(<Marketplaces<T>>::contains_key(marketplace_id), Error::<T>::MarketplaceNotFound);

    Self::insert_in_auth_market_lists(
      account.clone(),
      MarketplaceRole::Participant,
      marketplace_id,
    )?;
    Self::deposit_event(Event::AuthorityAdded(account, MarketplaceRole::Participant));

    Ok(())
  }

  pub fn do_remove_authority(
    authority: T::AccountId,
    account: T::AccountId,
    authority_type: MarketplaceRole,
    marketplace_id: [u8; 32],
  ) -> DispatchResult {
    //ensure the origin is owner or admin
    //Self::can_enroll(authority.clone(), marketplace_id)?;
    Self::is_authorized(authority.clone(), &marketplace_id, Permission::RemoveAuth)?;
    //ensure the account has the selected authority before to try to remove
    // <T as pallet::Config>::Rbac handles the if role doesnt hasnt been asigned to the user
    //ensure!(Self::does_exist_authority(account.clone(), marketplace_id, authority_type), Error::<T>::AuthorityNotFoundForUser);

    match authority_type {
      MarketplaceRole::Owner => {
        ensure!(Self::owner_exist(marketplace_id), Error::<T>::OwnerNotFound);
        return Err(Error::<T>::CantRemoveOwner.into());
      },
      MarketplaceRole::Admin => {
        // Admins can not delete themselves
        ensure!(authority != account, Error::<T>::AdminCannotRemoveItself);

        // Admis cannot be deleted between them, only the owner can
        ensure!(!Self::is_admin(authority, marketplace_id), Error::<T>::CannotDeleteAdmin);

        Self::remove_from_market_lists(account.clone(), authority_type, marketplace_id)?;
      },
      _ => {
        Self::remove_from_market_lists(account.clone(), authority_type, marketplace_id)?;
      },
    }

    Self::deposit_event(Event::AuthorityRemoved(account, authority_type));
    Ok(())
  }

  pub fn do_update_label_marketplace(
    authority: T::AccountId,
    marketplace_id: [u8; 32],
    new_label: BoundedVec<u8, T::LabelMaxLen>,
  ) -> DispatchResult {
    //ensure the marketplace exists
    ensure!(<Marketplaces<T>>::contains_key(marketplace_id), Error::<T>::MarketplaceNotFound);
    //ensure the origin is owner or admin
    //Self::can_enroll(authority, marketplace_id)?;
    Self::is_authorized(authority, &marketplace_id, Permission::UpdateLabel)?;
    //update marketplace
    Self::update_label(marketplace_id, new_label)?;
    Self::deposit_event(Event::MarketplaceLabelUpdated(marketplace_id));
    Ok(())
  }

  pub fn do_remove_marketplace(
    authority: T::AccountId,
    marketplace_id: [u8; 32],
  ) -> DispatchResult {
    //ensure the marketplace exists
    ensure!(<Marketplaces<T>>::contains_key(marketplace_id), Error::<T>::MarketplaceNotFound);
    //ensure the origin is owner or admin
    //Self::can_enroll(authority, marketplace_id)?;
    Self::is_authorized(authority, &marketplace_id, Permission::RemoveMarketplace)?;
    //remove marketplace
    Self::remove_selected_marketplace(marketplace_id)?;
    Self::deposit_event(Event::MarketplaceRemoved(marketplace_id));
    Ok(())
  }

  pub fn do_enlist_sell_offer(
    authority: T::AccountId,
    marketplace_id: [u8; 32],
    collection_id: T::CollectionId,
    item_id: T::ItemId,
    price: T::Balance,
    percentage: u32,
  ) -> Result<[u8; 32], DispatchError> {
    //This function is only called by the owner of the marketplace
    //ensure the marketplace exists
    ensure!(<Marketplaces<T>>::contains_key(marketplace_id), Error::<T>::MarketplaceNotFound);
    Self::is_authorized(authority.clone(), &marketplace_id, Permission::EnlistSellOffer)?;
    //ensure the collection exists
    if let Some(a) = pallet_uniques::Pallet::<T>::owner(collection_id, item_id) {
      ensure!(a == authority, Error::<T>::NotOwner);
    } else {
      return Err(Error::<T>::CollectionNotFound.into());
    }

    //ensure the price is valid
    Self::is_the_offer_valid(price, Permill::from_percent(percentage))?;

    //Add timestamp to the offer
    let creation_date = Self::get_timestamp_in_milliseconds().ok_or(Error::<T>::TimestampError)?;

    //create offer structure

    let marketplace =
      <Marketplaces<T>>::get(marketplace_id).ok_or(Error::<T>::MarketplaceNotFound)?;

    let offer_data = OfferData::<T> {
      marketplace_id,
      collection_id,
      item_id,
      creator: authority.clone(),
      price,
      fee: price * Permill::deconstruct(marketplace.sell_fee).into() / 1_000_000u32.into(),
      percentage: Permill::from_percent(percentage),
      creation_date,
      status: OfferStatus::Open,
      offer_type: OfferType::SellOrder,
      buyer: None,
    };

    //create an offer_id
    let offer_id = offer_data.using_encoded(blake2_256);

    //insert in OffersByItem
    <OffersByItem<T>>::try_mutate(collection_id, item_id, |offers| offers.try_push(offer_id))
      .map_err(|_| Error::<T>::OfferStorageError)?;

    //insert in OffersByAccount
    <OffersByAccount<T>>::try_mutate(authority, |offers| offers.try_push(offer_id))
      .map_err(|_| Error::<T>::OfferStorageError)?;

    //insert in OffersInfo
    // ensure the offer_id doesn't exist
    ensure!(!<OffersInfo<T>>::contains_key(offer_id), Error::<T>::OfferAlreadyExists);
    <OffersInfo<T>>::insert(offer_id, offer_data);

    //Insert in OffersByMarketplace
    <OffersByMarketplace<T>>::try_mutate(marketplace_id, |offers| offers.try_push(offer_id))
      .map_err(|_| Error::<T>::OfferStorageError)?;

    pallet_fruniques::Pallet::<T>::do_freeze(&collection_id, item_id)?;

    Self::deposit_event(Event::OfferStored(collection_id, item_id, offer_id));
    Ok(offer_id)
  }

  pub fn do_enlist_buy_offer(
    authority: T::AccountId,
    marketplace_id: [u8; 32],
    collection_id: T::CollectionId,
    item_id: T::ItemId,
    price: T::Balance,
    percentage: u32,
  ) -> Result<[u8; 32], DispatchError> {
    //ensure the marketplace exists
    ensure!(<Marketplaces<T>>::contains_key(marketplace_id), Error::<T>::MarketplaceNotFound);

    //ensure the collection exists
    //For this case user doesn't need to be the owner of the collection
    //but the owner of the item cannot create a buy offer for their own collection
    if let Some(a) = pallet_uniques::Pallet::<T>::owner(collection_id, item_id) {
      ensure!(a != authority, Error::<T>::CannotCreateOffer);
    } else {
      return Err(Error::<T>::CollectionNotFound.into());
    }

    //ensure the holder of NFT is in the same marketplace as the caller making the offer
    Self::can_this_item_receive_buy_orders(
      &marketplace_id,
      authority.clone(),
      &collection_id,
      &item_id,
    )?;

    //Get asset id
    let asset_id = <Marketplaces<T>>::get(marketplace_id)
      .ok_or(Error::<T>::MarketplaceNotFound)?
      .asset_id;

    //ensure user has enough balance to create the offer
    let total_user_balance =
      pallet_mapped_assets::Pallet::<T>::balance(asset_id, authority.clone());

    ensure!(total_user_balance >= price, Error::<T>::NotEnoughBalance);

    //ensure the price is valid
    Self::is_the_offer_valid(price, Permill::from_percent(percentage))?;

    //Add timestamp to the offer
    let creation_date = Self::get_timestamp_in_milliseconds().ok_or(Error::<T>::TimestampError)?;

    //create offer structure
    let marketplace =
      <Marketplaces<T>>::get(marketplace_id).ok_or(Error::<T>::MarketplaceNotFound)?;
    let offer_data = OfferData::<T> {
      marketplace_id,
      collection_id,
      item_id,
      creator: authority.clone(),
      price,
      fee: price * Permill::deconstruct(marketplace.buy_fee).into() / 1_000_000u32.into(),
      percentage: Permill::from_percent(percentage),
      creation_date,
      status: OfferStatus::Open,
      offer_type: OfferType::BuyOrder,
      buyer: None,
    };

    //create an offer_id
    let offer_id = offer_data.using_encoded(blake2_256);

    //insert in OffersByItem
    //An item can receive multiple buy offers
    <OffersByItem<T>>::try_mutate(collection_id, item_id, |offers| offers.try_push(offer_id))
      .map_err(|_| Error::<T>::OfferStorageError)?;

    //insert in OffersByAccount
    <OffersByAccount<T>>::try_mutate(authority, |offers| offers.try_push(offer_id))
      .map_err(|_| Error::<T>::OfferStorageError)?;

    //insert in OffersInfo
    // ensure the offer_id doesn't exist
    ensure!(!<OffersInfo<T>>::contains_key(offer_id), Error::<T>::OfferAlreadyExists);
    <OffersInfo<T>>::insert(offer_id, offer_data);

    //Insert in OffersByMarketplace
    <OffersByMarketplace<T>>::try_mutate(marketplace_id, |offers| offers.try_push(offer_id))
      .map_err(|_| Error::<T>::OfferStorageError)?;

    Self::deposit_event(Event::OfferStored(collection_id, item_id, offer_id));

    Ok(offer_id)
  }

  pub fn do_take_sell_offer(origin: OriginFor<T>, offer_id: [u8; 32]) -> DispatchResult
  where
    <T as pallet_uniques::Config>::ItemId: From<u32>,
  {
    //This extrinsic is called by the user who wants to buy the item
    //get offer data
    let buyer = ensure_signed(origin.clone())?;
    let offer_data = <OffersInfo<T>>::get(offer_id).ok_or(Error::<T>::OfferNotFound)?;
    let marketplace_id = offer_data.marketplace_id;

    Self::is_authorized(buyer.clone(), &offer_data.marketplace_id, Permission::TakeSellOffer)?;

    //ensure the collection & owner exists
    let owner_item =
      pallet_uniques::Pallet::<T>::owner(offer_data.collection_id, offer_data.item_id)
        .ok_or(Error::<T>::OwnerNotFound)?;

    //ensure owner is not the same as the buyer
    ensure!(owner_item != buyer, Error::<T>::CannotTakeOffer);

    //ensure the offer_id exists in OffersByItem
    Self::does_exist_offer_id_for_this_item(
      offer_data.collection_id,
      offer_data.item_id,
      offer_id,
    )?;

    //ensure the offer is open and available
    ensure!(offer_data.status == OfferStatus::Open, Error::<T>::OfferIsNotAvailable);
    //TODO: Use free_balance instead of total_balance
    //Get asset id
    let asset_id = <Marketplaces<T>>::get(marketplace_id)
      .ok_or(Error::<T>::MarketplaceNotFound)?
      .asset_id;

    //ensure user has enough balance to create the offer
    let total_amount_buyer =
      pallet_mapped_assets::Pallet::<T>::balance(asset_id.clone(), buyer.clone());
    //ensure the buyer has enough balance to buy the item
    ensure!(total_amount_buyer > offer_data.price, Error::<T>::NotEnoughBalance);

    let marketplace =
      <Marketplaces<T>>::get(offer_data.marketplace_id).ok_or(Error::<T>::OfferNotFound)?;
    let owners_cut: T::Balance = offer_data.price - offer_data.fee;

    //Transfer the balance
    pallet_mapped_assets::Pallet::<T>::transfer(
      origin.clone(),
      asset_id.clone().into(),
      T::Lookup::unlookup(owner_item.clone()),
      owners_cut,
    )?;

    pallet_mapped_assets::Pallet::<T>::transfer(
      origin.clone(),
      asset_id.clone().into(),
      T::Lookup::unlookup(marketplace.creator.clone()),
      offer_data.fee,
    )?;

    pallet_fruniques::Pallet::<T>::do_thaw(&offer_data.collection_id, offer_data.item_id)?;
    if offer_data.percentage == Permill::from_percent(100) {
      //Use uniques transfer function to transfer the item to the buyer
      pallet_uniques::Pallet::<T>::do_transfer(
        offer_data.collection_id,
        offer_data.item_id,
        buyer.clone(),
        |_, _| Ok(()),
      )?;
    } else {
      let parent_info = pallet_fruniques::types::ParentInfo {
        collection_id: offer_data.collection_id,
        parent_id: offer_data.item_id,
        parent_weight: offer_data.percentage,
        is_hierarchical: true,
      };
      let metadata = pallet_fruniques::Pallet::<T>::get_nft_metadata(
        offer_data.collection_id,
        offer_data.item_id,
      );

      pallet_fruniques::Pallet::<T>::do_spawn(
        offer_data.collection_id,
        buyer.clone(),
        metadata,
        None,
        Some(parent_info),
      )?;
    }

    //update offer status from all marketplaces
    Self::update_offers_status(
      buyer.clone(),
      offer_data.collection_id,
      offer_data.item_id,
      offer_data.marketplace_id,
    )?;

    //remove all the offers associated with the item
    Self::delete_all_offers_for_this_item(offer_data.collection_id, offer_data.item_id)?;

    Self::deposit_event(Event::OfferWasAccepted(offer_id, buyer));
    Ok(())
  }

  pub fn do_take_buy_offer(authority: T::AccountId, offer_id: [u8; 32]) -> DispatchResult
  where
    <T as pallet_uniques::Config>::ItemId: From<u32>,
  {
    //This extrinsic is called by the owner of the item who accepts the buy offer created by a marketparticipant
    //get offer data
    let offer_data = <OffersInfo<T>>::get(offer_id).ok_or(Error::<T>::OfferNotFound)?;

    Self::is_authorized(authority.clone(), &offer_data.marketplace_id, Permission::TakeBuyOffer)?;

    //ensure the collection & owner exists
    let owner_item =
      pallet_uniques::Pallet::<T>::owner(offer_data.collection_id, offer_data.item_id)
        .ok_or(Error::<T>::OwnerNotFound)?;

    //ensure only owner of the item can call the extrinsic
    ensure!(owner_item == authority, Error::<T>::NotOwner);

    //ensure owner is not the same as the buy_offer_creator
    ensure!(owner_item != offer_data.creator, Error::<T>::CannotTakeOffer);

    //ensure the offer_id exists in OffersByItem
    Self::does_exist_offer_id_for_this_item(
      offer_data.collection_id,
      offer_data.item_id,
      offer_id,
    )?;

    //ensure the offer is open and available
    ensure!(offer_data.status == OfferStatus::Open, Error::<T>::OfferIsNotAvailable);

    let marketplace_id = offer_data.marketplace_id;
    //Get asset id
    let asset_id = <Marketplaces<T>>::get(marketplace_id)
      .ok_or(Error::<T>::MarketplaceNotFound)?
      .asset_id;

    //ensure user has enough balance to create the offer
    let total_amount_buyer =
      pallet_mapped_assets::Pallet::<T>::balance(asset_id.clone(), offer_data.creator.clone());
    //ensure the buy_offer_creator has enough balance to buy the item
    ensure!(total_amount_buyer > offer_data.price, Error::<T>::NotEnoughBalance);

    let marketplace =
      <Marketplaces<T>>::get(offer_data.marketplace_id).ok_or(Error::<T>::OfferNotFound)?;
    let owners_cut: T::Balance = offer_data.price - offer_data.fee;
    //Transfer the balance to the owner of the item
    pallet_mapped_assets::Pallet::<T>::transfer(
      RawOrigin::Signed(offer_data.creator.clone()).into(),
      asset_id.clone().into(),
      T::Lookup::unlookup(owner_item.clone()),
      owners_cut,
    )?;

    pallet_mapped_assets::Pallet::<T>::transfer(
      RawOrigin::Signed(offer_data.creator.clone()).into(),
      asset_id.clone().into(),
      T::Lookup::unlookup(marketplace.creator.clone()),
      offer_data.fee,
    )?;

    pallet_fruniques::Pallet::<T>::do_thaw(&offer_data.collection_id, offer_data.item_id)?;

    if offer_data.percentage == Permill::from_percent(100) {
      //Use uniques transfer function to transfer the item to the buyer
      pallet_uniques::Pallet::<T>::do_transfer(
        offer_data.collection_id,
        offer_data.item_id,
        offer_data.creator.clone(),
        |_, _| Ok(()),
      )?;
    } else {
      let parent_info = pallet_fruniques::types::ParentInfo {
        collection_id: offer_data.collection_id,
        parent_id: offer_data.item_id,
        parent_weight: offer_data.percentage,
        is_hierarchical: true,
      };
      let metadata = pallet_fruniques::Pallet::<T>::get_nft_metadata(
        offer_data.collection_id,
        offer_data.item_id,
      );

      pallet_fruniques::Pallet::<T>::do_spawn(
        offer_data.collection_id,
        offer_data.creator.clone(),
        metadata,
        None,
        Some(parent_info),
      )?;
    }

    //update offer status from all marketplaces
    Self::update_offers_status(
      offer_data.creator.clone(),
      offer_data.collection_id,
      offer_data.item_id,
      offer_data.marketplace_id,
    )?;

    //remove all the offers associated with the item
    Self::delete_all_offers_for_this_item(offer_data.collection_id, offer_data.item_id)?;

    Self::deposit_event(Event::OfferWasAccepted(offer_id, offer_data.creator));
    Ok(())
  }

  pub fn do_remove_offer(authority: T::AccountId, offer_id: [u8; 32]) -> DispatchResult {
    //ensure the offer_id exists
    ensure!(<OffersInfo<T>>::contains_key(offer_id), Error::<T>::OfferNotFound);

    //get offer data
    let offer_data = <OffersInfo<T>>::get(offer_id).ok_or(Error::<T>::OfferNotFound)?;
    Self::is_authorized(authority.clone(), &offer_data.marketplace_id, Permission::RemoveOffer)?;

    //ensure the offer status is Open
    ensure!(offer_data.status == OfferStatus::Open, Error::<T>::CannotDeleteOffer);

    // ensure the authority is the creator of the offer
    ensure!(offer_data.creator == authority, Error::<T>::CannotRemoveOffer);

    //ensure the offer_id exists in OffersByItem
    Self::does_exist_offer_id_for_this_item(
      offer_data.collection_id,
      offer_data.item_id,
      offer_id,
    )?;

    if offer_data.offer_type == OfferType::SellOrder {
      pallet_fruniques::Pallet::<T>::do_thaw(&offer_data.collection_id, offer_data.item_id)?;
    }

    //remove the offer from OfferInfo
    <OffersInfo<T>>::remove(offer_id);

    //remove the offer from OffersByMarketplace
    <OffersByMarketplace<T>>::try_mutate(offer_data.marketplace_id, |offers| {
      let offer_index =
        offers.iter().position(|x| *x == offer_id).ok_or(Error::<T>::OfferNotFound)?;
      offers.remove(offer_index);
      Ok(())
    })
    .map_err(|_: Error<T>| Error::<T>::OfferNotFound)?;

    //remove the offer from OffersByAccount
    <OffersByAccount<T>>::try_mutate(authority, |offers| {
      let offer_index =
        offers.iter().position(|x| *x == offer_id).ok_or(Error::<T>::OfferNotFound)?;
      offers.remove(offer_index);
      Ok(())
    })
    .map_err(|_: Error<T>| Error::<T>::OfferNotFound)?;

    //remove the offer from OffersByItem
    <OffersByItem<T>>::try_mutate(offer_data.collection_id, offer_data.item_id, |offers| {
      let offer_index =
        offers.iter().position(|x| *x == offer_id).ok_or(Error::<T>::OfferNotFound)?;
      offers.remove(offer_index);
      Ok(())
    })
    .map_err(|_: Error<T>| Error::<T>::OfferNotFound)?;

    Self::deposit_event(Event::OfferRemoved(offer_id, offer_data.marketplace_id));

    Ok(())
  }

  /*---- Helper functions ----*/

  pub fn set_up_application(
    fields: Fields<T>,
    custodian_fields: Option<CustodianFields<T>>,
  ) -> (Option<T::AccountId>, BoundedVec<ApplicationField, T::MaxFiles>) {
    let mut f: Vec<ApplicationField> = fields
      .iter()
      .map(|tuple| ApplicationField {
        display_name: tuple.0.clone(),
        cid: tuple.1.clone(),
        custodian_cid: None,
      })
      .collect();
    let custodian = match custodian_fields {
      Some(c_fields) => {
        for (i, field) in f.iter_mut().enumerate() {
          field.custodian_cid = Some(c_fields.1[i].clone());
        }

        Some(c_fields.0)
      },
      _ => None,
    };
    (custodian, BoundedVec::<ApplicationField, T::MaxFiles>::try_from(f).unwrap_or_default())
  }

  fn insert_in_auth_market_lists(
    authority: T::AccountId,
    role: MarketplaceRole,
    marketplace_id: [u8; 32],
  ) -> DispatchResult {
    <T as pallet::Config>::Rbac::assign_role_to_user(
      authority,
      Self::pallet_id(),
      &marketplace_id,
      role.id(),
    )?;

    Ok(())
  }

  fn insert_in_applicants_lists(
    applicant: T::AccountId,
    status: ApplicationStatus,
    marketplace_id: [u8; 32],
  ) -> DispatchResult {
    <ApplicantsByMarketplace<T>>::try_mutate(marketplace_id, status, |applicants| {
      applicants.try_push(applicant)
    })
    .map_err(|_| Error::<T>::ExceedMaxApplicants)?;

    Ok(())
  }

  fn insert_custodian(
    custodian: T::AccountId,
    marketplace_id: [u8; 32],
    applicant: T::AccountId,
  ) -> DispatchResult {
    <Custodians<T>>::try_mutate(custodian, marketplace_id, |applications| {
      applications.try_push(applicant)
    })
    .map_err(|_| Error::<T>::ExceedMaxApplicationsPerCustodian)?;

    Ok(())
  }

  fn remove_from_applicants_lists(
    applicant: T::AccountId,
    status: ApplicationStatus,
    marketplace_id: [u8; 32],
  ) -> DispatchResult {
    <ApplicantsByMarketplace<T>>::try_mutate::<_, _, _, DispatchError, _>(
      marketplace_id,
      status,
      |applicants| {
        let applicant_index = applicants
          .iter()
          .position(|a| *a == applicant.clone())
          .ok_or(Error::<T>::ApplicantNotFound)?;
        applicants.remove(applicant_index);

        Ok(())
      },
    )
  }

  pub fn remove_from_market_lists(
    account: T::AccountId,
    author_type: MarketplaceRole,
    marketplace_id: [u8; 32],
  ) -> DispatchResult {
    <T as pallet::Config>::Rbac::remove_role_from_user(
      account,
      Self::pallet_id(),
      &marketplace_id,
      author_type.id(),
    )?;
    Ok(())
  }

  fn change_applicant_status(
    applicant: T::AccountId,
    marketplace_id: [u8; 32],
    next_status: ApplicationStatus,
    feedback: BoundedVec<u8, T::MaxFeedbackLen>,
  ) -> DispatchResult {
    let mut prev_status = ApplicationStatus::default();
    let app_id = <ApplicationsByAccount<T>>::get(applicant.clone(), marketplace_id)
      .ok_or(Error::<T>::ApplicationNotFound)?;
    <Applications<T>>::try_mutate::<_, _, DispatchError, _>(app_id, |application| {
      application.as_ref().ok_or(Error::<T>::ApplicationNotFound)?;
      if let Some(a) = application {
        prev_status.clone_from(&a.status);
        a.feedback = feedback;
        a.status.clone_from(&next_status)
      }
      Ok(())
    })?;
    ensure!(prev_status != next_status, Error::<T>::AlreadyEnrolled);
    //remove from previous state list
    Self::remove_from_applicants_lists(applicant.clone(), prev_status, marketplace_id)?;

    //insert in current state list
    Self::insert_in_applicants_lists(applicant.clone(), next_status, marketplace_id)?;

    if prev_status == ApplicationStatus::Approved {
      <T as pallet::Config>::Rbac::remove_role_from_user(
        applicant.clone(),
        Self::pallet_id(),
        &marketplace_id,
        MarketplaceRole::Participant.id(),
      )?;
    }
    if next_status == ApplicationStatus::Approved {
      <T as pallet::Config>::Rbac::assign_role_to_user(
        applicant,
        Self::pallet_id(),
        &marketplace_id,
        MarketplaceRole::Participant.id(),
      )?
    }

    Ok(())
  }

  pub fn do_block_user(
    authority: T::AccountId,
    marketplace_id: [u8; 32],
    user: T::AccountId,
  ) -> DispatchResult {
    // ensure the marketplace exists
    ensure!(<Marketplaces<T>>::contains_key(marketplace_id), Error::<T>::MarketplaceNotFound);
    // ensure the origin is authorized to block users
    Self::is_authorized(authority.clone(), &marketplace_id, Permission::BlockUser)?;
    // ensure the user is not already a participant of the marketplace
    ensure!(!Self::has_any_role(user.clone(), &marketplace_id), Error::<T>::UserAlreadyParticipant);
    // ensure the user is not already blocked
    ensure!(!Self::is_user_blocked(user.clone(), marketplace_id), Error::<T>::UserAlreadyBlocked);

    // insert the user in the blocked list
    <BlockedUsersByMarketplace<T>>::try_mutate(marketplace_id, |blocked_list| {
      blocked_list.try_push(user.clone())
    })
    .map_err(|_| Error::<T>::ExceedMaxBlockedUsers)?;

    Self::deposit_event(Event::UserBlocked(marketplace_id, user.clone()));
    Ok(())
  }

  pub fn do_unblock_user(
    authority: T::AccountId,
    marketplace_id: [u8; 32],
    user: T::AccountId,
  ) -> DispatchResult {
    // ensure the marketplace exists
    ensure!(<Marketplaces<T>>::contains_key(marketplace_id), Error::<T>::MarketplaceNotFound);
    // ensure the origin is authorized to block users
    Self::is_authorized(authority.clone(), &marketplace_id, Permission::BlockUser)?;
    // ensure the user is not already a participant of the marketplace
    ensure!(!Self::has_any_role(user.clone(), &marketplace_id), Error::<T>::UserAlreadyParticipant);
    // ensure the user is blocked
    ensure!(Self::is_user_blocked(user.clone(), marketplace_id), Error::<T>::UserIsNotBlocked);

    // remove the user from the block list
    <BlockedUsersByMarketplace<T>>::try_mutate::<_, _, DispatchError, _>(
      marketplace_id,
      |blocked_list| {
        let user_index = blocked_list
          .iter()
          .position(|a| *a == user.clone())
          .ok_or(Error::<T>::UserNotFound)?;
        blocked_list.remove(user_index);
        Ok(())
      },
    )?;
    Self::deposit_event(Event::UserUnblocked(marketplace_id, user.clone()));
    Ok(())
  }

  fn is_user_blocked(user: T::AccountId, marketplace_id: [u8; 32]) -> bool {
    <BlockedUsersByMarketplace<T>>::get(marketplace_id).contains(&user)
  }

  fn is_authorized(
    authority: T::AccountId,
    marketplace_id: &[u8; 32],
    permission: Permission,
  ) -> DispatchResult {
    <T as pallet::Config>::Rbac::is_authorized(
      authority,
      Self::pallet_id(),
      marketplace_id,
      &permission.id(),
    )
  }

  /// Let us know if the selected account has at least one role in the marketplace.
  fn has_any_role(account: T::AccountId, marketplace_id: &[u8; 32]) -> bool {
    let pallet_id = Self::pallet_id();
    <T as pallet::Config>::Rbac::does_user_have_any_role_in_scope(
      account,
      pallet_id,
      marketplace_id,
    )
  }

  ///Lets us know if the selected user is an admin.
  /// It returns true if the user is an admin, false otherwise.
  fn is_admin(account: T::AccountId, marketplace_id: [u8; 32]) -> bool {
    <T as pallet::Config>::Rbac::has_role(
      account,
      Self::pallet_id(),
      &marketplace_id,
      [MarketplaceRole::Admin.id()].to_vec(),
    )
    .is_ok()
  }

  /// Let us know if the selected account has the selected authority type.
  /// It returns true if the account has the authority type, false otherwise
  // fn  does_exist_authority(account: T::AccountId, marketplace_id: [u8;32], authority_type: MarketplaceRole) -> bool{
  //     let roles = match <MarketplacesByAuthority<T>>::try_get(account, marketplace_id){
  //         Ok(roles) => roles,
  //         Err(_) => return false,
  //     };

  //     roles.iter().any(|authority| authority == &authority_type)
  // }

  /// Let us know if there's an owner for the selected marketplace.
  /// It returns true if there's an owner, false otherwise
  fn owner_exist(marketplace_id: [u8; 32]) -> bool {
    // let owners =  match <AuthoritiesByMarketplace<T>>::try_get( marketplace_id, MarketplaceAuthority::Owner){
    //     Ok(owners) => owners,
    //     Err(_) => return false,
    // };

    //owners.len() == 1
    <T as pallet::Config>::Rbac::get_role_users_len(
      Self::pallet_id(),
      &marketplace_id,
      &MarketplaceRole::Owner.id(),
    ) == 1
  }

  /// Let us update the marketplace's label.
  /// It returns ok if the update was successful, error otherwise.
  fn update_label(
    marketplace_id: [u8; 32],
    new_label: BoundedVec<u8, T::LabelMaxLen>,
  ) -> DispatchResult {
    <Marketplaces<T>>::try_mutate(marketplace_id, |marketplace| {
      let market = marketplace.as_mut().ok_or(Error::<T>::MarketplaceNotFound)?;
      market.label = new_label;
      Ok(())
    })
  }

  /// Let us delete the selected marketplace
  /// and remove all of its associated authorities from all the storage sources.
  /// If returns ok if the deletion was successful, error otherwise.
  /// Errors only could happen if the storage sources are corrupted.
  fn remove_selected_marketplace(marketplace_id: [u8; 32]) -> DispatchResult {
    //TODO: evaluate use iter_key_prefix ->instead iter()
    //Before to remove the marketplace, we need to remove all its associated authorities
    // as well as the applicants/applications.

    //First we need to get the list of all the authorities for the marketplace.
    let mut applications = Vec::new();

    // remove from Applications lists
    for ele in <ApplicationsByAccount<T>>::iter() {
      if ele.1 == marketplace_id {
        applications.push(ele.2);
      }
    }

    for application in applications {
      <Applications<T>>::remove(application);
    }

    // remove from ApplicationsByAccount list
    <ApplicationsByAccount<T>>::iter().for_each(|(_k1, _k2, _k3)| {
      <ApplicationsByAccount<T>>::remove(_k1, marketplace_id);
    });

    // remove from ApplicantsByMarketplace list
    let _ = <ApplicantsByMarketplace<T>>::clear_prefix(marketplace_id, 1000, None);

    // remove from Custodians list
    <Custodians<T>>::iter().for_each(|(_k1, _k2, _k3)| {
      <Custodians<T>>::remove(_k1, marketplace_id);
    });

    // remove from Marketplaces list
    <Marketplaces<T>>::remove(marketplace_id);

    <T as pallet::Config>::Rbac::remove_scope(Self::pallet_id(), marketplace_id)?;

    Ok(())
  }

  /// Let us check the curent status of the selected application.
  /// If the status is rejected, we can safely remove its data from the storage sources
  /// so the user can apply again.
  /// It doesn't affect any other storage source/workflow.
  pub fn is_application_in_rejected_status(
    account: T::AccountId,
    marketplace_id: [u8; 32],
  ) -> DispatchResult {
    //check if user is blocked
    ensure!(!Self::is_user_blocked(account.clone(), marketplace_id), Error::<T>::UserIsBlocked);
    let application_id = <ApplicationsByAccount<T>>::try_get(account.clone(), marketplace_id)
      .map_err(|_| Error::<T>::ApplicationIdNotFound)?;

    let application =
      <Applications<T>>::try_get(application_id).map_err(|_| Error::<T>::ApplicationNotFound)?;

    match application.status {
      ApplicationStatus::Pending => return Err(Error::<T>::ApplicationStatusStillPending.into()),
      ApplicationStatus::Approved => {
        return Err(Error::<T>::ApplicationHasAlreadyBeenApproved.into())
      },
      ApplicationStatus::Rejected => {
        //If status is Rejected, we need to delete the previous application from all the storage sources.
        <Applications<T>>::remove(application_id);
        <ApplicationsByAccount<T>>::remove(account.clone(), marketplace_id);
        Self::remove_from_applicants_lists(account, ApplicationStatus::Rejected, marketplace_id)?;
      },
    }
    Ok(())
  }

  fn get_timestamp_in_milliseconds() -> Option<u64> {
    let timestamp: u64 = T::Timestamp::now().into();

    Some(timestamp)
  }

  fn _is_offer_status(offer_id: [u8; 32], offer_status: OfferStatus) -> bool {
    //we already know that the offer exists, so we don't need to check it here.
    if let Some(offer) = <OffersInfo<T>>::get(offer_id) {
      offer.status == offer_status
    } else {
      false
    }
  }

  fn does_exist_offer_id_for_this_item(
    collection_id: T::CollectionId,
    item_id: T::ItemId,
    offer_id: [u8; 32],
  ) -> DispatchResult {
    let offers =
      <OffersByItem<T>>::try_get(collection_id, item_id).map_err(|_| Error::<T>::OfferNotFound)?;
    //find the offer_id in the vector of offers_ids
    offers.iter().find(|&x| *x == offer_id).ok_or(Error::<T>::OfferNotFound)?;
    Ok(())
  }

  //sell orders here...

  fn update_offers_status(
    buyer: T::AccountId,
    collection_id: T::CollectionId,
    item_id: T::ItemId,
    marketplace_id: [u8; 32],
  ) -> DispatchResult {
    let offer_ids =
      <OffersByItem<T>>::try_get(collection_id, item_id).map_err(|_| Error::<T>::OfferNotFound)?;

    for offer_id in offer_ids {
      <OffersInfo<T>>::try_mutate::<_, _, DispatchError, _>(offer_id, |offer| {
        let offer = offer.as_mut().ok_or(Error::<T>::OfferNotFound)?;
        offer.status = OfferStatus::Closed;
        offer.buyer = Some((buyer.clone(), marketplace_id));
        Ok(())
      })?;
    }
    Ok(())
  }

  fn is_the_offer_valid(price: T::Balance, percentage: Permill) -> DispatchResult {
    let minimun_amount: T::Balance = 0u32.into();
    ensure!(price > minimun_amount, Error::<T>::PriceMustBeGreaterThanZero);
    ensure!(percentage <= Permill::from_percent(100), Error::<T>::ExceedMaxPercentage);
    ensure!(percentage >= Permill::from_percent(1), Error::<T>::ExceedMinPercentage);
    Ok(())
  }

  fn can_this_item_receive_sell_orders(
    collection_id: T::CollectionId,
    item_id: T::ItemId,
    marketplace_id: [u8; 32],
  ) -> DispatchResult {
    let offers = <OffersByItem<T>>::get(collection_id, item_id);

    //if len is == 0, it means that there is no offers for this item, maybe it's the first entry
    if offers.len() > 0 {
      for offer in offers {
        let offer_info = <OffersInfo<T>>::get(offer).ok_or(Error::<T>::OfferNotFound)?;
        //ensure the offer_type is SellOrder, because this vector also contains buy offers.
        if offer_info.marketplace_id == marketplace_id
          && offer_info.offer_type == OfferType::SellOrder
        {
          return Err(Error::<T>::OfferAlreadyExists.into());
        }
      }
    }

    Ok(())
  }

  fn can_this_item_receive_buy_orders(
    marketplace_id: &[u8; 32],
    buyer: T::AccountId,
    class_id: &T::CollectionId,
    instance_id: &T::ItemId,
  ) -> DispatchResult {
    //First we check if the buyer is authorized to buy on this marketplace
    Self::is_authorized(buyer, marketplace_id, Permission::EnlistBuyOffer)?;

    //We need to check if the owner is in the marketplace
    if let Some(owner) = pallet_uniques::Pallet::<T>::owner(*class_id, *instance_id) {
      if Self::is_authorized(owner, marketplace_id, Permission::EnlistSellOffer).is_ok() {
        return Ok(());
      }
    }
    Err(Error::<T>::OwnerNotInMarketplace.into())
  }

  fn _delete_all_sell_orders_for_this_item(
    collection_id: T::CollectionId,
    item_id: T::ItemId,
  ) -> DispatchResult {
    //ensure the item has offers associated with it.
    ensure!(<OffersByItem<T>>::contains_key(collection_id, item_id), Error::<T>::OfferNotFound);

    let offers_ids = <OffersByItem<T>>::take(collection_id, item_id);
    //let mut remaining_offer_ids: Vec<[u8;32]> = Vec::new();
    let mut buy_offer_ids: BoundedVec<[u8; 32], T::MaxOffersPerMarket> = BoundedVec::default();

    for offer_id in offers_ids {
      let offer_info = <OffersInfo<T>>::get(offer_id).ok_or(Error::<T>::OfferNotFound)?;
      //ensure the offer_type is SellOrder, because this vector also contains offers of BuyOrder OfferType.
      if offer_info.offer_type != OfferType::SellOrder {
        buy_offer_ids.try_push(offer_id).map_err(|_| Error::<T>::LimitExceeded)?;
      }
    }
    //ensure we already took the entry from the storagemap, so we can insert it again.
    ensure!(!<OffersByItem<T>>::contains_key(collection_id, item_id), Error::<T>::OfferNotFound);
    <OffersByItem<T>>::insert(collection_id, item_id, buy_offer_ids);

    Ok(())
  }

  fn delete_all_offers_for_this_item(
    collection_id: T::CollectionId,
    item_id: T::ItemId,
  ) -> DispatchResult {
    pallet_fruniques::Pallet::<T>::do_thaw(&collection_id, item_id)?;
    <OffersByItem<T>>::remove(collection_id, item_id);
    Ok(())
  }

  pub fn do_ask_for_redeem(
    who: T::AccountId,
    marketplace: MarketplaceId,
    collection_id: T::CollectionId,
    item_id: T::ItemId,
  ) -> DispatchResult {
    ensure!(<Marketplaces<T>>::contains_key(marketplace), Error::<T>::MarketplaceNotFound);
    Self::is_authorized(who.clone(), &marketplace, Permission::AskForRedemption)?;
    //ensure the collection exists
    if let Some(a) = pallet_uniques::Pallet::<T>::owner(collection_id, item_id) {
      ensure!(a == who, Error::<T>::NotOwner);
    } else {
      return Err(Error::<T>::CollectionNotFound.into());
    }

    let redemption_data: RedemptionData<T> = RedemptionData {
      creator: who.clone(),
      redeemed_by: None,
      collection_id,
      item_id,
      is_redeemed: false,
    };

    // Gen market id
    let redemption_id = redemption_data.using_encoded(blake2_256);
    // ensure the generated id is unique
    ensure!(
      !<AskingForRedemption<T>>::contains_key(marketplace, redemption_id),
      Error::<T>::RedemptionRequestAlreadyExists
    );

    <AskingForRedemption<T>>::insert(marketplace, redemption_id, redemption_data);
    Self::deposit_event(Event::RedemptionRequested(marketplace, redemption_id, who));

    Ok(())
  }

  pub fn do_accept_redeem(
    who: T::AccountId,
    marketplace: MarketplaceId,
    redemption_id: RedemptionId,
  ) -> DispatchResult
  where
    <T as pallet_uniques::Config>::ItemId: From<u32>,
  {
    ensure!(<Marketplaces<T>>::contains_key(marketplace), Error::<T>::MarketplaceNotFound);
    Self::is_authorized(who.clone(), &marketplace, Permission::AcceptRedemption)?;

    ensure!(
      <AskingForRedemption<T>>::contains_key(marketplace, redemption_id),
      Error::<T>::RedemptionRequestNotFound
    );

    <AskingForRedemption<T>>::try_mutate::<_, _, _, DispatchError, _>(
      marketplace,
      redemption_id,
      |redemption_data| -> DispatchResult {
        let redemption_data =
          redemption_data.as_mut().ok_or(Error::<T>::RedemptionRequestNotFound)?;
        ensure!(redemption_data.is_redeemed == false, Error::<T>::RedemptionRequestAlreadyRedeemed);
        ensure!(redemption_data.is_redeemed == false, Error::<T>::RedemptionRequestAlreadyRedeemed);
        redemption_data.is_redeemed = true;
        redemption_data.redeemed_by = Some(who.clone());
        Self::deposit_event(Event::RedemptionAccepted(marketplace, redemption_id, who));
        pallet_fruniques::Pallet::<T>::do_redeem(
          redemption_data.collection_id,
          redemption_data.item_id,
        )?;

        Ok(())
      },
    )?;

    Ok(())
  }
  pub fn pallet_id() -> IdOrVec {
    IdOrVec::Vec(Self::module_name().as_bytes().to_vec())
  }
}