-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathlib.rs
More file actions
936 lines (845 loc) · 35.8 KB
/
lib.rs
File metadata and controls
936 lines (845 loc) · 35.8 KB
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
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::dispatch::{
DispatchError, DispatchResult, DispatchResultWithPostInfo, PostDispatchInfo,
};
use frame_support::traits::Get;
use frame_support::weights::Weight;
use frame_support::{ensure, require_transactional};
use sp_std::collections::btree_map::BTreeMap;
use sp_std::collections::btree_set::BTreeSet;
use sp_std::{vec, vec::Vec};
use pallet_asset::Frozen;
use pallet_base::try_next_pre;
use pallet_portfolio::{PortfolioLockedNFT, PortfolioNFT};
use polymesh_primitives::asset::{AssetId, AssetName, AssetType, NonFungibleType};
use polymesh_primitives::asset_metadata::{AssetMetadataKey, AssetMetadataValue};
use polymesh_primitives::nft::{
NFTCollection, NFTCollectionId, NFTCollectionKeys, NFTCount, NFTId, NFTMetadataAttribute, NFTs,
};
use polymesh_primitives::settlement::InstructionId;
use polymesh_primitives::{
traits::{ComplianceFnConfig, NFTTrait},
IdentityId, Memo, PortfolioId, PortfolioKind, PortfolioUpdateReason, WeightMeter,
};
type Asset<T> = pallet_asset::Pallet<T>;
type ExternalAgents<T> = pallet_external_agents::Pallet<T>;
type IdentityPallet<T> = pallet_identity::Pallet<T>;
type Portfolio<T> = pallet_portfolio::Pallet<T>;
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
pub trait WeightInfo {
fn create_nft_collection(n: u32) -> Weight;
fn issue_nft(n: u32) -> Weight;
fn redeem_nft(n: u32) -> Weight;
fn base_nft_transfer(n: u32) -> Weight;
fn controller_transfer(n: u32) -> Weight;
}
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::{OptionQuery, *};
use frame_system::pallet_prelude::*;
#[pallet::config]
pub trait Config:
frame_system::Config
+ pallet_asset::Config
+ pallet_asset::checkpoint::Config
+ pallet_identity::Config
+ pallet_portfolio::Config
{
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type WeightInfo: WeightInfo;
type Compliance: ComplianceFnConfig;
#[pallet::constant]
type MaxNumberOfCollectionKeys: Get<u8>;
#[pallet::constant]
type MaxNumberOfNFTsCount: Get<u32>;
}
const STORAGE_VERSION: StorageVersion = StorageVersion::new(5);
#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
pub struct Pallet<T>(_);
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Emitted when a new nft collection is created.
NftCollectionCreated(IdentityId, AssetId, NFTCollectionId),
/// Emitted when NFTs were issued, redeemed or transferred.
/// Contains the [`IdentityId`] of the receiver/issuer/redeemer, the [`NFTs`], the [`PortfolioId`] of the source, the [`PortfolioId`]
/// of the destination and the [`PortfolioUpdateReason`].
NFTPortfolioUpdated(
IdentityId,
NFTs,
Option<PortfolioId>,
Option<PortfolioId>,
PortfolioUpdateReason,
),
}
/// The total number of NFTs per identity.
#[pallet::storage]
pub type NumberOfNFTs<T: Config> =
StorageDoubleMap<_, Blake2_128Concat, AssetId, Identity, IdentityId, NFTCount, ValueQuery>;
/// The collection id corresponding to each asset.
#[pallet::storage]
pub type CollectionAsset<T: Config> =
StorageMap<_, Blake2_128Concat, AssetId, NFTCollectionId, ValueQuery>;
/// All collection details for a given collection id.
#[pallet::storage]
pub type Collection<T: Config> =
StorageMap<_, Blake2_128Concat, NFTCollectionId, NFTCollection, ValueQuery>;
/// All mandatory metadata keys for a given collection.
#[pallet::storage]
#[pallet::unbounded]
pub type CollectionKeys<T: Config> =
StorageMap<_, Blake2_128Concat, NFTCollectionId, BTreeSet<AssetMetadataKey>, ValueQuery>;
/// The metadata value of an nft given its collection id, token id and metadata key.
#[pallet::storage]
#[pallet::unbounded]
pub type MetadataValue<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
(NFTCollectionId, NFTId),
Blake2_128Concat,
AssetMetadataKey,
AssetMetadataValue,
ValueQuery,
>;
/// The total number of NFTs in a collection.
#[pallet::storage]
pub type NFTsInCollection<T: Config> =
StorageMap<_, Blake2_128Concat, AssetId, NFTCount, ValueQuery>;
/// Tracks the owner of an NFT
#[pallet::storage]
pub type NFTOwner<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
AssetId,
Blake2_128Concat,
NFTId,
PortfolioId,
OptionQuery,
>;
/// The last `NFTId` used for an NFT.
#[pallet::storage]
pub type CurrentNFTId<T: Config> =
StorageMap<_, Blake2_128Concat, NFTCollectionId, NFTId, OptionQuery>;
/// The last `NFTCollectionId` used for a collection.
#[pallet::storage]
pub type CurrentCollectionId<T: Config> = StorageValue<_, NFTCollectionId, OptionQuery>;
#[pallet::genesis_config]
#[derive(Default)]
pub struct GenesisConfig;
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {}
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_runtime_upgrade() -> Weight {
polymesh_primitives::migrate::frame_v2_migrate::<Pallet<T>>("NFT", STORAGE_VERSION)
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Cretes a new `NFTCollection`.
///
/// # Arguments
/// * `origin` - contains the secondary key of the caller (i.e. who signed the transaction to execute this function).
/// * `asset_id` - optional [`AssetId`] associated to the new collection. `None` will create a new asset.
/// * `nft_type` - in case the asset hasn't been created yet, one will be created with the given type.
/// * `collection_keys` - all mandatory metadata keys that the tokens in the collection must have.
///
/// ## Errors
/// - `CollectionAlredyRegistered` - if the asset_id is already associated to an NFT collection.
/// - `InvalidAssetType` - if the associated asset is not of type NFT.
/// - `MaxNumberOfKeysExceeded` - if the number of metadata keys for the collection is greater than the maximum allowed.
/// - `UnregisteredMetadataKey` - if any of the metadata keys needed for the collection has not been registered.
/// - `DuplicateMetadataKey` - if a duplicate metadata keys has been passed as input.
///
/// # Permissions
/// * Asset
#[pallet::weight(<T as Config>::WeightInfo::create_nft_collection(collection_keys.len() as u32))]
#[pallet::call_index(0)]
pub fn create_nft_collection(
origin: OriginFor<T>,
asset_id: Option<AssetId>,
nft_type: Option<NonFungibleType>,
collection_keys: NFTCollectionKeys,
) -> DispatchResult {
Self::base_create_nft_collection(origin, asset_id, nft_type, collection_keys)
}
/// Issues an NFT to the caller.
///
/// # Arguments
/// * `origin` - is a signer that has permissions to act as an agent of `asset_id`.
/// * `asset_id` - the [`AssetId`] of the NFT collection.
/// * `nft_metadata_attributes` - all mandatory metadata keys and values for the NFT.
/// - `portfolio_kind` - the portfolio that will receive the minted nft.
///
/// ## Errors
/// - `CollectionNotFound` - if the collection associated to the given asset_id has not been created.
/// - `InvalidMetadataAttribute` - if the number of attributes is not equal to the number set in the collection or attempting to set a value for a key not definied in the collection.
/// - `DuplicateMetadataKey` - if a duplicate metadata keys has been passed as input.
///
///
/// # Permissions
/// * Asset
/// * Portfolio
#[pallet::weight(<T as Config>::WeightInfo::issue_nft(nft_metadata_attributes.len() as u32))]
#[pallet::call_index(1)]
pub fn issue_nft(
origin: OriginFor<T>,
asset_id: AssetId,
nft_metadata_attributes: Vec<NFTMetadataAttribute>,
portfolio_kind: PortfolioKind,
) -> DispatchResult {
Self::base_issue_nft(origin, asset_id, nft_metadata_attributes, portfolio_kind)
}
/// Redeems the given NFT from the caller's portfolio.
///
/// # Arguments
/// * `origin` - is a signer that has permissions to act as an agent of `asset_id`.
/// * `asset_id` - the [`AssetId`] of the NFT collection.
/// * `nft_id` - the id of the NFT to be burned.
/// * `portfolio_kind` - the portfolio that contains the nft.
///
/// ## Errors
/// - `CollectionNotFound` - if the collection associated to the given asset_id has not been created.
/// - `NFTNotFound` - if the given NFT does not exist in the portfolio.
///
/// # Permissions
/// * Asset
/// * Portfolio
#[pallet::weight(<T as Config>::WeightInfo::redeem_nft(
number_of_keys.map_or(
u32::from(T::MaxNumberOfCollectionKeys::get()),
|v| u32::from(v)
)
))]
#[pallet::call_index(2)]
pub fn redeem_nft(
origin: OriginFor<T>,
asset_id: AssetId,
nft_id: NFTId,
portfolio_kind: PortfolioKind,
number_of_keys: Option<u8>,
) -> DispatchResultWithPostInfo {
Self::base_redeem_nft(origin, asset_id, nft_id, portfolio_kind, number_of_keys)
}
/// Forces the transfer of NFTs from a given portfolio to the caller's portfolio.
///
/// # Arguments
/// * `origin` - is a signer that has permissions to act as an agent of `asset_id`.
/// * `nft_id` - the [`NFTId`] of the NFT to be transferred.
/// * `source_portfolio` - the [`PortfolioId`] that currently holds the NFT.
/// * `callers_portfolio_kind` - the [`PortfolioKind`] of the caller's portfolio.
///
/// # Permissions
/// * Asset
/// * Portfolio
#[pallet::weight(<T as Config>::WeightInfo::controller_transfer(nfts.len() as u32))]
#[pallet::call_index(3)]
pub fn controller_transfer(
origin: OriginFor<T>,
nfts: NFTs,
source_portfolio: PortfolioId,
callers_portfolio_kind: PortfolioKind,
) -> DispatchResult {
Self::base_controller_transfer(origin, nfts, source_portfolio, callers_portfolio_kind)
}
}
#[pallet::error]
pub enum Error<T> {
/// An overflow while calculating the balance.
BalanceOverflow,
/// An underflow while calculating the balance.
BalanceUnderflow,
/// The asset_id is already associated to an NFT collection.
CollectionAlredyRegistered,
/// The NFT collection does not exist.
CollectionNotFound,
/// A duplicate metadata key has been passed as parameter.
DuplicateMetadataKey,
/// Duplicate ids are not allowed.
DuplicatedNFTId,
/// The asset must be of type non-fungible.
InvalidAssetType,
/// Either the number of keys or the key identifier does not match the keys defined for the collection.
InvalidMetadataAttribute,
/// Failed to transfer an NFT - NFT collection not found.
InvalidNFTTransferCollectionNotFound,
/// Failed to transfer an NFT - attempt to move to the same portfolio.
InvalidNFTTransferSamePortfolio,
/// Failed to transfer an NFT - NFT not found in portfolio.
InvalidNFTTransferNFTNotOwned,
/// Failed to transfer an NFT - identity count would overflow.
InvalidNFTTransferCountOverflow,
/// Failed to transfer an NFT - compliance failed.
InvalidNFTTransferComplianceFailure,
/// Failed to transfer an NFT - asset is frozen.
InvalidNFTTransferFrozenAsset,
/// Failed to transfer an NFT - the number of nfts in the identity is insufficient.
InvalidNFTTransferInsufficientCount,
/// The maximum number of metadata keys was exceeded.
MaxNumberOfKeysExceeded,
/// The maximum number of nfts being transferred in one leg was exceeded.
MaxNumberOfNFTsPerLegExceeded,
/// The NFT does not exist.
NFTNotFound,
/// At least one of the metadata keys has not been registered.
UnregisteredMetadataKey,
/// It is not possible to transferr zero nft.
ZeroCount,
/// An overflow while calculating the updated supply.
SupplyOverflow,
/// An underflow while calculating the updated supply.
SupplyUnderflow,
/// Failed to transfer an NFT - nft is locked.
InvalidNFTTransferNFTIsLocked,
/// The sender identity can't be the same as the receiver identity.
InvalidNFTTransferSenderIdMatchesReceiverId,
/// The receiver has an invalid CDD.
InvalidNFTTransferInvalidReceiverCDD,
/// The sender has an invalid CDD.
InvalidNFTTransferInvalidSenderCDD,
/// There's no asset associated to the given asset_id.
InvalidAssetId,
/// The NFT is locked.
NFTIsLocked,
/// The number of keys in the collection is greater than the input.
NumberOfKeysIsLessThanExpected,
}
}
impl<T: Config> Pallet<T> {
fn base_create_nft_collection(
origin: T::RuntimeOrigin,
asset_id: Option<AssetId>,
nft_type: Option<NonFungibleType>,
collection_keys: NFTCollectionKeys,
) -> DispatchResult {
// Verifies if the caller has asset permission and if the asset is an NFT.
let (create_asset, caller_did, asset_id) = {
match asset_id {
Some(asset_id) => match Asset::<T>::nft_asset(&asset_id) {
Some(is_nft_asset) => {
ensure!(is_nft_asset, Error::<T>::InvalidAssetType);
let caller_did = <ExternalAgents<T>>::ensure_agent_asset_perms(
origin.clone(),
asset_id,
)?
.primary_did;
(false, caller_did, asset_id)
}
None => return Err(Error::<T>::InvalidAssetId.into()),
},
None => {
let caller_data =
IdentityPallet::<T>::ensure_origin_call_permissions(origin.clone())?;
let asset_id = Asset::<T>::generate_asset_id(caller_data.sender, false);
(true, caller_data.primary_did, asset_id)
}
}
};
// Verifies if the asset_id is already associated to an NFT collection
ensure!(
!CollectionAsset::<T>::contains_key(&asset_id),
Error::<T>::CollectionAlredyRegistered
);
// Verifies if the maximum number of keys is respected
ensure!(
collection_keys.len() <= (T::MaxNumberOfCollectionKeys::get() as usize),
Error::<T>::MaxNumberOfKeysExceeded
);
// Verifies that there are no duplicated keys
let n_keys = collection_keys.len();
let collection_keys: BTreeSet<AssetMetadataKey> = collection_keys.into_iter().collect();
ensure!(
n_keys == collection_keys.len(),
Error::<T>::DuplicateMetadataKey
);
// Verifies that all keys have been registered
for key in &collection_keys {
ensure!(
Asset::<T>::check_asset_metadata_key_exists(&asset_id, key),
Error::<T>::UnregisteredMetadataKey
)
}
// Creates an nft asset if it hasn't been created yet
if create_asset {
let nft_type = nft_type.ok_or(Error::<T>::InvalidAssetType)?;
Asset::<T>::create_asset(
origin,
AssetName(Vec::new()),
false,
AssetType::NonFungible(nft_type),
Vec::new(),
None,
)?;
}
// Creates the nft collection
let collection_id = Self::update_current_collection_id()?;
let nft_collection = NFTCollection::new(collection_id, asset_id.clone());
Collection::<T>::insert(&collection_id, nft_collection);
CollectionKeys::<T>::insert(&collection_id, collection_keys);
CollectionAsset::<T>::insert(&asset_id, &collection_id);
Self::deposit_event(Event::NftCollectionCreated(
caller_did,
asset_id,
collection_id,
));
Ok(())
}
fn base_issue_nft(
origin: T::RuntimeOrigin,
asset_id: AssetId,
metadata_attributes: Vec<NFTMetadataAttribute>,
portfolio_kind: PortfolioKind,
) -> DispatchResult {
// Verifies if the collection exists
let collection_id =
CollectionAsset::<T>::try_get(&asset_id).map_err(|_| Error::<T>::CollectionNotFound)?;
// Verifies if the caller has the right permissions (regarding asset and portfolio)
let caller_portfolio = Asset::<T>::ensure_origin_asset_and_portfolio_permissions(
origin,
asset_id.clone(),
portfolio_kind,
false,
)?;
Portfolio::<T>::ensure_portfolio_validity(&caller_portfolio)?;
// Verifies that all mandatory keys are being set and that there are no duplicated keys
let mandatory_keys: BTreeSet<AssetMetadataKey> = CollectionKeys::<T>::get(&collection_id);
ensure!(
mandatory_keys.len() == metadata_attributes.len(),
Error::<T>::InvalidMetadataAttribute
);
let n_keys = metadata_attributes.len();
let nft_attributes: BTreeMap<_, _> = metadata_attributes
.into_iter()
.map(|a| (a.key, a.value))
.collect();
ensure!(
n_keys == nft_attributes.len(),
Error::<T>::DuplicateMetadataKey
);
for metadata_key in nft_attributes.keys() {
ensure!(
mandatory_keys.contains(metadata_key),
Error::<T>::InvalidMetadataAttribute
);
}
// Mints the NFT and adds it to the caller's portfolio
let new_supply = NFTsInCollection::<T>::get(&asset_id)
.checked_add(1)
.ok_or(Error::<T>::SupplyOverflow)?;
let new_balance = NumberOfNFTs::<T>::get(&asset_id, &caller_portfolio.did)
.checked_add(1)
.ok_or(Error::<T>::BalanceOverflow)?;
let nft_id = Self::update_current_nft_id(&collection_id)?;
NFTsInCollection::<T>::insert(&asset_id, new_supply);
NumberOfNFTs::<T>::insert(&asset_id, &caller_portfolio.did, new_balance);
for (metadata_key, metadata_value) in nft_attributes.into_iter() {
MetadataValue::<T>::insert((&collection_id, &nft_id), metadata_key, metadata_value);
}
PortfolioNFT::<T>::insert(caller_portfolio, (asset_id, nft_id), true);
NFTOwner::<T>::insert(asset_id, nft_id, caller_portfolio);
Self::deposit_event(Event::NFTPortfolioUpdated(
caller_portfolio.did,
NFTs::new_unverified(asset_id, vec![nft_id]),
None,
Some(caller_portfolio),
PortfolioUpdateReason::Issued {
funding_round_name: None,
},
));
Ok(())
}
fn base_redeem_nft(
origin: T::RuntimeOrigin,
asset_id: AssetId,
nft_id: NFTId,
portfolio_kind: PortfolioKind,
number_of_keys: Option<u8>,
) -> DispatchResultWithPostInfo {
// Verifies if the collection exists
let collection_id =
CollectionAsset::<T>::try_get(&asset_id).map_err(|_| Error::<T>::CollectionNotFound)?;
// Ensure origin is agent with custody and permissions for portfolio.
let caller_portfolio = Asset::<T>::ensure_origin_asset_and_portfolio_permissions(
origin,
asset_id,
portfolio_kind,
true,
)?;
// Verifies if the NFT exists
ensure!(
PortfolioNFT::<T>::contains_key(&caller_portfolio, (&asset_id, &nft_id)),
Error::<T>::NFTNotFound
);
ensure!(
!PortfolioLockedNFT::<T>::contains_key(&caller_portfolio, (&asset_id, &nft_id)),
Error::<T>::NFTIsLocked
);
// Burns the NFT
let new_supply = NFTsInCollection::<T>::get(&asset_id)
.checked_sub(1)
.ok_or(Error::<T>::SupplyUnderflow)?;
let new_balance = NumberOfNFTs::<T>::get(&asset_id, &caller_portfolio.did)
.checked_sub(1)
.ok_or(Error::<T>::BalanceUnderflow)?;
NFTsInCollection::<T>::insert(&asset_id, new_supply);
NumberOfNFTs::<T>::insert(&asset_id, &caller_portfolio.did, new_balance);
PortfolioNFT::<T>::remove(&caller_portfolio, (&asset_id, &nft_id));
NFTOwner::<T>::remove(asset_id, nft_id);
let removed_keys = MetadataValue::<T>::drain_prefix((&collection_id, &nft_id)).count();
if let Some(number_of_keys) = number_of_keys {
ensure!(
usize::from(number_of_keys) >= removed_keys,
Error::<T>::NumberOfKeysIsLessThanExpected,
);
}
Self::deposit_event(Event::NFTPortfolioUpdated(
caller_portfolio.did,
NFTs::new_unverified(asset_id, vec![nft_id]),
Some(caller_portfolio),
None,
PortfolioUpdateReason::Redeemed,
));
Ok(PostDispatchInfo::from(Some(
<T as Config>::WeightInfo::redeem_nft(removed_keys as u32),
)))
}
/// Tranfer ownership of all NFTs.
#[require_transactional]
pub fn base_nft_transfer(
sender_portfolio: PortfolioId,
receiver_portfolio: PortfolioId,
nfts: NFTs,
instruction_id: InstructionId,
instruction_memo: Option<Memo>,
caller_did: IdentityId,
weight_meter: &mut WeightMeter,
) -> DispatchResult {
// Verifies if all rules for transfering the NFTs are being respected
Self::validate_nft_transfer(
&sender_portfolio,
&receiver_portfolio,
&nfts,
false,
Some(weight_meter),
)?;
// Transfer ownership of the NFTs
Self::unverified_nfts_transfer(&sender_portfolio, &receiver_portfolio, &nfts);
Self::deposit_event(Event::NFTPortfolioUpdated(
caller_did,
nfts,
Some(sender_portfolio),
Some(receiver_portfolio),
PortfolioUpdateReason::Transferred {
instruction_id: Some(instruction_id),
instruction_memo,
},
));
Ok(())
}
/// Returns `Ok` if all rules for transferring the NFTs are satisfied.
pub fn validate_nft_transfer(
sender_portfolio: &PortfolioId,
receiver_portfolio: &PortfolioId,
nfts: &NFTs,
is_controller_transfer: bool,
weight_meter: Option<&mut WeightMeter>,
) -> DispatchResult {
// Verifies if there is a collection associated to the NFTs
if !CollectionAsset::<T>::contains_key(nfts.asset_id()) {
return Err(Error::<T>::InvalidNFTTransferCollectionNotFound.into());
}
// Verifies that the sender and receiver are not the same
ensure!(
sender_portfolio.did != receiver_portfolio.did,
Error::<T>::InvalidNFTTransferSenderIdMatchesReceiverId
);
// Verifies that the sender has the required nft count
let nfts_transferred = nfts.len() as u64;
ensure!(
NumberOfNFTs::<T>::get(nfts.asset_id(), sender_portfolio.did) >= nfts_transferred,
Error::<T>::InvalidNFTTransferInsufficientCount
);
// Verifies that the number of nfts being transferred are within the allowed limits
Self::ensure_within_nfts_transfer_limits(nfts)?;
// Verifies that all ids are unique
Self::ensure_no_duplicate_nfts(nfts)?;
// Verfies that the sender owns the nfts
Self::ensure_nft_ownership(sender_portfolio, nfts)?;
// Verfies that the receiver will not overflow
NumberOfNFTs::<T>::get(nfts.asset_id(), receiver_portfolio.did)
.checked_add(nfts_transferred)
.ok_or(Error::<T>::InvalidNFTTransferCountOverflow)?;
// Controllers are exempt from compliance and frozen rules.
if is_controller_transfer {
return Ok(());
}
// Verifies that the asset is not frozen
ensure!(
!Frozen::<T>::get(nfts.asset_id()),
Error::<T>::InvalidNFTTransferFrozenAsset
);
// Verifies if the receiver has a valid CDD claim.
ensure!(
IdentityPallet::<T>::has_valid_cdd(receiver_portfolio.did),
Error::<T>::InvalidNFTTransferInvalidReceiverCDD
);
// Verifies if the sender has a valid CDD claim.
ensure!(
IdentityPallet::<T>::has_valid_cdd(sender_portfolio.did),
Error::<T>::InvalidNFTTransferInvalidSenderCDD
);
// Verifies that all compliance rules are being respected
if !T::Compliance::is_compliant(
nfts.asset_id(),
sender_portfolio.did,
receiver_portfolio.did,
weight_meter.ok_or(Error::<T>::InvalidNFTTransferComplianceFailure)?,
)? {
return Err(Error::<T>::InvalidNFTTransferComplianceFailure.into());
}
Ok(())
}
/// Returns `Ok` if `sender_portfolio` has all nfts and they are not locked. Otherwise, returns an `Err`.
fn ensure_nft_ownership(sender_portfolio: &PortfolioId, nfts: &NFTs) -> DispatchResult {
// Verfies that the sender owns the nfts and that they are not locked
for nft_id in nfts.ids() {
ensure!(
PortfolioNFT::<T>::contains_key(sender_portfolio, (nfts.asset_id(), nft_id)),
Error::<T>::InvalidNFTTransferNFTNotOwned
);
ensure!(
!PortfolioLockedNFT::<T>::contains_key(sender_portfolio, (nfts.asset_id(), nft_id)),
Error::<T>::InvalidNFTTransferNFTIsLocked
);
}
Ok(())
}
/// Verifies that the number of NFTs being transferred is greater than zero and less or equal to `MaxNumberOfNFTsPerLeg`.
pub fn ensure_within_nfts_transfer_limits(nfts: &NFTs) -> DispatchResult {
ensure!(nfts.len() > 0, Error::<T>::ZeroCount);
ensure!(
nfts.len() <= (T::MaxNumberOfNFTsCount::get() as usize),
Error::<T>::MaxNumberOfNFTsPerLegExceeded
);
Ok(())
}
/// Verifies that there are no duplicate ids in the `NFTs` struct.
pub fn ensure_no_duplicate_nfts(nfts: &NFTs) -> DispatchResult {
let unique_nfts: BTreeSet<&NFTId> = nfts.ids().iter().collect();
ensure!(unique_nfts.len() == nfts.len(), Error::<T>::DuplicatedNFTId);
Ok(())
}
/// Updates the storage for transferring all `nfts` from `sender_portfolio` to `receiver_portfolio`.
fn unverified_nfts_transfer(
sender_portfolio: &PortfolioId,
receiver_portfolio: &PortfolioId,
nfts: &NFTs,
) {
// Update the balance of the sender and the receiver
let transferred_amount = nfts.len() as u64;
NumberOfNFTs::<T>::mutate(nfts.asset_id(), sender_portfolio.did, |balance| {
*balance = balance.saturating_sub(transferred_amount)
});
NumberOfNFTs::<T>::mutate(nfts.asset_id(), receiver_portfolio.did, |balance| {
*balance = balance.saturating_add(transferred_amount)
});
// Update the portfolio of the sender and the receiver
for nft_id in nfts.ids() {
PortfolioNFT::<T>::remove(sender_portfolio, (nfts.asset_id(), nft_id));
PortfolioNFT::<T>::insert(receiver_portfolio, (nfts.asset_id(), nft_id), true);
NFTOwner::<T>::insert(nfts.asset_id(), nft_id, receiver_portfolio);
}
}
pub fn base_controller_transfer(
origin: T::RuntimeOrigin,
nfts: NFTs,
source_portfolio: PortfolioId,
callers_portfolio_kind: PortfolioKind,
) -> DispatchResult {
// Ensure origin is agent with custody and permissions for portfolio.
let caller_portfolio = Asset::<T>::ensure_origin_asset_and_portfolio_permissions(
origin,
*nfts.asset_id(),
callers_portfolio_kind,
true,
)?;
// Verifies if all rules for transfering the NFTs are being respected
Self::validate_nft_transfer(&source_portfolio, &caller_portfolio, &nfts, true, None)?;
// Transfer ownership of the NFTs
Self::unverified_nfts_transfer(&source_portfolio, &caller_portfolio, &nfts);
Self::deposit_event(Event::NFTPortfolioUpdated(
caller_portfolio.did,
nfts,
Some(source_portfolio),
Some(caller_portfolio),
PortfolioUpdateReason::ControllerTransfer,
));
Ok(())
}
/// Returns a vector containing all errors for the transfer. An empty vec means there's no error.
pub fn nft_transfer_report(
sender_portfolio: &PortfolioId,
receiver_portfolio: &PortfolioId,
nfts: &NFTs,
skip_locked_check: bool,
weight_meter: &mut WeightMeter,
) -> Vec<DispatchError> {
let mut nft_transfer_errors = Vec::new();
// If the collection doesn't exist, there's no point in assessing anything else
if !CollectionAsset::<T>::contains_key(nfts.asset_id()) {
return vec![Error::<T>::InvalidNFTTransferCollectionNotFound.into()];
}
if Frozen::<T>::get(nfts.asset_id()) {
nft_transfer_errors.push(Error::<T>::InvalidNFTTransferFrozenAsset.into());
}
if sender_portfolio.did == receiver_portfolio.did {
nft_transfer_errors
.push(Error::<T>::InvalidNFTTransferSenderIdMatchesReceiverId.into());
}
let nfts_transferred = nfts.len() as u64;
if NumberOfNFTs::<T>::get(nfts.asset_id(), &sender_portfolio.did) < nfts_transferred {
nft_transfer_errors.push(Error::<T>::InvalidNFTTransferInsufficientCount.into());
}
if let Err(e) = Self::ensure_within_nfts_transfer_limits(nfts) {
nft_transfer_errors.push(e);
}
if let Err(e) = Self::ensure_no_duplicate_nfts(nfts) {
nft_transfer_errors.push(e);
}
if skip_locked_check {
for nft_id in nfts.ids() {
if !PortfolioNFT::<T>::contains_key(sender_portfolio, (nfts.asset_id(), nft_id)) {
nft_transfer_errors.push(Error::<T>::InvalidNFTTransferNFTNotOwned.into());
break;
}
}
} else {
if let Err(e) = Self::ensure_nft_ownership(sender_portfolio, nfts) {
nft_transfer_errors.push(e);
}
}
if !IdentityPallet::<T>::has_valid_cdd(receiver_portfolio.did) {
nft_transfer_errors.push(Error::<T>::InvalidNFTTransferInvalidReceiverCDD.into());
}
if !IdentityPallet::<T>::has_valid_cdd(sender_portfolio.did) {
nft_transfer_errors.push(Error::<T>::InvalidNFTTransferInvalidSenderCDD.into());
}
if NumberOfNFTs::<T>::get(nfts.asset_id(), &receiver_portfolio.did)
.checked_add(nfts_transferred)
.is_none()
{
nft_transfer_errors.push(Error::<T>::InvalidNFTTransferCountOverflow.into());
}
match T::Compliance::is_compliant(
nfts.asset_id(),
sender_portfolio.did,
receiver_portfolio.did,
weight_meter,
) {
Ok(is_compliant) => {
if !is_compliant {
nft_transfer_errors
.push(Error::<T>::InvalidNFTTransferComplianceFailure.into());
}
}
Err(e) => {
nft_transfer_errors.push(e);
}
}
nft_transfer_errors
}
/// Adds one to `CurrentCollectionId`.
fn update_current_collection_id() -> Result<NFTCollectionId, DispatchError> {
CurrentCollectionId::<T>::try_mutate(|current_collection_id| match current_collection_id {
Some(current_id) => {
let new_id = try_next_pre::<T, _>(current_id)?;
*current_collection_id = Some(new_id);
Ok::<NFTCollectionId, DispatchError>(new_id)
}
None => {
let new_id = NFTCollectionId(1);
*current_collection_id = Some(new_id);
Ok::<NFTCollectionId, DispatchError>(new_id)
}
})
}
/// Adds one to the `NFTId` that belongs to `collection_id`.
fn update_current_nft_id(collection_id: &NFTCollectionId) -> Result<NFTId, DispatchError> {
CurrentNFTId::<T>::try_mutate(collection_id, |current_nft_id| match current_nft_id {
Some(current_id) => {
let new_nft_id = try_next_pre::<T, _>(current_id)?;
*current_nft_id = Some(new_nft_id);
Ok::<NFTId, DispatchError>(new_nft_id)
}
None => {
let new_nft_id = NFTId(1);
*current_nft_id = Some(new_nft_id);
Ok::<NFTId, DispatchError>(new_nft_id)
}
})
}
/// Transfers all `nfts` from `sender_pid` to `receiver_pid`.
/// Note: This functions skips all compliance checks and only checks for onwership.
pub fn simplified_nft_transfer(
sender_pid: PortfolioId,
receiver_pid: PortfolioId,
nfts: NFTs,
inst_id: InstructionId,
inst_memo: Option<Memo>,
caller_did: IdentityId,
) -> DispatchResult {
Portfolio::<T>::ensure_portfolio_validity(&receiver_pid)?;
Self::ensure_sender_owns_nfts(&sender_pid, &nfts)?;
Self::unverified_nfts_transfer(&sender_pid, &receiver_pid, &nfts);
Self::deposit_event(Event::NFTPortfolioUpdated(
caller_did,
nfts,
Some(sender_pid),
Some(receiver_pid),
PortfolioUpdateReason::Transferred {
instruction_id: Some(inst_id),
instruction_memo: inst_memo,
},
));
Ok(())
}
/// Returns `Ok` if `sender_pid` holds all nfts.
fn ensure_sender_owns_nfts(sender_pid: &PortfolioId, nfts: &NFTs) -> DispatchResult {
for nft_id in nfts.ids() {
ensure!(
PortfolioNFT::<T>::contains_key(sender_pid, (nfts.asset_id(), nft_id)),
Error::<T>::InvalidNFTTransferNFTNotOwned
);
}
Ok(())
}
}
impl<T: Config> NFTTrait<T::RuntimeOrigin> for Pallet<T> {
fn is_collection_key(asset_id: &AssetId, metadata_key: &AssetMetadataKey) -> bool {
match CollectionAsset::<T>::try_get(asset_id) {
Ok(collection_id) => {
let key_set = CollectionKeys::<T>::get(&collection_id);
key_set.contains(metadata_key)
}
Err(_) => false,
}
}
fn move_portfolio_owner(asset_id: AssetId, nft_id: NFTId, new_owner_portfolio: PortfolioId) {
NFTOwner::<T>::insert(asset_id, nft_id, new_owner_portfolio);
}
#[cfg(feature = "runtime-benchmarks")]
fn create_nft_collection(
origin: T::RuntimeOrigin,
asset_id: Option<AssetId>,
nft_type: Option<NonFungibleType>,
collection_keys: NFTCollectionKeys,
) -> DispatchResult {
Pallet::<T>::create_nft_collection(origin, asset_id, nft_type, collection_keys)
}
}