-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.rs
1389 lines (1212 loc) · 44.2 KB
/
functions.rs
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
use super::*;
use crate::types::*;
use frame_support::{pallet_prelude::*, traits::Time};
use frame_system::{pallet_prelude::*, RawOrigin};
use pallet_rbac::types::*;
use scale_info::prelude::vec; // vec![] macro
use sp_io::hashing::blake2_256;
use sp_runtime::sp_std::vec::Vec; // vec primitive
use sp_runtime::{traits::StaticLookup, 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(())
}
/// Creates a new marketplace
/// The owner and admin are added to the marketplace as authorities
/// The asset_id is the currency of the marketplace and it's assumed to exist
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.clone(), 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 an offer_id
let offer_id = (marketplace_id, authority.clone(), collection_id.clone(), creation_date)
.using_encoded(blake2_256);
//create offer structure
let marketplace =
<Marketplaces<T>>::get(marketplace_id).ok_or(Error::<T>::MarketplaceNotFound)?;
let offer_data = OfferData::<T> {
marketplace_id,
collection_id: collection_id.clone(),
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,
};
//ensure there is no a previous sell offer for this item
Self::can_this_item_receive_sell_orders(collection_id.clone(), item_id, marketplace_id)?;
//insert in OffersByItem
<OffersByItem<T>>::try_mutate(collection_id.clone(), 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.clone(), 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 an offer_id
let offer_id = (marketplace_id, authority.clone(), collection_id.clone(), creation_date)
.using_encoded(blake2_256);
//create offer structure
let marketplace =
<Marketplaces<T>>::get(marketplace_id).ok_or(Error::<T>::MarketplaceNotFound)?;
let offer_data = OfferData::<T> {
marketplace_id,
collection_id: collection_id.clone(),
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,
};
//insert in OffersByItem
//An item can receive multiple buy offers
<OffersByItem<T>>::try_mutate(collection_id.clone(), 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.clone(),
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.clone(),
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,
)?;
//T::Currency::transfer(&buyer, &owner_item, owners_cut, KeepAlive)?;
pallet_mapped_assets::Pallet::<T>::transfer(
origin.clone(),
asset_id.clone().into(),
T::Lookup::unlookup(marketplace.creator.clone()),
offer_data.fee,
)?;
//T::Currency::transfer(&buyer, &marketplace.creator, offer_data.fee, KeepAlive)?;
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.clone(),
offer_data.item_id,
buyer.clone(),
|_, _| Ok(()),
)?;
} else {
let parent_info = pallet_fruniques::types::ParentInfo {
collection_id: offer_data.collection_id.clone(),
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.clone(),
offer_data.item_id,
);
pallet_fruniques::Pallet::<T>::do_spawn(
offer_data.collection_id.clone(),
buyer.clone(),
metadata,
None,
Some(parent_info),
)?;
}
//update offer status from all marketplaces
Self::update_offers_status(
buyer.clone(),
offer_data.collection_id.clone(),
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.clone(),
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.clone(),
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,
)?;
//T::Currency::transfer(&offer_data.creator, &owner_item, owners_cut, KeepAlive)?;
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,
)?;
/* T::Currency::transfer(
&offer_data.creator,
&marketplace.creator,
offer_data.fee,
KeepAlive,
)?; */
pallet_fruniques::Pallet::<T>::do_thaw(
&offer_data.collection_id.clone(),
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.clone(),
offer_data.item_id,
offer_data.creator.clone(),
|_, _| Ok(()),
)?;
} else {
let parent_info = pallet_fruniques::types::ParentInfo {
collection_id: offer_data.collection_id.clone(),
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.clone(),
offer_data.item_id,
);
pallet_fruniques::Pallet::<T>::do_spawn(
offer_data.collection_id.clone(),
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.clone(),
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.clone(),
offer_data.item_id,
offer_id,
)?;
if offer_data.offer_type == OfferType::SellOrder {
pallet_fruniques::Pallet::<T>::do_thaw(
&offer_data.collection_id.clone(),
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(())
},