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.rsdiffbeforeafterboth1#[macro_export]2macro_rules! impl_common_runtime_apis {3 (4 $(5 #![custom_apis]67 $($custom_apis:tt)+8 )?9 ) => {10 impl_runtime_apis! {11 $($($custom_apis)+)?1213 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {14 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {15 dispatch_unique_runtime!(collection.account_tokens(account))16 }17 fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {18 dispatch_unique_runtime!(collection.collection_tokens())19 }20 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {21 dispatch_unique_runtime!(collection.token_exists(token))22 }2324 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {25 dispatch_unique_runtime!(collection.token_owner(token))26 }27 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {28 let budget = up_data_structs::budget::Value::new(5);2930 Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))31 }32 fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {33 dispatch_unique_runtime!(collection.const_metadata(token))34 }3536 fn collection_properties(37 collection: CollectionId,38 keys: Option<Vec<Vec<u8>>>39 ) -> Result<Vec<Property>, DispatchError> {40 let keys = keys.map(41 |keys| pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)42 ).transpose()?;4344 pallet_common::Pallet::<Runtime>::filter_collection_properties(collection, keys)45 }4647 fn token_properties(48 collection: CollectionId,49 token_id: TokenId,50 keys: Option<Vec<Vec<u8>>>51 ) -> Result<Vec<Property>, DispatchError> {52 let keys = keys.map(53 |keys| pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)54 ).transpose()?;5556 dispatch_unique_runtime!(collection.token_properties(token_id, keys))57 }5859 fn property_permissions(60 collection: CollectionId,61 keys: Option<Vec<Vec<u8>>>62 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {63 let keys = keys.map(64 |keys| pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)65 ).transpose()?;6667 pallet_common::Pallet::<Runtime>::filter_property_permissions(collection, keys)68 }6970 fn token_data(71 collection: CollectionId,72 token_id: TokenId,73 keys: Option<Vec<Vec<u8>>>74 ) -> Result<TokenData<CrossAccountId>, DispatchError> {75 let token_data = TokenData {76 const_data: Self::const_metadata(collection, token_id)?,77 properties: Self::token_properties(collection, token_id, keys)?,78 owner: Self::token_owner(collection, token_id)?79 };8081 Ok(token_data)82 }8384 fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {85 dispatch_unique_runtime!(collection.total_supply())86 }87 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {88 dispatch_unique_runtime!(collection.account_balance(account))89 }90 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {91 dispatch_unique_runtime!(collection.balance(account, token))92 }93 fn allowance(94 collection: CollectionId,95 sender: CrossAccountId,96 spender: CrossAccountId,97 token: TokenId,98 ) -> Result<u128, DispatchError> {99 dispatch_unique_runtime!(collection.allowance(sender, spender, token))100 }101102 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {103 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))104 }105 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {106 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))107 }108 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {109 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))110 }111 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {112 dispatch_unique_runtime!(collection.last_token_id())113 }114 fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {115 Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))116 }117 fn collection_stats() -> Result<CollectionStats, DispatchError> {118 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())119 }120 fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {121 Ok(<$crate::sponsoring::UniqueSponsorshipPredict<Runtime> as122 $crate::sponsoring::SponsorshipPredict<Runtime>>::predict(123 collection,124 account,125 token))126 }127128 fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {129 Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))130 }131 }132133 impl rmrk_rpc::RmrkApi<134 Block,135 AccountId,136 RmrkCollectionInfo<AccountId>,137 RmrkInstanceInfo<AccountId>,138 RmrkResourceInfo,139 RmrkPropertyInfo,140 RmrkBaseInfo<AccountId>,141 RmrkPartType,142 RmrkTheme143 > for Runtime {144 fn last_collection_idx() -> Result<RmrkCollectionId, DispatchError> {145 Ok(RmrkCore::last_collection_idx())146 }147 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;150 use scale_info::prelude::string::String;151 use pallet_proxy_rmrk_core::{RmrkProperty, misc::CollectionType};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 ?155156 let collection_id = CollectionId(collection_id);157 let collection = <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_typed_nft_collection(collection_id, CollectionType::Regular)?;158159 let metadata = BoundedVec::try_from(160 <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_collection_property(collection_id, RmrkProperty::Metadata)?.into_inner()161 ).map_err(|_| <pallet_common::Error<Runtime>>::PropertyKeyIsTooLong)?;162163 let nfts_count = (dispatch_unique_runtime!(collection_id.total_supply()) as Result<u32, DispatchError>)?; // todo? <Runtime>::total_supply(collection_id)164165 Ok(Some(RmrkCollectionInfo {166 issuer: collection.owner.clone(),167 metadata,168 max: collection.limits.token_limit,169 symbol: BoundedVec::try_from(170 collection.token_prefix.clone().into_inner()171 ).map_err(|_| <pallet_common::Error<Runtime>>::PropertyKeyIsTooLong)?,172 nfts_count173 }))174 }175 fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {176 use frame_support::BoundedVec;177 use up_data_structs::mapping::TokenAddressMapping;178 use pallet_proxy_rmrk_core::{RmrkProperty, misc::RmrkDecode};179180 let collection_id = CollectionId(collection_id);181 let nft_id = TokenId(nft_by_id);182183 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) {185 Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),186 None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone())187 },188 None => return Ok(None)189 };190191 // 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));207208 Ok(Some(RmrkInstanceInfo {209 owner: owner,210 //recipient: , // prop?211 royalty: properties[0].clone().decode_property().unwrap(),212 metadata: properties[1].clone(),213 equipped: properties[2].clone().decode_property().unwrap(),214 pending: allowance.is_some(),215 }))216 }217 fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {218 let cross_account_id = CrossAccountId::from_sub(account_id);219 let collection_id = CollectionId(collection_id);220 Ok(221 (dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id)) as Result<Vec<TokenId>, DispatchError>)?222 //<Runtime as up_rpc::UniqueApi<Block, CrossAccountId, AccountId>>::account_tokens(collection_id, cross_account_id)?223 .into_iter()224 .map(|token| token.0)225 .collect::<Vec<_>>()226 )227 }228 fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {229 use up_data_structs::mapping::TokenAddressMapping;230231 let collection_id = CollectionId(collection_id);232 let nft_id = TokenId(nft_id);233 let cross_account_id = CrossAccountId::from_eth(234 EvmTokenAddressMapping::token_to_address(collection_id, nft_id)235 );236237 Ok(238 pallet_nonfungible::Owned::<Runtime>::iter_prefix((collection_id, cross_account_id))239 .map(|(child_id, _)| RmrkNftChild {240 collection_id: collection_id.0, // todo make sure they're always from this collection // spoiler: they're not241 nft_id: child_id.0,242 })243 .collect()244 )245 }246 fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {247 use frame_support::BoundedVec;248249 let collection_id = CollectionId(collection_id);250 let properties = pallet_common::Pallet::<Runtime>::collection_properties(collection_id);251252 return Ok(match filter_keys {253 Some(keys) => {254 let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;255 let properties = keys256 .into_iter()257 .filter_map(|key| {258 properties.get(&key).map(|value| RmrkPropertyInfo {259 key: BoundedVec::try_from(key.into_inner()).unwrap(),260 value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),261 })262 })263 .collect();264265 properties266 }267 None => {268 properties269 .iter()270 .filter_map(|(key, value)| Some(RmrkPropertyInfo {271 key: BoundedVec::try_from(key.clone().into_inner()).unwrap(),272 value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),273 }))274 .collect()275 }276 });277 }278 fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {279 use frame_support::BoundedVec;280281 let collection_id = CollectionId(collection_id);282 let token_id = TokenId(nft_id);283284 let properties = pallet_nonfungible::Pallet::<Runtime>::token_properties((collection_id, token_id)); // todo look into usage of pallet_nonfungible285286 // todo displace to a function? redundant code piece with collection props287 return Ok(match filter_keys {288 Some(keys) => {289 let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;290 let properties = keys291 .into_iter()292 .filter_map(|key| {293 properties.get(&key).map(|value| RmrkPropertyInfo {294 key: BoundedVec::try_from(key.into_inner()).unwrap(),295 value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),296 })297 })298 .collect();299300 properties301 }302 None => {303 properties304 .iter()305 .filter_map(|(key, value)| Some(RmrkPropertyInfo {306 key: BoundedVec::try_from(key.clone().into_inner()).unwrap(),307 value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),308 }))309 .collect()310 }311 });312 }313 fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {314 use frame_support::BoundedVec;315 use pallet_proxy_rmrk_core::RmrkProperty;316317 let collection_id = CollectionId(collection_id);318 let nft_id = TokenId(nft_id);319320 // 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>>();*/334335 Ok(Vec::new(/*[RmrkResourceInfo {336337 }]*/))338 }339 fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {340 todo!()341 }342 fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {343 use frame_support::BoundedVec;344 use scale_info::prelude::string::String;345 use pallet_proxy_rmrk_core::{RmrkProperty, misc::CollectionType};346347 let collection_id = CollectionId(base_id);348 let collection = <pallet_proxy_rmrk_core::Pallet<Runtime>>::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(357 |key| BoundedVec::try_from(358 <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_collection_property(collection_id, key).unwrap().into_inner()359 )360 )361 // todo not-a-rmrk-collection error362 .collect::<Result<Vec<_>, _>>()363 .map_err(|_| <pallet_proxy_rmrk_core::Error<Runtime>>::CollectionUnknown)?;364365 Ok(Some(RmrkBaseInfo {366 issuer: collection.owner.clone(),367 base_type: properties[0].clone(),368 symbol: BoundedVec::try_from(369 collection.token_prefix.clone().into_inner()370 ).map_err(|_| <pallet_common::Error<Runtime>>::PropertyKeyIsTooLong)?,371 }))372 }373 fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {374 use frame_support::BoundedVec;375 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{RmrkNft, RmrkDecode}};376377 let collection_id = CollectionId(base_id);378 // todo check prop for being a base379380 let parts = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?381 .iter()382 .filter_map(|token_id| {383 let nft_type = <pallet_nonfungible::TokenData<Runtime>>::get((collection_id, token_id))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>>();401402 match nft_type {403 FixedPart => Some(RmrkPartType::FixedPart(RmrkFixedPart {404 id: token_id.0,405 src: properties[0].clone().decode_property().unwrap(),406 z: properties[1].clone().decode_property().unwrap(),407 })),408 SlotPart => Some(RmrkPartType::SlotPart(RmrkSlotPart {409 id: token_id.0,410 src: properties[0].clone().decode_property().unwrap(),411 z: properties[1].clone().decode_property().unwrap(),412 equippable: properties[2].clone().decode_property().unwrap(),413 })),414 _ => None415 }416 })417 .collect();418419 Ok(parts)420 }421 fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {422 use frame_support::BoundedVec;423 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{RmrkNft, RmrkDecode}};424425 let collection_id = CollectionId(base_id);426 // todo make sure this is theme427428 let theme_names = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?429 .iter()430 .filter_map(|token_id| {431 let nft_type = <pallet_nonfungible::TokenData<Runtime>>::get((collection_id, token_id))432 .unwrap()433 .rmrk_nft_type()?;434435 match nft_type {436 Theme => Some(437 <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_property(438 collection_id, *token_id, RmrkProperty::ThemeName439 ).unwrap()440 .into_inner()441 ),442 _ => None443 }444 })445 .collect::<Vec<RmrkThemeName>>();446447 Ok(theme_names)448 }449 fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {450 use frame_support::BoundedVec;451452 let collection_id = CollectionId(base_id);453454 // todo one theme. filter collection tokens according to theme name, should result in one455 // (is it possible to search with iter_prefix for part of a struct that satisfies?..)456 // filter properties according to filter_keys and load them into resulting theme.properties457 let themes = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?458 .iter()459 .filter_map(|token_id| {460 let properties = pallet_nonfungible::Pallet::<Runtime>::token_properties((collection_id, token_id));461462 // todo ping properties for "rmrk:nft-type"463 // if none, skip, None464 // ugh gonna go through ALL properties, searching for matches for "rmrk:theme-property-<key>"465 let nft_type = "theme";466 match nft_type {467 "theme" => Some(RmrkTheme {468 name: BoundedVec::try_from(469 <pallet_nonfungible::TokenData<Runtime>>::get((collection_id, token_id))470 .map(|t| t.const_data)471 .unwrap_or_default()472 .into_inner()473 ).unwrap(),474 // todo? (dispatch_unique_runtime!(collection_id.const_metadata(token_id)) as Result<Vec<u8>, DispatchError>)?,475 properties: Vec::new(), // pain in the ass476 inherit: false, // "rmrk:theme-inherit"477 }),478 _ => None479 }480 })481 .collect::<Vec<_>>();482483 // todo484 Ok(Some(themes[0].clone()))485 }486 }487488 impl sp_api::Core<Block> for Runtime {489 fn version() -> RuntimeVersion {490 VERSION491 }492493 fn execute_block(block: Block) {494 Executive::execute_block(block)495 }496497 fn initialize_block(header: &<Block as BlockT>::Header) {498 Executive::initialize_block(header)499 }500 }501502 impl sp_api::Metadata<Block> for Runtime {503 fn metadata() -> OpaqueMetadata {504 OpaqueMetadata::new(Runtime::metadata().into())505 }506 }507508 impl sp_block_builder::BlockBuilder<Block> for Runtime {509 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {510 Executive::apply_extrinsic(extrinsic)511 }512513 fn finalize_block() -> <Block as BlockT>::Header {514 Executive::finalize_block()515 }516517 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {518 data.create_extrinsics()519 }520521 fn check_inherents(522 block: Block,523 data: sp_inherents::InherentData,524 ) -> sp_inherents::CheckInherentsResult {525 data.check_extrinsics(&block)526 }527528 // fn random_seed() -> <Block as BlockT>::Hash {529 // RandomnessCollectiveFlip::random_seed().0530 // }531 }532533 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {534 fn validate_transaction(535 source: TransactionSource,536 tx: <Block as BlockT>::Extrinsic,537 hash: <Block as BlockT>::Hash,538 ) -> TransactionValidity {539 Executive::validate_transaction(source, tx, hash)540 }541 }542543 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {544 fn offchain_worker(header: &<Block as BlockT>::Header) {545 Executive::offchain_worker(header)546 }547 }548549 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {550 fn chain_id() -> u64 {551 <Runtime as pallet_evm::Config>::ChainId::get()552 }553554 fn account_basic(address: H160) -> EVMAccount {555 EVM::account_basic(&address)556 }557558 fn gas_price() -> U256 {559 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()560 }561562 fn account_code_at(address: H160) -> Vec<u8> {563 EVM::account_codes(address)564 }565566 fn author() -> H160 {567 <pallet_evm::Pallet<Runtime>>::find_author()568 }569570 fn storage_at(address: H160, index: U256) -> H256 {571 let mut tmp = [0u8; 32];572 index.to_big_endian(&mut tmp);573 EVM::account_storages(address, H256::from_slice(&tmp[..]))574 }575576 #[allow(clippy::redundant_closure)]577 fn call(578 from: H160,579 to: H160,580 data: Vec<u8>,581 value: U256,582 gas_limit: U256,583 max_fee_per_gas: Option<U256>,584 max_priority_fee_per_gas: Option<U256>,585 nonce: Option<U256>,586 estimate: bool,587 access_list: Option<Vec<(H160, Vec<H256>)>>,588 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {589 let config = if estimate {590 let mut config = <Runtime as pallet_evm::Config>::config().clone();591 config.estimate = true;592 Some(config)593 } else {594 None595 };596597 let is_transactional = false;598 <Runtime as pallet_evm::Config>::Runner::call(599 CrossAccountId::from_eth(from),600 to,601 data,602 value,603 gas_limit.low_u64(),604 max_fee_per_gas,605 max_priority_fee_per_gas,606 nonce,607 access_list.unwrap_or_default(),608 is_transactional,609 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),610 ).map_err(|err| err.into())611 }612613 #[allow(clippy::redundant_closure)]614 fn create(615 from: H160,616 data: Vec<u8>,617 value: U256,618 gas_limit: U256,619 max_fee_per_gas: Option<U256>,620 max_priority_fee_per_gas: Option<U256>,621 nonce: Option<U256>,622 estimate: bool,623 access_list: Option<Vec<(H160, Vec<H256>)>>,624 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {625 let config = if estimate {626 let mut config = <Runtime as pallet_evm::Config>::config().clone();627 config.estimate = true;628 Some(config)629 } else {630 None631 };632633 let is_transactional = false;634 <Runtime as pallet_evm::Config>::Runner::create(635 CrossAccountId::from_eth(from),636 data,637 value,638 gas_limit.low_u64(),639 max_fee_per_gas,640 max_priority_fee_per_gas,641 nonce,642 access_list.unwrap_or_default(),643 is_transactional,644 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),645 ).map_err(|err| err.into())646 }647648 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {649 Ethereum::current_transaction_statuses()650 }651652 fn current_block() -> Option<pallet_ethereum::Block> {653 Ethereum::current_block()654 }655656 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {657 Ethereum::current_receipts()658 }659660 fn current_all() -> (661 Option<pallet_ethereum::Block>,662 Option<Vec<pallet_ethereum::Receipt>>,663 Option<Vec<TransactionStatus>>664 ) {665 (666 Ethereum::current_block(),667 Ethereum::current_receipts(),668 Ethereum::current_transaction_statuses()669 )670 }671672 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {673 xts.into_iter().filter_map(|xt| match xt.0.function {674 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),675 _ => None676 }).collect()677 }678679 fn elasticity() -> Option<Permill> {680 None681 }682 }683684 impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {685 fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic {686 UncheckedExtrinsic::new_unsigned(687 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),688 )689 }690 }691692 impl sp_session::SessionKeys<Block> for Runtime {693 fn decode_session_keys(694 encoded: Vec<u8>,695 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {696 SessionKeys::decode_into_raw_public_keys(&encoded)697 }698699 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {700 SessionKeys::generate(seed)701 }702 }703704 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {705 fn slot_duration() -> sp_consensus_aura::SlotDuration {706 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())707 }708709 fn authorities() -> Vec<AuraId> {710 Aura::authorities().to_vec()711 }712 }713714 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {715 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {716 ParachainSystem::collect_collation_info(header)717 }718 }719720 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {721 fn account_nonce(account: AccountId) -> Index {722 System::account_nonce(account)723 }724 }725726 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {727 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {728 TransactionPayment::query_info(uxt, len)729 }730 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {731 TransactionPayment::query_fee_details(uxt, len)732 }733 }734735 /*736 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>737 for Runtime738 {739 fn call(740 origin: AccountId,741 dest: AccountId,742 value: Balance,743 gas_limit: u64,744 input_data: Vec<u8>,745 ) -> pallet_contracts_primitives::ContractExecResult {746 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)747 }748749 fn instantiate(750 origin: AccountId,751 endowment: Balance,752 gas_limit: u64,753 code: pallet_contracts_primitives::Code<Hash>,754 data: Vec<u8>,755 salt: Vec<u8>,756 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>757 {758 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)759 }760761 fn get_storage(762 address: AccountId,763 key: [u8; 32],764 ) -> pallet_contracts_primitives::GetStorageResult {765 Contracts::get_storage(address, key)766 }767768 fn rent_projection(769 address: AccountId,770 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {771 Contracts::rent_projection(address)772 }773 }774 */775776 #[cfg(feature = "runtime-benchmarks")]777 impl frame_benchmarking::Benchmark<Block> for Runtime {778 fn benchmark_metadata(extra: bool) -> (779 Vec<frame_benchmarking::BenchmarkList>,780 Vec<frame_support::traits::StorageInfo>,781 ) {782 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};783 use frame_support::traits::StorageInfoTrait;784785 let mut list = Vec::<BenchmarkList>::new();786787 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);788 list_benchmark!(list, extra, pallet_common, Common);789 list_benchmark!(list, extra, pallet_unique, Unique);790 list_benchmark!(list, extra, pallet_structure, Structure);791 list_benchmark!(list, extra, pallet_inflation, Inflation);792 list_benchmark!(list, extra, pallet_fungible, Fungible);793 list_benchmark!(list, extra, pallet_refungible, Refungible);794 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);795 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);796797 let storage_info = AllPalletsReversedWithSystemFirst::storage_info();798799 return (list, storage_info)800 }801802 fn dispatch_benchmark(803 config: frame_benchmarking::BenchmarkConfig804 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {805 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};806807 let allowlist: Vec<TrackedStorageKey> = vec![808 // Total Issuance809 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),810811 // Block Number812 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),813 // Execution Phase814 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),815 // Event Count816 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),817 // System Events818 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),819820 // Evm CurrentLogs821 hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),822823 // Transactional depth824 hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),825 ];826827 let mut batches = Vec::<BenchmarkBatch>::new();828 let params = (&config, &allowlist);829830 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);831 add_benchmark!(params, batches, pallet_common, Common);832 add_benchmark!(params, batches, pallet_unique, Unique);833 add_benchmark!(params, batches, pallet_structure, Structure);834 add_benchmark!(params, batches, pallet_inflation, Inflation);835 add_benchmark!(params, batches, pallet_fungible, Fungible);836 add_benchmark!(params, batches, pallet_refungible, Refungible);837 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);838 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);839840 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }841 Ok(batches)842 }843 }844845 #[cfg(feature = "try-runtime")]846 impl frame_try_runtime::TryRuntime<Block> for Runtime {847 fn on_runtime_upgrade() -> (Weight, Weight) {848 log::info!("try-runtime::on_runtime_upgrade unique-chain.");849 let weight = Executive::try_runtime_upgrade().unwrap();850 (weight, RuntimeBlockWeights::get().max_block)851 }852853 fn execute_block_no_check(block: Block) -> Weight {854 Executive::execute_block_no_check(block)855 }856 }857 }858 }859}tests/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