difftreelog
feat(rmrk-rpc) nft resources and priorities
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
@@ -486,9 +486,8 @@
}
}
- // 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)
+ <CollectionHandle<T>>::try_get(collection_id).is_ok()
}
pub fn nft_exists(collection_id: CollectionId, nft_id: TokenId) -> bool {
pallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/misc.rs
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -26,18 +26,6 @@
}
}
-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()
- }
-}
-
#[derive(Encode, Decode, PartialEq, Eq)]
pub enum CollectionType {
Regular,
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -49,6 +49,7 @@
},
NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,
FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart, EquippableList as RmrkEquippableList,
+ BasicResource as RmrkBasicResource, ComposableResource as RmrkComposableResource, SlotResource as RmrkSlotResource,
};
mod bounded;
@@ -925,17 +926,14 @@
}
}
-pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;
pub type RmrkCollectionInfo<AccountId> =
CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;
pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;
pub type RmrkResourceInfo = ResourceInfo<
- BoundedVec<u8, RmrkResourceSymbolLimit>,
+ RmrkBoundedResource,
RmrkString,
- BoundedVec<RmrkPartId, RmrkPartsLimit>,
+ RmrkBoundedParts,
>;
-pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;
-pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;
pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;
pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;
pub type RmrkPartType =
@@ -943,6 +941,13 @@
pub type RmrkThemeProperty = ThemeProperty<RmrkString>;
pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;
+pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;
+pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;
+pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;
+
+type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;
+type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>;
+
pub type RmrkRpcString = Vec<u8>;
pub type RmrkThemeName = RmrkRpcString;
pub type RmrkPropertyKey = RmrkRpcString;
primitives/data-structs/src/rmrk.rsdiffbeforeafterboth--- a/primitives/data-structs/src/rmrk.rs
+++ b/primitives/data-structs/src/rmrk.rs
@@ -154,7 +154,7 @@
pub value: BoundedValue,
}
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug, TypeInfo, MaxEncodedLen)]
+#[derive(Encode, Decode, Default, Eq, PartialEq, Clone, Debug, TypeInfo, MaxEncodedLen)]
#[cfg_attr(feature = "std", derive(Serialize))]
#[cfg_attr(
feature = "std",
@@ -275,7 +275,7 @@
pub thumb: Option<BoundedString>,
}
-#[derive(Encode, Decode, Eq, PartialEq, Clone, Debug, TypeInfo, MaxEncodedLen)]
+#[derive(Encode, Decode, Derivative, Eq, PartialEq, Clone, Debug, TypeInfo, MaxEncodedLen)]
#[cfg_attr(feature = "std", derive(Serialize))]
#[cfg_attr(
feature = "std",
@@ -286,7 +286,9 @@
"#
)
)]
-pub enum ResourceTypes<BoundedString, BoundedParts> {
+#[derivative(Default(bound=""))]
+pub enum ResourceTypes<BoundedString: Default, BoundedParts> {
+ #[derivative(Default)]
Basic(BasicResource<BoundedString>),
Composable(ComposableResource<BoundedString, BoundedParts>),
Slot(SlotResource<BoundedString>),
@@ -305,7 +307,7 @@
"#
)
)]
-pub struct ResourceInfo<BoundedResource, BoundedString, BoundedParts> {
+pub struct ResourceInfo<BoundedResource, BoundedString: Default, BoundedParts> {
/// id is a 5-character string of reasonable uniqueness.
/// The combination of base ID and resource id should be unique across the entire RMRK
/// ecosystem which
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| Common::bytes_keys_to_property_keys(keys)42 ).transpose()?;4344 Common::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| Common::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| Common::bytes_keys_to_property_keys(keys)65 ).transpose()?;6667 Common::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 }147148 fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {149 use frame_support::BoundedVec;150 use scale_info::prelude::string::String;151 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkRebind, RmrkDecode}};152153 let collection_id = CollectionId(collection_id);154 let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Regular) {155 Ok(c) => c,156 Err(_) => return Ok(None),157 };158159 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 features161162 Ok(Some(RmrkCollectionInfo {163 issuer: collection.owner.clone(),164 metadata: RmrkCore::get_collection_property(collection_id, RmrkProperty::Metadata)?.decode_or_default(),165 max: collection.limits.token_limit,166 symbol: collection.token_prefix.rebind(), // change167 nfts_count168 }))169 }170171 fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {172 use frame_support::BoundedVec;173 use up_data_structs::mapping::TokenAddressMapping;174 use pallet_proxy_rmrk_core::{RmrkProperty, misc::RmrkDecode};175176 let collection_id = CollectionId(collection_id);177 let nft_id = TokenId(nft_by_id);178 if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(None); }179180 let owner = match (dispatch_unique_runtime!(collection_id.token_owner(nft_id)) as Result<Option<CrossAccountId>, DispatchError>)? {181 Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {182 Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),183 None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone())184 },185 None => return Ok(None)186 };187188 let allowance = pallet_nonfungible::Allowance::<Runtime>::get((collection_id, nft_id));189190 Ok(Some(RmrkInstanceInfo {191 owner: owner,192 royalty: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::RoyaltyInfo)?.decode_or_default(),193 metadata: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Metadata)?.decode_or_default(),194 equipped: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Equipped)?.decode_or_default(),195 pending: allowance.is_some(),196 }))197 }198199 fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {200 let cross_account_id = CrossAccountId::from_sub(account_id);201 let collection_id = CollectionId(collection_id);202 if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); }203204 Ok(205 (dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id)) as Result<Vec<TokenId>, DispatchError>)?206 //<Runtime as up_rpc::UniqueApi<Block, CrossAccountId, AccountId>>::account_tokens(collection_id, cross_account_id)?207 .into_iter()208 .map(|token| token.0)209 .collect::<Vec<_>>()210 )211 }212213 fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {214 use up_data_structs::mapping::TokenAddressMapping;215216 let collection_id = CollectionId(collection_id);217 let nft_id = TokenId(nft_id);218 if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(Vec::new()); }219220 let cross_account_id = CrossAccountId::from_eth(221 EvmTokenAddressMapping::token_to_address(collection_id, nft_id)222 );223224 Ok(225 pallet_nonfungible::Owned::<Runtime>::iter_prefix((collection_id, cross_account_id))226 .map(|(child_id, _)| RmrkNftChild {227 collection_id: collection_id.0, // todo make sure they're always from this collection // spoiler: they're not228 nft_id: child_id.0,229 })230 .collect()231 )232 }233234 fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {235 use pallet_proxy_rmrk_core::misc::CollectionType;236237 let collection_id = CollectionId(collection_id);238 if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() {239 return Ok(Vec::new());240 }241242 let properties = RmrkCore::filter_user_properties(243 collection_id,244 /* token_id = */ None,245 filter_keys,246 |key, value| RmrkPropertyInfo {247 key,248 value249 }250 )?;251252 Ok(properties)253 }254255 fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {256 use pallet_proxy_rmrk_core::misc::NftType;257258 let collection_id = CollectionId(collection_id);259 let token_id = TokenId(nft_id);260261 if RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Regular).is_err() {262 return Ok(Vec::new());263 }264265 let properties = RmrkCore::filter_user_properties(266 collection_id,267 Some(token_id),268 filter_keys,269 |key, value| RmrkPropertyInfo {270 key,271 value272 }273 )?;274275 Ok(properties)276 }277278 fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {279 use frame_support::BoundedVec;280 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType}};281282 let collection_id = CollectionId(collection_id);283 if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }284285 let nft_id = TokenId(nft_id);286 if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Resource).is_err() { return Ok(Vec::new()); }287288 Ok(Vec::new(/*[RmrkResourceInfo {289290 }]*/))291 }292293 fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {294 todo!()295 }296297 fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {298 use frame_support::BoundedVec;299 use scale_info::prelude::string::String;300 use pallet_proxy_rmrk_core::{301 RmrkProperty, misc::{CollectionType, RmrkRebind, RmrkDecode},302 };303304 let collection_id = CollectionId(base_id);305 let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Base) {306 Ok(c) => c,307 Err(_) => return Ok(None),308 };309310 Ok(Some(RmrkBaseInfo {311 issuer: collection.owner.clone(),312 base_type: RmrkCore::get_collection_property(collection_id, RmrkProperty::BaseType)?.decode_or_default(),313 symbol: collection.token_prefix.rebind(),314 }))315 }316317 fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {318 use frame_support::BoundedVec;319 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};320321 let collection_id = CollectionId(base_id);322 if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() { return Ok(Vec::new()); }323324 let parts = (dispatch_unique_runtime!(collection_id.collection_tokens()))?325 .into_iter()326 .filter_map(|token_id| {327 let nft_type = RmrkCore::get_nft_type(collection_id, token_id).ok()?;328329 match nft_type {330 NftType::FixedPart => Some(RmrkPartType::FixedPart(RmrkFixedPart {331 id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),332 src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),333 z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),334 })),335 NftType::SlotPart => Some(RmrkPartType::SlotPart(RmrkSlotPart {336 id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),337 src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),338 z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),339 equippable: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::EquippableList).ok()?.decode_or_default(),340 })),341 _ => None342 }343 })344 .collect();345346 Ok(parts)347 }348349 fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {350 use frame_support::BoundedVec;351 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};352353 let collection_id = CollectionId(base_id);354 if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {355 return Ok(Vec::new());356 }357358 let theme_names = (dispatch_unique_runtime!(collection_id.collection_tokens()))?359 .iter()360 .filter_map(|token_id| {361 let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();362363 match nft_type {364 Theme => Some(365 RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ThemeName).unwrap().decode_or_default()366 ),367 _ => None368 }369 })370 .collect();371372 Ok(theme_names)373 }374375 fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {376 use frame_support::BoundedVec;377 use pallet_proxy_rmrk_core::{378 RmrkProperty,379 misc::{CollectionType, NftType, RmrkDecode}380 };381382 let collection_id = CollectionId(base_id);383 if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {384 return Ok(None);385 }386387 let theme_info = (dispatch_unique_runtime!(collection_id.collection_tokens()))?388 .into_iter()389 .find_map(|token_id| {390 RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Theme).ok()?;391392 let name: RmrkString = RmrkCore::get_nft_property(393 collection_id, token_id, RmrkProperty::ThemeName394 ).ok()?.decode_or_default();395396 if name == theme_name {397 Some((name, token_id))398 } else {399 None400 }401 });402403 let (name, theme_id) = match theme_info {404 Some((name, theme_id)) => (name, theme_id),405 None => return Ok(None)406 };407408 let properties = RmrkCore::filter_user_properties(409 collection_id,410 Some(theme_id),411 filter_keys,412 |key, value| RmrkThemeProperty {413 key,414 value415 }416 )?;417418 let inherit = RmrkCore::get_nft_property(419 collection_id,420 theme_id,421 RmrkProperty::ThemeInherit422 )?.decode_or_default();423424 let theme = RmrkTheme {425 name,426 properties,427 inherit,428 };429430 Ok(Some(theme))431 }432 }433434 impl sp_api::Core<Block> for Runtime {435 fn version() -> RuntimeVersion {436 VERSION437 }438439 fn execute_block(block: Block) {440 Executive::execute_block(block)441 }442443 fn initialize_block(header: &<Block as BlockT>::Header) {444 Executive::initialize_block(header)445 }446 }447448 impl sp_api::Metadata<Block> for Runtime {449 fn metadata() -> OpaqueMetadata {450 OpaqueMetadata::new(Runtime::metadata().into())451 }452 }453454 impl sp_block_builder::BlockBuilder<Block> for Runtime {455 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {456 Executive::apply_extrinsic(extrinsic)457 }458459 fn finalize_block() -> <Block as BlockT>::Header {460 Executive::finalize_block()461 }462463 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {464 data.create_extrinsics()465 }466467 fn check_inherents(468 block: Block,469 data: sp_inherents::InherentData,470 ) -> sp_inherents::CheckInherentsResult {471 data.check_extrinsics(&block)472 }473474 // fn random_seed() -> <Block as BlockT>::Hash {475 // RandomnessCollectiveFlip::random_seed().0476 // }477 }478479 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {480 fn validate_transaction(481 source: TransactionSource,482 tx: <Block as BlockT>::Extrinsic,483 hash: <Block as BlockT>::Hash,484 ) -> TransactionValidity {485 Executive::validate_transaction(source, tx, hash)486 }487 }488489 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {490 fn offchain_worker(header: &<Block as BlockT>::Header) {491 Executive::offchain_worker(header)492 }493 }494495 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {496 fn chain_id() -> u64 {497 <Runtime as pallet_evm::Config>::ChainId::get()498 }499500 fn account_basic(address: H160) -> EVMAccount {501 EVM::account_basic(&address)502 }503504 fn gas_price() -> U256 {505 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()506 }507508 fn account_code_at(address: H160) -> Vec<u8> {509 EVM::account_codes(address)510 }511512 fn author() -> H160 {513 <pallet_evm::Pallet<Runtime>>::find_author()514 }515516 fn storage_at(address: H160, index: U256) -> H256 {517 let mut tmp = [0u8; 32];518 index.to_big_endian(&mut tmp);519 EVM::account_storages(address, H256::from_slice(&tmp[..]))520 }521522 #[allow(clippy::redundant_closure)]523 fn call(524 from: H160,525 to: H160,526 data: Vec<u8>,527 value: U256,528 gas_limit: U256,529 max_fee_per_gas: Option<U256>,530 max_priority_fee_per_gas: Option<U256>,531 nonce: Option<U256>,532 estimate: bool,533 access_list: Option<Vec<(H160, Vec<H256>)>>,534 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {535 let config = if estimate {536 let mut config = <Runtime as pallet_evm::Config>::config().clone();537 config.estimate = true;538 Some(config)539 } else {540 None541 };542543 let is_transactional = false;544 <Runtime as pallet_evm::Config>::Runner::call(545 CrossAccountId::from_eth(from),546 to,547 data,548 value,549 gas_limit.low_u64(),550 max_fee_per_gas,551 max_priority_fee_per_gas,552 nonce,553 access_list.unwrap_or_default(),554 is_transactional,555 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),556 ).map_err(|err| err.into())557 }558559 #[allow(clippy::redundant_closure)]560 fn create(561 from: H160,562 data: Vec<u8>,563 value: U256,564 gas_limit: U256,565 max_fee_per_gas: Option<U256>,566 max_priority_fee_per_gas: Option<U256>,567 nonce: Option<U256>,568 estimate: bool,569 access_list: Option<Vec<(H160, Vec<H256>)>>,570 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {571 let config = if estimate {572 let mut config = <Runtime as pallet_evm::Config>::config().clone();573 config.estimate = true;574 Some(config)575 } else {576 None577 };578579 let is_transactional = false;580 <Runtime as pallet_evm::Config>::Runner::create(581 CrossAccountId::from_eth(from),582 data,583 value,584 gas_limit.low_u64(),585 max_fee_per_gas,586 max_priority_fee_per_gas,587 nonce,588 access_list.unwrap_or_default(),589 is_transactional,590 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),591 ).map_err(|err| err.into())592 }593594 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {595 Ethereum::current_transaction_statuses()596 }597598 fn current_block() -> Option<pallet_ethereum::Block> {599 Ethereum::current_block()600 }601602 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {603 Ethereum::current_receipts()604 }605606 fn current_all() -> (607 Option<pallet_ethereum::Block>,608 Option<Vec<pallet_ethereum::Receipt>>,609 Option<Vec<TransactionStatus>>610 ) {611 (612 Ethereum::current_block(),613 Ethereum::current_receipts(),614 Ethereum::current_transaction_statuses()615 )616 }617618 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {619 xts.into_iter().filter_map(|xt| match xt.0.function {620 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),621 _ => None622 }).collect()623 }624625 fn elasticity() -> Option<Permill> {626 None627 }628 }629630 impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {631 fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic {632 UncheckedExtrinsic::new_unsigned(633 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),634 )635 }636 }637638 impl sp_session::SessionKeys<Block> for Runtime {639 fn decode_session_keys(640 encoded: Vec<u8>,641 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {642 SessionKeys::decode_into_raw_public_keys(&encoded)643 }644645 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {646 SessionKeys::generate(seed)647 }648 }649650 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {651 fn slot_duration() -> sp_consensus_aura::SlotDuration {652 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())653 }654655 fn authorities() -> Vec<AuraId> {656 Aura::authorities().to_vec()657 }658 }659660 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {661 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {662 ParachainSystem::collect_collation_info(header)663 }664 }665666 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {667 fn account_nonce(account: AccountId) -> Index {668 System::account_nonce(account)669 }670 }671672 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {673 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {674 TransactionPayment::query_info(uxt, len)675 }676 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {677 TransactionPayment::query_fee_details(uxt, len)678 }679 }680681 /*682 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>683 for Runtime684 {685 fn call(686 origin: AccountId,687 dest: AccountId,688 value: Balance,689 gas_limit: u64,690 input_data: Vec<u8>,691 ) -> pallet_contracts_primitives::ContractExecResult {692 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)693 }694695 fn instantiate(696 origin: AccountId,697 endowment: Balance,698 gas_limit: u64,699 code: pallet_contracts_primitives::Code<Hash>,700 data: Vec<u8>,701 salt: Vec<u8>,702 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>703 {704 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)705 }706707 fn get_storage(708 address: AccountId,709 key: [u8; 32],710 ) -> pallet_contracts_primitives::GetStorageResult {711 Contracts::get_storage(address, key)712 }713714 fn rent_projection(715 address: AccountId,716 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {717 Contracts::rent_projection(address)718 }719 }720 */721722 #[cfg(feature = "runtime-benchmarks")]723 impl frame_benchmarking::Benchmark<Block> for Runtime {724 fn benchmark_metadata(extra: bool) -> (725 Vec<frame_benchmarking::BenchmarkList>,726 Vec<frame_support::traits::StorageInfo>,727 ) {728 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};729 use frame_support::traits::StorageInfoTrait;730731 let mut list = Vec::<BenchmarkList>::new();732733 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);734 list_benchmark!(list, extra, pallet_common, Common);735 list_benchmark!(list, extra, pallet_unique, Unique);736 list_benchmark!(list, extra, pallet_structure, Structure);737 list_benchmark!(list, extra, pallet_inflation, Inflation);738 list_benchmark!(list, extra, pallet_fungible, Fungible);739 list_benchmark!(list, extra, pallet_refungible, Refungible);740 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);741 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);742743 let storage_info = AllPalletsReversedWithSystemFirst::storage_info();744745 return (list, storage_info)746 }747748 fn dispatch_benchmark(749 config: frame_benchmarking::BenchmarkConfig750 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {751 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};752753 let allowlist: Vec<TrackedStorageKey> = vec![754 // Total Issuance755 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),756757 // Block Number758 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),759 // Execution Phase760 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),761 // Event Count762 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),763 // System Events764 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),765766 // Evm CurrentLogs767 hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),768769 // Transactional depth770 hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),771 ];772773 let mut batches = Vec::<BenchmarkBatch>::new();774 let params = (&config, &allowlist);775776 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);777 add_benchmark!(params, batches, pallet_common, Common);778 add_benchmark!(params, batches, pallet_unique, Unique);779 add_benchmark!(params, batches, pallet_structure, Structure);780 add_benchmark!(params, batches, pallet_inflation, Inflation);781 add_benchmark!(params, batches, pallet_fungible, Fungible);782 add_benchmark!(params, batches, pallet_refungible, Refungible);783 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);784 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);785786 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }787 Ok(batches)788 }789 }790791 #[cfg(feature = "try-runtime")]792 impl frame_try_runtime::TryRuntime<Block> for Runtime {793 fn on_runtime_upgrade() -> (Weight, Weight) {794 log::info!("try-runtime::on_runtime_upgrade unique-chain.");795 let weight = Executive::try_runtime_upgrade().unwrap();796 (weight, RuntimeBlockWeights::get().max_block)797 }798799 fn execute_block_no_check(block: Block) -> Weight {800 Executive::execute_block_no_check(block)801 }802 }803 }804 }805}1#[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| Common::bytes_keys_to_property_keys(keys)42 ).transpose()?;4344 Common::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| Common::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| Common::bytes_keys_to_property_keys(keys)65 ).transpose()?;6667 Common::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 }147148 fn collection_by_id(collection_id: RmrkCollectionId) -> Result<Option<RmrkCollectionInfo<AccountId>>, DispatchError> {149 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};150151 let collection_id = CollectionId(collection_id);152 let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Regular) {153 Ok(c) => c,154 Err(_) => return Ok(None),155 };156157 let nfts_count = dispatch_unique_runtime!(collection_id.total_supply())?;158159 Ok(Some(RmrkCollectionInfo {160 issuer: collection.owner.clone(),161 metadata: RmrkCore::get_collection_property(collection_id, RmrkProperty::Metadata)?.decode_or_default(),162 max: collection.limits.token_limit,163 symbol: collection.token_prefix.decode_or_default(),164 nfts_count165 }))166 }167168 fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {169 use up_data_structs::mapping::TokenAddressMapping;170 use pallet_proxy_rmrk_core::{RmrkProperty, misc::RmrkDecode};171172 let collection_id = CollectionId(collection_id);173 let nft_id = TokenId(nft_by_id);174 if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(None); }175176 let owner = match dispatch_unique_runtime!(collection_id.token_owner(nft_id))? {177 Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {178 Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),179 None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone())180 },181 None => return Ok(None)182 };183184 let allowance = pallet_nonfungible::Allowance::<Runtime>::get((collection_id, nft_id));185186 Ok(Some(RmrkInstanceInfo {187 owner: owner,188 royalty: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::RoyaltyInfo)?.decode_or_default(),189 metadata: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Metadata)?.decode_or_default(),190 equipped: RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::Equipped)?.decode_or_default(),191 pending: allowance.is_some(),192 }))193 }194195 fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {196 use pallet_proxy_rmrk_core::misc::CollectionType;197198 let cross_account_id = CrossAccountId::from_sub(account_id);199 let collection_id = CollectionId(collection_id);200 if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() { return Ok(Vec::new()); }201202 Ok(203 dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id))?204 .into_iter()205 .map(|token| token.0)206 .collect()207 )208 }209210 fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {211 use up_data_structs::mapping::TokenAddressMapping;212213 let collection_id = CollectionId(collection_id);214 let nft_id = TokenId(nft_id);215 if !RmrkCore::nft_exists(collection_id, nft_id) { return Ok(Vec::new()); }216217 let cross_account_id = CrossAccountId::from_eth(218 EvmTokenAddressMapping::token_to_address(collection_id, nft_id)219 );220221 Ok(222 pallet_nonfungible::Owned::<Runtime>::iter_prefix((collection_id, cross_account_id))223 .map(|(child_id, _)| RmrkNftChild {224 collection_id: collection_id.0, // todo make sure they're always from this collection // spoiler: they're not225 nft_id: child_id.0,226 }).collect()227 )228 }229230 fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {231 use pallet_proxy_rmrk_core::misc::CollectionType;232233 let collection_id = CollectionId(collection_id);234 if RmrkCore::ensure_collection_type(collection_id, CollectionType::Regular).is_err() {235 return Ok(Vec::new());236 }237238 let properties = RmrkCore::filter_user_properties(239 collection_id,240 /* token_id = */ None,241 filter_keys,242 |key, value| RmrkPropertyInfo {243 key,244 value245 }246 )?;247248 Ok(properties)249 }250251 fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {252 use pallet_proxy_rmrk_core::misc::NftType;253254 let collection_id = CollectionId(collection_id);255 let token_id = TokenId(nft_id);256257 if RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Regular).is_err() {258 return Ok(Vec::new());259 }260261 let properties = RmrkCore::filter_user_properties(262 collection_id,263 Some(token_id),264 filter_keys,265 |key, value| RmrkPropertyInfo {266 key,267 value268 }269 )?;270271 Ok(properties)272 }273274 fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {275 use frame_support::BoundedVec;276 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};277278 let collection_id = CollectionId(collection_id);279 if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); } // todo make sure the collection type doesn't matter280281 let nft_id = TokenId(nft_id);282 if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Resource).is_err() { return Ok(Vec::new()); }283284 let resource_collection_id: CollectionId = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourceCollection)285 .unwrap()286 .decode_or_default();287 if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }288289 let resources = pallet_nonfungible::TokenProperties::<Runtime>::iter_prefix((resource_collection_id,))290 .filter_map(|(resource_id, properties)| Some(RmrkResourceInfo {291 id: BoundedVec::default(), // todo ResourceId property292 pending: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::PendingResourceAccept).unwrap().decode_or_default(),293 pending_removal: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::PendingResourceRemoval).unwrap().decode_or_default(),294 resource: RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::ResourceType).unwrap().decode_or_default(),/* {295 RmrkResourceTypes::Basic(resource) => RmrkResourceTypes::Basic(),/*(RmrkBasicResource {296 src: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Src).unwrap().decode_or_default(),297 metadata: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Metadata).unwrap().decode_or_default(),298 license: RmrkCore::get_nft_property_inner(properties, RmrkProperty::License).unwrap().decode_or_default(),299 thumb: RmrkCore::get_nft_property_inner(properties, RmrkProperty::Thumb).unwrap().decode_or_default(),300 },*///BasicResource<BoundedString>)301 _ => todo!(), //RmrkResourceTypes::Composable(ComposableResource<BoundedString, BoundedParts>),302 //RmrkResourceTypes::Slot(SlotResource<BoundedString>),303 },*/304 }))305 .collect();306307 Ok(resources)308 }309310 fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {311 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};312313 let collection_id = CollectionId(collection_id);314 if !RmrkCore::collection_exists(collection_id) { return Ok(Vec::new()); } // todo ensure the collection type doesn't matter315316 let nft_id = TokenId(nft_id);317 if RmrkCore::ensure_nft_type(collection_id, nft_id, NftType::Resource).is_err() { return Ok(Vec::new()); }318319 /*let resource_collection_id: CollectionId = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourceCollection)320 .unwrap()321 .decode_or_default();322 if RmrkCore::ensure_collection_type(collection_id, CollectionType::Resource).is_err() { return Ok(Vec::new()); }323324 let resources = pallet_nonfungible::TokenProperties::<Runtime>::iter_prefix((resource_collection_id,))325 .filter_map(|(resource_id, properties)| Some((326 resource_id, // ResourceId property327 RmrkCore::get_nft_property(resource_collection_id, resource_id, RmrkProperty::Priority).unwrap().decode_or_default(),328 )))329 .collect()330 .sort_by_key(|(_, index)| *index)331 .into_iter().map(|(resource_id, _)| resource_id)*/332 let priorities = RmrkCore::get_nft_property(collection_id, nft_id, RmrkProperty::ResourcePriorities)?.decode_or_default();333334 Ok(priorities)335 }336337 fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {338 use pallet_proxy_rmrk_core::{339 RmrkProperty, misc::{CollectionType, RmrkDecode},340 };341342 let collection_id = CollectionId(base_id);343 let collection = match RmrkCore::get_typed_nft_collection(collection_id, CollectionType::Base) {344 Ok(c) => c,345 Err(_) => return Ok(None),346 };347348 Ok(Some(RmrkBaseInfo {349 issuer: collection.owner.clone(),350 base_type: RmrkCore::get_collection_property(collection_id, RmrkProperty::BaseType)?.decode_or_default(),351 symbol: collection.token_prefix.decode_or_default(),352 }))353 }354355 fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {356 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};357358 let collection_id = CollectionId(base_id);359 if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() { return Ok(Vec::new()); }360361 let parts = dispatch_unique_runtime!(collection_id.collection_tokens())?362 .into_iter()363 .filter_map(|token_id| {364 let nft_type = RmrkCore::get_nft_type(collection_id, token_id).ok()?;365366 match nft_type {367 NftType::FixedPart => Some(RmrkPartType::FixedPart(RmrkFixedPart {368 id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),369 src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),370 z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),371 })),372 NftType::SlotPart => Some(RmrkPartType::SlotPart(RmrkSlotPart {373 id: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ExternalPartId).ok()?.decode_or_default(),374 src: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::Src).ok()?.decode_or_default(),375 z: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::ZIndex).ok()?.decode_or_default(),376 equippable: RmrkCore::get_nft_property(collection_id, token_id, RmrkProperty::EquippableList).ok()?.decode_or_default(),377 })),378 _ => None379 }380 })381 .collect();382383 Ok(parts)384 }385386 fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {387 use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};388389 let collection_id = CollectionId(base_id);390 if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {391 return Ok(Vec::new());392 }393394 let theme_names = dispatch_unique_runtime!(collection_id.collection_tokens())?395 .iter()396 .filter_map(|token_id| {397 let nft_type = RmrkCore::get_nft_type(collection_id, *token_id).unwrap();398399 match nft_type {400 Theme => Some(401 RmrkCore::get_nft_property(collection_id, *token_id, RmrkProperty::ThemeName).unwrap().decode_or_default()402 ),403 _ => None404 }405 })406 .collect();407408 Ok(theme_names)409 }410411 fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {412 use pallet_proxy_rmrk_core::{413 RmrkProperty,414 misc::{CollectionType, NftType, RmrkDecode}415 };416417 let collection_id = CollectionId(base_id);418 if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {419 return Ok(None);420 }421422 let theme_info = dispatch_unique_runtime!(collection_id.collection_tokens())?423 .into_iter()424 .find_map(|token_id| {425 RmrkCore::ensure_nft_type(collection_id, token_id, NftType::Theme).ok()?;426427 let name: RmrkString = RmrkCore::get_nft_property(428 collection_id, token_id, RmrkProperty::ThemeName429 ).ok()?.decode_or_default();430431 if name == theme_name {432 Some((name, token_id))433 } else {434 None435 }436 });437438 let (name, theme_id) = match theme_info {439 Some((name, theme_id)) => (name, theme_id),440 None => return Ok(None)441 };442443 let properties = RmrkCore::filter_user_properties(444 collection_id,445 Some(theme_id),446 filter_keys,447 |key, value| RmrkThemeProperty {448 key,449 value450 }451 )?;452453 let inherit = RmrkCore::get_nft_property(454 collection_id,455 theme_id,456 RmrkProperty::ThemeInherit457 )?.decode_or_default();458459 let theme = RmrkTheme {460 name,461 properties,462 inherit,463 };464465 Ok(Some(theme))466 }467 }468469 impl sp_api::Core<Block> for Runtime {470 fn version() -> RuntimeVersion {471 VERSION472 }473474 fn execute_block(block: Block) {475 Executive::execute_block(block)476 }477478 fn initialize_block(header: &<Block as BlockT>::Header) {479 Executive::initialize_block(header)480 }481 }482483 impl sp_api::Metadata<Block> for Runtime {484 fn metadata() -> OpaqueMetadata {485 OpaqueMetadata::new(Runtime::metadata().into())486 }487 }488489 impl sp_block_builder::BlockBuilder<Block> for Runtime {490 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {491 Executive::apply_extrinsic(extrinsic)492 }493494 fn finalize_block() -> <Block as BlockT>::Header {495 Executive::finalize_block()496 }497498 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {499 data.create_extrinsics()500 }501502 fn check_inherents(503 block: Block,504 data: sp_inherents::InherentData,505 ) -> sp_inherents::CheckInherentsResult {506 data.check_extrinsics(&block)507 }508509 // fn random_seed() -> <Block as BlockT>::Hash {510 // RandomnessCollectiveFlip::random_seed().0511 // }512 }513514 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {515 fn validate_transaction(516 source: TransactionSource,517 tx: <Block as BlockT>::Extrinsic,518 hash: <Block as BlockT>::Hash,519 ) -> TransactionValidity {520 Executive::validate_transaction(source, tx, hash)521 }522 }523524 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {525 fn offchain_worker(header: &<Block as BlockT>::Header) {526 Executive::offchain_worker(header)527 }528 }529530 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {531 fn chain_id() -> u64 {532 <Runtime as pallet_evm::Config>::ChainId::get()533 }534535 fn account_basic(address: H160) -> EVMAccount {536 EVM::account_basic(&address)537 }538539 fn gas_price() -> U256 {540 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()541 }542543 fn account_code_at(address: H160) -> Vec<u8> {544 EVM::account_codes(address)545 }546547 fn author() -> H160 {548 <pallet_evm::Pallet<Runtime>>::find_author()549 }550551 fn storage_at(address: H160, index: U256) -> H256 {552 let mut tmp = [0u8; 32];553 index.to_big_endian(&mut tmp);554 EVM::account_storages(address, H256::from_slice(&tmp[..]))555 }556557 #[allow(clippy::redundant_closure)]558 fn call(559 from: H160,560 to: H160,561 data: Vec<u8>,562 value: U256,563 gas_limit: U256,564 max_fee_per_gas: Option<U256>,565 max_priority_fee_per_gas: Option<U256>,566 nonce: Option<U256>,567 estimate: bool,568 access_list: Option<Vec<(H160, Vec<H256>)>>,569 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {570 let config = if estimate {571 let mut config = <Runtime as pallet_evm::Config>::config().clone();572 config.estimate = true;573 Some(config)574 } else {575 None576 };577578 let is_transactional = false;579 <Runtime as pallet_evm::Config>::Runner::call(580 CrossAccountId::from_eth(from),581 to,582 data,583 value,584 gas_limit.low_u64(),585 max_fee_per_gas,586 max_priority_fee_per_gas,587 nonce,588 access_list.unwrap_or_default(),589 is_transactional,590 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),591 ).map_err(|err| err.into())592 }593594 #[allow(clippy::redundant_closure)]595 fn create(596 from: H160,597 data: Vec<u8>,598 value: U256,599 gas_limit: U256,600 max_fee_per_gas: Option<U256>,601 max_priority_fee_per_gas: Option<U256>,602 nonce: Option<U256>,603 estimate: bool,604 access_list: Option<Vec<(H160, Vec<H256>)>>,605 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {606 let config = if estimate {607 let mut config = <Runtime as pallet_evm::Config>::config().clone();608 config.estimate = true;609 Some(config)610 } else {611 None612 };613614 let is_transactional = false;615 <Runtime as pallet_evm::Config>::Runner::create(616 CrossAccountId::from_eth(from),617 data,618 value,619 gas_limit.low_u64(),620 max_fee_per_gas,621 max_priority_fee_per_gas,622 nonce,623 access_list.unwrap_or_default(),624 is_transactional,625 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),626 ).map_err(|err| err.into())627 }628629 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {630 Ethereum::current_transaction_statuses()631 }632633 fn current_block() -> Option<pallet_ethereum::Block> {634 Ethereum::current_block()635 }636637 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {638 Ethereum::current_receipts()639 }640641 fn current_all() -> (642 Option<pallet_ethereum::Block>,643 Option<Vec<pallet_ethereum::Receipt>>,644 Option<Vec<TransactionStatus>>645 ) {646 (647 Ethereum::current_block(),648 Ethereum::current_receipts(),649 Ethereum::current_transaction_statuses()650 )651 }652653 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {654 xts.into_iter().filter_map(|xt| match xt.0.function {655 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),656 _ => None657 }).collect()658 }659660 fn elasticity() -> Option<Permill> {661 None662 }663 }664665 impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {666 fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic {667 UncheckedExtrinsic::new_unsigned(668 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),669 )670 }671 }672673 impl sp_session::SessionKeys<Block> for Runtime {674 fn decode_session_keys(675 encoded: Vec<u8>,676 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {677 SessionKeys::decode_into_raw_public_keys(&encoded)678 }679680 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {681 SessionKeys::generate(seed)682 }683 }684685 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {686 fn slot_duration() -> sp_consensus_aura::SlotDuration {687 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())688 }689690 fn authorities() -> Vec<AuraId> {691 Aura::authorities().to_vec()692 }693 }694695 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {696 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {697 ParachainSystem::collect_collation_info(header)698 }699 }700701 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {702 fn account_nonce(account: AccountId) -> Index {703 System::account_nonce(account)704 }705 }706707 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {708 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {709 TransactionPayment::query_info(uxt, len)710 }711 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {712 TransactionPayment::query_fee_details(uxt, len)713 }714 }715716 /*717 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>718 for Runtime719 {720 fn call(721 origin: AccountId,722 dest: AccountId,723 value: Balance,724 gas_limit: u64,725 input_data: Vec<u8>,726 ) -> pallet_contracts_primitives::ContractExecResult {727 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)728 }729730 fn instantiate(731 origin: AccountId,732 endowment: Balance,733 gas_limit: u64,734 code: pallet_contracts_primitives::Code<Hash>,735 data: Vec<u8>,736 salt: Vec<u8>,737 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>738 {739 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)740 }741742 fn get_storage(743 address: AccountId,744 key: [u8; 32],745 ) -> pallet_contracts_primitives::GetStorageResult {746 Contracts::get_storage(address, key)747 }748749 fn rent_projection(750 address: AccountId,751 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {752 Contracts::rent_projection(address)753 }754 }755 */756757 #[cfg(feature = "runtime-benchmarks")]758 impl frame_benchmarking::Benchmark<Block> for Runtime {759 fn benchmark_metadata(extra: bool) -> (760 Vec<frame_benchmarking::BenchmarkList>,761 Vec<frame_support::traits::StorageInfo>,762 ) {763 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};764 use frame_support::traits::StorageInfoTrait;765766 let mut list = Vec::<BenchmarkList>::new();767768 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);769 list_benchmark!(list, extra, pallet_common, Common);770 list_benchmark!(list, extra, pallet_unique, Unique);771 list_benchmark!(list, extra, pallet_structure, Structure);772 list_benchmark!(list, extra, pallet_inflation, Inflation);773 list_benchmark!(list, extra, pallet_fungible, Fungible);774 list_benchmark!(list, extra, pallet_refungible, Refungible);775 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);776 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);777778 let storage_info = AllPalletsReversedWithSystemFirst::storage_info();779780 return (list, storage_info)781 }782783 fn dispatch_benchmark(784 config: frame_benchmarking::BenchmarkConfig785 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {786 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};787788 let allowlist: Vec<TrackedStorageKey> = vec![789 // Total Issuance790 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),791792 // Block Number793 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),794 // Execution Phase795 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),796 // Event Count797 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),798 // System Events799 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),800801 // Evm CurrentLogs802 hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),803804 // Transactional depth805 hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),806 ];807808 let mut batches = Vec::<BenchmarkBatch>::new();809 let params = (&config, &allowlist);810811 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);812 add_benchmark!(params, batches, pallet_common, Common);813 add_benchmark!(params, batches, pallet_unique, Unique);814 add_benchmark!(params, batches, pallet_structure, Structure);815 add_benchmark!(params, batches, pallet_inflation, Inflation);816 add_benchmark!(params, batches, pallet_fungible, Fungible);817 add_benchmark!(params, batches, pallet_refungible, Refungible);818 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);819 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);820821 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }822 Ok(batches)823 }824 }825826 #[cfg(feature = "try-runtime")]827 impl frame_try_runtime::TryRuntime<Block> for Runtime {828 fn on_runtime_upgrade() -> (Weight, Weight) {829 log::info!("try-runtime::on_runtime_upgrade unique-chain.");830 let weight = Executive::try_runtime_upgrade().unwrap();831 (weight, RuntimeBlockWeights::get().max_block)832 }833834 fn execute_block_no_check(block: Block) -> Weight {835 Executive::execute_block_no_check(block)836 }837 }838 }839 }840}tests/src/nesting/properties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/properties.test.ts
+++ b/tests/src/nesting/properties.test.ts
@@ -711,7 +711,7 @@
});
});
- it('Forbids changing/deleting properties of a token if the property is permanent (constant)', async () => {
+ it('Forbids changing/deleting properties of a token if the property is permanent (immutable)', async () => {
await usingApi(async api => {
let i = -1;
for (const permission of constitution) {