difftreelog
feat(rmrk-rpc) decoding properties
in: master
3 files changed
pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use frame_support::{pallet_prelude::*, transactional, BoundedVec, dispatch::DispatchResult};20use frame_system::{pallet_prelude::*, ensure_signed};21use sp_runtime::{DispatchError, Permill, traits::StaticLookup};22use sp_std::vec::Vec;23use up_data_structs::*;24use pallet_common::{Pallet as PalletCommon, Error as CommonError, CollectionHandle, CommonCollectionOperations};25use pallet_nonfungible::{Pallet as PalletNft, NonfungibleHandle};26use pallet_evm::account::CrossAccountId;2728pub use pallet::*;2930pub mod misc;31pub mod property;3233use misc::*;34pub use property::*;3536#[frame_support::pallet]37pub mod pallet {38 use super::*;39 use pallet_evm::account;4041 #[pallet::config]42 pub trait Config: frame_system::Config43 + pallet_common::Config44 + pallet_nonfungible::Config45 + account::Config {46 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;47 }4849 #[pallet::pallet]50 #[pallet::generate_store(pub(super) trait Store)]51 pub struct Pallet<T>(_);5253 #[pallet::event]54 #[pallet::generate_deposit(pub(super) fn deposit_event)]55 pub enum Event<T: Config> {56 CollectionCreated {57 issuer: T::AccountId,58 collection_id: RmrkCollectionId,59 },60 CollectionDestroyed {61 issuer: T::AccountId,62 collection_id: RmrkCollectionId,63 },64 IssuerChanged {65 old_issuer: T::AccountId,66 new_issuer: T::AccountId,67 collection_id: RmrkCollectionId,68 },69 CollectionLocked {70 issuer: T::AccountId,71 collection_id: RmrkCollectionId,72 },73 NftMinted {74 owner: T::AccountId,75 collection_id: RmrkCollectionId,76 nft_id: RmrkNftId,77 },78 NFTBurned {79 owner: T::AccountId,80 nft_id: RmrkNftId,81 },82 }8384 #[pallet::error]85 pub enum Error<T> {86 /* Unique-specific events */87 CorruptedCollectionType,88 NftTypeEncodeError,89 RmrkPropertyKeyIsTooLong,90 RmrkPropertyValueIsTooLong,9192 /* RMRK compatible events */93 CollectionNotEmpty,94 NoAvailableCollectionId,95 NoAvailableNftId,96 CollectionUnknown,97 NoPermission,98 CollectionFullOrLocked,99 }100101 #[pallet::call]102 impl<T: Config> Pallet<T> {103 #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]104 #[transactional]105 pub fn create_collection(106 origin: OriginFor<T>,107 metadata: RmrkString,108 max: Option<u32>,109 symbol: RmrkCollectionSymbol,110 ) -> DispatchResult {111 let sender = ensure_signed(origin)?;112113 let limits = CollectionLimits {114 owner_can_transfer: Some(false),115 token_limit: max,116 ..Default::default()117 };118119 let data = CreateCollectionData {120 limits: Some(limits),121 token_prefix: symbol.into_inner()122 .try_into()123 .map_err(|_| <CommonError<T>>::CollectionTokenPrefixLimitExceeded)?,124 ..Default::default()125 };126127 let collection_id_res = <PalletNft<T>>::init_collection(sender.clone(), data);128129 if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {130 return Err(<Error<T>>::NoAvailableCollectionId.into());131 }132133 let collection_id = collection_id_res?;134135 let collection = Self::get_nft_collection(collection_id)?.into_inner();136137 <PalletCommon<T>>::set_scoped_collection_properties(138 &collection,139 PropertyScope::Rmrk,140 [141 rmrk_property!(Config=T, Metadata: metadata)?,142 rmrk_property!(Config=T, CollectionType: CollectionType::Regular)?,143 ].into_iter()144 )?;145146 Self::deposit_event(Event::CollectionCreated {147 issuer: sender,148 collection_id: collection_id.0149 });150151 Ok(())152 }153154 #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]155 #[transactional]156 pub fn destroy_collection(157 origin: OriginFor<T>,158 collection_id: RmrkCollectionId,159 ) -> DispatchResult {160 let sender = ensure_signed(origin)?;161 let cross_sender = T::CrossAccountId::from_sub(sender.clone());162163 let unique_collection_id = collection_id.into();164165 let collection = Self::get_typed_nft_collection(unique_collection_id, CollectionType::Regular)?;166167 ensure!(collection.total_supply() == 0, <Error<T>>::CollectionNotEmpty);168169 <PalletNft<T>>::destroy_collection(collection, &cross_sender)170 .map_err(Self::map_common_err_to_proxy)?;171172 Self::deposit_event(Event::CollectionDestroyed { issuer: sender, collection_id });173174 Ok(())175 }176177 #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]178 #[transactional]179 pub fn change_collection_issuer(180 origin: OriginFor<T>,181 collection_id: RmrkCollectionId,182 new_issuer: <T::Lookup as StaticLookup>::Source,183 ) -> DispatchResult {184 let sender = ensure_signed(origin)?;185186 let new_issuer = T::Lookup::lookup(new_issuer)?;187188 Self::change_collection_owner(189 collection_id.into(),190 CollectionType::Regular,191 sender.clone(),192 new_issuer.clone()193 )?;194195 Self::deposit_event(Event::IssuerChanged {196 old_issuer: sender,197 new_issuer,198 collection_id,199 });200201 Ok(())202 }203204 #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]205 #[transactional]206 pub fn lock_collection(207 origin: OriginFor<T>,208 collection_id: RmrkCollectionId,209 ) -> DispatchResult {210 let sender = ensure_signed(origin)?;211 let cross_sender = T::CrossAccountId::from_sub(sender.clone());212213 let collection = Self::get_typed_nft_collection(214 collection_id.into(),215 CollectionType::Regular216 )?;217218 Self::check_collection_owner(&collection, &cross_sender)?;219220 let token_count = collection.total_supply();221222 let mut collection = collection.into_inner();223 collection.limits.token_limit = Some(token_count);224 collection.save()?;225226 Self::deposit_event(Event::CollectionLocked { issuer: sender, collection_id });227228 Ok(())229 }230231 #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]232 #[transactional]233 pub fn mint_nft(234 origin: OriginFor<T>,235 owner: T::AccountId,236 collection_id: RmrkCollectionId,237 recipient: Option<T::AccountId>,238 royalty_amount: Option<Permill>,239 metadata: RmrkString,240 ) -> DispatchResult {241 let sender = ensure_signed(origin)?;242 let sender = T::CrossAccountId::from_sub(sender);243 let cross_owner = T::CrossAccountId::from_sub(owner.clone());244245 let royalty_info = royalty_amount.map(|amount| rmrk::RoyaltyInfo {246 recipient: recipient.unwrap_or_else(|| owner.clone()),247 amount248 });249250 let nft_id = Self::create_nft(251 sender,252 cross_owner,253 collection_id.into(),254 CollectionType::Regular,255 NftType::Regular,256 [257 rmrk_property!(Config=T, RoyaltyInfo: royalty_info)?,258 rmrk_property!(Config=T, Metadata: metadata)?,259 rmrk_property!(Config=T, Equipped: false)?,260 rmrk_property!(Config=T, ResourceCollection: None::<CollectionId>)?,261 rmrk_property!(Config=T, ResourcePriorities: <Vec<u8>>::new())?,262 ].into_iter()263 )?;264265 Self::deposit_event(Event::NftMinted {266 owner,267 collection_id,268 nft_id: nft_id.0269 });270271 Ok(())272 }273274 #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]275 #[transactional]276 pub fn burn_nft(277 origin: OriginFor<T>,278 collection_id: RmrkCollectionId,279 nft_id: RmrkNftId,280 ) -> DispatchResult {281 let sender = ensure_signed(origin.clone())?;282 let cross_sender = T::CrossAccountId::from_sub(sender.clone());283284 Self::destroy_nft(285 cross_sender,286 collection_id.into(),287 CollectionType::Regular,288 nft_id.into()289 )?;290291 Self::deposit_event(Event::NFTBurned { owner: sender, nft_id });292293 Ok(())294 }295 }296}297298impl<T: Config> Pallet<T> {299 fn create_nft(300 sender: T::CrossAccountId,301 owner: T::CrossAccountId,302 collection_id: CollectionId,303 collection_type: CollectionType,304 nft_type: NftType,305 properties: impl Iterator<Item=Property>306 ) -> Result<TokenId, DispatchError> {307 let collection = Self::get_typed_nft_collection(308 collection_id,309 collection_type310 )?;311312 let data = CreateNftExData {313 const_data: nft_type.encode()314 .try_into()315 .map_err(|_| <Error<T>>::NftTypeEncodeError)?,316 properties: BoundedVec::default(),317 owner,318 };319320 let budget = budget::Value::new(2);321322 <PalletNft<T>>::create_item(323 &collection,324 &sender,325 data,326 &budget,327 ).map_err(Self::map_common_err_to_proxy)?;328329 let nft_id = <PalletNft<T>>::current_token_id(&collection);330331 <PalletNft<T>>::set_scoped_token_properties(332 &collection,333 nft_id,334 PropertyScope::Rmrk,335 properties336 )?;337338 Ok(nft_id)339 }340341 fn destroy_nft(342 sender: T::CrossAccountId,343 collection_id: CollectionId,344 collection_type: CollectionType,345 token_id: TokenId346 ) -> DispatchResult {347 let collection = Self::get_typed_nft_collection(348 collection_id,349 collection_type350 )?;351352 <PalletNft<T>>::burn(&collection, &sender, token_id)353 .map_err(Self::map_common_err_to_proxy)?;354355 Ok(())356 }357358 fn change_collection_owner(359 collection_id: CollectionId,360 collection_type: CollectionType,361 sender: T::AccountId,362 new_owner: T::AccountId,363 ) -> DispatchResult {364 let collection = Self::get_typed_nft_collection(365 collection_id,366 collection_type367 )?;368 Self::check_collection_owner(&collection, &T::CrossAccountId::from_sub(sender))?;369370 let mut collection = collection.into_inner();371372 collection.owner = new_owner;373 collection.save()374 }375376 fn check_collection_owner(collection: &NonfungibleHandle<T>, account: &T::CrossAccountId) -> DispatchResult {377 collection.check_is_owner(account)378 .map_err(Self::map_common_err_to_proxy)379 }380381 pub fn get_nft_collection(collection_id: CollectionId) -> Result<NonfungibleHandle<T>, DispatchError> {382 let collection = <CollectionHandle<T>>::try_get(collection_id)383 .map_err(|_| <Error<T>>::CollectionUnknown)?384 .into_nft_collection()?;385386 Ok(collection)387 }388389 pub fn get_collection_property(collection_id: CollectionId, key: RmrkProperty) -> Result<PropertyValue, DispatchError> {390 let collection_property = <PalletCommon<T>>::collection_properties(collection_id)391 .get(&rmrk_property!(Config=T, key)?)392 .ok_or(<Error<T>>::CollectionUnknown)?393 .clone();394395 Ok(collection_property)396 }397398 pub fn get_collection_type(collection_id: CollectionId) -> Result<CollectionType, DispatchError> {399 let value = Self::get_collection_property(collection_id, RmrkProperty::CollectionType)?;400 let collection_type: CollectionType = (&value)401 .try_into()402 .map_err(<Error<T>>::from)?;403404 Ok(collection_type)405 }406407 pub fn get_nft_property(collection_id: CollectionId, nft_id: TokenId, key: RmrkProperty) -> Result<PropertyValue, DispatchError> {408 let nft_property = <PalletNft<T>>::token_properties((collection_id, nft_id))409 .get(&rmrk_property!(Config=T, key)?)410 .ok_or(<Error<T>>::NoAvailableNftId)?411 .clone();412413 Ok(nft_property)414 }415416 pub fn check_collection_type(collection_id: CollectionId, collection_type: CollectionType) -> DispatchResult {417 let actual_type = Self::get_collection_type(collection_id)?;418 ensure!(actual_type == collection_type, <CommonError<T>>::NoPermission);419420 Ok(())421 }422423 fn get_typed_nft_collection(424 collection_id: CollectionId,425 collection_type: CollectionType426 ) -> Result<NonfungibleHandle<T>, DispatchError> {427 Self::check_collection_type(collection_id, collection_type)?;428429 Self::get_nft_collection(collection_id)430 }431432 fn map_common_err_to_proxy(err: DispatchError) -> DispatchError {433 map_common_err_to_proxy! {434 match err {435 NoPermission => NoPermission,436 CollectionTokenLimitExceeded => CollectionFullOrLocked437 }438 }439 }440}pallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/misc.rs
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -82,6 +82,18 @@
}
}
+pub trait RmrkDecode<T: Decode> {
+ fn decode_property(&self) -> Option<T>;
+}
+
+impl<T: Decode> RmrkDecode<T> for RmrkString {
+ fn decode_property(&self) -> Option<T> { // todo access runtime errors? // but then rmrk_nft_type must have it too
+ let mut value = self.as_slice();
+
+ T::decode(&mut value).ok()
+ }
+}
+
#[derive(Encode, Decode, PartialEq, Eq)]
pub enum CollectionType {
Regular,
runtime/common/src/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -148,17 +148,18 @@
// TODO decide on displacement to palettes -- does RMRK belong there, spread across common and nonfungible?
use frame_support::BoundedVec;
use scale_info::prelude::string::String;
- use pallet_proxy_rmrk_core::RmrkProperty;
+ use pallet_proxy_rmrk_core::{RmrkProperty, misc::CollectionType};
- // todo check if this is a rmrk collection? or simply trust and provide anyway?
+ // todo check if this is a rmrk standard collection? or simply trust and provide anyway?
// client-is-always-right / enforce authority and order ?
let collection_id = CollectionId(collection_id);
- let collection = <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_collection(collection_id)?;
- // todo Vec::from(["rmrk:metadata", "rmrk:collection-type"])
+ let collection = <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_typed_nft_collection(collection_id, CollectionType::Regular)?;
+
let metadata = BoundedVec::try_from(
<pallet_proxy_rmrk_core::Pallet<Runtime>>::get_collection_property(collection_id, RmrkProperty::Metadata)?.into_inner()
- ).map_err(|_| <pallet_common::Error<Runtime>>::PropertyKeyIsTooLong)?;//unwrap_or_default();
+ ).map_err(|_| <pallet_common::Error<Runtime>>::PropertyKeyIsTooLong)?;
+
let nfts_count = (dispatch_unique_runtime!(collection_id.total_supply()) as Result<u32, DispatchError>)?; // todo? <Runtime>::total_supply(collection_id)
Ok(Some(RmrkCollectionInfo {
@@ -174,11 +175,11 @@
fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {
use frame_support::BoundedVec;
use up_data_structs::mapping::TokenAddressMapping;
- use pallet_proxy_rmrk_core::RmrkProperty;
+ use pallet_proxy_rmrk_core::{RmrkProperty, misc::RmrkDecode};
let collection_id = CollectionId(collection_id);
let nft_id = TokenId(nft_by_id);
-
+
let owner = match (dispatch_unique_runtime!(collection_id.token_owner(nft_id)) as Result<Option<CrossAccountId>, DispatchError>)? {
Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {
Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),
@@ -187,6 +188,7 @@
None => return Ok(None)
};
+ // todo displace querying property key array to rmrk proxy pallet
let keys = [
RmrkProperty::RoyaltyInfo,
RmrkProperty::Metadata,
@@ -196,19 +198,20 @@
let properties = keys.into_iter().map(
|key| BoundedVec::try_from(
- // todo nft property, not collection
<pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_property(collection_id, nft_id, key).unwrap().into_inner()
).unwrap()
)
.collect::<Vec<RmrkString>>();
+
+ let allowance = pallet_nonfungible::Allowance::<Runtime>::get((collection_id, nft_id));
Ok(Some(RmrkInstanceInfo {
owner: owner,
//recipient: , // prop?
- royalty: None,//Permill::from_percent(0), // prop, decode
+ royalty: properties[0].clone().decode_property().unwrap(),
metadata: properties[1].clone(),
- equipped: false, // prop, decode
- pending: false, // prop, decode
+ equipped: properties[2].clone().decode_property().unwrap(),
+ pending: allowance.is_some(),
}))
}
fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {
@@ -234,7 +237,7 @@
Ok(
pallet_nonfungible::Owned::<Runtime>::iter_prefix((collection_id, cross_account_id))
.map(|(child_id, _)| RmrkNftChild {
- collection_id: collection_id.0, // todo make sure they're always from this collection
+ collection_id: collection_id.0, // todo make sure they're always from this collection // spoiler: they're not
nft_id: child_id.0,
})
.collect()
@@ -315,7 +318,7 @@
let nft_id = TokenId(nft_id);
// let keys = [
- // RmrkProperty::Royalty,
+ // RmrkProperty::RoyaltyInfo,
// RmrkProperty::Metadata,
// RmrkProperty::Equipped,
// RmrkProperty::Pending,
@@ -339,10 +342,11 @@
fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {
use frame_support::BoundedVec;
use scale_info::prelude::string::String;
- use pallet_proxy_rmrk_core::RmrkProperty;
+ use pallet_proxy_rmrk_core::{RmrkProperty, misc::CollectionType};
let collection_id = CollectionId(base_id);
- let collection = <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_collection(collection_id)?;
+ let collection = <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_typed_nft_collection(collection_id, CollectionType::Base)?;
+ // todo check prop for being a base
// todo export to macro? redundancy
let keys = [
@@ -368,46 +372,47 @@
}
fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {
use frame_support::BoundedVec;
- use pallet_proxy_rmrk_core::RmrkProperty;
+ use pallet_proxy_rmrk_core::{RmrkProperty, misc::{RmrkNft, RmrkDecode}};
let collection_id = CollectionId(base_id);
-
- let keys = [
- //RmrkProperty::NftType)?,
- //RmrkProperty::PartId)?,
- RmrkProperty::Src,
- RmrkProperty::ZIndex,
- RmrkProperty::EquippableList,
- ];
+ // todo check prop for being a base
let parts = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?
.iter()
.filter_map(|token_id| {
- /*let properties = keys.into_iter().map(
+ let nft_type = <pallet_nonfungible::TokenData<Runtime>>::get((collection_id, token_id))
+ //.map_err(|_| ) // no need, tis a filter_map
+ .unwrap()
+ .rmrk_nft_type()?;
+
+ // dislocate to rmrkproxycore and simply send an array of keys
+ let keys = [
+ //RmrkProperty::PartId)?,
+ RmrkProperty::Src,
+ RmrkProperty::ZIndex,
+ RmrkProperty::EquippableList,
+ ];
+
+ let properties = keys.into_iter().map(
|key| BoundedVec::try_from(
<pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_property(collection_id, *token_id, key).unwrap().into_inner()
).unwrap()
- ).collect::<Vec<RmrkString>>();*/
+ ).collect::<Vec<RmrkString>>();
- // todo ping properties for "rmrk:nft-type"
- // if none, skip, None
- let nft_type = "fixed-part";
-
match nft_type {
- "fixed-part" => Some(RmrkPartType::FixedPart(RmrkFixedPart {
+ FixedPart => Some(RmrkPartType::FixedPart(RmrkFixedPart {
id: token_id.0,
- src: BoundedVec::default(), // "rmrk:src"
- z: 0, // "rmrk:z-index"
+ src: properties[0].clone().decode_property().unwrap(),
+ z: properties[1].clone().decode_property().unwrap(),
})),
- "slot-part" => Some(RmrkPartType::SlotPart(RmrkSlotPart {
+ SlotPart => Some(RmrkPartType::SlotPart(RmrkSlotPart {
id: token_id.0,
- equippable: RmrkEquippableList::Empty, // "rmrk:equippable-list" ?
- src: BoundedVec::default(), // "rmrk:src"
- z: 0, // "rmrk:z-index"
+ src: properties[0].clone().decode_property().unwrap(),
+ z: properties[1].clone().decode_property().unwrap(),
+ equippable: properties[2].clone().decode_property().unwrap(),
})),
_ => None
}
-
})
.collect();
@@ -415,24 +420,29 @@
}
fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {
use frame_support::BoundedVec;
+ use pallet_proxy_rmrk_core::{RmrkProperty, misc::{RmrkNft, RmrkDecode}};
let collection_id = CollectionId(base_id);
+ // todo make sure this is theme
let theme_names = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?
.iter()
.filter_map(|token_id| {
- let properties = pallet_nonfungible::Pallet::<Runtime>::token_properties((collection_id, token_id));
-
- // todo ping property for "rmrk:nft-type"
- // if none or not "theme", skip, None
- let nft_type = "theme";
- // can't call dispatch_unique_runtime! from here??
- <pallet_nonfungible::TokenData<Runtime>>::get((collection_id, token_id))
- .map(|t| t.const_data.into_inner())
- //.unwrap_or_default()
- // todo rework to reduce independence
+ let nft_type = <pallet_nonfungible::TokenData<Runtime>>::get((collection_id, token_id))
+ .unwrap()
+ .rmrk_nft_type()?;
+
+ match nft_type {
+ Theme => Some(
+ <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_property(
+ collection_id, *token_id, RmrkProperty::ThemeName
+ ).unwrap()
+ .into_inner()
+ ),
+ _ => None
+ }
})
- .collect();
+ .collect::<Vec<RmrkThemeName>>();
Ok(theme_names)
}