This repository was archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathlib.rs
1725 lines (1612 loc) · 56.5 KB
/
lib.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
// This file is part of Substrate.
// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # Unique (Items) Module
//!
//! A simple, secure module for dealing with non-fungible items.
//!
//! ## Related Modules
//!
//! * [`System`](../frame_system/index.html)
//! * [`Support`](../frame_support/index.html)
#![recursion_limit = "256"]
// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
#[cfg(test)]
pub mod mock;
#[cfg(test)]
mod tests;
mod common_functions;
mod features;
mod impl_nonfungibles;
mod types;
pub mod macros;
pub mod weights;
use codec::{Decode, Encode};
use frame_support::traits::{
tokens::{AttributeNamespace, Locker},
BalanceStatus::Reserved,
Currency, EnsureOriginWithArg, ReservableCurrency,
};
use frame_system::Config as SystemConfig;
use sp_runtime::{
traits::{Saturating, StaticLookup, Zero},
ArithmeticError, RuntimeDebug,
};
use sp_std::prelude::*;
pub use pallet::*;
pub use types::*;
pub use weights::WeightInfo;
type AccountIdLookupOf<T> = <<T as SystemConfig>::Lookup as StaticLookup>::Source;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::{pallet_prelude::*, traits::ExistenceRequirement};
use frame_system::pallet_prelude::*;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T, I = ()>(_);
#[cfg(feature = "runtime-benchmarks")]
pub trait BenchmarkHelper<CollectionId, ItemId> {
fn collection(i: u16) -> CollectionId;
fn item(i: u16) -> ItemId;
}
#[cfg(feature = "runtime-benchmarks")]
impl<CollectionId: From<u16>, ItemId: From<u16>> BenchmarkHelper<CollectionId, ItemId> for () {
fn collection(i: u16) -> CollectionId {
i.into()
}
fn item(i: u16) -> ItemId {
i.into()
}
}
#[pallet::config]
/// The module configuration trait.
pub trait Config<I: 'static = ()>: frame_system::Config {
/// The overarching event type.
type RuntimeEvent: From<Event<Self, I>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Identifier for the collection of item.
type CollectionId: Member + Parameter + MaxEncodedLen + Copy + Incrementable;
/// The type used to identify a unique item within a collection.
type ItemId: Member + Parameter + MaxEncodedLen + Copy;
/// The currency mechanism, used for paying for reserves.
type Currency: ReservableCurrency<Self::AccountId>;
/// The origin which may forcibly create or destroy an item or otherwise alter privileged
/// attributes.
type ForceOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// Standard collection creation is only allowed if the origin attempting it and the
/// collection are in this set.
type CreateOrigin: EnsureOriginWithArg<
Self::RuntimeOrigin,
Self::CollectionId,
Success = Self::AccountId,
>;
/// Locker trait to enable Locking mechanism downstream.
type Locker: Locker<Self::CollectionId, Self::ItemId>;
/// The basic amount of funds that must be reserved for collection.
#[pallet::constant]
type CollectionDeposit: Get<DepositBalanceOf<Self, I>>;
/// The basic amount of funds that must be reserved for an item.
#[pallet::constant]
type ItemDeposit: Get<DepositBalanceOf<Self, I>>;
/// The basic amount of funds that must be reserved when adding metadata to your item.
#[pallet::constant]
type MetadataDepositBase: Get<DepositBalanceOf<Self, I>>;
/// The basic amount of funds that must be reserved when adding an attribute to an item.
#[pallet::constant]
type AttributeDepositBase: Get<DepositBalanceOf<Self, I>>;
/// The additional funds that must be reserved for the number of bytes store in metadata,
/// either "normal" metadata or attribute metadata.
#[pallet::constant]
type DepositPerByte: Get<DepositBalanceOf<Self, I>>;
/// The maximum length of data stored on-chain.
#[pallet::constant]
type StringLimit: Get<u32>;
/// The maximum length of an attribute key.
#[pallet::constant]
type KeyLimit: Get<u32>;
/// The maximum length of an attribute value.
#[pallet::constant]
type ValueLimit: Get<u32>;
/// The maximum approvals an item could have.
#[pallet::constant]
type ApprovalsLimit: Get<u32>;
/// The maximum attributes approvals an item could have.
#[pallet::constant]
type ItemAttributesApprovalsLimit: Get<u32>;
/// The max number of tips a user could send.
#[pallet::constant]
type MaxTips: Get<u32>;
/// The max duration in blocks for deadlines.
#[pallet::constant]
type MaxDeadlineDuration: Get<<Self as SystemConfig>::BlockNumber>;
/// Disables some of pallet's features.
#[pallet::constant]
type Features: Get<PalletFeatures>;
#[cfg(feature = "runtime-benchmarks")]
/// A set of helper functions for benchmarking.
type Helper: BenchmarkHelper<Self::CollectionId, Self::ItemId>;
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
}
/// Details of a collection.
#[pallet::storage]
pub(super) type Collection<T: Config<I>, I: 'static = ()> = StorageMap<
_,
Blake2_128Concat,
T::CollectionId,
CollectionDetails<T::AccountId, DepositBalanceOf<T, I>>,
>;
/// The collection, if any, of which an account is willing to take ownership.
#[pallet::storage]
pub(super) type OwnershipAcceptance<T: Config<I>, I: 'static = ()> =
StorageMap<_, Blake2_128Concat, T::AccountId, T::CollectionId>;
/// The items held by any given account; set out this way so that items owned by a single
/// account can be enumerated.
#[pallet::storage]
pub(super) type Account<T: Config<I>, I: 'static = ()> = StorageNMap<
_,
(
NMapKey<Blake2_128Concat, T::AccountId>, // owner
NMapKey<Blake2_128Concat, T::CollectionId>,
NMapKey<Blake2_128Concat, T::ItemId>,
),
(),
OptionQuery,
>;
/// The collections owned by any given account; set out this way so that collections owned by
/// a single account can be enumerated.
#[pallet::storage]
pub(super) type CollectionAccount<T: Config<I>, I: 'static = ()> = StorageDoubleMap<
_,
Blake2_128Concat,
T::AccountId,
Blake2_128Concat,
T::CollectionId,
(),
OptionQuery,
>;
/// The items in existence and their ownership details.
#[pallet::storage]
/// Stores collection roles as per account.
pub(super) type CollectionRoleOf<T: Config<I>, I: 'static = ()> = StorageDoubleMap<
_,
Blake2_128Concat,
T::CollectionId,
Blake2_128Concat,
T::AccountId,
CollectionRoles,
OptionQuery,
>;
/// The items in existence and their ownership details.
#[pallet::storage]
pub(super) type Item<T: Config<I>, I: 'static = ()> = StorageDoubleMap<
_,
Blake2_128Concat,
T::CollectionId,
Blake2_128Concat,
T::ItemId,
ItemDetails<T::AccountId, ItemDepositOf<T, I>, ApprovalsOf<T, I>>,
OptionQuery,
>;
/// Metadata of a collection.
#[pallet::storage]
pub(super) type CollectionMetadataOf<T: Config<I>, I: 'static = ()> = StorageMap<
_,
Blake2_128Concat,
T::CollectionId,
CollectionMetadata<DepositBalanceOf<T, I>, T::StringLimit>,
OptionQuery,
>;
/// Metadata of an item.
#[pallet::storage]
pub(super) type ItemMetadataOf<T: Config<I>, I: 'static = ()> = StorageDoubleMap<
_,
Blake2_128Concat,
T::CollectionId,
Blake2_128Concat,
T::ItemId,
ItemMetadata<DepositBalanceOf<T, I>, T::StringLimit>,
OptionQuery,
>;
/// Attributes of a collection.
#[pallet::storage]
pub(super) type Attribute<T: Config<I>, I: 'static = ()> = StorageNMap<
_,
(
NMapKey<Blake2_128Concat, T::CollectionId>,
NMapKey<Blake2_128Concat, Option<T::ItemId>>,
NMapKey<Blake2_128Concat, AttributeNamespace<T::AccountId>>,
NMapKey<Blake2_128Concat, BoundedVec<u8, T::KeyLimit>>,
),
(BoundedVec<u8, T::ValueLimit>, AttributeDepositOf<T, I>),
OptionQuery,
>;
/// A price of an item.
#[pallet::storage]
pub(super) type ItemPriceOf<T: Config<I>, I: 'static = ()> = StorageDoubleMap<
_,
Blake2_128Concat,
T::CollectionId,
Blake2_128Concat,
T::ItemId,
(ItemPrice<T, I>, Option<T::AccountId>),
OptionQuery,
>;
/// Item attribute approvals.
#[pallet::storage]
pub(super) type ItemAttributesApprovalsOf<T: Config<I>, I: 'static = ()> = StorageDoubleMap<
_,
Blake2_128Concat,
T::CollectionId,
Blake2_128Concat,
T::ItemId,
ItemAttributesApprovals<T, I>,
ValueQuery,
>;
/// Stores the `CollectionId` that is going to be used for the next collection.
/// This gets incremented whenever a new collection is created.
#[pallet::storage]
pub(super) type NextCollectionId<T: Config<I>, I: 'static = ()> =
StorageValue<_, T::CollectionId, OptionQuery>;
/// Handles all the pending swaps.
#[pallet::storage]
pub(super) type PendingSwapOf<T: Config<I>, I: 'static = ()> = StorageDoubleMap<
_,
Blake2_128Concat,
T::CollectionId,
Blake2_128Concat,
T::ItemId,
PendingSwap<
T::CollectionId,
T::ItemId,
PriceWithDirection<ItemPrice<T, I>>,
<T as SystemConfig>::BlockNumber,
>,
OptionQuery,
>;
/// Config of a collection.
#[pallet::storage]
pub(super) type CollectionConfigOf<T: Config<I>, I: 'static = ()> =
StorageMap<_, Blake2_128Concat, T::CollectionId, CollectionConfigFor<T, I>, OptionQuery>;
/// Config of an item.
#[pallet::storage]
pub(super) type ItemConfigOf<T: Config<I>, I: 'static = ()> = StorageDoubleMap<
_,
Blake2_128Concat,
T::CollectionId,
Blake2_128Concat,
T::ItemId,
ItemConfig,
OptionQuery,
>;
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config<I>, I: 'static = ()> {
/// A `collection` was created.
Created { collection: T::CollectionId, creator: T::AccountId, owner: T::AccountId },
/// A `collection` was force-created.
ForceCreated { collection: T::CollectionId, owner: T::AccountId },
/// A `collection` was destroyed.
Destroyed { collection: T::CollectionId },
/// An `item` was issued.
Issued { collection: T::CollectionId, item: T::ItemId, owner: T::AccountId },
/// An `item` was transferred.
Transferred {
collection: T::CollectionId,
item: T::ItemId,
from: T::AccountId,
to: T::AccountId,
},
/// An `item` was destroyed.
Burned { collection: T::CollectionId, item: T::ItemId, owner: T::AccountId },
/// An `item` became non-transferable.
ItemTransferLocked { collection: T::CollectionId, item: T::ItemId },
/// An `item` became transferable.
ItemTransferUnlocked { collection: T::CollectionId, item: T::ItemId },
/// `item` metadata or attributes were locked.
ItemPropertiesLocked {
collection: T::CollectionId,
item: T::ItemId,
lock_metadata: bool,
lock_attributes: bool,
},
/// Some `collection` was locked.
CollectionLocked { collection: T::CollectionId },
/// The owner changed.
OwnerChanged { collection: T::CollectionId, new_owner: T::AccountId },
/// The management team changed.
TeamChanged {
collection: T::CollectionId,
issuer: T::AccountId,
admin: T::AccountId,
freezer: T::AccountId,
},
/// An `item` of a `collection` has been approved by the `owner` for transfer by
/// a `delegate`.
ApprovedTransfer {
collection: T::CollectionId,
item: T::ItemId,
owner: T::AccountId,
delegate: T::AccountId,
deadline: Option<<T as SystemConfig>::BlockNumber>,
},
/// An approval for a `delegate` account to transfer the `item` of an item
/// `collection` was cancelled by its `owner`.
ApprovalCancelled {
collection: T::CollectionId,
item: T::ItemId,
owner: T::AccountId,
delegate: T::AccountId,
},
/// All approvals of an item got cancelled.
AllApprovalsCancelled { collection: T::CollectionId, item: T::ItemId, owner: T::AccountId },
/// A `collection` has had its config changed by the `Force` origin.
CollectionConfigChanged { collection: T::CollectionId },
/// New metadata has been set for a `collection`.
CollectionMetadataSet { collection: T::CollectionId, data: BoundedVec<u8, T::StringLimit> },
/// Metadata has been cleared for a `collection`.
CollectionMetadataCleared { collection: T::CollectionId },
/// New metadata has been set for an item.
MetadataSet {
collection: T::CollectionId,
item: T::ItemId,
data: BoundedVec<u8, T::StringLimit>,
},
/// Metadata has been cleared for an item.
MetadataCleared { collection: T::CollectionId, item: T::ItemId },
/// Metadata has been cleared for an item.
Redeposited { collection: T::CollectionId, successful_items: Vec<T::ItemId> },
/// New attribute metadata has been set for a `collection` or `item`.
AttributeSet {
collection: T::CollectionId,
maybe_item: Option<T::ItemId>,
key: BoundedVec<u8, T::KeyLimit>,
value: BoundedVec<u8, T::ValueLimit>,
namespace: AttributeNamespace<T::AccountId>,
},
/// Attribute metadata has been cleared for a `collection` or `item`.
AttributeCleared {
collection: T::CollectionId,
maybe_item: Option<T::ItemId>,
key: BoundedVec<u8, T::KeyLimit>,
namespace: AttributeNamespace<T::AccountId>,
},
/// A new approval to modify item attributes was added.
ItemAttributesApprovalAdded {
collection: T::CollectionId,
item: T::ItemId,
delegate: T::AccountId,
},
/// A new approval to modify item attributes was removed.
ItemAttributesApprovalRemoved {
collection: T::CollectionId,
item: T::ItemId,
delegate: T::AccountId,
},
/// Ownership acceptance has changed for an account.
OwnershipAcceptanceChanged { who: T::AccountId, maybe_collection: Option<T::CollectionId> },
/// Max supply has been set for a collection.
CollectionMaxSupplySet { collection: T::CollectionId, max_supply: u32 },
/// Mint settings for a collection had changed.
CollectionMintSettingsUpdated { collection: T::CollectionId },
/// Event gets emmited when the `NextCollectionId` gets incremented.
NextCollectionIdIncremented { next_id: T::CollectionId },
/// The price was set for the instance.
ItemPriceSet {
collection: T::CollectionId,
item: T::ItemId,
price: ItemPrice<T, I>,
whitelisted_buyer: Option<T::AccountId>,
},
/// The price for the instance was removed.
ItemPriceRemoved { collection: T::CollectionId, item: T::ItemId },
/// An item was bought.
ItemBought {
collection: T::CollectionId,
item: T::ItemId,
price: ItemPrice<T, I>,
seller: T::AccountId,
buyer: T::AccountId,
},
/// A tip was sent.
TipSent {
collection: T::CollectionId,
item: T::ItemId,
sender: T::AccountId,
receiver: T::AccountId,
amount: DepositBalanceOf<T, I>,
},
/// An `item` swap intent was created.
SwapCreated {
offered_collection: T::CollectionId,
offered_item: T::ItemId,
desired_collection: T::CollectionId,
desired_item: Option<T::ItemId>,
price: Option<PriceWithDirection<ItemPrice<T, I>>>,
deadline: <T as SystemConfig>::BlockNumber,
},
/// The swap was cancelled.
SwapCancelled {
offered_collection: T::CollectionId,
offered_item: T::ItemId,
desired_collection: T::CollectionId,
desired_item: Option<T::ItemId>,
price: Option<PriceWithDirection<ItemPrice<T, I>>>,
deadline: <T as SystemConfig>::BlockNumber,
},
/// The swap has been claimed.
SwapClaimed {
sent_collection: T::CollectionId,
sent_item: T::ItemId,
sent_item_owner: T::AccountId,
received_collection: T::CollectionId,
received_item: T::ItemId,
received_item_owner: T::AccountId,
price: Option<PriceWithDirection<ItemPrice<T, I>>>,
deadline: <T as SystemConfig>::BlockNumber,
},
}
#[pallet::error]
pub enum Error<T, I = ()> {
/// The signing account has no permission to do the operation.
NoPermission,
/// The given item ID is unknown.
UnknownCollection,
/// The item ID has already been used for an item.
AlreadyExists,
/// The approval had a deadline that expired, so the approval isn't valid anymore.
ApprovalExpired,
/// The owner turned out to be different to what was expected.
WrongOwner,
/// The witness data given does not match the current state of the chain.
BadWitness,
/// Collection ID is already taken.
CollectionIdInUse,
/// Items within that collection are non-transferable.
ItemsNonTransferable,
/// The provided account is not a delegate.
NotDelegate,
/// The delegate turned out to be different to what was expected.
WrongDelegate,
/// No approval exists that would allow the transfer.
Unapproved,
/// The named owner has not signed ownership acceptance of the collection.
Unaccepted,
/// The item is locked (non-transferable).
ItemLocked,
/// Item's attributes are locked.
LockedItemAttributes,
/// Collection's attributes are locked.
LockedCollectionAttributes,
/// Item's metadata is locked.
LockedItemMetadata,
/// Collection's metadata is locked.
LockedCollectionMetadata,
/// All items have been minted.
MaxSupplyReached,
/// The max supply is locked and can't be changed.
MaxSupplyLocked,
/// The provided max supply is less to the amount of items a collection already has.
MaxSupplyTooSmall,
/// The given item ID is unknown.
UnknownItem,
/// Swap doesn't exist.
UnknownSwap,
/// Item is not for sale.
NotForSale,
/// The provided bid is too low.
BidTooLow,
/// The item has reached its approval limit.
ReachedApprovalLimit,
/// The deadline has already expired.
DeadlineExpired,
/// The duration provided should be less or equal to MaxDeadlineDuration.
WrongDuration,
/// The method is disabled by system settings.
MethodDisabled,
/// The provided is setting can't be set.
WrongSetting,
/// Item's config already exists and should be equal to the provided one.
InconsistentItemConfig,
/// Config for a collection or an item can't be found.
NoConfig,
/// Some roles were not cleared.
RolesNotCleared,
/// Mint has not started yet.
MintNotStarted,
/// Mint has already ended.
MintEnded,
/// The provided Item was already used for claiming.
AlreadyClaimed,
/// The provided data is incorrect.
IncorrectData,
}
#[pallet::call]
impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// Issue a new collection of non-fungible items from a public origin.
///
/// This new collection has no items initially and its owner is the origin.
///
/// The origin must be Signed and the sender must have sufficient funds free.
///
/// `ItemDeposit` funds of sender are reserved.
///
/// Parameters:
/// - `admin`: The admin of this collection. The admin is the initial address of each
/// member of the collection's admin team.
///
/// Emits `Created` event when successful.
///
/// Weight: `O(1)`
#[pallet::weight(T::WeightInfo::create())]
pub fn create(
origin: OriginFor<T>,
admin: AccountIdLookupOf<T>,
config: CollectionConfigFor<T, I>,
) -> DispatchResult {
let collection =
NextCollectionId::<T, I>::get().unwrap_or(T::CollectionId::initial_value());
let owner = T::CreateOrigin::ensure_origin(origin, &collection)?;
let admin = T::Lookup::lookup(admin)?;
// DepositRequired can be disabled by calling the force_create() only
ensure!(
!config.has_disabled_setting(CollectionSetting::DepositRequired),
Error::<T, I>::WrongSetting
);
Self::do_create_collection(
collection,
owner.clone(),
admin.clone(),
config,
T::CollectionDeposit::get(),
Event::Created { collection, creator: owner, owner: admin },
)
}
/// Issue a new collection of non-fungible items from a privileged origin.
///
/// This new collection has no items initially.
///
/// The origin must conform to `ForceOrigin`.
///
/// Unlike `create`, no funds are reserved.
///
/// - `owner`: The owner of this collection of items. The owner has full superuser
/// permissions
/// over this item, but may later change and configure the permissions using
/// `transfer_ownership` and `set_team`.
///
/// Emits `ForceCreated` event when successful.
///
/// Weight: `O(1)`
#[pallet::weight(T::WeightInfo::force_create())]
pub fn force_create(
origin: OriginFor<T>,
owner: AccountIdLookupOf<T>,
config: CollectionConfigFor<T, I>,
) -> DispatchResult {
T::ForceOrigin::ensure_origin(origin)?;
let owner = T::Lookup::lookup(owner)?;
let collection =
NextCollectionId::<T, I>::get().unwrap_or(T::CollectionId::initial_value());
Self::do_create_collection(
collection,
owner.clone(),
owner.clone(),
config,
Zero::zero(),
Event::ForceCreated { collection, owner },
)
}
/// Destroy a collection of fungible items.
///
/// The origin must conform to `ForceOrigin` or must be `Signed` and the sender must be the
/// owner of the `collection`.
///
/// - `collection`: The identifier of the collection to be destroyed.
/// - `witness`: Information on the items minted in the collection. This must be
/// correct.
///
/// Emits `Destroyed` event when successful.
///
/// Weight: `O(n + m)` where:
/// - `n = witness.items`
/// - `m = witness.item_metadatas`
/// - `a = witness.attributes`
#[pallet::weight(T::WeightInfo::destroy(
witness.items,
witness.item_metadatas,
witness.attributes,
))]
pub fn destroy(
origin: OriginFor<T>,
collection: T::CollectionId,
witness: DestroyWitness,
) -> DispatchResultWithPostInfo {
let maybe_check_owner = T::ForceOrigin::try_origin(origin)
.map(|_| None)
.or_else(|origin| ensure_signed(origin).map(Some).map_err(DispatchError::from))?;
let details = Self::do_destroy_collection(collection, witness, maybe_check_owner)?;
Ok(Some(T::WeightInfo::destroy(
details.items,
details.item_metadatas,
details.attributes,
))
.into())
}
/// Mint an item of a particular collection.
///
/// The origin must be Signed and the sender must be the Issuer of the `collection`.
///
/// - `collection`: The collection of the item to be minted.
/// - `item`: An identifier of the new item.
/// - `witness_data`: When the mint type is `HolderOf(collection_id)`, then the owned
/// item_id from that collection needs to be provided within the witness data object.
///
/// Emits `Issued` event when successful.
///
/// Weight: `O(1)`
#[pallet::weight(T::WeightInfo::mint())]
pub fn mint(
origin: OriginFor<T>,
collection: T::CollectionId,
item: T::ItemId,
witness_data: Option<MintWitness<T::ItemId>>,
) -> DispatchResult {
let caller = ensure_signed(origin)?;
let collection_config = Self::get_collection_config(&collection)?;
let item_settings = collection_config.mint_settings.default_item_settings;
let item_config = ItemConfig { settings: item_settings };
Self::do_mint(
collection,
item,
caller.clone(),
item_config,
false,
|collection_details, collection_config| {
let mint_settings = collection_config.mint_settings;
let now = frame_system::Pallet::<T>::block_number();
if let Some(start_block) = mint_settings.start_block {
ensure!(start_block <= now, Error::<T, I>::MintNotStarted);
}
if let Some(end_block) = mint_settings.end_block {
ensure!(end_block >= now, Error::<T, I>::MintEnded);
}
match mint_settings.mint_type {
MintType::Issuer => {
ensure!(
Self::has_role(&collection, &caller, CollectionRole::Issuer),
Error::<T, I>::NoPermission
)
},
MintType::HolderOf(collection_id) => {
let MintWitness { owner_of_item } =
witness_data.ok_or(Error::<T, I>::BadWitness)?;
let has_item = Account::<T, I>::contains_key((
&caller,
&collection_id,
&owner_of_item,
));
ensure!(has_item, Error::<T, I>::BadWitness);
let attribute_key = Self::construct_attribute_key(
PalletAttributes::<T::CollectionId>::UsedToClaim(collection)
.encode(),
)?;
let key = (
&collection_id,
Some(owner_of_item),
AttributeNamespace::Pallet,
&attribute_key,
);
let already_claimed = Attribute::<T, I>::contains_key(key.clone());
ensure!(!already_claimed, Error::<T, I>::AlreadyClaimed);
let value = Self::construct_attribute_value(vec![0])?;
Attribute::<T, I>::insert(
key,
(value, AttributeDeposit { account: None, amount: Zero::zero() }),
);
},
_ => {},
}
if let Some(price) = mint_settings.price {
T::Currency::transfer(
&caller,
&collection_details.owner,
price,
ExistenceRequirement::KeepAlive,
)?;
}
Ok(())
},
)
}
/// Mint an item of a particular collection from a privileged origin.
///
/// The origin must conform to `ForceOrigin` or must be `Signed` and the sender must be the
/// Issuer of the `collection`.
///
/// - `collection`: The collection of the item to be minted.
/// - `item`: An identifier of the new item.
/// - `owner`: An owner of the minted item.
/// - `item_config`: A config of the new item.
///
/// Emits `Issued` event when successful.
///
/// Weight: `O(1)`
#[pallet::weight(T::WeightInfo::force_mint())]
pub fn force_mint(
origin: OriginFor<T>,
collection: T::CollectionId,
item: T::ItemId,
owner: AccountIdLookupOf<T>,
item_config: ItemConfig,
) -> DispatchResult {
let maybe_check_origin = T::ForceOrigin::try_origin(origin)
.map(|_| None)
.or_else(|origin| ensure_signed(origin).map(Some).map_err(DispatchError::from))?;
let owner = T::Lookup::lookup(owner)?;
if let Some(check_origin) = maybe_check_origin {
ensure!(
Self::has_role(&collection, &check_origin, CollectionRole::Issuer),
Error::<T, I>::NoPermission
);
}
Self::do_mint(collection, item, owner, item_config, true, |_, _| Ok(()))
}
/// Destroy a single item.
///
/// Origin must be Signed and the sender should be the Admin of the `collection`.
///
/// - `collection`: The collection of the item to be burned.
/// - `item`: The item to be burned.
/// - `check_owner`: If `Some` then the operation will fail with `WrongOwner` unless the
/// item is owned by this value.
///
/// Emits `Burned` with the actual amount burned.
///
/// Weight: `O(1)`
/// Modes: `check_owner.is_some()`.
#[pallet::weight(T::WeightInfo::burn())]
pub fn burn(
origin: OriginFor<T>,
collection: T::CollectionId,
item: T::ItemId,
check_owner: Option<AccountIdLookupOf<T>>,
) -> DispatchResult {
let origin = ensure_signed(origin)?;
let check_owner = check_owner.map(T::Lookup::lookup).transpose()?;
Self::do_burn(collection, item, |details| {
let is_admin = Self::has_role(&collection, &origin, CollectionRole::Admin);
let is_permitted = is_admin || details.owner == origin;
ensure!(is_permitted, Error::<T, I>::NoPermission);
ensure!(
check_owner.map_or(true, |o| o == details.owner),
Error::<T, I>::WrongOwner
);
Ok(())
})
}
/// Move an item from the sender account to another.
///
/// Origin must be Signed and the signing account must be either:
/// - the Admin of the `collection`;
/// - the Owner of the `item`;
/// - the approved delegate for the `item` (in this case, the approval is reset).
///
/// Arguments:
/// - `collection`: The collection of the item to be transferred.
/// - `item`: The item to be transferred.
/// - `dest`: The account to receive ownership of the item.
///
/// Emits `Transferred`.
///
/// Weight: `O(1)`
#[pallet::weight(T::WeightInfo::transfer())]
pub fn transfer(
origin: OriginFor<T>,
collection: T::CollectionId,
item: T::ItemId,
dest: AccountIdLookupOf<T>,
) -> DispatchResult {
let origin = ensure_signed(origin)?;
let dest = T::Lookup::lookup(dest)?;
Self::do_transfer(collection, item, dest, |_, details| {
let is_admin = Self::has_role(&collection, &origin, CollectionRole::Admin);
if details.owner != origin && !is_admin {
let deadline =
details.approvals.get(&origin).ok_or(Error::<T, I>::NoPermission)?;
if let Some(d) = deadline {
let block_number = frame_system::Pallet::<T>::block_number();
ensure!(block_number <= *d, Error::<T, I>::ApprovalExpired);
}
}
Ok(())
})
}
/// Re-evaluate the deposits on some items.
///
/// Origin must be Signed and the sender should be the Owner of the `collection`.
///
/// - `collection`: The collection of the items to be reevaluated.
/// - `items`: The items of the collection whose deposits will be reevaluated.
///
/// NOTE: This exists as a best-effort function. Any items which are unknown or
/// in the case that the owner account does not have reservable funds to pay for a
/// deposit increase are ignored. Generally the owner isn't going to call this on items
/// whose existing deposit is less than the refreshed deposit as it would only cost them,
/// so it's of little consequence.
///
/// It will still return an error in the case that the collection is unknown of the signer
/// is not permitted to call it.
///
/// Weight: `O(items.len())`
#[pallet::weight(T::WeightInfo::redeposit(items.len() as u32))]
pub fn redeposit(
origin: OriginFor<T>,
collection: T::CollectionId,
items: Vec<T::ItemId>,
) -> DispatchResult {
let origin = ensure_signed(origin)?;
let collection_details =
Collection::<T, I>::get(&collection).ok_or(Error::<T, I>::UnknownCollection)?;
ensure!(collection_details.owner == origin, Error::<T, I>::NoPermission);
let config = Self::get_collection_config(&collection)?;
let deposit = match config.is_setting_enabled(CollectionSetting::DepositRequired) {
true => T::ItemDeposit::get(),
false => Zero::zero(),
};
let mut successful = Vec::with_capacity(items.len());
for item in items.into_iter() {
let mut details = match Item::<T, I>::get(&collection, &item) {
Some(x) => x,
None => continue,
};
let old = details.deposit.amount;
if old > deposit {
T::Currency::unreserve(&details.deposit.account, old - deposit);
} else if deposit > old {
if T::Currency::reserve(&details.deposit.account, deposit - old).is_err() {
// NOTE: No alterations made to collection_details in this iteration so far,
// so this is OK to do.
continue
}
} else {
continue
}
details.deposit.amount = deposit;
Item::<T, I>::insert(&collection, &item, &details);
successful.push(item);
}
Self::deposit_event(Event::<T, I>::Redeposited {
collection,
successful_items: successful,
});
Ok(())
}
/// Disallow further unprivileged transfer of an item.
///
/// Origin must be Signed and the sender should be the Freezer of the `collection`.
///
/// - `collection`: The collection of the item to be changed.
/// - `item`: The item to become non-transferable.
///
/// Emits `ItemTransferLocked`.
///
/// Weight: `O(1)`
#[pallet::weight(T::WeightInfo::lock_item_transfer())]
pub fn lock_item_transfer(
origin: OriginFor<T>,
collection: T::CollectionId,
item: T::ItemId,
) -> DispatchResult {