-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathfunctions.rs
930 lines (819 loc) · 29 KB
/
functions.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
// Copyright (C) 2021-2022 RMRK
// This file is part of rmrk-core.
// License: Apache 2.0 modified by RMRK, see LICENSE.md
#![allow(clippy::too_many_arguments)]
use super::*;
use codec::{Codec, Decode, Encode};
use frame_support::traits::{tokens::Locker, Get};
use sp_runtime::{
traits::{Saturating, TrailingZeroInput},
ArithmeticError,
};
use sp_std::collections::btree_set::BTreeSet;
// Randomness to generate NFT virtual accounts
pub const SALT_RMRK_NFT: &[u8; 8] = b"RmrkNft/";
impl<T: Config> Priority<StringLimitOf<T>, T::AccountId, BoundedVec<ResourceId, T::MaxPriorities>>
for Pallet<T>
where
T: pallet_uniques::Config<CollectionId = CollectionId, ItemId = NftId>,
{
fn priority_set(
sender: T::AccountId,
collection_id: CollectionId,
nft_id: NftId,
priorities: BoundedVec<ResourceId, T::MaxPriorities>,
) -> DispatchResult {
let (root_owner, _) = Pallet::<T>::lookup_root_owner(collection_id, nft_id)?;
ensure!(sender == root_owner, Error::<T>::NoPermission);
// Check NFT lock status
ensure!(!Pallet::<T>::is_locked(collection_id, nft_id), pallet_uniques::Error::<T>::Locked);
Priorities::<T>::remove_prefix((collection_id, nft_id), None);
let mut priority_index = 0;
for resource_id in priorities {
Priorities::<T>::insert((collection_id, nft_id, resource_id), priority_index);
priority_index += 1;
}
Self::deposit_event(Event::PrioritySet { collection_id, nft_id });
Ok(())
}
}
impl<T: Config> Property<KeyLimitOf<T>, ValueLimitOf<T>, T::AccountId> for Pallet<T>
where
T: pallet_uniques::Config<CollectionId = CollectionId, ItemId = NftId>,
{
fn property_set(
sender: T::AccountId,
collection_id: CollectionId,
maybe_nft_id: Option<NftId>,
key: KeyLimitOf<T>,
value: ValueLimitOf<T>,
) -> DispatchResult {
let collection =
Collections::<T>::get(&collection_id).ok_or(Error::<T>::CollectionUnknown)?;
ensure!(collection.issuer == sender, Error::<T>::NoPermission);
if let Some(nft_id) = &maybe_nft_id {
// Check NFT lock status
ensure!(
!Pallet::<T>::is_locked(collection_id, *nft_id),
pallet_uniques::Error::<T>::Locked
);
let (root_owner, _) = Pallet::<T>::lookup_root_owner(collection_id, *nft_id)?;
ensure!(root_owner == collection.issuer, Error::<T>::NoPermission);
}
Properties::<T>::insert((&collection_id, maybe_nft_id, &key), &value);
Ok(())
}
// Internal function to set a property for downstream `Origin::root()` calls.
fn do_set_property(
collection_id: CollectionId,
maybe_nft_id: Option<NftId>,
key: KeyLimitOf<T>,
value: ValueLimitOf<T>,
) -> sp_runtime::DispatchResult {
// Ensure collection exists
Collections::<T>::get(&collection_id).ok_or(Error::<T>::CollectionUnknown)?;
Properties::<T>::insert((&collection_id, maybe_nft_id, &key), &value);
Self::deposit_event(Event::PropertySet { collection_id, maybe_nft_id, key, value });
Ok(())
}
// Internal function to remove a property for downstream `Origin::root()` calls.
fn do_remove_property(
collection_id: CollectionId,
maybe_nft_id: Option<NftId>,
key: KeyLimitOf<T>,
) -> sp_runtime::DispatchResult {
Properties::<T>::remove((&collection_id, maybe_nft_id, &key));
Self::deposit_event(Event::PropertyRemoved { collection_id, maybe_nft_id, key });
Ok(())
}
}
impl<T: Config>
Resource<BoundedVec<u8, T::StringLimit>, T::AccountId, BoundedVec<PartId, T::PartsLimit>>
for Pallet<T>
where
T: pallet_uniques::Config<CollectionId = CollectionId, ItemId = NftId>,
{
fn resource_add(
sender: T::AccountId,
collection_id: CollectionId,
nft_id: NftId,
resource: ResourceTypes<BoundedVec<u8, T::StringLimit>, BoundedVec<PartId, T::PartsLimit>>,
adding_on_mint: bool,
resource_id: ResourceId,
) -> Result<ResourceId, DispatchError> {
ensure!(
Resources::<T>::get((collection_id, nft_id, resource_id)).is_none(),
Error::<T>::ResourceAlreadyExists
);
let collection = Self::collections(collection_id).ok_or(Error::<T>::CollectionUnknown)?;
ensure!(collection.issuer == sender, Error::<T>::NoPermission);
let (root_owner, _) = Pallet::<T>::lookup_root_owner(collection_id, nft_id)?;
// Check NFT lock status
ensure!(!Pallet::<T>::is_locked(collection_id, nft_id), pallet_uniques::Error::<T>::Locked);
match resource.clone() {
ResourceTypes::Basic(_r) => (),
ResourceTypes::Composable(r) => {
EquippableBases::<T>::insert((collection_id, nft_id, r.base), ());
if let Some((base, slot)) = r.slot {
EquippableSlots::<T>::insert(
(collection_id, nft_id, resource_id, base, slot),
(),
);
}
},
ResourceTypes::Slot(r) => {
EquippableSlots::<T>::insert(
(collection_id, nft_id, resource_id, r.base, r.slot),
(),
);
},
}
// Resource should be in a pending state if the rootowner of the resource is not the sender
// of the transaction, unless the resource is being added on mint. This prevents the
// situation where an NFT being minted *directly to* a non-owned NFT *with resources* will
// have those resources be *pending*. While the minted NFT itself will be pending, it is
// inefficent and unnecessary to have the resources also be pending. Otherwise, in such a
// case, the owner would have to accept not only the NFT but also all originally-added
// resources.
let pending = (root_owner != sender) && !adding_on_mint;
let res: ResourceInfo<BoundedVec<u8, T::StringLimit>, BoundedVec<PartId, T::PartsLimit>> =
ResourceInfo::<BoundedVec<u8, T::StringLimit>, BoundedVec<PartId, T::PartsLimit>> {
id: resource_id,
pending,
pending_removal: false,
resource,
};
Resources::<T>::insert((collection_id, nft_id, resource_id), res);
Ok(resource_id)
}
fn accept(
sender: T::AccountId,
collection_id: CollectionId,
nft_id: NftId,
resource_id: ResourceId,
) -> DispatchResult {
let (root_owner, _) = Pallet::<T>::lookup_root_owner(collection_id, nft_id)?;
ensure!(root_owner == sender, Error::<T>::NoPermission);
// Check NFT lock status
ensure!(!Pallet::<T>::is_locked(collection_id, nft_id), pallet_uniques::Error::<T>::Locked);
Resources::<T>::try_mutate_exists(
(collection_id, nft_id, resource_id),
|resource| -> DispatchResult {
if let Some(res) = resource {
res.pending = false;
}
Ok(())
},
)?;
Self::deposit_event(Event::ResourceAccepted { nft_id, resource_id });
Ok(())
}
fn resource_remove(
sender: T::AccountId,
collection_id: CollectionId,
nft_id: NftId,
resource_id: ResourceId,
) -> DispatchResult {
let collection = Self::collections(collection_id).ok_or(Error::<T>::CollectionUnknown)?;
let (root_owner, _) = Pallet::<T>::lookup_root_owner(collection_id, nft_id)?;
ensure!(collection.issuer == sender, Error::<T>::NoPermission);
ensure!(
Resources::<T>::contains_key((collection_id, nft_id, resource_id)),
Error::<T>::ResourceDoesntExist
);
if root_owner == sender {
Resources::<T>::remove((collection_id, nft_id, resource_id));
} else {
Resources::<T>::try_mutate_exists(
(collection_id, nft_id, resource_id),
|resource| -> DispatchResult {
if let Some(res) = resource {
res.pending_removal = true;
}
Ok(())
},
)?;
}
Ok(())
}
fn accept_removal(
sender: T::AccountId,
collection_id: CollectionId,
nft_id: NftId,
resource_id: ResourceId,
) -> DispatchResult {
let (root_owner, _) = Pallet::<T>::lookup_root_owner(collection_id, nft_id)?;
ensure!(root_owner == sender, Error::<T>::NoPermission);
ensure!(
Resources::<T>::contains_key((collection_id, nft_id, &resource_id)),
Error::<T>::ResourceDoesntExist
);
Resources::<T>::try_mutate_exists(
(collection_id, nft_id, resource_id),
|resource| -> DispatchResult {
if let Some(res) = resource {
ensure!(res.pending_removal, Error::<T>::ResourceNotPending);
*resource = None;
}
Ok(())
},
)?;
Ok(())
}
}
impl<T: Config> Collection<StringLimitOf<T>, BoundedCollectionSymbolOf<T>, T::AccountId>
for Pallet<T>
where
T: pallet_uniques::Config<CollectionId = CollectionId, ItemId = NftId>,
{
fn issuer(_collection_id: CollectionId) -> Option<T::AccountId> {
None
}
fn collection_create(
issuer: T::AccountId,
metadata: StringLimitOf<T>,
max: Option<u32>,
symbol: BoundedCollectionSymbolOf<T>,
) -> Result<CollectionId, DispatchError> {
let collection =
CollectionInfo { issuer: issuer.clone(), metadata, max, symbol, nfts_count: 0 };
let collection_id =
<CollectionIndex<T>>::try_mutate(|n| -> Result<CollectionId, DispatchError> {
let id = *n;
ensure!(id != CollectionId::max_value(), Error::<T>::NoAvailableCollectionId);
*n += 1;
Ok(id)
})?;
// Call the pallet_uniques function to create collection
pallet_uniques::Pallet::<T>::do_create_collection(
collection_id,
issuer.clone(),
issuer.clone(),
T::CollectionDeposit::get(),
false,
pallet_uniques::Event::Created {
collection: collection_id,
creator: issuer.clone(),
owner: issuer.clone(),
},
)?;
Collections::<T>::insert(collection_id, collection);
Self::deposit_event(Event::CollectionCreated { issuer, collection_id });
Ok(collection_id)
}
fn collection_burn(_issuer: T::AccountId, collection_id: CollectionId) -> DispatchResult {
let collection = Self::collections(collection_id).ok_or(Error::<T>::CollectionUnknown)?;
ensure!(collection.nfts_count == 0, Error::<T>::CollectionNotEmpty);
Collections::<T>::remove(collection_id);
Ok(())
}
fn collection_change_issuer(
collection_id: CollectionId,
new_issuer: T::AccountId,
) -> Result<(T::AccountId, CollectionId), DispatchError> {
ensure!(Collections::<T>::contains_key(collection_id), Error::<T>::NoAvailableCollectionId);
Collections::<T>::try_mutate_exists(collection_id, |collection| -> DispatchResult {
if let Some(col) = collection {
col.issuer = new_issuer.clone();
}
Ok(())
})?;
Ok((new_issuer, collection_id))
}
fn collection_lock(
sender: T::AccountId,
collection_id: CollectionId,
) -> Result<CollectionId, DispatchError> {
Collections::<T>::try_mutate_exists(collection_id, |collection| -> DispatchResult {
let collection = collection.as_mut().ok_or(Error::<T>::CollectionUnknown)?;
ensure!(collection.issuer == sender, Error::<T>::NoPermission);
collection.max = Some(collection.nfts_count);
Ok(())
})?;
Ok(collection_id)
}
}
impl<T: Config> Nft<T::AccountId, StringLimitOf<T>, BoundedResourceInfoTypeOf<T>> for Pallet<T>
where
T: pallet_uniques::Config<CollectionId = CollectionId, ItemId = NftId>,
{
type MaxRecursions = T::MaxRecursions;
fn nft_mint(
sender: T::AccountId,
owner: T::AccountId,
nft_id: NftId,
collection_id: CollectionId,
royalty_recipient: Option<T::AccountId>,
royalty_amount: Option<Permill>,
metadata: StringLimitOf<T>,
transferable: bool,
resources: Option<BoundedResourceInfoTypeOf<T>>,
) -> sp_std::result::Result<(CollectionId, NftId), DispatchError> {
ensure!(!Self::nft_exists((collection_id, nft_id)), Error::<T>::NftAlreadyExists);
let collection = Self::collections(collection_id).ok_or(Error::<T>::CollectionUnknown)?;
// Prevent minting when nfts_count is greater than the collection max.
if let Some(max) = collection.max {
ensure!(collection.nfts_count < max, Error::<T>::CollectionFullOrLocked);
}
// NFT should be pending if minting to another account
let pending = owner != sender;
let mut royalty = None;
if let Some(amount) = royalty_amount {
match royalty_recipient {
Some(recipient) => {
royalty = Some(RoyaltyInfo { recipient, amount });
},
None => {
// If a royalty amount is passed but no recipient, defaults to the sender
royalty = Some(RoyaltyInfo { recipient: owner.clone(), amount });
},
}
};
let nft = NftInfo {
owner: AccountIdOrCollectionNftTuple::AccountId(owner.clone()),
royalty,
metadata,
equipped: false,
pending,
transferable,
};
Nfts::<T>::insert(collection_id, nft_id, nft);
// increment nfts counter
let nfts_count = collection.nfts_count.checked_add(1).ok_or(ArithmeticError::Overflow)?;
Collections::<T>::try_mutate(collection_id, |collection| -> DispatchResult {
let collection = collection.as_mut().ok_or(Error::<T>::CollectionUnknown)?;
collection.nfts_count = nfts_count;
Ok(())
})?;
// Call do_mint for pallet_uniques
pallet_uniques::Pallet::<T>::do_mint(collection_id, nft_id, owner.clone(), |_details| {
Ok(())
})?;
// Add all at-mint resources
if let Some(resources) = resources {
for res in resources {
Self::resource_add(
sender.clone(),
collection_id,
nft_id,
res.resource,
true,
res.id,
)?;
}
}
Self::deposit_event(Event::NftMinted {
owner: AccountIdOrCollectionNftTuple::AccountId(owner),
collection_id,
nft_id,
});
Ok((collection_id, nft_id))
}
fn nft_mint_directly_to_nft(
sender: T::AccountId,
owner: (CollectionId, NftId),
nft_id: NftId,
collection_id: CollectionId,
royalty_recipient: Option<T::AccountId>,
royalty_amount: Option<Permill>,
metadata: StringLimitOf<T>,
transferable: bool,
resources: Option<BoundedResourceInfoTypeOf<T>>,
) -> sp_std::result::Result<(CollectionId, NftId), DispatchError> {
ensure!(!Self::nft_exists((collection_id, nft_id)), Error::<T>::NftAlreadyExists);
let collection = Self::collections(collection_id).ok_or(Error::<T>::CollectionUnknown)?;
// Prevent minting when nfts_count is greater than the collection max.
if let Some(max) = collection.max {
ensure!(collection.nfts_count < max, Error::<T>::CollectionFullOrLocked);
}
// Calculate the rootowner of the intended owner of the minted NFT
let (rootowner, _) = Self::lookup_root_owner(owner.0, owner.1)?;
// NFT should be pending if minting either to an NFT owned by another account
let pending = rootowner != sender;
let mut royalty = None;
if let Some(amount) = royalty_amount {
match royalty_recipient {
Some(recipient) => {
royalty = Some(RoyaltyInfo { recipient, amount });
},
None => {
royalty = Some(RoyaltyInfo { recipient: rootowner, amount });
},
}
};
let nft = NftInfo {
owner: AccountIdOrCollectionNftTuple::CollectionAndNftTuple(owner.0, owner.1),
royalty,
metadata,
equipped: false,
pending,
transferable,
};
Nfts::<T>::insert(collection_id, nft_id, nft);
// increment nfts counter
let nfts_count = collection.nfts_count.checked_add(1).ok_or(ArithmeticError::Overflow)?;
Collections::<T>::try_mutate(collection_id, |collection| -> DispatchResult {
let collection = collection.as_mut().ok_or(Error::<T>::CollectionUnknown)?;
collection.nfts_count = nfts_count;
Ok(())
})?;
// For Uniques, we need to decode the "virtual account" ID to be the owner
let uniques_owner = Self::nft_to_account_id(owner.0, owner.1);
pallet_uniques::Pallet::<T>::do_mint(collection_id, nft_id, uniques_owner, |_details| {
Ok(())
})?;
// Add all at-mint resources
if let Some(resources) = resources {
for res in resources {
Self::resource_add(
sender.clone(),
collection_id,
nft_id,
res.resource,
true,
res.id,
)?;
}
}
Self::deposit_event(Event::NftMinted {
owner: AccountIdOrCollectionNftTuple::CollectionAndNftTuple(owner.0, owner.1),
collection_id,
nft_id,
});
Ok((collection_id, nft_id))
}
fn nft_burn(
collection_id: CollectionId,
nft_id: NftId,
max_recursions: u32,
) -> sp_std::result::Result<(CollectionId, NftId), DispatchError> {
ensure!(max_recursions > 0, Error::<T>::TooManyRecursions);
// Remove self from parent's Children storage
if let Some(nft) = Self::nfts(collection_id, nft_id) {
if let AccountIdOrCollectionNftTuple::CollectionAndNftTuple(parent_col, parent_nft) =
nft.owner
{
Children::<T>::remove((parent_col, parent_nft), (collection_id, nft_id));
}
}
Nfts::<T>::remove(collection_id, nft_id);
Resources::<T>::remove_prefix((collection_id, nft_id), None);
for ((child_collection_id, child_nft_id), _) in
Children::<T>::drain_prefix((collection_id, nft_id))
{
Self::nft_burn(child_collection_id, child_nft_id, max_recursions - 1)?;
}
// decrement nfts counter
Collections::<T>::try_mutate(collection_id, |collection| -> DispatchResult {
let collection = collection.as_mut().ok_or(Error::<T>::CollectionUnknown)?;
collection.nfts_count.saturating_dec();
Ok(())
})?;
Ok((collection_id, nft_id))
}
fn nft_send(
sender: T::AccountId,
collection_id: CollectionId,
nft_id: NftId,
new_owner: AccountIdOrCollectionNftTuple<T::AccountId>,
) -> sp_std::result::Result<(T::AccountId, bool), DispatchError> {
// Get current owner for child removal later
let parent = pallet_uniques::Pallet::<T>::owner(collection_id, nft_id);
// Check if parent returns None which indicates the NFT is not available
ensure!(parent.is_some(), Error::<T>::NoAvailableNftId); // <- is this error wrong?
let (root_owner, _root_nft) = Pallet::<T>::lookup_root_owner(collection_id, nft_id)?;
// Check ownership
ensure!(sender == root_owner, Error::<T>::NoPermission);
// Get NFT info
let mut sending_nft =
Nfts::<T>::get(collection_id, nft_id).ok_or(Error::<T>::NoAvailableNftId)?;
// Check NFT is transferable
Self::check_is_transferable(&sending_nft)?;
// NFT cannot be sent if it is equipped
Self::check_is_not_equipped(&sending_nft)?;
// Needs to be pending if the sending to an account or to a non-owned NFT
let mut approval_required = true;
// Prepare transfer
let new_owner_account = match new_owner.clone() {
AccountIdOrCollectionNftTuple::AccountId(id) => {
approval_required = false;
id
},
AccountIdOrCollectionNftTuple::CollectionAndNftTuple(cid, nid) => {
// Check if NFT target exists
ensure!(Nfts::<T>::contains_key(cid, nid), Error::<T>::NoAvailableNftId);
// Check if sending to self
ensure!(
(collection_id, nft_id) != (cid, nid),
Error::<T>::CannotSendToDescendentOrSelf
);
// Check if collection_id & nft_id are descendent of cid & nid
ensure!(
!Pallet::<T>::is_x_descendent_of_y(cid, nid, collection_id, nft_id),
Error::<T>::CannotSendToDescendentOrSelf
);
let (recipient_root_owner, _root_nft) = Pallet::<T>::lookup_root_owner(cid, nid)?;
if recipient_root_owner == root_owner {
approval_required = false;
}
// Convert to virtual account
Pallet::<T>::nft_to_account_id::<T::AccountId>(cid, nid)
},
};
sending_nft.owner = new_owner;
// Nfts::<T>::insert(collection_id, nft_id, sending_nft);
if approval_required {
Nfts::<T>::try_mutate_exists(collection_id, nft_id, |nft| -> DispatchResult {
if let Some(nft) = nft {
nft.pending = true;
}
Ok(())
})?;
} else {
Nfts::<T>::insert(collection_id, nft_id, sending_nft);
}
if let Some(current_owner) = parent {
// Handle Children StorageMap for NFTs
let current_owner_cid_nid =
Pallet::<T>::decode_nft_account_id::<T::AccountId>(current_owner);
if let Some(current_owner_cid_nid) = current_owner_cid_nid {
// Remove child from parent
Pallet::<T>::remove_child(current_owner_cid_nid, (collection_id, nft_id));
}
}
// add child to new parent if NFT virtual address
let new_owner_cid_nid =
Pallet::<T>::decode_nft_account_id::<T::AccountId>(new_owner_account.clone());
if let Some(new_owner_cid_nid) = new_owner_cid_nid {
Pallet::<T>::add_child(new_owner_cid_nid, (collection_id, nft_id));
}
Ok((new_owner_account, approval_required))
}
fn nft_accept(
sender: T::AccountId,
collection_id: CollectionId,
nft_id: NftId,
new_owner: AccountIdOrCollectionNftTuple<T::AccountId>,
) -> Result<(T::AccountId, CollectionId, NftId), DispatchError> {
let (root_owner, _root_nft) = Pallet::<T>::lookup_root_owner(collection_id, nft_id)?;
// Check ownership
ensure!(sender == root_owner, Error::<T>::NoPermission);
// Get NFT info
let mut sending_nft =
Nfts::<T>::get(collection_id, nft_id).ok_or(Error::<T>::NoAvailableNftId)?;
// Prepare acceptance
let new_owner_account = match new_owner {
AccountIdOrCollectionNftTuple::AccountId(id) => id,
AccountIdOrCollectionNftTuple::CollectionAndNftTuple(cid, nid) => {
// Check if NFT target exists
ensure!(Nfts::<T>::contains_key(cid, nid), Error::<T>::NoAvailableNftId);
// Check if sending to self
ensure!(
(collection_id, nft_id) != (cid, nid),
Error::<T>::CannotSendToDescendentOrSelf
);
// Check if collection_id & nft_id are descendent of cid & nid
ensure!(
!Pallet::<T>::is_x_descendent_of_y(cid, nid, collection_id, nft_id),
Error::<T>::CannotSendToDescendentOrSelf
);
let (recipient_root_owner, _root_nft) = Pallet::<T>::lookup_root_owner(cid, nid)?;
ensure!(recipient_root_owner == root_owner, Error::<T>::CannotAcceptNonOwnedNft);
// Convert to virtual account
Pallet::<T>::nft_to_account_id::<T::AccountId>(cid, nid)
},
};
Nfts::<T>::try_mutate(collection_id, nft_id, |nft| -> DispatchResult {
if let Some(nft) = nft {
nft.pending = false;
}
Ok(())
})?;
Ok((new_owner_account, collection_id, nft_id))
}
fn nft_reject(
sender: T::AccountId,
collection_id: CollectionId,
nft_id: NftId,
max_recursions: u32,
) -> Result<(T::AccountId, CollectionId, NftId), DispatchError> {
// Look up root owner in Uniques to ensure permissions
let (root_owner, _root_nft) = Pallet::<T>::lookup_root_owner(collection_id, nft_id)?;
let nft = Nfts::<T>::get(collection_id, nft_id);
// Ensure NFT is pending (cannot reject non-pending NFT) and exists in Nfts storage
match nft {
None => return Err(Error::<T>::NoAvailableNftId.into()),
Some(nft) => ensure!(nft.pending, Error::<T>::CannotRejectNonPendingNft),
}
// Check ownership
ensure!(sender == root_owner, Error::<T>::CannotRejectNonOwnedNft);
// Get current owner, which we will use to remove the Children storage
if let Some(parent_account_id) = pallet_uniques::Pallet::<T>::owner(collection_id, nft_id) {
// Decode the parent_account_id to extract the parent (CollectionId, NftId)
if let Some(parent) =
Pallet::<T>::decode_nft_account_id::<T::AccountId>(parent_account_id)
{
// Remove the parent-child Children storage
Self::remove_child(parent, (collection_id, nft_id));
}
}
// Get NFT info
let mut rejecting_nft =
Nfts::<T>::get(collection_id, nft_id).ok_or(Error::<T>::NoAvailableNftId)?;
Self::nft_burn(collection_id, nft_id, max_recursions)?;
Ok((sender, collection_id, nft_id))
}
}
impl<T: Config> Locker<CollectionId, NftId> for Pallet<T>
where
T: pallet_uniques::Config<CollectionId = CollectionId, ItemId = NftId>,
{
fn is_locked(collection_id: CollectionId, nft_id: NftId) -> bool {
Lock::<T>::get((collection_id, nft_id))
}
}
impl<T: Config> Pallet<T>
where
T: pallet_uniques::Config<CollectionId = CollectionId, ItemId = NftId>,
{
pub fn iterate_nft_children(
collection_id: CollectionId,
nft_id: NftId,
) -> impl Iterator<Item = NftChild> {
Children::<T>::iter_key_prefix((collection_id, nft_id))
.into_iter()
.map(|(collection_id, nft_id)| NftChild { collection_id, nft_id })
}
pub fn iterate_resources(
collection_id: CollectionId,
nft_id: NftId,
) -> impl Iterator<Item = ResourceInfoOf<T>> {
Resources::<T>::iter_prefix_values((collection_id, nft_id))
}
pub fn query_properties(
collection_id: CollectionId,
nft_id: Option<NftId>,
filter_keys: Option<BTreeSet<BoundedVec<u8, <T as pallet_uniques::Config>::KeyLimit>>>,
) -> impl Iterator<Item = PropertyInfoOf<T>> {
Properties::<T>::iter_prefix((collection_id, nft_id))
.filter(move |(key, _)| match &filter_keys {
Some(filter_keys) => filter_keys.contains(key),
None => true,
})
.map(|(key, value)| PropertyInfoOf::<T> { key, value })
}
/// Encodes a RMRK NFT with randomness + `collection_id` + `nft_id` into a virtual account
/// then returning the `AccountId`. Note that we must be careful of the size of `AccountId`
/// as it must be wide enough to keep the size of the prefix as well as the `collection_id`
/// and `nft_id`.
///
/// Parameters:
/// - `collection_id`: Collection ID that the NFT is contained in
/// - `nft_id`: NFT ID to be encoded into a virtual account
///
/// Output:
/// `AccountId`: Encoded virtual account that represents the NFT
pub fn nft_to_account_id<AccountId: Codec>(
collection_id: CollectionId,
nft_id: NftId,
) -> AccountId {
(SALT_RMRK_NFT, collection_id, nft_id)
.using_encoded(|b| AccountId::decode(&mut TrailingZeroInput::new(b)))
.expect("Decoding with trailing zero never fails; qed.")
}
/// Decodes a RMRK NFT a suspected virtual account
/// then returns an `Option<(CollectionId, NftId)>
/// where `None` is returned when there is an actual account
/// and `Some(tuple)` returns tuple of `CollectionId` & `NftId`
///
/// Parameters:
/// - `account_id`: Encoded NFT virtual account or account owner
///
/// Output:
/// `Option<(CollectionId, NftId)>`
pub fn decode_nft_account_id<AccountId: Codec>(
account_id: T::AccountId,
) -> Option<(CollectionId, NftId)> {
let (prefix, tuple, suffix) = account_id
.using_encoded(|mut b| {
let slice = &mut b;
let r = <([u8; 8], (CollectionId, NftId))>::decode(slice);
r.map(|(prefix, tuple)| (prefix, tuple, slice.to_vec()))
})
.ok()?;
// Check prefix and suffix to avoid collision attack
if &prefix == SALT_RMRK_NFT && suffix.iter().all(|&x| x == 0) {
Some(tuple)
} else {
None
}
}
/// Looks up the root owner of an NFT and returns a `Result` with an AccountId and
/// a tuple of the root `(CollectionId, NftId)`
/// or an `Error::<T>::NoAvailableNftId` in the case that the NFT is already burned
///
/// Parameters:
/// - `collection_id`: Collection ID of the NFT to lookup the root owner
/// - `nft_id`: NFT ID that is to be looked up for the root owner
///
/// Output:
/// - `Result<(T::AcccountId, (CollectionId, NftId)), Error<T>>`
#[allow(clippy::type_complexity)]
pub fn lookup_root_owner(
collection_id: CollectionId,
nft_id: NftId,
) -> Result<(T::AccountId, (CollectionId, NftId)), Error<T>> {
let parent = pallet_uniques::Pallet::<T>::owner(collection_id, nft_id);
// Check if parent returns None which indicates the NFT is not available
parent.as_ref().ok_or(Error::<T>::NoAvailableNftId)?;
let owner = parent.unwrap();
match Self::decode_nft_account_id::<T::AccountId>(owner.clone()) {
None => Ok((owner, (collection_id, nft_id))),
Some((cid, nid)) => Pallet::<T>::lookup_root_owner(cid, nid),
}
}
/// Add a child to a parent NFT
///
/// Parameters:
/// - `parent`: Tuple of (CollectionId, NftId) of the parent NFT
/// - `child`: Tuple of (CollectionId, NftId) of the child NFT to be added
///
/// Output:
/// - Adding a `child` to the Children StorageMap of the `parent`
pub fn add_child(parent: (CollectionId, NftId), child: (CollectionId, NftId)) {
Children::<T>::insert((parent.0, parent.1), (child.0, child.1), ());
}
/// Remove a child from a parent NFT
///
/// Parameters:
/// - `parent`: Tuple of (CollectionId, NftId) of the parent NFT
/// - `child`: Tuple of (CollectionId, NftId) of the child NFT to be removed
///
/// Output:
/// - Removing a `child` from the Children StorageMap of the `parent`
pub fn remove_child(parent: (CollectionId, NftId), child: (CollectionId, NftId)) {
Children::<T>::remove((parent.0, parent.1), (child.0, child.1));
}
/// Check whether a NFT is descends from a suspected parent NFT
/// and return a `bool` if NFT is or not
///
/// Parameters:
/// - `child_collection_id`: Collection ID of the NFT to lookup the root owner
/// - `child_nft_id`: NFT ID that is to be looked up for the root owner
/// - `parent_collection_id`: Collection ID of the NFT to lookup the root owner
/// - `parent_nft_id`: NFT ID that is to be looked up for the root owner
/// Output:
/// - `bool`
pub fn is_x_descendent_of_y(
child_collection_id: CollectionId,
child_nft_id: NftId,
parent_collection_id: CollectionId,
parent_nft_id: NftId,
) -> bool {
let mut found_child = false;
let parent = pallet_uniques::Pallet::<T>::owner(child_collection_id, child_nft_id);
// Check if parent returns None which indicates the NFT is not available
if parent.is_none() {
return found_child
}
let owner = parent.as_ref().unwrap();
match Self::decode_nft_account_id::<T::AccountId>(owner.clone()) {
None => found_child,
Some((cid, nid)) => {
if (cid, nid) == (parent_collection_id, parent_nft_id) {
found_child = true
} else {
found_child = Pallet::<T>::is_x_descendent_of_y(
cid,
nid,
parent_collection_id,
parent_nft_id,
)
}
found_child
},
}
}
pub fn set_lock(nft: (CollectionId, NftId), lock_status: bool) -> bool {
Lock::<T>::mutate(nft, |lock| {
*lock = lock_status;
*lock
});
lock_status
}
// Check NFT is transferable
pub fn check_is_transferable(nft: &InstanceInfoOf<T>) -> DispatchResult {
ensure!(nft.transferable, Error::<T>::NonTransferable);
Ok(())
}
/// Helper function for checking if an NFT exists
pub fn nft_exists(item: (CollectionId, NftId)) -> bool {
let (item_collection_id, item_nft_id) = item;
Nfts::<T>::get(item_collection_id, item_nft_id).is_some()
}
// Check NFT is not equipped
pub fn check_is_not_equipped(nft: &InstanceInfoOf<T>) -> DispatchResult {
ensure!(!nft.equipped, Error::<T>::CannotSendEquippedItem);
Ok(())
}
}