-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathnft_sale.rs
1689 lines (1560 loc) · 54 KB
/
nft_sale.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
//! Phala World NFT Sale Pallet
use frame_support::{
ensure,
traits::{
tokens::{nonfungibles::InspectEnumerable, ExistenceRequirement},
Currency, UnixTime,
},
transactional, BoundedVec,
};
use frame_system::{ensure_signed, pallet_prelude::*, Origin};
use codec::Encode;
use sp_core::{sr25519, H256};
use sp_runtime::DispatchResult;
use sp_std::prelude::*;
pub use pallet_rmrk_core::types::*;
pub use pallet_rmrk_market;
pub use crate::traits::{
primitives::*, CareerType, NftSaleInfo, NftSaleType, OverlordMessage, PreorderInfo, Purpose,
RaceType, RarityType, StatusType,
};
use rmrk_traits::primitives::*;
pub type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
pub use self::pallet::*;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::{dispatch::DispatchResult, pallet_prelude::*, traits::ReservableCurrency};
use pallet_rmrk_core::BoundedCollectionSymbolOf;
type PreorderInfoOf<T> = PreorderInfo<
<T as frame_system::Config>::AccountId,
BoundedVec<u8, <T as pallet_uniques::Config>::StringLimit>,
>;
/// Configure the pallet by specifying the parameters and types on which it depends.
#[pallet::config]
pub trait Config: frame_system::Config + pallet_rmrk_core::Config {
/// Because this pallet emits events, it depends on the runtime's definition of an event.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
/// The origin which may forcibly buy, sell, list/unlist, offer & withdraw offer on Tokens
type GovernanceOrigin: EnsureOrigin<Self::Origin>;
/// The market currency mechanism.
type Currency: ReservableCurrency<Self::AccountId>;
/// Time in UnixTime
type Time: UnixTime;
/// Seconds per Era that will increment the Era storage value every interval
#[pallet::constant]
type SecondsPerEra: Get<u64>;
/// Minimum amount of PHA to claim a Spirit
#[pallet::constant]
type MinBalanceToClaimSpirit: Get<BalanceOf<Self>>;
/// Price of Legendary Origin of Shell Price
#[pallet::constant]
type LegendaryOriginOfShellPrice: Get<BalanceOf<Self>>;
/// Price of Magic Origin of Shell Price
#[pallet::constant]
type MagicOriginOfShellPrice: Get<BalanceOf<Self>>;
/// Price of Prime Origin of Shell Price
#[pallet::constant]
type PrimeOriginOfShellPrice: Get<BalanceOf<Self>>;
/// Max mint per Race
#[pallet::constant]
type IterLimit: Get<u32>;
}
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
/// Preorder index that is the key to the Preorders StorageMap
#[pallet::storage]
#[pallet::getter(fn preorder_index)]
pub type PreorderIndex<T: Config> = StorageValue<_, PreorderId, ValueQuery>;
/// Preorder info map for user preorders
#[pallet::storage]
#[pallet::getter(fn preorders)]
pub type Preorders<T: Config> = StorageMap<_, Twox64Concat, PreorderId, PreorderInfoOf<T>>;
/// Owners that have made a preorder during intial preorder phase
#[pallet::storage]
#[pallet::getter(fn owner_has_preorder)]
pub type OwnerHasPreorder<T: Config> =
StorageMap<_, Twox64Concat, T::AccountId, bool, ValueQuery>;
/// Origin of Shells inventory
#[pallet::storage]
#[pallet::getter(fn origin_of_shells_inventory)]
pub type OriginOfShellsInventory<T: Config> =
StorageDoubleMap<_, Blake2_128Concat, RarityType, Blake2_128Concat, RaceType, NftSaleInfo>;
/// Phala World Zero Day `BlockNumber` this will be used to determine Eras
#[pallet::storage]
#[pallet::getter(fn zero_day)]
pub(super) type ZeroDay<T: Config> = StorageValue<_, u64>;
/// The current Era from the initial ZeroDay BlockNumber
#[pallet::storage]
#[pallet::getter(fn era)]
pub type Era<T: Config> = StorageValue<_, EraId, ValueQuery>;
/// Spirits can be claimed
#[pallet::storage]
#[pallet::getter(fn can_claim_spirits)]
pub type CanClaimSpirits<T: Config> = StorageValue<_, bool, ValueQuery>;
/// Rare Origin of Shells can be purchased
#[pallet::storage]
#[pallet::getter(fn can_purchase_rare_origin_of_shells)]
pub type CanPurchaseRareOriginOfShells<T: Config> = StorageValue<_, bool, ValueQuery>;
/// Origin of Shells can be purchased by whitelist
#[pallet::storage]
#[pallet::getter(fn can_purchase_prime_origin_of_shells)]
pub type CanPurchasePrimeOriginOfShells<T: Config> = StorageValue<_, bool, ValueQuery>;
/// Origin of Shells can be preordered
#[pallet::storage]
#[pallet::getter(fn can_preorder_origin_of_shells)]
pub type CanPreorderOriginOfShells<T: Config> = StorageValue<_, bool, ValueQuery>;
/// Last Day of Sale any Origin of Shell can be purchased
#[pallet::storage]
#[pallet::getter(fn last_day_of_sale)]
pub type LastDayOfSale<T: Config> = StorageValue<_, bool, ValueQuery>;
/// Spirit Collection ID
#[pallet::storage]
#[pallet::getter(fn spirit_collection_id)]
pub type SpiritCollectionId<T: Config> = StorageValue<_, CollectionId, OptionQuery>;
/// Origin of Shell Collection ID
#[pallet::storage]
#[pallet::getter(fn origin_of_shell_collection_id)]
pub type OriginOfShellCollectionId<T: Config> = StorageValue<_, CollectionId, OptionQuery>;
/// Career StorageMap count
#[pallet::storage]
#[pallet::getter(fn career_type_count)]
pub type CareerTypeCount<T: Config> = StorageMap<_, Twox64Concat, CareerType, u32, ValueQuery>;
/// Origin of Shells Inventory has been initialized
#[pallet::storage]
#[pallet::getter(fn is_origin_of_shells_inventory_set)]
pub type IsOriginOfShellsInventorySet<T: Config> = StorageValue<_, bool, ValueQuery>;
/// Spirits Metadata
#[pallet::storage]
#[pallet::getter(fn spirits_metadata)]
pub type SpiritsMetadata<T: Config> = StorageValue<_, BoundedVec<u8, T::StringLimit>>;
/// Origin of Shells Metadata
#[pallet::storage]
#[pallet::getter(fn origin_of_shells_metadata)]
pub type OriginOfShellsMetadata<T: Config> =
StorageMap<_, Twox64Concat, RaceType, BoundedVec<u8, T::StringLimit>>;
/// Overlord Admin account of Phala World
#[pallet::storage]
pub(super) type Overlord<T: Config> = StorageValue<_, T::AccountId, OptionQuery>;
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_finalize(_n: T::BlockNumber) {
if let Some(zero_day) = <ZeroDay<T>>::get() {
let current_time = T::Time::now().as_secs();
if current_time > zero_day {
let secs_since_zero_day = current_time - zero_day;
let current_era = <Era<T>>::get();
if secs_since_zero_day / T::SecondsPerEra::get() > current_era {
let new_era = Era::<T>::mutate(|era| {
*era += 1;
*era
});
Self::deposit_event(Event::NewEra {
time: current_time,
era: new_era,
});
}
}
}
}
}
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
/// `BlockNumber` of Phala World Zero Day
pub zero_day: Option<u64>,
/// Overlord Admin account of Phala World
pub overlord: Option<T::AccountId>,
/// Current Era of Phala World
pub era: u64,
/// bool for if a Spirit is claimable
pub can_claim_spirits: bool,
/// bool for if a Rare Origin of Shell can be purchased
pub can_purchase_rare_origin_of_shells: bool,
/// bool for Prime Origin of Shell purchases through whitelist
pub can_purchase_prime_origin_of_shells: bool,
/// bool for if an Origin of Shell can be preordered
pub can_preorder_origin_of_shells: bool,
/// bool for the last day of sale for Origin of Shell
pub last_day_of_sale: bool,
/// CollectionId of Spirit Collection
pub spirit_collection_id: Option<CollectionId>,
/// CollectionId of Origin of Shell Collection
pub origin_of_shell_collection_id: Option<CollectionId>,
/// Is Origin of Shells Inventory set?
pub is_origin_of_shells_inventory_set: bool,
}
#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self {
zero_day: None,
overlord: None,
era: 0,
can_claim_spirits: false,
can_purchase_rare_origin_of_shells: false,
can_purchase_prime_origin_of_shells: false,
can_preorder_origin_of_shells: false,
last_day_of_sale: false,
spirit_collection_id: None,
origin_of_shell_collection_id: None,
is_origin_of_shells_inventory_set: false,
}
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig<T>
where
T: pallet_uniques::Config<CollectionId = CollectionId, ItemId = NftId>,
{
fn build(&self) {
if let Some(ref zero_day) = self.zero_day {
<ZeroDay<T>>::put(zero_day);
}
if let Some(ref overlord) = self.overlord {
<Overlord<T>>::put(overlord);
}
let era = self.era;
<Era<T>>::put(era);
let can_claim_spirits = self.can_claim_spirits;
<CanClaimSpirits<T>>::put(can_claim_spirits);
let can_purchase_rare_origin_of_shells = self.can_purchase_rare_origin_of_shells;
<CanPurchaseRareOriginOfShells<T>>::put(can_purchase_rare_origin_of_shells);
let can_purchase_prime_origin_of_shells = self.can_purchase_prime_origin_of_shells;
<CanPurchasePrimeOriginOfShells<T>>::put(can_purchase_prime_origin_of_shells);
let can_preorder_origin_of_shells = self.can_preorder_origin_of_shells;
<CanPreorderOriginOfShells<T>>::put(can_preorder_origin_of_shells);
let last_day_of_sale = self.last_day_of_sale;
<LastDayOfSale<T>>::put(last_day_of_sale);
if let Some(spirit_collection_id) = self.spirit_collection_id {
<SpiritCollectionId<T>>::put(spirit_collection_id);
}
if let Some(origin_of_shell_collection_id) = self.origin_of_shell_collection_id {
<OriginOfShellCollectionId<T>>::put(origin_of_shell_collection_id);
}
let is_origin_of_shells_inventory_set = self.is_origin_of_shells_inventory_set;
<IsOriginOfShellsInventorySet<T>>::put(is_origin_of_shells_inventory_set);
}
}
// Pallets use events to inform users when important changes are made.
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Phala World clock zero day started
WorldClockStarted { start_time: u64 },
/// Start of a new era
NewEra { time: u64, era: u64 },
/// Spirit has been claimed
SpiritClaimed {
owner: T::AccountId,
collection_id: CollectionId,
nft_id: NftId,
},
/// A chance to get an Origin of Shell through preorder
OriginOfShellPreordered {
owner: T::AccountId,
preorder_id: PreorderId,
},
/// Origin of Shell minted from the preorder
OriginOfShellMinted {
rarity_type: RarityType,
collection_id: CollectionId,
nft_id: NftId,
owner: T::AccountId,
race: RaceType,
career: CareerType,
},
/// Spirit collection id was set
SpiritCollectionIdSet { collection_id: CollectionId },
/// Origin of Shell collection id was set
OriginOfShellCollectionIdSet { collection_id: CollectionId },
/// Origin of Shell inventory updated
OriginOfShellInventoryUpdated { rarity_type: RarityType },
/// Spirit Claims status has changed
ClaimSpiritStatusChanged { status: bool },
/// Purchase Rare Origin of Shells status has changed
PurchaseRareOriginOfShellsStatusChanged { status: bool },
/// Purchase Prime Origin of Shells status changed
PurchasePrimeOriginOfShellsStatusChanged { status: bool },
/// Preorder Origin of Shells status has changed
PreorderOriginOfShellsStatusChanged { status: bool },
/// Chosen preorder was minted to owner
ChosenPreorderMinted {
preorder_id: PreorderId,
owner: T::AccountId,
},
/// Not chosen preorder was refunded to owner
NotChosenPreorderRefunded {
preorder_id: PreorderId,
owner: T::AccountId,
},
/// Last Day of Sale status has changed
LastDayOfSaleStatusChanged { status: bool },
OverlordChanged {
old_overlord: Option<T::AccountId>,
new_overlord: T::AccountId,
},
/// Origin of Shells Inventory was set
OriginOfShellsInventoryWasSet { status: bool },
/// Gift a Origin of Shell for giveaway or reserved NFT to owner
OriginOfShellGiftedToOwner {
owner: T::AccountId,
nft_sale_type: NftSaleType,
},
/// Spirits Metadata was set
SpiritsMetadataSet {
spirits_metadata: BoundedVec<u8, T::StringLimit>,
},
/// Origin of Shells Metadata was set
OriginOfShellsMetadataSet {
origin_of_shells_metadata: Vec<(RaceType, BoundedVec<u8, T::StringLimit>)>,
},
}
// Errors inform users that something went wrong.
#[pallet::error]
pub enum Error<T> {
WorldClockAlreadySet,
SpiritClaimNotAvailable,
RareOriginOfShellPurchaseNotAvailable,
PrimeOriginOfShellPurchaseNotAvailable,
PreorderOriginOfShellNotAvailable,
PreorderClaimNotAvailable,
SpiritAlreadyClaimed,
InvalidSpiritClaim,
InvalidMetadata,
MustOwnSpiritToPurchase,
OriginOfShellAlreadyPurchased,
BelowMinimumBalanceThreshold,
WhitelistVerificationFailed,
InvalidPurchase,
NoAvailablePreorderId,
PreorderClaimNotDetected,
RefundClaimNotDetected,
PreorderIsPending,
PreordersCorrupted,
NotPreorderOwner,
RaceMintMaxReached,
OverlordNotSet,
RequireOverlordAccount,
InvalidStatusType,
WrongRarityType,
SpiritCollectionNotSet,
SpiritCollectionIdAlreadySet,
SpiritsMetadataNotSet,
OriginOfShellCollectionNotSet,
OriginOfShellCollectionIdAlreadySet,
OriginOfShellInventoryCorrupted,
OriginOfShellInventoryAlreadySet,
OriginOfShellsMetadataNotSet,
UnableToAddAttributes,
KeyTooLong,
NoAvailableRaceGivewayLeft,
NoAvailableRaceReservedLeft,
WrongNftSaleType,
}
// Dispatchable functions allows users to interact with the pallet and invoke state changes.
// These functions materialize as "extrinsics", which are often compared to transactions.
// Dispatchable functions must be annotated with a weight and must return a DispatchResult.
#[pallet::call]
impl<T: Config> Pallet<T>
where
T: pallet_uniques::Config<CollectionId = CollectionId, ItemId = NftId>,
{
/// Claim a spirit for any account with at least 10 PHA in their account
///
/// Parameters:
/// - origin: The origin of the extrinsic.
#[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn claim_spirit(origin: OriginFor<T>) -> DispatchResult {
let sender = ensure_signed(origin.clone())?;
ensure!(
CanClaimSpirits::<T>::get(),
Error::<T>::SpiritClaimNotAvailable
);
let overlord = Self::overlord()?;
// Check Balance has minimum required
ensure!(
<T as pallet::Config>::Currency::can_reserve(
&sender,
T::MinBalanceToClaimSpirit::get()
),
Error::<T>::BelowMinimumBalanceThreshold
);
// Mint Spirit NFT
Self::do_mint_spirit_nft(overlord, sender)?;
Ok(())
}
/// Redeem spirit function is called when an account has a `SpiritClaimTicket` that enables
/// an account to acquire a Spirit NFT without the 10 PHA minimum requirement, such that,
/// the account has a valid `SpiritClaimTicket` signed by the Overlord admin account.
///
/// Parameters:
/// - origin: The origin of the extrinsic.
#[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn redeem_spirit(
origin: OriginFor<T>,
signature: sr25519::Signature,
) -> DispatchResult {
let sender = ensure_signed(origin.clone())?;
ensure!(
CanClaimSpirits::<T>::get(),
Error::<T>::SpiritClaimNotAvailable
);
let overlord = Self::overlord()?;
// verify the claim ticket
ensure!(
Self::verify_claim(&overlord, &sender, signature, Purpose::RedeemSpirit),
Error::<T>::InvalidSpiritClaim
);
// Mint Spirit NFT
Self::do_mint_spirit_nft(overlord, sender)?;
Ok(())
}
/// Buy a rare origin_of_shell of either type Magic or Legendary. Both Rarity Types
/// will have a set price. These will also be limited in quantity and on a first come, first
/// serve basis.
///
/// Parameters:
/// - origin: The origin of the extrinsic.
/// - rarity_type: The type of origin_of_shell to be purchased.
/// - race: The race of the origin_of_shell chosen by the user.
/// - career: The career of the origin_of_shell chosen by the user or auto-generated based
/// on metadata
#[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn buy_rare_origin_of_shell(
origin: OriginFor<T>,
rarity_type: RarityType,
race: RaceType,
career: CareerType,
) -> DispatchResult {
let sender = ensure_signed(origin.clone())?;
ensure!(
CanPurchaseRareOriginOfShells::<T>::get(),
Error::<T>::RareOriginOfShellPurchaseNotAvailable
);
let overlord = Self::overlord()?;
// Get Origin of Shell Price based on Rarity Type
let origin_of_shell_price = match rarity_type {
RarityType::Legendary => T::LegendaryOriginOfShellPrice::get(),
RarityType::Magic => T::MagicOriginOfShellPrice::get(),
_ => return Err(Error::<T>::InvalidPurchase.into()),
};
// Mint origin of shell
Self::do_mint_origin_of_shell_nft(
overlord,
sender,
rarity_type,
race,
career,
0,
origin_of_shell_price,
NftSaleType::ForSale,
!LastDayOfSale::<T>::get(),
)?;
Ok(())
}
/// Accounts that have been whitelisted can purchase an Origin of Shell. The only Origin of
/// Shell type available for this purchase are Prime
///
/// Parameters:
/// - origin: The origin of the extrinsic purchasing the Prime Origin of Shell
/// - message: OverlordMessage with account and purpose
/// - signature: The signature of the account that is claiming the spirit.
/// - race: The race that the user has chosen (limited # of races)
/// - career: The career that the user has chosen (unlimited careers)
#[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn buy_prime_origin_of_shell(
origin: OriginFor<T>,
signature: sr25519::Signature,
race: RaceType,
career: CareerType,
) -> DispatchResult {
let sender = ensure_signed(origin.clone())?;
let is_last_day_of_sale = LastDayOfSale::<T>::get();
ensure!(
CanPurchasePrimeOriginOfShells::<T>::get(),
Error::<T>::PrimeOriginOfShellPurchaseNotAvailable
);
let overlord = Self::overlord()?;
// Check if valid message purpose is 'BuyPrimeOriginOfShells' and verify whitelist
// account
ensure!(
Self::verify_claim(
&overlord,
&sender,
signature,
Purpose::BuyPrimeOriginOfShells
) || is_last_day_of_sale,
Error::<T>::WhitelistVerificationFailed
);
// Get Prime Origin of Shell price
let origin_of_shell_price = T::PrimeOriginOfShellPrice::get();
// Mint origin of shell
Self::do_mint_origin_of_shell_nft(
overlord,
sender,
RarityType::Prime,
race,
career,
0,
origin_of_shell_price,
NftSaleType::ForSale,
!is_last_day_of_sale,
)?;
Ok(())
}
/// Users can pre-order an Origin of Shell. This will enable users that are non-whitelisted
/// to be added to the queue of users that can claim Origin of Shells. Those that come after
/// the whitelist pre-sale will be able to win the chance to acquire an Origin of Shell
/// based on their choice of race and career as they will have a limited quantity.
///
/// Parameters:
/// - origin: The origin of the extrinsic preordering the origin_of_shell
/// - race: The race that the user has chosen (limited # of races)
/// - career: The career that the user has chosen (limited # of careers)
#[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn preorder_origin_of_shell(
origin: OriginFor<T>,
race: RaceType,
career: CareerType,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
let is_last_day_of_sale = LastDayOfSale::<T>::get();
ensure!(
is_last_day_of_sale
|| (CanPreorderOriginOfShells::<T>::get()
&& !OwnerHasPreorder::<T>::get(&sender)),
Error::<T>::PreorderOriginOfShellNotAvailable
);
// Has Spirit Collection been set
let spirit_collection_id = Self::get_spirit_collection_id()?;
// Must own a spirit NFT
ensure!(
Self::owns_nft_in_collection(&sender, spirit_collection_id),
Error::<T>::MustOwnSpiritToPurchase
);
let origin_of_shell_collection_id = Self::get_origin_of_shell_collection_id()?;
// If not the last day of sale then ensure account doesn't own an Origin of Shell
ensure!(
is_last_day_of_sale
|| !Self::owns_nft_in_collection(&sender, origin_of_shell_collection_id),
Error::<T>::OriginOfShellAlreadyPurchased
);
// Get preorder_id for new preorder
let preorder_id =
<PreorderIndex<T>>::try_mutate(|n| -> Result<PreorderId, DispatchError> {
let id = *n;
ensure!(
id != PreorderId::max_value(),
Error::<T>::NoAvailablePreorderId
);
*n += 1;
Ok(id)
})?;
// Get Race's Origin of Shell metadata
let metadata = Self::get_origin_of_shell_metadata(race)?;
let preorder = PreorderInfo {
owner: sender.clone(),
race,
career,
metadata,
};
// Reserve currency for the preorder at the Prime origin_of_shell price
<T as pallet::Config>::Currency::reserve(&sender, T::PrimeOriginOfShellPrice::get())?;
Preorders::<T>::insert(preorder_id, preorder);
// Add to storage if first phase of preorders
if !is_last_day_of_sale {
OwnerHasPreorder::<T>::insert(&sender, true);
}
Self::deposit_event(Event::OriginOfShellPreordered {
owner: sender,
preorder_id,
});
Ok(())
}
/// This is an admin only function that will mint the list of `Chosen` preorders and will
/// mint the Origin of Shell NFT to the preorder owner.
///
/// Parameters:
/// `origin`: Expected to come from Overlord admin account
/// `preorders`: Vec of Preorder IDs that were `Chosen`
#[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn mint_chosen_preorders(
origin: OriginFor<T>,
preorders: Vec<PreorderId>,
) -> DispatchResult {
// Ensure Overlord account makes call
let sender = ensure_signed(origin)?;
Self::ensure_overlord(&sender)?;
// Get price of prime origin of shell
let origin_of_shell_price = T::PrimeOriginOfShellPrice::get();
// Is last day of sale
let is_last_day_of_sale = LastDayOfSale::<T>::get();
// Get iter limit
let iter_limit = T::IterLimit::get();
let mut index = 0;
// Iterate through the preorder_statuses Vec
for preorder_id in preorders {
if index < iter_limit {
// Get the chosen preorder
let preorder_info = Preorders::<T>::take(preorder_id)
.ok_or(Error::<T>::NoAvailablePreorderId)?;
// Get owner of preorder
let preorder_owner = preorder_info.owner.clone();
// Unreserve from owner account
<T as pallet::Config>::Currency::unreserve(
&preorder_owner,
origin_of_shell_price,
);
// Mint origin of shell
Self::do_mint_origin_of_shell_nft(
sender.clone(),
preorder_owner.clone(),
RarityType::Prime,
preorder_info.race,
preorder_info.career,
0,
origin_of_shell_price,
NftSaleType::ForSale,
false,
)?;
// Remove from OwnerHasPreorder from storage if not last day of sale
if !is_last_day_of_sale {
OwnerHasPreorder::<T>::remove(&preorder_owner);
}
Self::deposit_event(Event::ChosenPreorderMinted {
preorder_id,
owner: preorder_owner,
});
index += 1;
} else {
// Break from iterator to ensure block size doesn't grow too large. Re-call this
// function and it will start from where it left off.
break;
}
}
Ok(())
}
/// This is an admin only function that will be used to refund the preorders that were not
/// selected during the preorders drawing.
///
/// Parameters:
/// `origin`: Expected to come from Overlord admin account
/// `preorders`: Preorder ids of the not chosen preorders
#[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn refund_not_chosen_preorders(
origin: OriginFor<T>,
preorders: Vec<PreorderId>,
) -> DispatchResult {
// Ensure Overlord account makes call
let sender = ensure_signed(origin)?;
Self::ensure_overlord(&sender)?;
// Get price of prime origin of shell
let origin_of_shell_price = T::PrimeOriginOfShellPrice::get();
// Is last day of sale
let is_last_day_of_sale = LastDayOfSale::<T>::get();
// Get iter limit
let iter_limit = T::IterLimit::get();
let mut index = 0;
// Iterate through the preorder_statuses Vec
for preorder_id in preorders {
if index < iter_limit {
// Get the PreorderInfoOf<T>
let preorder_info = Preorders::<T>::take(preorder_id)
.ok_or(Error::<T>::NoAvailablePreorderId)?;
// Refund reserved currency back to owner account
<T as pallet::Config>::Currency::unreserve(
&preorder_info.owner,
origin_of_shell_price,
);
// Remove from OwnerHasPreorder from storage if not last day of sale
if !is_last_day_of_sale {
OwnerHasPreorder::<T>::remove(&preorder_info.owner);
}
Self::deposit_event(Event::NotChosenPreorderRefunded {
preorder_id,
owner: preorder_info.owner,
});
index += 1;
} else {
// Break from iterator to ensure block size doesn't grow too large. Re-call this
// function and it will start from where it left off.
break;
}
}
Ok(())
}
/// This is an admin only function that will be used to mint either a giveaway or a reserved Origin of Shell NFT
///
/// Parameters:
/// `origin`: Expected to come from Overlord admin account
/// `owner`: Owner to gift the Origin of Shell to
/// - rarity_type: The type of origin_of_shell to be gifted.
/// - `race`: The race of the origin_of_shell chosen by the user.
/// - `career`: The career of the origin_of_shell chosen by the user or auto-generated based
/// on metadata
/// - `nft_sale_type`: Either a `NftSaleType::Giveaway` or `NftSaleType::Reserved`
#[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
#[transactional]
pub fn mint_gift_origin_of_shell(
origin: OriginFor<T>,
owner: T::AccountId,
rarity_type: RarityType,
race: RaceType,
career: CareerType,
nft_sale_type: NftSaleType,
) -> DispatchResult {
// Ensure Overlord account makes call
let sender = ensure_signed(origin)?;
Self::ensure_overlord(&sender)?;
// Ensure not a `NftSaleType::ForSale`
ensure!(
nft_sale_type != NftSaleType::ForSale,
Error::<T>::WrongNftSaleType
);
// Mint origin of shell
Self::do_mint_origin_of_shell_nft(
sender,
owner.clone(),
rarity_type,
race,
career,
0,
Default::default(),
nft_sale_type,
false,
)?;
Self::deposit_event(Event::OriginOfShellGiftedToOwner {
owner,
nft_sale_type,
});
Ok(())
}
/// Privileged function set the Overlord Admin account of Phala World
///
/// Parameters:
/// - origin: Expected to be called by `GovernanceOrigin`
/// - new_overlord: T::AccountId
#[pallet::weight(0)]
pub fn set_overlord(
origin: OriginFor<T>,
new_overlord: T::AccountId,
) -> DispatchResultWithPostInfo {
// This is a public call, so we ensure that the origin is some signed account.
T::GovernanceOrigin::ensure_origin(origin)?;
let old_overlord = <Overlord<T>>::get();
Overlord::<T>::put(&new_overlord);
Self::deposit_event(Event::OverlordChanged {
old_overlord,
new_overlord,
});
// GameOverlord user does not pay a fee
Ok(Pays::No.into())
}
/// Phala World Zero Day is set to begin the tracking of the official time starting at the
/// current timestamp when `initialize_world_clock` is called by the `Overlord`
///
/// Parameters:
/// `origin`: Expected to be called by `Overlord` admin account
#[pallet::weight(0)]
pub fn initialize_world_clock(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
// Ensure Overlord account makes call
let sender = ensure_signed(origin)?;
Self::ensure_overlord(&sender)?;
// Ensure ZeroDay is None as this can only be set once
ensure!(Self::zero_day() == None, Error::<T>::WorldClockAlreadySet);
let now = T::Time::now().as_secs();
let zero_day = now - (now % T::SecondsPerEra::get());
ZeroDay::<T>::put(zero_day);
Self::deposit_event(Event::WorldClockStarted {
start_time: zero_day,
});
Ok(Pays::No.into())
}
/// Privileged function to set the status for one of the defined StatusTypes like
/// ClaimSpirits, PurchaseRareOriginOfShells, or PreorderOriginOfShells to enable
/// functionality in Phala World
///
/// Parameters:
/// - `origin` - Expected Overlord admin account to set the status
/// - `status` - `bool` to set the status to
/// - `status_type` - `StatusType` to set the status for
#[pallet::weight(0)]
pub fn set_status_type(
origin: OriginFor<T>,
status: bool,
status_type: StatusType,
) -> DispatchResultWithPostInfo {
// Ensure Overlord account makes call
let sender = ensure_signed(origin)?;
Self::ensure_overlord(&sender)?;
// Match StatusType and call helper function to set status
match status_type {
StatusType::ClaimSpirits => Self::set_claim_spirits_status(status)?,
StatusType::PurchaseRareOriginOfShells => {
Self::set_purchase_rare_origin_of_shells_status(status)?
}
StatusType::PurchasePrimeOriginOfShells => {
Self::set_purchase_prime_origin_of_shells_status(status)?
}
StatusType::PreorderOriginOfShells => {
Self::set_preorder_origin_of_shells_status(status)?
}
StatusType::LastDayOfSale => Self::set_last_day_of_sale_status(status)?,
}
Ok(Pays::No.into())
}
/// Initialize the settings for the non-whitelist preorder period amount of races &
/// giveaways available for the Origin of Shell NFTs. This is a privileged function and can
/// only be executed by the Overlord account. This will call the helper function
/// `set_initial_origin_of_shell_inventory`
///
/// Parameters:
/// - `origin` - Expected Overlord admin account
#[pallet::weight(0)]
pub fn init_rarity_type_counts(origin: OriginFor<T>) -> DispatchResult {
// Ensure Overlord account makes call
let sender = ensure_signed(origin)?;
Self::ensure_overlord(&sender)?;
// Call helper function
Self::set_initial_origin_of_shell_inventory()?;
Self::deposit_event(Event::OriginOfShellsInventoryWasSet { status: true });
Ok(())
}
/// Update for the non-whitelist preorder period amount of races & giveaways available for
/// the Origin of Shell NFTs. This is a privileged function and can only be executed by the
/// Overlord account. Update the OriginOfShellInventory counts by incrementing them based on
/// the defined counts
///
/// Parameters:
/// - `origin` - Expected Overlord admin account
/// - `rarity_type` - Type of Origin of Shell
/// - `for_sale_count` - Number of Origin of Shells for sale
/// - `giveaway_count` - Number of Origin of Shells for giveaways
/// - `reserve_count` - Number of Origin of Shells to be reserved
#[pallet::weight(0)]
pub fn update_rarity_type_counts(
origin: OriginFor<T>,
rarity_type: RarityType,
for_sale_count: u32,
giveaway_count: u32,
) -> DispatchResult {
// Ensure Overlord account makes call
let sender = ensure_signed(origin)?;
Self::ensure_overlord(&sender)?;
// Ensure they are updating the RarityType::Prime
ensure!(
rarity_type == RarityType::Prime,
Error::<T>::WrongRarityType
);
// Mutate the existing storage for the Prime Origin of Shells
Self::update_nft_sale_info(
rarity_type,
RaceType::AISpectre,
for_sale_count,
giveaway_count,
);
Self::update_nft_sale_info(
rarity_type,
RaceType::Cyborg,
for_sale_count,
giveaway_count,
);
Self::update_nft_sale_info(
rarity_type,
RaceType::Pandroid,
for_sale_count,
giveaway_count,
);
Self::update_nft_sale_info(
rarity_type,
RaceType::XGene,
for_sale_count,
giveaway_count,
);
Self::deposit_event(Event::OriginOfShellInventoryUpdated { rarity_type });
Ok(())
}
/// Privileged function to set the collection id for the Spirits collection
///
/// Parameters:
/// - `origin` - Expected Overlord admin account to set the Spirit Collection ID
/// - `collection_id` - Collection ID of the Spirit Collection
#[pallet::weight(0)]
pub fn set_spirit_collection_id(
origin: OriginFor<T>,
collection_id: CollectionId,
) -> DispatchResultWithPostInfo {
// Ensure Overlord account makes call
let sender = ensure_signed(origin)?;
Self::ensure_overlord(&sender)?;
// If Spirit Collection ID is greater than 0 then the collection ID was already set
ensure!(
SpiritCollectionId::<T>::get().is_none(),
Error::<T>::SpiritCollectionIdAlreadySet
);
<SpiritCollectionId<T>>::put(collection_id);
Self::deposit_event(Event::SpiritCollectionIdSet { collection_id });
Ok(Pays::No.into())
}
/// Privileged function to set the collection id for the Origin of Shell collection
///
/// Parameters:
/// - `origin` - Expected Overlord admin account to set the Origin of Shell Collection ID
/// - `collection_id` - Collection ID of the Origin of Shell Collection
#[pallet::weight(0)]
pub fn set_origin_of_shell_collection_id(
origin: OriginFor<T>,
collection_id: CollectionId,
) -> DispatchResultWithPostInfo {
// Ensure Overlord account makes call
let sender = ensure_signed(origin)?;
Self::ensure_overlord(&sender)?;
// If Origin of Shell Collection ID is greater than 0 then the collection ID was already
// set
ensure!(
OriginOfShellCollectionId::<T>::get().is_none(),
Error::<T>::OriginOfShellCollectionIdAlreadySet
);
<OriginOfShellCollectionId<T>>::put(collection_id);