git.delta.rocks / unique-network / refs/commits / 3ee9e950e03f

difftreelog

refactor move properties around

Yaroslav Bolyukin2022-05-27parent: #a034a2f.patch.diff
in: master

18 files changed

modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
73 token: TokenId,73 token: TokenId,
74 at: Option<BlockHash>,74 at: Option<BlockHash>,
75 ) -> Result<Option<CrossAccountId>>;75 ) -> Result<Option<CrossAccountId>>;
76 #[rpc(name = "unique_constMetadata")]
77 fn const_metadata(
78 &self,
79 collection: CollectionId,
80 token: TokenId,
81 at: Option<BlockHash>,
82 ) -> Result<Vec<u8>>;
8376
84 #[rpc(name = "unique_collectionProperties")]77 #[rpc(name = "unique_collectionProperties")]
85 fn collection_properties(78 fn collection_properties(
419 pass_method!(412 pass_method!(
420 topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api413 topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api
421 );414 );
422 pass_method!(
423 const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>, unique_api
424 );
425 pass_method!(total_supply(collection: CollectionId) -> u32, unique_api);415 pass_method!(total_supply(collection: CollectionId) -> u32, unique_api);
426 pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32, unique_api);416 pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32, unique_api);
427 pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string(), unique_api);417 pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string(), unique_api);
modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
86 let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();86 let name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
87 let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();87 let description = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
88 let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();88 let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
89 let offchain_schema = create_data::<OFFCHAIN_SCHEMA_LIMIT>();
90 let const_on_chain_schema = create_data::<CONST_ON_CHAIN_SCHEMA_LIMIT>();
91 handler(89 handler(
92 owner,90 owner,
93 CreateCollectionData {91 CreateCollectionData {
94 mode,92 mode,
95 name,93 name,
96 description,94 description,
97 token_prefix,95 token_prefix,
98 offchain_schema,
99 const_on_chain_schema,
100 ..Default::default()96 ..Default::default()
101 },97 },
102 )98 )
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
55 SponsoringRateLimit,55 SponsoringRateLimit,
56 budget::Budget,56 budget::Budget,
57 COLLECTION_FIELD_LIMIT,57 COLLECTION_FIELD_LIMIT,
58 CollectionField,
59 PhantomType,58 PhantomType,
60 Property,59 Property,
61 Properties,60 Properties,
77 RmrkPartType,76 RmrkPartType,
78 RmrkTheme,77 RmrkTheme,
79 RmrkNftChild,78 RmrkNftChild,
79 CollectionPermissions,
80 SchemaVersion,
80};81};
8182
82pub use pallet::*;83pub use pallet::*;
436 QueryKind = ValueQuery,437 QueryKind = ValueQuery,
437 >;438 >;
438439
439 /// Large variable-size collection fields are extracted here
440 #[pallet::storage]440 #[pallet::storage]
441 pub type CollectionData<T> = StorageNMap<
442 Key = (
443 Key<Twox64Concat, CollectionId>,
444 Key<Twox64Concat, CollectionField>,
445 ),
446 Value = BoundedVec<u8, ConstU32<COLLECTION_FIELD_LIMIT>>,
447 QueryKind = ValueQuery,
448 >;
449
450 #[pallet::storage]
451 pub type AdminAmount<T> = StorageMap<441 pub type AdminAmount<T> = StorageMap<
452 Hasher = Blake2_128Concat,442 Hasher = Blake2_128Concat,
453 Key = CollectionId,443 Key = CollectionId,
505 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {495 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {
506 use up_data_structs::{CollectionVersion1, CollectionVersion2};496 use up_data_structs::{CollectionVersion1, CollectionVersion2};
507 <CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {497 <CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {
508 Self::set_field_raw(498 let mut props = Vec::new();
499 if !v.offchain_schema.is_empty() {
500 props.push(Property {
501 key: b"_old_offchainSchema".to_vec().try_into().unwrap(),
502 value: v.offchain_schema.clone().into_inner().try_into().expect("offchain schema too big"),
503 });
504 }
505 if !v.variable_on_chain_schema.is_empty() {
506 props.push(Property {
507 key: b"_old_variableOnChainSchema".to_vec().try_into().unwrap(),
508 value: v.variable_on_chain_schema.clone().into_inner().try_into().expect("offchain schema too big"),
509 });
510 }
511 if !v.const_on_chain_schema.is_empty() {
512 props.push(Property {
513 key: b"_old_constOnChainSchema".to_vec().try_into().unwrap(),
514 value: v.const_on_chain_schema.clone().into_inner().try_into().expect("offchain schema too big"),
515 });
516 }
517 props.push(Property {
518 key: b"_old_schemaVersion".to_vec().try_into().unwrap(),
519 value: match v.schema_version {
520 SchemaVersion::ImageURL => b"ImageUrl".as_slice(),
521 SchemaVersion::Unique => b"Unique".as_slice(),
522 }.to_vec().try_into().unwrap(),
523 });
524 Self::set_scoped_collection_properties(
509 id,525 id,
510 CollectionField::OffchainSchema,526 PropertyScope::None,
511 v.offchain_schema.clone().into_inner(),527 props.into_iter(),
512 )528 ).expect("existing data larger than properties");
513 .expect("data has lower bounds than field");
514 Self::set_field_raw(
515 id,
516 CollectionField::ConstOnChainSchema,
517 v.const_on_chain_schema.clone().into_inner(),
518 )
519 .expect("data has lower bounds than field");
520
521 Some(CollectionVersion2::from(v))529 Some(CollectionVersion2::from(v))
522 });530 });
587 owner_can_transfer: Some(limits.owner_can_transfer()),595 owner_can_transfer: Some(limits.owner_can_transfer()),
588 owner_can_destroy: Some(limits.owner_can_destroy()),596 owner_can_destroy: Some(limits.owner_can_destroy()),
589 transfers_enabled: Some(limits.transfers_enabled()),597 transfers_enabled: Some(limits.transfers_enabled()),
590 nesting_rule: Some(limits.nesting_rule().clone()),
591 };598 };
592599
593 Some(effective_limits)600 Some(effective_limits)
599 description,606 description,
600 owner,607 owner,
601 mode,608 mode,
602 access,
603 token_prefix,609 token_prefix,
604 mint_mode,
605 schema_version,
606 sponsorship,610 sponsorship,
607 limits,611 limits,
612 permissions,
608 } = <CollectionById<T>>::get(collection)?;613 } = <CollectionById<T>>::get(collection)?;
609614
610 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)615 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)
628 description: description.into_inner(),633 description: description.into_inner(),
629 owner,634 owner,
630 mode,635 mode,
631 access,
632 token_prefix: token_prefix.into_inner(),636 token_prefix: token_prefix.into_inner(),
633 mint_mode,
634 schema_version,
635 sponsorship,637 sponsorship,
636 limits,638 limits,
637 offchain_schema: <CollectionData<T>>::get((639 permissions,
638 collection,
639 CollectionField::OffchainSchema,
640 ))
641 .into_inner(),
642 const_on_chain_schema: <CollectionData<T>>::get((
643 collection,
644 CollectionField::ConstOnChainSchema,
645 ))
646 .into_inner(),
647 token_property_permissions,640 token_property_permissions,
648 properties,641 properties,
649 })642 })
650 }643 }
651}644}
652645
646macro_rules! limit_default {
647 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
648 $(
649 if let Some($new) = $new.$field {
650 let $old = $old.$field($($arg)?);
651 let _ = $new;
652 let _ = $old;
653 $check
654 } else {
655 $new.$field = $old.$field
656 }
657 )*
658 }};
659}
660macro_rules! limit_default_clone {
661 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
662 $(
663 if let Some($new) = $new.$field.clone() {
664 let $old = $old.$field($($arg)?);
665 let _ = $new;
666 let _ = $old;
667 $check
668 } else {
669 $new.$field = $old.$field.clone()
670 }
671 )*
672 }};
673}
674
653impl<T: Config> Pallet<T> {675impl<T: Config> Pallet<T> {
654 pub fn init_collection(676 pub fn init_collection(
655 owner: T::AccountId,677 owner: T::AccountId,
681 owner: owner.clone(),703 owner: owner.clone(),
682 name: data.name,704 name: data.name,
683 mode: data.mode.clone(),705 mode: data.mode.clone(),
684 mint_mode: false,
685 access: data.access.unwrap_or_default(),
686 description: data.description,706 description: data.description,
687 token_prefix: data.token_prefix,707 token_prefix: data.token_prefix,
688 schema_version: data.schema_version.unwrap_or_default(),
689 sponsorship: data708 sponsorship: data
690 .pending_sponsor709 .pending_sponsor
691 .map(SponsorshipState::Unconfirmed)710 .map(SponsorshipState::Unconfirmed)
694 .limits713 .limits
695 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))714 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))
696 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,715 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,
716 permissions: data
717 .permissions
718 .map(|permissions| Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions))
719 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,
697 };720 };
698721
699 let mut collection_properties = up_data_structs::CollectionProperties::get();722 let mut collection_properties = up_data_structs::CollectionProperties::get();
732 <CreatedCollectionCount<T>>::put(created_count);755 <CreatedCollectionCount<T>>::put(created_count);
733 <Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));756 <Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));
734 <CollectionById<T>>::insert(id, collection);757 <CollectionById<T>>::insert(id, collection);
735 Self::set_field_raw(
736 id,
737 CollectionField::OffchainSchema,
738 data.offchain_schema.into_inner(),
739 )
740 .expect("data has lower bounds than field");
741 Self::set_field_raw(
742 id,
743 CollectionField::ConstOnChainSchema,
744 data.const_on_chain_schema.into_inner(),
745 )
746 .expect("data has lower bounds than field");
747 Ok(id)758 Ok(id)
748 }759 }
749760
766777
767 <DestroyedCollectionCount<T>>::put(destroyed_collections);778 <DestroyedCollectionCount<T>>::put(destroyed_collections);
768 <CollectionById<T>>::remove(collection.id);779 <CollectionById<T>>::remove(collection.id);
769 <CollectionData<T>>::remove_prefix((collection.id,), None);
770 <AdminAmount<T>>::remove(collection.id);780 <AdminAmount<T>>::remove(collection.id);
771 <IsAdmin<T>>::remove_prefix((collection.id,), None);781 <IsAdmin<T>>::remove_prefix((collection.id,), None);
772 <Allowlist<T>>::remove_prefix((collection.id,), None);782 <Allowlist<T>>::remove_prefix((collection.id,), None);
866 Ok(())876 Ok(())
867 }877 }
868878
879 // For migrations
880 pub fn set_property_permission_unchecked(
881 collection: CollectionId,
882 property_permission: PropertyKeyPermission,
883 ) -> DispatchResult {
884 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {
885 permissions.try_set(property_permission.key, property_permission.permission)
886 })
887 .map_err(<Error<T>>::from)?;
888 Ok(())
889 }
890
869 pub fn set_property_permission(891 pub fn set_property_permission(
870 collection: &CollectionHandle<T>,892 collection: &CollectionHandle<T>,
871 sender: &T::CrossAccountId,893 sender: &T::CrossAccountId,
989 Ok(key_permissions)1011 Ok(key_permissions)
990 }1012 }
9911013
992 fn set_field_raw(
993 collection_id: CollectionId,
994 field: CollectionField,
995 value: Vec<u8>,
996 ) -> DispatchResult {
997 if !value.is_empty() {
998 <CollectionData<T>>::insert(
999 (collection_id, field),
1000 BoundedVec::try_from(value).map_err(|_| <Error<T>>::CollectionFieldSizeExceeded)?,
1001 )
1002 } else {
1003 <CollectionData<T>>::remove((collection_id, field));
1004 }
1005 Ok(())
1006 }
1007
1008 pub fn set_field(
1009 collection: &CollectionHandle<T>,
1010 sender: &T::CrossAccountId,
1011 field: CollectionField,
1012 value: Vec<u8>,
1013 ) -> DispatchResult {
1014 collection.check_is_owner_or_admin(sender)?;
1015
1016 // =========
1017
1018 Self::set_field_raw(collection.id, field, value)
1019 }
1020
1021 pub fn toggle_allowlist(1014 pub fn toggle_allowlist(
1022 collection: &CollectionHandle<T>,1015 collection: &CollectionHandle<T>,
1023 sender: &T::CrossAccountId,1016 sender: &T::CrossAccountId,
1077 old_limit: &CollectionLimits,1070 old_limit: &CollectionLimits,
1078 mut new_limit: CollectionLimits,1071 mut new_limit: CollectionLimits,
1079 ) -> Result<CollectionLimits, DispatchError> {1072 ) -> Result<CollectionLimits, DispatchError> {
1080 macro_rules! limit_default {
1081 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{
1082 $(
1083 if let Some($new) = $new.$field {
1084 let $old = $old.$field($($arg)?);
1085 let _ = $new;
1086 let _ = $old;
1087 $check
1088 } else {
1089 $new.$field = $old.$field
1090 }
1091 )*
1092 }};
1093 }
1094
1095 limit_default!(old_limit, new_limit,1073 limit_default!(old_limit, new_limit,
1096 account_token_ownership_limit => ensure!(1074 account_token_ownership_limit => ensure!(
1097 new_limit <= MAX_TOKEN_OWNERSHIP,1075 new_limit <= MAX_TOKEN_OWNERSHIP,
1123 ),1101 ),
1124 sponsored_data_rate_limit => {},1102 sponsored_data_rate_limit => {},
1125 transfers_enabled => {},1103 transfers_enabled => {},
1104 );
1105 Ok(new_limit)
1106 }
1107 pub fn clamp_permissions(
1108 mode: CollectionMode,
1109 old_limit: &CollectionPermissions,
1110 mut new_limit: CollectionPermissions,
1111 ) -> Result<CollectionPermissions, DispatchError> {
1112 limit_default_clone!(old_limit, new_limit,
1126 );1113 );
1127 Ok(new_limit)1114 Ok(new_limit)
1128 }1115 }
1253 fn last_token_id(&self) -> TokenId;1240 fn last_token_id(&self) -> TokenId;
12541241
1255 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;1242 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;
1256 fn const_metadata(&self, token: TokenId) -> Vec<u8>;
1257 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;1243 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;
1258 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;1244 fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;
1259 /// Amount of unique collection tokens1245 /// Amount of unique collection tokens
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
51 <SelfWeightOf<T>>::burn_item()51 <SelfWeightOf<T>>::burn_item()
52 }52 }
5353
54 fn set_collection_properties(amount: u32) -> Weight {54 fn set_collection_properties(_amount: u32) -> Weight {
55 // Error55 // Error
56 056 0
57 }57 }
5858
59 fn delete_collection_properties(amount: u32) -> Weight {59 fn delete_collection_properties(_amount: u32) -> Weight {
60 // Error60 // Error
61 061 0
62 }62 }
6363
64 fn set_token_properties(amount: u32) -> Weight {64 fn set_token_properties(_amount: u32) -> Weight {
65 // Error65 // Error
66 066 0
67 }67 }
6868
69 fn delete_token_properties(amount: u32) -> Weight {69 fn delete_token_properties(_amount: u32) -> Weight {
70 // Error70 // Error
71 071 0
72 }72 }
7373
74 fn set_property_permissions(amount: u32) -> Weight {74 fn set_property_permissions(_amount: u32) -> Weight {
75 // Error75 // Error
76 076 0
77 }77 }
321 fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {321 fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {
322 None322 None
323 }323 }
324 fn const_metadata(&self, _token: TokenId) -> Vec<u8> {
325 Vec::new()
326 }
327324
328 fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {325 fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {
329 None326 None
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
168 .checked_sub(amount)168 .checked_sub(amount)
169 .ok_or(<CommonError<T>>::TokenValueTooLow)?;169 .ok_or(<CommonError<T>>::TokenValueTooLow)?;
170170
171 if collection.access == AccessMode::AllowList {171 if collection.permissions.access() == AccessMode::AllowList {
172 collection.check_allowlist(owner)?;172 collection.check_allowlist(owner)?;
173 }173 }
174174
210 <CommonError<T>>::TransferNotAllowed,210 <CommonError<T>>::TransferNotAllowed,
211 );211 );
212212
213 if collection.access == AccessMode::AllowList {213 if collection.permissions.access() == AccessMode::AllowList {
214 collection.check_allowlist(from)?;214 collection.check_allowlist(from)?;
215 collection.check_allowlist(to)?;215 collection.check_allowlist(to)?;
216 }216 }
280 ) -> DispatchResult {280 ) -> DispatchResult {
281 if !collection.is_owner_or_admin(sender) {281 if !collection.is_owner_or_admin(sender) {
282 ensure!(282 ensure!(
283 collection.mint_mode,283 collection.permissions.mint_mode(),
284 <CommonError<T>>::PublicMintingNotAllowed284 <CommonError<T>>::PublicMintingNotAllowed
285 );285 );
286 collection.check_allowlist(sender)?;286 collection.check_allowlist(sender)?;
380 spender: &T::CrossAccountId,380 spender: &T::CrossAccountId,
381 amount: u128,381 amount: u128,
382 ) -> DispatchResult {382 ) -> DispatchResult {
383 if collection.access == AccessMode::AllowList {383 if collection.permissions.access() == AccessMode::AllowList {
384 collection.check_allowlist(owner)?;384 collection.check_allowlist(owner)?;
385 collection.check_allowlist(spender)?;385 collection.check_allowlist(spender)?;
386 }386 }
408 if spender.conv_eq(from) {408 if spender.conv_eq(from) {
409 return Ok(None);409 return Ok(None);
410 }410 }
411 if collection.access == AccessMode::AllowList {411 if collection.permissions.access() == AccessMode::AllowList {
412 // `from`, `to` checked in [`transfer`]412 // `from`, `to` checked in [`transfer`]
413 collection.check_allowlist(spender)?;413 collection.check_allowlist(spender)?;
414 }414 }
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
29const SEED: u32 = 1;29const SEED: u32 = 1;
3030
31fn create_max_item_data<T: Config>(owner: T::CrossAccountId) -> CreateItemData<T> {31fn create_max_item_data<T: Config>(owner: T::CrossAccountId) -> CreateItemData<T> {
32 let const_data = create_data::<CUSTOM_DATA_LIMIT>();
33 CreateItemData::<T> {32 CreateItemData::<T> {
34 const_data,
35 owner,33 owner,
36 properties: Default::default(),34 properties: Default::default(),
37 }35 }
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
116) -> Result<CreateItemData<T>, DispatchError> {116) -> Result<CreateItemData<T>, DispatchError> {
117 match data {117 match data {
118 up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {118 up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {
119 const_data: data.const_data,
120 properties: data.properties,119 properties: data.properties,
121 owner: to.clone(),120 owner: to.clone(),
122 }),121 }),
377 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {376 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {
378 <TokenData<T>>::get((self.id, token)).map(|t| t.owner)377 <TokenData<T>>::get((self.id, token)).map(|t| t.owner)
379 }378 }
380 fn const_metadata(&self, token: TokenId) -> Vec<u8> {
381 <TokenData<T>>::get((self.id, token))
382 .map(|t| t.const_data)
383 .unwrap_or_default()
384 .into_inner()
385 }
386379
387 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {380 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {
388 <Pallet<T>>::token_properties((self.id, token_id))381 <Pallet<T>>::token_properties((self.id, token_id))
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
109 }109 }
110}110}
111
112fn error_unsupported_schema_version() -> Error {
113 alloc::format!(
114 "Unsupported schema version! Support only {:?}",
115 SchemaVersion::ImageURL
116 )
117 .as_str()
118 .into()
119}
120111
121#[derive(ToLog)]112#[derive(ToLog)]
122pub enum ERC721Events {113pub enum ERC721Events {
167 /// Returns token's const_metadata158 /// Returns token's const_metadata
168 #[solidity(rename_selector = "tokenURI")]159 #[solidity(rename_selector = "tokenURI")]
169 fn token_uri(&self, token_id: uint256) -> Result<string> {160 fn token_uri(&self, token_id: uint256) -> Result<string> {
170 if !matches!(self.schema_version, SchemaVersion::ImageURL) {
171 return Err(error_unsupported_schema_version());
172 }
173
174 self.consume_store_reads(1)?;161 self.consume_store_reads(1)?;
175 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;162 let _token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
176 Ok(string::from_utf8_lossy(163 Ok(string::from_utf8_lossy(
177 &<TokenData<T>>::get((self.id, token_id))
178 .ok_or("token not found")?164 todo!()
179 .const_data,
180 )165 )
181 .into())166 .into())
182 }167 }
344 self,329 self,
345 &caller,330 &caller,
346 CreateItemData::<T> {331 CreateItemData::<T> {
347 const_data: BoundedVec::default(),
348 properties: BoundedVec::default(),332 properties: BoundedVec::default(),
349 owner: to,333 owner: to,
350 },334 },
366 token_id: uint256,350 token_id: uint256,
367 token_uri: string,351 token_uri: string,
368 ) -> Result<bool> {352 ) -> Result<bool> {
369 if !matches!(self.schema_version, SchemaVersion::ImageURL) {
370 return Err(error_unsupported_schema_version());
371 }
372
373 let caller = T::CrossAccountId::from_eth(caller);353 let caller = T::CrossAccountId::from_eth(caller);
374 let to = T::CrossAccountId::from_eth(to);354 let to = T::CrossAccountId::from_eth(to);
385 return Err("item id should be next".into());365 return Err("item id should be next".into());
386 }366 }
367
368 todo!("token uri");
387369
388 <Pallet<T>>::create_item(370 <Pallet<T>>::create_item(
389 self,371 self,
390 &caller,372 &caller,
391 CreateItemData::<T> {373 CreateItemData::<T> {
392 const_data: Vec::<u8>::from(token_uri)
393 .try_into()
394 .map_err(|_| "token uri is too long")?,
395 properties: BoundedVec::default(),374 properties: BoundedVec::default(),
396 owner: to,375 owner: to,
397 },376 },
477 }456 }
478 let data = (0..total_tokens)457 let data = (0..total_tokens)
479 .map(|_| CreateItemData::<T> {458 .map(|_| CreateItemData::<T> {
480 const_data: BoundedVec::default(),
481 properties: BoundedVec::default(),459 properties: BoundedVec::default(),
482 owner: to.clone(),460 owner: to.clone(),
483 })461 })
496 to: address,474 to: address,
497 tokens: Vec<(uint256, string)>,475 tokens: Vec<(uint256, string)>,
498 ) -> Result<bool> {476 ) -> Result<bool> {
499 if !matches!(self.schema_version, SchemaVersion::ImageURL) {
500 return Err(error_unsupported_schema_version());
501 }
502
503 let caller = T::CrossAccountId::from_eth(caller);477 let caller = T::CrossAccountId::from_eth(caller);
504 let to = T::CrossAccountId::from_eth(to);478 let to = T::CrossAccountId::from_eth(to);
517 }491 }
518 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;492 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
519493
494 todo!("token uri");
520 data.push(CreateItemData::<T> {495 data.push(CreateItemData::<T> {
521 const_data: Vec::<u8>::from(token_uri)
522 .try_into()
523 .map_err(|_| "token uri is too long")?,
524 properties: BoundedVec::default(),496 properties: BoundedVec::default(),
525 owner: to.clone(),497 owner: to.clone(),
526 });498 });
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
33use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};33use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
34use sp_core::H160;34use sp_core::H160;
35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
36use sp_std::{vec::Vec, vec};36use sp_std::{vec::Vec, vec, collections::btree_set::BTreeSet};
37use core::ops::Deref;37use core::ops::Deref;
38use sp_std::collections::btree_map::BTreeMap;38use sp_std::collections::btree_map::BTreeMap;
39use codec::{Encode, Decode, MaxEncodedLen};39use codec::{Encode, Decode, MaxEncodedLen};
52#[struct_versioning::versioned(version = 2, upper)]52#[struct_versioning::versioned(version = 2, upper)]
53#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]53#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]
54pub struct ItemData<CrossAccountId> {54pub struct ItemData<CrossAccountId> {
55 #[version(..2)]
55 pub const_data: BoundedVec<u8, CustomDataLimit>,56 pub const_data: BoundedVec<u8, CustomDataLimit>,
5657
57 #[version(..2)]58 #[version(..2)]
148 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {149 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
149 fn on_runtime_upgrade() -> Weight {150 fn on_runtime_upgrade() -> Weight {
150 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {151 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {
152 let mut had_consts = BTreeSet::new();
151 <TokenData<T>>::translate_values::<ItemDataVersion1<T::CrossAccountId>, _>(|v| {153 <TokenData<T>>::translate::<ItemDataVersion1<T::CrossAccountId>, _>(|(collection, token), v| {
154 let mut props = vec![];
155 if !v.const_data.is_empty() {
156 props.push(Property {
157 key: b"_old_constData".to_vec().try_into().unwrap(),
158 value: v.const_data.clone().into_inner().try_into().expect("const too long"),
159 });
160 had_consts.insert(collection);
161 }
162 if !v.variable_data.is_empty() {
163 props.push(Property {
164 key: b"_old_variableData".to_vec().try_into().unwrap(),
165 value: v.variable_data.clone().into_inner().try_into().expect("variable too long"),
166 })
167 }
168 if !props.is_empty() {
169 Self::set_scoped_token_properties(
170 collection,
171 token,
172 PropertyScope::None,
173 props.into_iter(),
174 ).expect("existing token data exceeds property storage");
175 }
152 Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))176 Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))
153 })177 });
178 for collection in had_consts {
179 <PalletCommon<T>>::set_property_permission_unchecked(
180 collection,
181 PropertyKeyPermission {
182 key: b"_old_constData".to_vec().try_into().unwrap(),
183 permission: PropertyPermission {
184 mutable: false,
185 collection_admin: true,
186 token_owner: false,
187 },
188 }
189 ).expect("failed to configure permission");
190 }
154 }191 }
155192
156 0193 0
267 <CommonError<T>>::NoPermission304 <CommonError<T>>::NoPermission
268 );305 );
269306
270 if collection.access == AccessMode::AllowList {307 if collection.permissions.access() == AccessMode::AllowList {
271 collection.check_allowlist(sender)?;308 collection.check_allowlist(sender)?;
272 }309 }
273310
493 <CommonError<T>>::NoPermission530 <CommonError<T>>::NoPermission
494 );531 );
495532
496 if collection.access == AccessMode::AllowList {533 if collection.permissions.access() == AccessMode::AllowList {
497 collection.check_allowlist(from)?;534 collection.check_allowlist(from)?;
498 collection.check_allowlist(to)?;535 collection.check_allowlist(to)?;
499 }536 }
579 ) -> DispatchResult {616 ) -> DispatchResult {
580 if !collection.is_owner_or_admin(sender) {617 if !collection.is_owner_or_admin(sender) {
581 ensure!(618 ensure!(
582 collection.mint_mode,619 collection.permissions.mint_mode(),
583 <CommonError<T>>::PublicMintingNotAllowed620 <CommonError<T>>::PublicMintingNotAllowed
584 );621 );
585 collection.check_allowlist(sender)?;622 collection.check_allowlist(sender)?;
639 <TokenData<T>>::insert(676 <TokenData<T>>::insert(
640 (collection.id, token),677 (collection.id, token),
641 ItemData {678 ItemData {
642 const_data: data.const_data.clone(),679 // const_data: data.const_data.clone(),
643 owner: data.owner.clone(),680 owner: data.owner.clone(),
644 },681 },
645 );682 );
756 token: TokenId,793 token: TokenId,
757 spender: Option<&T::CrossAccountId>,794 spender: Option<&T::CrossAccountId>,
758 ) -> DispatchResult {795 ) -> DispatchResult {
759 if collection.access == AccessMode::AllowList {796 if collection.permissions.access() == AccessMode::AllowList {
760 collection.check_allowlist(sender)?;797 collection.check_allowlist(sender)?;
761 if let Some(spender) = spender {798 if let Some(spender) = spender {
762 collection.check_allowlist(spender)?;799 collection.check_allowlist(spender)?;
791 if spender.conv_eq(from) {828 if spender.conv_eq(from) {
792 return Ok(());829 return Ok(());
793 }830 }
794 if collection.access == AccessMode::AllowList {831 if collection.permissions.access() == AccessMode::AllowList {
795 // `from`, `to` checked in [`transfer`]832 // `from`, `to` checked in [`transfer`]
796 collection.check_allowlist(spender)?;833 collection.check_allowlist(spender)?;
797 }834 }
875 );912 );
876 Ok(())913 Ok(())
877 }914 }
878 match handle.limits.nesting_rule() {915 match handle.permissions.nesting() {
879 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),916 NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),
880 NestingRule::Owner => {917 NestingRule::Owner => {
881 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?918 ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?
modifiedpallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth
403 nft_type: NftType,403 nft_type: NftType,
404 properties: impl Iterator<Item=Property>404 properties: impl Iterator<Item=Property>
405 ) -> Result<TokenId, DispatchError> {405 ) -> Result<TokenId, DispatchError> {
406 todo!("store nft type");
406 let data = CreateNftExData {407 let data = CreateNftExData {
407 const_data: nft_type.encode()
408 .try_into()
409 .map_err(|_| <Error<T>>::NftTypeEncodeError)?,
410 properties: BoundedVec::default(),408 properties: BoundedVec::default(),
411 owner: owner.clone(),409 owner: owner.clone(),
412 };410 };
528 Ok(nft_property)526 Ok(nft_property)
529 }527 }
530528
531 pub fn get_nft_type(collection_id: CollectionId, token_id: TokenId) -> Result<NftType, DispatchError> {529 pub fn get_nft_type(_collection_id: CollectionId, _token_id: TokenId) -> Result<NftType, DispatchError> {
532 let token_data = <TokenData<T>>::get((collection_id, token_id))
533 .ok_or(<Error<T>>::NoAvailableNftId)?;
534
535 let mut const_data = token_data.const_data.as_slice();
536
537 NftType::decode(&mut const_data).map_err(|_| <Error<T>>::NoAvailableNftId.into())530 todo!("should get it from properties?")
538 }531 }
539532
540 pub fn ensure_nft_type(collection_id: CollectionId, token_id: TokenId, nft_type: NftType) -> DispatchResult {533 pub fn ensure_nft_type(collection_id: CollectionId, token_id: TokenId, nft_type: NftType) -> DispatchResult {
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
336 fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {336 fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {
337 None337 None
338 }338 }
339 fn const_metadata(&self, token: TokenId) -> Vec<u8> {
340 <TokenData<T>>::get((self.id, token))
341 .const_data
342 .into_inner()
343 }
344339
345 fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {340 fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {
346 None341 None
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
321 <CommonError<T>>::TransferNotAllowed321 <CommonError<T>>::TransferNotAllowed
322 );322 );
323323
324 if collection.access == AccessMode::AllowList {324 if collection.permissions.access() == AccessMode::AllowList {
325 collection.check_allowlist(from)?;325 collection.check_allowlist(from)?;
326 collection.check_allowlist(to)?;326 collection.check_allowlist(to)?;
327 }327 }
424 ) -> DispatchResult {424 ) -> DispatchResult {
425 if !collection.is_owner_or_admin(sender) {425 if !collection.is_owner_or_admin(sender) {
426 ensure!(426 ensure!(
427 collection.mint_mode,427 collection.permissions.mint_mode(),
428 <CommonError<T>>::PublicMintingNotAllowed428 <CommonError<T>>::PublicMintingNotAllowed
429 );429 );
430 collection.check_allowlist(sender)?;430 collection.check_allowlist(sender)?;
566 token: TokenId,566 token: TokenId,
567 amount: u128,567 amount: u128,
568 ) -> DispatchResult {568 ) -> DispatchResult {
569 if collection.access == AccessMode::AllowList {569 if collection.permissions.access() == AccessMode::AllowList {
570 collection.check_allowlist(sender)?;570 collection.check_allowlist(sender)?;
571 collection.check_allowlist(spender)?;571 collection.check_allowlist(spender)?;
572 }572 }
598 if spender.conv_eq(from) {598 if spender.conv_eq(from) {
599 return Ok(None);599 return Ok(None);
600 }600 }
601 if collection.access == AccessMode::AllowList {601 if collection.permissions.access() == AccessMode::AllowList {
602 // `from`, `to` checked in [`transfer`]602 // `from`, `to` checked in [`transfer`]
603 collection.check_allowlist(spender)?;603 collection.check_allowlist(spender)?;
604 }604 }
modifiedpallets/unique/src/benchmarking.rsdiffbeforeafterboth
130 let collection = create_nft_collection::<T>(caller.clone())?;130 let collection = create_nft_collection::<T>(caller.clone())?;
131 }: _(RawOrigin::Signed(caller.clone()), collection, false)131 }: _(RawOrigin::Signed(caller.clone()), collection, false)
132132
133 set_offchain_schema {
134 let b in 0..OFFCHAIN_SCHEMA_LIMIT;
135
136 let caller: T::AccountId = account("caller", 0, SEED);
137 let collection = create_nft_collection::<T>(caller.clone())?;
138 let data = create_var_data(b);
139 }: set_offchain_schema(RawOrigin::Signed(caller.clone()), collection, data)
140
141 set_const_on_chain_schema {
142 let b in 0..CONST_ON_CHAIN_SCHEMA_LIMIT;
143
144 let caller: T::AccountId = account("caller", 0, SEED);
145 let collection = create_nft_collection::<T>(caller.clone())?;
146 let data = create_var_data(b);
147 }: set_const_on_chain_schema(RawOrigin::Signed(caller.clone()), collection, data)
148
149 set_schema_version {
150 let caller: T::AccountId = account("caller", 0, SEED);
151 let collection = create_nft_collection::<T>(caller.clone())?;
152 }: set_schema_version(RawOrigin::Signed(caller.clone()), collection, SchemaVersion::Unique)
153133
154 set_collection_limits{134 set_collection_limits{
155 let caller: T::AccountId = account("caller", 0, SEED);135 let caller: T::AccountId = account("caller", 0, SEED);
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
35use frame_system::{self as system, ensure_signed};35use frame_system::{self as system, ensure_signed};
36use sp_runtime::{sp_std::prelude::Vec};36use sp_runtime::{sp_std::prelude::Vec};
37use up_data_structs::{37use up_data_structs::{
38 CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT, MAX_COLLECTION_NAME_LENGTH,38 MAX_COLLECTION_NAME_LENGTH,
39 MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, AccessMode, CreateItemData,39 MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, AccessMode, CreateItemData,
40 CollectionLimits, CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState,40 CollectionLimits, CollectionPermissions, CollectionId, CollectionMode, TokenId, SponsorshipState,
41 CreateCollectionData, CreateItemExData, budget, CollectionField, Property, PropertyKey,41 CreateCollectionData, CreateItemExData, budget, Property, PropertyKey,
42 PropertyKeyPermission,42 PropertyKeyPermission,
43};43};
44use pallet_evm::account::CrossAccountId;44use pallet_evm::account::CrossAccountId;
162 /// * collection_id: Globally unique collection identifier.162 /// * collection_id: Globally unique collection identifier.
163 CollectionLimitSet(CollectionId),163 CollectionLimitSet(CollectionId),
164
165 CollectionPermissionSet(CollectionId),
164166
165 /// Mint permission was set167 /// Mint permission was set
166 ///168 ///
419 Ok(())421 Ok(())
420 }422 }
421
422 /// Toggle between normal and allow list access for the methods with access for `Anyone`.
423 ///
424 /// # Permissions
425 ///
426 /// * Collection Owner.
427 ///
428 /// # Arguments
429 ///
430 /// * collection_id.
431 ///
432 /// * mode: [AccessMode]
433 #[weight = <SelfWeightOf<T>>::set_public_access_mode()]
434 #[transactional]
435 pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult
436 {
437 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
438
439 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
440 target_collection.check_is_owner(&sender)?;
441
442 target_collection.access = mode.clone();
443
444 <Pallet<T>>::deposit_event(Event::<T>::PublicAccessModeSet(
445 collection_id,
446 mode
447 ));
448
449 target_collection.save()
450 }
451
452 /// Allows Anyone to create tokens if:
453 /// * Allow List is enabled, and
454 /// * Address is added to allow list, and
455 /// * This method was called with True parameter
456 ///
457 /// # Permissions
458 /// * Collection Owner
459 ///
460 /// # Arguments
461 ///
462 /// * collection_id.
463 ///
464 /// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.
465 #[weight = <SelfWeightOf<T>>::set_mint_permission()]
466 #[transactional]
467 pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult
468 {
469 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
470
471 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
472 target_collection.check_is_owner(&sender)?;
473
474 target_collection.mint_mode = mint_permission;
475
476 <Pallet<T>>::deposit_event(Event::<T>::MintPermissionSet(
477 collection_id
478 ));
479
480 target_collection.save()
481 }
482423
483 /// Change the owner of the collection.424 /// Change the owner of the collection.
484 ///425 ///
941 dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))882 dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))
942 }883 }
943884
944 /// Set schema standard
945 /// ImageURL
946 /// Unique
947 ///
948 /// # Permissions
949 ///
950 /// * Collection Owner
951 /// * Collection Admin
952 ///
953 /// # Arguments
954 ///
955 /// * collection_id.
956 ///
957 /// * schema: SchemaVersion: enum
958 #[weight = <SelfWeightOf<T>>::set_schema_version()]885 #[weight = <SelfWeightOf<T>>::set_collection_limits()]
959 #[transactional]886 #[transactional]
960 pub fn set_schema_version(887 pub fn set_collection_limits(
961 origin,888 origin,
962 collection_id: CollectionId,889 collection_id: CollectionId,
963 version: SchemaVersion890 new_limit: CollectionLimits,
964 ) -> DispatchResult {891 ) -> DispatchResult {
965 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);892 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
966 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;893 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
967 target_collection.check_is_owner_or_admin(&sender)?;894 target_collection.check_is_owner(&sender)?;
968 target_collection.schema_version = version;895 let old_limit = &target_collection.limits;
969
970 <Pallet<T>>::deposit_event(Event::<T>::SchemaVersionSet(
971 collection_id
972 ));
973896
974 target_collection.save()897 target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;
975 }
976
977 /// Set off-chain data schema.
978 ///
979 /// # Permissions
980 ///
981 /// * Collection Owner
982 /// * Collection Admin
983 ///
984 /// # Arguments
985 ///
986 /// * collection_id.
987 ///
988 /// * schema: String representing the offchain data schema.
989 #[weight = <SelfWeightOf<T>>::set_offchain_schema(schema.len() as u32)]
990 #[transactional]
991 pub fn set_offchain_schema(
992 origin,
993 collection_id: CollectionId,
994 schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
995 ) -> DispatchResult {
996 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
997 let collection = <CollectionHandle<T>>::try_get(collection_id)?;
998
999 // =========
1000
1001 <PalletCommon<T>>::set_field(&collection, &sender, CollectionField::OffchainSchema, schema.into_inner())?;
1002
1003 <Pallet<T>>::deposit_event(Event::<T>::OffchainSchemaSet(
1004 collection_id
1005 ));
1006 Ok(())
1007 }
1008
1009 /// Set const on-chain data schema.
1010 ///
1011 /// # Permissions
1012 ///
1013 /// * Collection Owner
1014 /// * Collection Admin
1015 ///
1016 /// # Arguments
1017 ///
1018 /// * collection_id.
1019 ///
1020 /// * schema: String representing the const on-chain data schema.
1021 #[weight = <SelfWeightOf<T>>::set_const_on_chain_schema(schema.len() as u32)]
1022 #[transactional]
1023 pub fn set_const_on_chain_schema (
1024 origin,
1025 collection_id: CollectionId,
1026 schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>
1027 ) -> DispatchResult {
1028 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
1029 let collection = <CollectionHandle<T>>::try_get(collection_id)?;
1030
1031 // =========
1032
1033 <PalletCommon<T>>::set_field(&collection, &sender, CollectionField::ConstOnChainSchema, schema.into_inner())?;
1034898
1035 <Pallet<T>>::deposit_event(Event::<T>::ConstOnChainSchemaSet(899 <Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(
1036 collection_id900 collection_id
1037 ));901 ));
902
1038 Ok(())903 target_collection.save()
1039 }904 }
1040905
1041 #[weight = <SelfWeightOf<T>>::set_collection_limits()]906 #[weight = <SelfWeightOf<T>>::set_collection_limits()]
1042 #[transactional]907 #[transactional]
1043 pub fn set_collection_limits(908 pub fn set_collection_permissions(
1044 origin,909 origin,
1045 collection_id: CollectionId,910 collection_id: CollectionId,
1046 new_limit: CollectionLimits,911 new_limit: CollectionPermissions,
1047 ) -> DispatchResult {912 ) -> DispatchResult {
1048 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);913 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
1049 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;914 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
1050 target_collection.check_is_owner(&sender)?;915 target_collection.check_is_owner(&sender)?;
1051 let old_limit = &target_collection.limits;916 let old_limit = &target_collection.permissions;
1052917
1053 target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;918 target_collection.permissions = <PalletCommon<T>>::clamp_permissions(target_collection.mode.clone(), &old_limit, new_limit)?;
1054919
1055 <Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(920 <Pallet<T>>::deposit_event(Event::<T>::CollectionPermissionSet(
1056 collection_id921 collection_id
1057 ));922 ));
1058923
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
186#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]186#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
187#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]187#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
188pub struct TokenData<CrossAccountId> {188pub struct TokenData<CrossAccountId> {
189 pub const_data: Vec<u8>,
190 pub properties: Vec<Property>,189 pub properties: Vec<Property>,
191 pub owner: Option<CrossAccountId>,190 pub owner: Option<CrossAccountId>,
192}191}
223 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;222 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;
224}223}
225224
226#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]225#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]
227#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]226#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
228pub enum AccessMode {227pub enum AccessMode {
229 Normal,228 Normal,
296pub struct Collection<AccountId> {295pub struct Collection<AccountId> {
297 pub owner: AccountId,296 pub owner: AccountId,
298 pub mode: CollectionMode,297 pub mode: CollectionMode,
298 #[version(..2)]
299 pub access: AccessMode,299 pub access: AccessMode,
300 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,300 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
301 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,301 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
302 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,302 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
303
304 #[version(..2)]
303 pub mint_mode: bool,305 pub mint_mode: bool,
304306
305 #[version(..2)]307 #[version(..2)]
306 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,308 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
307309
310 #[version(..2)]
308 pub schema_version: SchemaVersion,311 pub schema_version: SchemaVersion,
309 pub sponsorship: SponsorshipState<AccountId>,312 pub sponsorship: SponsorshipState<AccountId>,
310313
311 #[version(..2)]
312 pub limits: CollectionLimitsVersion1, // Collection private restrictions314 pub limits: CollectionLimits,
315
313 #[version(2.., upper(limits.into()))]316 #[version(2.., upper(Default::default()))]
314 pub limits: CollectionLimitsVersion2,317 pub permissions: CollectionPermissions,
315318
316 #[version(..2)]319 #[version(..2)]
317 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,320 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,
329pub struct RpcCollection<AccountId> {332pub struct RpcCollection<AccountId> {
330 pub owner: AccountId,333 pub owner: AccountId,
331 pub mode: CollectionMode,334 pub mode: CollectionMode,
332 pub access: AccessMode,
333 pub name: Vec<u16>,335 pub name: Vec<u16>,
334 pub description: Vec<u16>,336 pub description: Vec<u16>,
335 pub token_prefix: Vec<u8>,337 pub token_prefix: Vec<u8>,
336 pub mint_mode: bool,
337 pub offchain_schema: Vec<u8>,
338 pub schema_version: SchemaVersion,
339 pub sponsorship: SponsorshipState<AccountId>,338 pub sponsorship: SponsorshipState<AccountId>,
340 pub limits: CollectionLimits,339 pub limits: CollectionLimits,
341 pub const_on_chain_schema: Vec<u8>,340 pub permissions: CollectionPermissions,
342 pub token_property_permissions: Vec<PropertyKeyPermission>,341 pub token_property_permissions: Vec<PropertyKeyPermission>,
343 pub properties: Vec<Property>,342 pub properties: Vec<Property>,
344}343}
345
346#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
347#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
348pub enum CollectionField {
349 ConstOnChainSchema,
350 OffchainSchema,
351}
352344
353#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]345#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]
354#[derivative(Debug, Default(bound = ""))]346#[derivative(Debug, Default(bound = ""))]
359 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,351 pub name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,
360 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,352 pub description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,
361 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,353 pub token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,
362 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,
363 pub schema_version: Option<SchemaVersion>,
364 pub pending_sponsor: Option<AccountId>,354 pub pending_sponsor: Option<AccountId>,
365 pub limits: Option<CollectionLimits>,355 pub limits: Option<CollectionLimits>,
366 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,356 pub permissions: Option<CollectionPermissions>,
367 pub token_property_permissions: CollectionPropertiesPermissionsVec,357 pub token_property_permissions: CollectionPropertiesPermissionsVec,
368 pub properties: CollectionPropertiesVec,358 pub properties: CollectionPropertiesVec,
369}359}
375 BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;365 BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
376366
377/// All fields are wrapped in `Option`s, where None means chain default367/// All fields are wrapped in `Option`s, where None means chain default
378#[struct_versioning::versioned(version = 2, upper)]
379#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]368#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
380#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]369#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
381pub struct CollectionLimits {370pub struct CollectionLimits {
396 pub owner_can_destroy: Option<bool>,385 pub owner_can_destroy: Option<bool>,
397 pub transfers_enabled: Option<bool>,386 pub transfers_enabled: Option<bool>,
398
399 #[version(2.., upper(None))]
400 pub nesting_rule: Option<NestingRule>,
401}387}
402388
403impl CollectionLimits {389impl CollectionLimits {
404 pub fn account_token_ownership_limit(&self) -> u32 {390 pub fn account_token_ownership_limit(&self) -> u32 {
405 self.account_token_ownership_limit391 self.account_token_ownership_limit
406 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)392 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)
444 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),430 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),
445 }431 }
446 }432 }
433}
434
435#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
436#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
437pub struct CollectionPermissions {
438 pub access: Option<AccessMode>,
439 pub mint_mode: Option<bool>,
440 pub nesting: Option<NestingRule>,
441}
442
443impl CollectionPermissions {
444 pub fn access(&self) -> AccessMode {
445 self.access.unwrap_or(AccessMode::Normal)
446 }
447 pub fn mint_mode(&self) -> bool {
448 self.mint_mode.unwrap_or(false)
449 }
447 pub fn nesting_rule(&self) -> &NestingRule {450 pub fn nesting(&self) -> &NestingRule {
448 static DEFAULT: NestingRule = NestingRule::Disabled;451 static DEFAULT: NestingRule = NestingRule::Disabled;
449 self.nesting_rule.as_ref().unwrap_or(&DEFAULT)452 self.nesting.as_ref().unwrap_or(&DEFAULT)
450 }453 }
451}454}
452455
453#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]456#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]
454#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]457#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
520#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]523#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
521#[derivative(Debug)]524#[derivative(Debug)]
522pub struct CreateNftExData<CrossAccountId> {525pub struct CreateNftExData<CrossAccountId> {
523 #[derivative(Debug(format_with = "bounded::vec_debug"))]
524 pub const_data: BoundedVec<u8, CustomDataLimit>,
525 #[derivative(Debug(format_with = "bounded::vec_debug"))]526 #[derivative(Debug(format_with = "bounded::vec_debug"))]
526 pub properties: CollectionPropertiesVec,527 pub properties: CollectionPropertiesVec,
527 pub owner: CrossAccountId,528 pub owner: CrossAccountId,
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
4141
42 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;42 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
43 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;43 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>>;
44 fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>>;
4544
46 fn collection_properties(collection: CollectionId, properties: Option<Vec<Vec<u8>>>) -> Result<Vec<Property>>;45 fn collection_properties(collection: CollectionId, properties: Option<Vec<Vec<u8>>>) -> Result<Vec<Property>>;
4746
modifiedruntime/common/src/runtime_apis.rsdiffbeforeafterboth
2929
30 Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))30 Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))
31 }31 }
32 fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {
33 dispatch_unique_runtime!(collection.const_metadata(token))
34 }
3532
36 fn collection_properties(33 fn collection_properties(
37 collection: CollectionId,34 collection: CollectionId,
73 keys: Option<Vec<Vec<u8>>>70 keys: Option<Vec<Vec<u8>>>
74 ) -> Result<TokenData<CrossAccountId>, DispatchError> {71 ) -> Result<TokenData<CrossAccountId>, DispatchError> {
75 let token_data = TokenData {72 let token_data = TokenData {
76 const_data: Self::const_metadata(collection, token_id)?,
77 properties: Self::token_properties(collection, token_id, keys)?,73 properties: Self::token_properties(collection, token_id, keys)?,
78 owner: Self::token_owner(collection, token_id)?74 owner: Self::token_owner(collection, token_id)?
79 };75 };
modifiedruntime/tests/src/tests.rsdiffbeforeafterboth
2398}2398}
2399// #endregion2399// #endregion
2400
2401#[test]
2402fn set_const_on_chain_schema() {
2403 new_test_ext().execute_with(|| {
2404 let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
2405
2406 let origin1 = Origin::signed(1);
2407 assert_ok!(Unique::set_const_on_chain_schema(
2408 origin1,
2409 collection_id,
2410 b"test const on chain schema".to_vec().try_into().unwrap()
2411 ));
2412
2413 assert_eq!(
2414 <pallet_common::CollectionData<Test>>::get((
2415 collection_id,
2416 CollectionField::ConstOnChainSchema
2417 )),
2418 b"test const on chain schema".to_vec()
2419 );
2420 });
2421}
24222400
2423#[test]2401#[test]
2424fn collection_transfer_flag_works() {2402fn collection_transfer_flag_works() {