difftreelog
feat(rmrk-rpc) rpc refactoring
in: master
6 files changed
pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -22,7 +22,7 @@
use sp_std::vec::Vec;
use up_data_structs::*;
use pallet_common::{Pallet as PalletCommon, Error as CommonError, CollectionHandle, CommonCollectionOperations};
-use pallet_nonfungible::{Pallet as PalletNft, NonfungibleHandle};
+use pallet_nonfungible::{Pallet as PalletNft, NonfungibleHandle, TokenData};
use pallet_evm::account::CrossAccountId;
pub use pallet::*;
@@ -396,6 +396,15 @@
Ok(collection)
}
+ // should this even be here, might displace it to common/nonfungible -- but they did not need it, only rmrk does
+ pub fn collection_exists(collection_id: CollectionId) -> bool {
+ <pallet_common::CollectionById<T>>::contains_key(collection_id)
+ }
+
+ pub fn nft_exists(collection_id: CollectionId, nft_id: TokenId) -> bool {
+ <TokenData<T>>::contains_key((collection_id, nft_id))
+ }
+
pub fn get_collection_property(collection_id: CollectionId, key: RmrkProperty) -> Result<PropertyValue, DispatchError> {
let collection_property = <PalletCommon<T>>::collection_properties(collection_id)
.get(&rmrk_property!(Config=T, key)?)
@@ -414,6 +423,13 @@
Ok(collection_type)
}
+ pub fn ensure_collection_type(collection_id: CollectionId, collection_type: CollectionType) -> DispatchResult {
+ let actual_type = Self::get_collection_type(collection_id)?;
+ ensure!(actual_type == collection_type, <CommonError<T>>::NoPermission);
+
+ Ok(())
+ }
+
pub fn get_nft_property(collection_id: CollectionId, nft_id: TokenId, key: RmrkProperty) -> Result<PropertyValue, DispatchError> {
let nft_property = <PalletNft<T>>::token_properties((collection_id, nft_id))
.get(&rmrk_property!(Config=T, key)?)
@@ -423,9 +439,16 @@
Ok(nft_property)
}
- pub fn check_collection_type(collection_id: CollectionId, collection_type: CollectionType) -> DispatchResult {
- let actual_type = Self::get_collection_type(collection_id)?;
- ensure!(actual_type == collection_type, <CommonError<T>>::NoPermission);
+ pub fn get_nft_type(collection_id: CollectionId, token_id: TokenId) -> Result<NftType, DispatchError> {
+ <TokenData<T>>::get((collection_id, token_id))
+ .unwrap()
+ .rmrk_nft_type()
+ .ok_or(<Error<T>>::NoAvailableNftId.into())
+ }
+
+ pub fn ensure_nft_type(collection_id: CollectionId, token_id: TokenId, nft_type: NftType) -> DispatchResult {
+ let actual_type = Self::get_nft_type(collection_id, token_id)?;
+ ensure!(actual_type == nft_type, <CommonError<T>>::NoPermission);
Ok(())
}
@@ -434,7 +457,7 @@
collection_id: CollectionId,
collection_type: CollectionType
) -> Result<NonfungibleHandle<T>, DispatchError> {
- Self::check_collection_type(collection_id, collection_type)?;
+ Self::ensure_collection_type(collection_id, collection_type)?;
Self::get_nft_collection(collection_id)
}
pallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/misc.rs
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -82,15 +82,27 @@
}
}
-pub trait RmrkDecode<T: Decode> {
- fn decode_property(&self) -> Option<T>;
+pub trait RmrkDecode<T: Decode + Default, S> {
+ fn decode_or_default(&self) -> 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
+impl<T: Decode + Default, S> RmrkDecode<T, S> for BoundedVec<u8, S> {
+ fn decode_or_default(&self) -> T {
let mut value = self.as_slice();
- T::decode(&mut value).ok()
+ T::decode(&mut value).unwrap_or_default()
+ }
+}
+
+pub trait RmrkRebind<T, S> {
+ fn rebind(&self) -> BoundedVec<u8, S>;
+}
+
+impl<T, S> RmrkRebind<T, S> for BoundedVec<u8, T> where BoundedVec<u8, S>: TryFrom<Vec<u8>> {
+ fn rebind(&self) -> BoundedVec<u8, S> {
+ BoundedVec::<u8, S>::try_from(
+ self.clone().into_inner()
+ ).unwrap_or_default()
}
}
primitives/data-structs/src/rmrk.rsdiffbeforeafterboth--- a/primitives/data-structs/src/rmrk.rs
+++ b/primitives/data-structs/src/rmrk.rs
@@ -360,14 +360,14 @@
}
#[cfg_attr(feature = "std", derive(Serialize))]
-#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, Eq, MaxEncodedLen)]
+#[derive(Encode, Decode, Debug, Default, TypeInfo, Clone, PartialEq, Eq, MaxEncodedLen)]
#[cfg_attr(
feature = "std",
serde(bound = "BoundedCollectionList: AsRef<[CollectionId]>")
)]
pub enum EquippableList<BoundedCollectionList> {
All,
- Empty,
+ #[default] Empty,
Custom(
#[cfg_attr(feature = "std", serde(with = "serialize::vec"))]
BoundedCollectionList
runtime/common/src/runtime_apis.rsdiffbeforeafterboth38 keys: Option<Vec<Vec<u8>>>38 keys: Option<Vec<Vec<u8>>>39 ) -> Result<Vec<Property>, DispatchError> {39 ) -> Result<Vec<Property>, DispatchError> {40 let keys = keys.map(40 let keys = keys.map(41 |keys| pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)41 |keys| Common::bytes_keys_to_property_keys(keys)42 ).transpose()?;42 ).transpose()?;434344 pallet_common::Pallet::<Runtime>::filter_collection_properties(collection, keys)44 Common::filter_collection_properties(collection, keys)45 }45 }464647 fn token_properties(47 fn token_properties(50 keys: Option<Vec<Vec<u8>>>50 keys: Option<Vec<Vec<u8>>>51 ) -> Result<Vec<Property>, DispatchError> {51 ) -> Result<Vec<Property>, DispatchError> {52 let keys = keys.map(52 let keys = keys.map(53 |keys| pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)53 |keys| Common::bytes_keys_to_property_keys(keys)54 ).transpose()?;54 ).transpose()?;555556 dispatch_unique_runtime!(collection.token_properties(token_id, keys))56 dispatch_unique_runtime!(collection.token_properties(token_id, keys))61 keys: Option<Vec<Vec<u8>>>61 keys: Option<Vec<Vec<u8>>>62 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {62 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {63 let keys = keys.map(63 let keys = keys.map(64 |keys| pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)64 |keys| Common::bytes_keys_to_property_keys(keys)65 ).transpose()?;65 ).transpose()?;666667 pallet_common::Pallet::<Runtime>::filter_property_permissions(collection, keys)67 Common::filter_property_permissions(collection, keys)68 }68 }696970 fn token_data(70 fn token_data(146 }146 }147147 fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {148 fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {148 // TODO decide on displacement to palettes -- does RMRK belong there, spread across common and nonfungible?149 use frame_support::BoundedVec;149 use frame_support::BoundedVec;150 use scale_info::prelude::string::String;150 use scale_info::prelude::string::String;151 use pallet_proxy_rmrk_core::{RmrkProperty, misc::CollectionType};151 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkRebind, RmrkDecode}};152153 // todo check if this is a rmrk standard collection? or simply trust and provide anyway?154 // client-is-always-right / enforce authority and order ?155152156 let collection_id = CollectionId(collection_id);153 let collection_id = CollectionId(collection_id);157 let collection = <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_typed_nft_collection(collection_id, CollectionType::Regular)?;154 let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Regular) {158159 let metadata = BoundedVec::try_from(155 Ok(c) => c,160 <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_collection_property(collection_id, RmrkProperty::Metadata)?.into_inner()161 ).map_err(|_| <pallet_common::Error<Runtime>>::PropertyKeyIsTooLong)?;156 Err(_) => return Ok(None),157 };162158163 let nfts_count = (dispatch_unique_runtime!(collection_id.total_supply()) as Result<u32, DispatchError>)?; // todo? <Runtime>::total_supply(collection_id)159 let nfts_count = (dispatch_unique_runtime!(collection_id.total_supply()) as Result<u32, DispatchError>)?;160 //<Runtime as up_rpc::UniqueApi>::total_supply(collection_id); // todo can't find UniqueApi with disabled default features164161165 Ok(Some(RmrkCollectionInfo {162 Ok(Some(RmrkCollectionInfo {166 issuer: collection.owner.clone(),163 issuer: collection.owner.clone(),167 metadata,164 metadata: RmrkCore::get_collection_property(collection_id, RmrkProperty::Metadata)?.decode_or_default(),168 max: collection.limits.token_limit,165 max: collection.limits.token_limit,169 symbol: BoundedVec::try_from(166 symbol: collection.token_prefix.rebind(), // change170 collection.token_prefix.clone().into_inner()171 ).map_err(|_| <pallet_common::Error<Runtime>>::PropertyKeyIsTooLong)?,172 nfts_count167 nfts_count173 }))168 }))174 }169 }179175180 let collection_id = CollectionId(collection_id);176 let collection_id = CollectionId(collection_id);181 let nft_id = TokenId(nft_by_id);177 let nft_id = TokenId(nft_by_id);178 if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(None); }182179183 let owner = match (dispatch_unique_runtime!(collection_id.token_owner(nft_id)) as Result<Option<CrossAccountId>, DispatchError>)? {180 let owner = match (dispatch_unique_runtime!(collection_id.token_owner(nft_id)) as Result<Option<CrossAccountId>, DispatchError>)? {184 Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {181 Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {188 None => return Ok(None)185 None => return Ok(None)189 };186 };190187 191 // todo displace querying property key array to rmrk proxy pallet192 let keys = [193 RmrkProperty::RoyaltyInfo,194 RmrkProperty::Metadata,195 RmrkProperty::Equipped,196 // ?? "rmrk:recipient", "rmrk:nft-type", "rmrk:resource-collection", "rmrk:resource-priorities"197 ];198199 let properties = keys.into_iter().map(200 |key| BoundedVec::try_from(201 <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_property(collection_id, nft_id, key).unwrap().into_inner()202 ).unwrap()203 )204 .collect::<Vec<RmrkString>>();205206 let allowance = pallet_nonfungible::Allowance::<Runtime>::get((collection_id, nft_id));188 let allowance = pallet_nonfungible::Allowance::<Runtime>::get((collection_id, nft_id));207189208 Ok(Some(RmrkInstanceInfo {190 Ok(Some(RmrkInstanceInfo {209 owner: owner,191 owner: owner,210 //recipient: , // prop?211 royalty: properties[0].clone().decode_property().unwrap(),192 royalty: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::RoyaltyInfo)?.decode_or_default(),212 metadata: properties[1].clone(),193 metadata: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Metadata)?.decode_or_default(),213 equipped: properties[2].clone().decode_property().unwrap(),194 equipped: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Equipped)?.decode_or_default(),214 pending: allowance.is_some(),195 pending: allowance.is_some(),215 }))196 }))216 }197 }198217 fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {199 fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {218 let cross_account_id = CrossAccountId::from_sub(account_id);200 let cross_account_id = CrossAccountId::from_sub(account_id);219 let collection_id = CollectionId(collection_id);201 let collection_id = CollectionId(collection_id);202 if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); }203220 Ok(204 Ok(221 (dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id)) as Result<Vec<TokenId>, DispatchError>)?205 (dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id)) as Result<Vec<TokenId>, DispatchError>)?230215231 let collection_id = CollectionId(collection_id);216 let collection_id = CollectionId(collection_id);232 let nft_id = TokenId(nft_id);217 let nft_id = TokenId(nft_id);218 if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(Vec::new()); }219233 let cross_account_id = CrossAccountId::from_eth(220 let cross_account_id = CrossAccountId::from_eth(234 EvmTokenAddressMapping::token_to_address(collection_id, nft_id)221 EvmTokenAddressMapping::token_to_address(collection_id, nft_id)245 }232 }233246 fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {234 fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {247 use frame_support::BoundedVec;235 use pallet_proxy_rmrk_core::misc::RmrkDecode;248236249 let collection_id = CollectionId(collection_id);237 let collection_id = CollectionId(collection_id);238 if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); }239250 let properties = pallet_common::Pallet::<Runtime>::collection_properties(collection_id);240 let properties = Common::collection_properties(collection_id);251241242 // todo repeated code252 return Ok(match filter_keys {243 return Ok(match filter_keys {253 Some(keys) => {244 Some(keys) => {254 let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;245 let keys = Common::bytes_keys_to_property_keys(keys)?;255 let properties = keys246 let properties = keys256 .into_iter()247 .into_iter()257 .filter_map(|key| {248 .filter_map(|key| {258 properties.get(&key).map(|value| RmrkPropertyInfo {249 properties.get(&key).map(|value| RmrkPropertyInfo {259 key: BoundedVec::try_from(key.into_inner()).unwrap(),250 key: key.decode_or_default(),260 value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),251 value: value.decode_or_default(),261 })252 })262 })253 })263 .collect();254 .collect();268 properties259 properties269 .iter()260 .iter()270 .filter_map(|(key, value)| Some(RmrkPropertyInfo {261 .filter_map(|(key, value)| Some(RmrkPropertyInfo {271 key: BoundedVec::try_from(key.clone().into_inner()).unwrap(),262 key: key.decode_or_default(),272 value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),263 value: value.decode_or_default(),273 }))264 }))274 .collect()265 .collect()275 }266 }276 });267 });277 }268 }269278 fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {270 fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {279 use frame_support::BoundedVec;271 use frame_support::BoundedVec;272 use pallet_proxy_rmrk_core::misc::RmrkDecode;280273281 let collection_id = CollectionId(collection_id);274 let collection_id = CollectionId(collection_id);282 let token_id = TokenId(nft_id);275 let token_id = TokenId(nft_id);276 if !RmrkCore::nft_exists(collection_id, token_id) { return Ok(Vec::new()); }283277284 let properties = pallet_nonfungible::Pallet::<Runtime>::token_properties((collection_id, token_id)); // todo look into usage of pallet_nonfungible278 let properties = Nonfungible::token_properties((collection_id, token_id));279 // todo look into this usage of pallet_nonfungible285280286 // todo displace to a function? redundant code piece with collection props281 // todo displace to a function? redundant code piece with collection props287 return Ok(match filter_keys {282 return Ok(match filter_keys {288 Some(keys) => {283 Some(keys) => {289 let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;284 let keys = Common::bytes_keys_to_property_keys(keys)?;290 let properties = keys285 let properties = keys291 .into_iter()286 .into_iter()292 .filter_map(|key| {287 .filter_map(|key| {293 properties.get(&key).map(|value| RmrkPropertyInfo {288 properties.get(&key).map(|value| RmrkPropertyInfo {294 key: BoundedVec::try_from(key.into_inner()).unwrap(),289 key: key.decode_or_default(),295 value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),290 value: value.decode_or_default(),296 })291 })297 })292 })298 .collect();293 .collect();303 properties298 properties304 .iter()299 .iter()305 .filter_map(|(key, value)| Some(RmrkPropertyInfo {300 .filter_map(|(key, value)| Some(RmrkPropertyInfo {306 key: BoundedVec::try_from(key.clone().into_inner()).unwrap(),301 key: key.decode_or_default(),307 value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),302 value: value.decode_or_default(),308 }))303 }))309 .collect()304 .collect()310 }305 }311 });306 });312 }307 }308313 fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {309 fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {314 use frame_support::BoundedVec;310 use frame_support::BoundedVec;315 use pallet_proxy_rmrk_core::RmrkProperty;311 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType}};316312317 let collection_id = CollectionId(collection_id);313 let collection_id = CollectionId(collection_id);314 if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }315318 let nft_id = TokenId(nft_id);316 let nft_id = TokenId(nft_id);319317 if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Resource).is_err() { return Ok(Vec::new()); }320 // let keys = [321 // RmrkProperty::RoyaltyInfo,322 // RmrkProperty::Metadata,323 // RmrkProperty::Equipped,324 // RmrkProperty::Pending,325 // // ?? "rmrk:recipient", "rmrk:nft-type", "rmrk:resource-collection", "rmrk:resource-priorities"326 // ];327328 /*let resources = keys.into_iter().map(329 |key| BoundedVec::try_from(330 <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_property(collection_id, nft_id, key).unwrap().into_inner()331 ).unwrap()332 )333 .collect::<Vec<RmrkString>>();*/334318335 Ok(Vec::new(/*[RmrkResourceInfo {319 Ok(Vec::new(/*[RmrkResourceInfo {336320 343 use frame_support::BoundedVec;329 use frame_support::BoundedVec;344 use scale_info::prelude::string::String;330 use scale_info::prelude::string::String;345 use pallet_proxy_rmrk_core::{RmrkProperty, misc::CollectionType};331 use pallet_proxy_rmrk_core::{332 RmrkProperty, misc::{CollectionType, RmrkRebind, RmrkDecode},333 };346334347 let collection_id = CollectionId(base_id);335 let collection_id = CollectionId(base_id);348 let collection = <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_typed_nft_collection(collection_id, CollectionType::Base)?;336 let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Base) {349 // todo check prop for being a base350351 // todo export to macro? redundancy352 let keys = [353 RmrkProperty::BaseType,354 ];355356 let properties = keys.into_iter().map(337 Ok(c) => c,357 |key| BoundedVec::try_from(358 <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_collection_property(collection_id, key).unwrap().into_inner()338 Err(_) => return Ok(None),359 )360 )361 // todo not-a-rmrk-collection error362 .collect::<Result<Vec<_>, _>>()363 .map_err(|_| <pallet_proxy_rmrk_core::Error<Runtime>>::CollectionUnknown)?;339 };364340365 Ok(Some(RmrkBaseInfo {341 Ok(Some(RmrkBaseInfo {366 issuer: collection.owner.clone(),342 issuer: collection.owner.clone(),367 base_type: properties[0].clone(),343 base_type: RmrkCore::get_collection_property(collection_id, RmrkProperty::BaseType)?.decode_or_default(),368 symbol: BoundedVec::try_from(344 symbol: collection.token_prefix.rebind(),369 collection.token_prefix.clone().into_inner()370 ).map_err(|_| <pallet_common::Error<Runtime>>::PropertyKeyIsTooLong)?,371 }))345 }))372 }346 }347373 fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {348 fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {374 use frame_support::BoundedVec;349 use frame_support::BoundedVec;375 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{RmrkNft, RmrkDecode}};350 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkNft, RmrkDecode}};376351377 let collection_id = CollectionId(base_id);352 let collection_id = CollectionId(base_id);378 // todo check prop for being a base353 if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() { return Ok(Vec::new()); }379354380 let parts = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?355 let parts = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?381 .iter()356 .iter()382 .filter_map(|token_id| {357 .filter_map(|token_id| {383 let nft_type = <pallet_nonfungible::TokenData<Runtime>>::get((collection_id, token_id))358 let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();384 //.map_err(|_| ) // no need, tis a filter_map385 .unwrap()386 .rmrk_nft_type()?;387388 // dislocate to rmrkproxycore and simply send an array of keys389 let keys = [390 //RmrkProperty::PartId)?,391 RmrkProperty::Src,392 RmrkProperty::ZIndex,393 RmrkProperty::EquippableList,394 ];395396 let properties = keys.into_iter().map(397 |key| BoundedVec::try_from(398 <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_property(collection_id, *token_id, key).unwrap().into_inner()399 ).unwrap()400 ).collect::<Vec<RmrkString>>();401359402 match nft_type {360 match nft_type {403 FixedPart => Some(RmrkPartType::FixedPart(RmrkFixedPart {361 FixedPart => Some(RmrkPartType::FixedPart(RmrkFixedPart {404 id: token_id.0,362 id: token_id.0,405 src: properties[0].clone().decode_property().unwrap(),363 src: RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::Src).unwrap().decode_or_default(),406 z: properties[1].clone().decode_property().unwrap(),364 z: RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ZIndex).unwrap().decode_or_default(),407 })),365 })),408 SlotPart => Some(RmrkPartType::SlotPart(RmrkSlotPart {366 SlotPart => Some(RmrkPartType::SlotPart(RmrkSlotPart {409 id: token_id.0,367 id: token_id.0,410 src: properties[0].clone().decode_property().unwrap(),368 src: RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::Src).unwrap().decode_or_default(),411 z: properties[1].clone().decode_property().unwrap(),369 z: RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ZIndex).unwrap().decode_or_default(),412 equippable: properties[2].clone().decode_property().unwrap(),370 equippable: RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::EquippableList).unwrap().decode_or_default(),413 })),371 })),414 _ => None372 _ => None415 }373 }428 let theme_names = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?387 let theme_names = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?429 .iter()388 .iter()430 .filter_map(|token_id| {389 .filter_map(|token_id| {431 let nft_type = <pallet_nonfungible::TokenData<Runtime>>::get((collection_id, token_id))390 let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();432 .unwrap()391 433 .rmrk_nft_type()?;434435 match nft_type {392 match nft_type {436 Theme => Some(393 Theme => Some(437 <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_property(394 RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ThemeName).unwrap().decode_or_default()438 collection_id, *token_id, RmrkProperty::ThemeName439 ).unwrap()440 .into_inner()441 ),395 ),442 _ => None396 _ => None443 }397 }457 let themes = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?412 let themes = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?458 .iter()413 .iter()459 .filter_map(|token_id| {414 .filter_map(|token_id| {460 let properties = pallet_nonfungible::Pallet::<Runtime>::token_properties((collection_id, token_id));415 let properties = Nonfungible::token_properties((collection_id, token_id));461416462 // todo ping properties for "rmrk:nft-type"417 // todo ping properties for "rmrk:nft-type"463 // if none, skip, None418 // if none, skip, Nonetests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -37,6 +37,7 @@
"testUnnesting": "mocha --timeout 9999999 -r ts-node/register ./**/unnest.test.ts",
"testStructure": "mocha --timeout 9999999 -r ts-node/register ./**/nesting/**.test.ts",
"testProperties": "mocha --timeout 9999999 -r ts-node/register ./**/properties.test.ts",
+ "testGraphs": "mocha --timeout 9999999 -r ts-node/register ./**/graphs.test.ts",
"testMigrationStructure": "mocha --timeout 9999999 -r ts-node/register ./**/nesting/migration-check.test.ts",
"testAddCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/addCollectionAdmin.test.ts",
"testSetSchemaVersion": "mocha --timeout 9999999 -r ts-node/register ./**/setSchemaVersion.test.ts",
tests/src/nesting/graphs.test.tsdiffbeforeafterboth--- a/tests/src/nesting/graphs.test.ts
+++ b/tests/src/nesting/graphs.test.ts
@@ -32,10 +32,10 @@
return collectionId;
}
-describe('Graphs', () => {
+describe.skip('Graphs', () => {
it('Ouroboros can\'t be created in a complex graph', async () => {
await usingApi(async api => {
- const alice = privateKey('//Alice');
+ const alice = privateKey('//alice');
const collection = await buildComplexObjectGraph(api, alice);
// to self
@@ -55,3 +55,197 @@
});
});
});
+
+import type { EventRecord } from '@polkadot/types/interfaces';
+import type { GenericEventData } from '@polkadot/types';
+import type { Option, Bytes } from '@polkadot/types-codec';
+import type {
+ RmrkTypesCollectionInfo as Collection,
+ RmrkTypesNftInfo as Nft,
+ RmrkTypesResourceInfo as Resource,
+ RmrkTypesBaseInfo as Base,
+ RmrkTypesPartType as PartType,
+ RmrkTypesNftChild as NftChild,
+ RmrkTypesTheme as Theme,
+ RmrkTypesPropertyInfo as Property,
+} from '@polkadot/types/lookup';
+
+interface TxResult<T> {
+ success: boolean;
+ successData: T | null;
+}
+
+export function extractTxResult<T>(
+ events: EventRecord[],
+ expectSection: string,
+ expectMethod: string,
+ extractAction: (data: GenericEventData) => T
+): TxResult<T> {
+ let success = false;
+ let successData = null;
+ events.forEach(({event: {data, method, section}}) => {
+ //console.log(expectSection + " "+ " " + section + " " + expectMethod + " " + method)
+ if (method == 'ExtrinsicSuccess') {
+ success = true;
+ } else if ((expectSection == section) && (expectMethod == method)) {
+ successData = extractAction(data);
+ }
+ });
+ const result: TxResult<T> = {
+ success,
+ successData,
+ };
+ return result;
+}
+
+export function extractRmrkCoreTxResult<T>(
+ events: EventRecord[],
+ expectMethod: string,
+ extractAction: (data: GenericEventData) => T
+): TxResult<T> {
+ return extractTxResult(events, 'rmrkCore', expectMethod, extractAction);
+}
+
+export async function expectTxFailure(expectedError: RegExp, promise: Promise<any>) {
+ await expect(promise).to.be.rejectedWith(expectedError);
+}
+
+export async function getCollectionsCount(api: ApiPromise): Promise<number> {
+ return (await api.rpc.rmrk.lastCollectionIdx()).toNumber();
+}
+
+export async function getCollection(api: ApiPromise, id: number): Promise<Option<Collection>> {
+ return api.rpc.rmrk.collectionById(id);
+}
+
+export async function createCollection(
+ api: ApiPromise,
+ issuerUri: string,
+ metadata: string,
+ max: number | null,
+ symbol: string
+): Promise<number> {
+ let collectionId = 0;
+
+ const oldCollectionCount = await getCollectionsCount(api);
+ const maxOptional = max ? max.toString() : null;
+ console.log(maxOptional)
+ console.log('right above me')
+
+ const issuer = privateKey(issuerUri);
+ const tx = api.tx.rmrkCore.createCollection(metadata, maxOptional, symbol);
+ const events = await executeTransaction(api, issuer, tx);
+
+ const collectionResult = extractRmrkCoreTxResult(
+ events, 'CollectionCreated', (data) => {
+ return parseInt(data[1].toString(), 10)
+ }
+ );
+ expect(collectionResult.success, 'Error: unable to create a collection').to.be.true;
+ const newCollectionCount = await getCollectionsCount(api);
+ expect(newCollectionCount).to.be.equal(oldCollectionCount + 1, 'Error: NFT collection count should increase');
+
+ collectionId = collectionResult.successData ?? 0;
+
+ console.log(collectionId);
+
+ const collectionOption = await getCollection(api, collectionId);
+
+ expect(collectionOption.isSome, 'Error: unable to fetch created NFT collection').to.be.true;
+
+ const collection = collectionOption.unwrap();
+
+ expect(collection.metadata.toUtf8()).to.be.equal(metadata, "Error: Invalid NFT collection metadata");
+ console.log(collection.max, max)
+ expect(collection.max.isSome).to.be.equal(max !== null, "Error: Invalid NFT collection max");
+
+ if (collection.max.isSome) {
+ expect(collection.max.unwrap().toNumber()).to.be.equal(max, "Error: Invalid NFT collection max");
+ }
+ expect(collection.symbol.toUtf8()).to.be.equal(symbol, "Error: Invalid NFT collection's symbol");
+ expect(collection.nftsCount.toNumber()).to.be.equal(0, "Error: NFT collection shoudn't have any tokens");
+ expect(collection.issuer.toString()).to.be.equal(issuer.address, "Error: Invalid NFT collection issuer");
+
+ return collectionId;
+}
+
+export async function deleteCollection(
+ api: ApiPromise,
+ issuerUri: string,
+ collectionId: string
+): Promise<number> {
+ const issuer = privateKey(issuerUri);
+ const tx = api.tx.rmrkCore.destroyCollection(collectionId);
+ const events = await executeTransaction(api, issuer, tx);
+
+ const collectionTxResult = extractRmrkCoreTxResult(
+ events,
+ "CollectionDestroy",
+ (data) => {
+ return parseInt(data[1].toString(), 10);
+ }
+ );
+ expect(collectionTxResult.success, 'Error: Unable to delete NFT collection').to.be.true;
+
+ const collection = await getCollection(
+ api,
+ parseInt(collectionId, 10)
+ );
+ expect(collection.isEmpty, 'Error: NFT collection should be deleted').to.be.true;
+
+ return 0;
+}
+
+describe('Something', () => {
+ const alice = '//Alice';
+ const bob = "//Bob";
+
+ it('create NFT collection', async () => {
+ await usingApi(async api => {
+ await createCollection(api, alice, 'test-metadata', 42, 'test-symbol');
+ //console.log((await api.rpc.rmrk.base(3)).toHuman());
+ });
+ });
+
+ it('create NFT collection without token limit', async () => {
+ await usingApi(async api => {
+ await createCollection(api, alice, 'no-limit-metadata', null, 'no-limit-symbol');
+ });
+ });
+
+ it("Delete NFT collection", async () => {
+ await usingApi(async api => {
+ await createCollection(
+ api,
+ alice,
+ "test-metadata",
+ null,
+ "test-symbol"
+ ).then(async (collectionId) => {
+ await deleteCollection(api, alice, collectionId.toString());
+ });
+ });
+ });
+
+ it("[Negative] delete non-existing NFT collection", async () => {
+ await usingApi(async api => {
+ const tx = deleteCollection(api, alice, "99999");
+ await expectTxFailure(/rmrkCore.CollectionUnknown/, tx);
+ });
+ });
+
+ it("[Negative] delete not an owner NFT collection", async () => {
+ await usingApi(async api => {
+ await createCollection(
+ api,
+ alice,
+ "test-metadata",
+ null,
+ "test-symbol"
+ ).then(async (collectionId) => {
+ const tx = deleteCollection(api, bob, collectionId.toString());
+ await expectTxFailure(/uniques.NoPermission/, tx);
+ });
+ });
+ });
+});
\ No newline at end of file