difftreelog
feat(rmrk-rpc) decoding properties
in: master
3 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
@@ -420,7 +420,7 @@
Ok(())
}
- fn get_typed_nft_collection(
+ pub fn get_typed_nft_collection(
collection_id: CollectionId,
collection_type: CollectionType
) -> Result<NonfungibleHandle<T>, DispatchError> {
pallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/misc.rs
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -82,6 +82,18 @@
}
}
+pub trait RmrkDecode<T: Decode> {
+ fn decode_property(&self) -> Option<T>;
+}
+
+impl<T: Decode> RmrkDecode<T> for RmrkString {
+ fn decode_property(&self) -> Option<T> { // todo access runtime errors? // but then rmrk_nft_type must have it too
+ let mut value = self.as_slice();
+
+ T::decode(&mut value).ok()
+ }
+}
+
#[derive(Encode, Decode, PartialEq, Eq)]
pub enum CollectionType {
Regular,
runtime/common/src/runtime_apis.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(<pallet_common::CreatedCollectionCount<Runtime>>::get().0) // todo storage from proxy pallet146 }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;152153 // todo check if this is a rmrk 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_nft_collection(collection_id)?;158 // todo Vec::from(["rmrk:metadata", "rmrk:collection-type"])159 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)?;//unwrap_or_default();162 let nfts_count = (dispatch_unique_runtime!(collection_id.total_supply()) as Result<u32, DispatchError>)?; // todo? <Runtime>::total_supply(collection_id)163164 Ok(Some(RmrkCollectionInfo {165 issuer: collection.owner.clone(),166 metadata,167 max: collection.limits.token_limit,168 symbol: BoundedVec::try_from(169 collection.token_prefix.clone().into_inner()170 ).map_err(|_| <pallet_common::Error<Runtime>>::PropertyKeyIsTooLong)?,171 nfts_count172 }))173 }174 fn nft_by_id(collection_id: RmrkCollectionId, nft_by_id: RmrkNftId) -> Result<Option<RmrkInstanceInfo<AccountId>>, DispatchError> {175 use frame_support::BoundedVec;176 use up_data_structs::mapping::TokenAddressMapping;177 use pallet_proxy_rmrk_core::RmrkProperty;178179 let collection_id = CollectionId(collection_id);180 let nft_id = TokenId(nft_by_id);181182 let owner = match (dispatch_unique_runtime!(collection_id.token_owner(nft_id)) as Result<Option<CrossAccountId>, DispatchError>)? {183 Some(owner) => match <Runtime as pallet_common::Config>::CrossTokenAddressMapping::address_to_token(&owner) {184 Some((col, tok)) => RmrkAccountIdOrCollectionNftTuple::CollectionAndNftTuple(col.0, tok.0),185 None => RmrkAccountIdOrCollectionNftTuple::AccountId(owner.as_sub().clone())186 },187 None => return Ok(None)188 };189190 let keys = [191 RmrkProperty::RoyaltyInfo,192 RmrkProperty::Metadata,193 RmrkProperty::Equipped,194 // ?? "rmrk:recipient", "rmrk:nft-type", "rmrk:resource-collection", "rmrk:resource-priorities"195 ];196197 let properties = keys.into_iter().map(198 |key| BoundedVec::try_from(199 // todo nft property, not collection200 <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_property(collection_id, nft_id, key).unwrap().into_inner()201 ).unwrap()202 )203 .collect::<Vec<RmrkString>>();204205 Ok(Some(RmrkInstanceInfo {206 owner: owner,207 //recipient: , // prop?208 royalty: None,//Permill::from_percent(0), // prop, decode209 metadata: properties[1].clone(),210 equipped: false, // prop, decode211 pending: false, // prop, decode212 }))213 }214 fn account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Result<Vec<RmrkNftId>, DispatchError> {215 let cross_account_id = CrossAccountId::from_sub(account_id);216 let collection_id = CollectionId(collection_id);217 Ok(218 (dispatch_unique_runtime!(collection_id.account_tokens(cross_account_id)) as Result<Vec<TokenId>, DispatchError>)?219 //<Runtime as up_rpc::UniqueApi<Block, CrossAccountId, AccountId>>::account_tokens(collection_id, cross_account_id)?220 .into_iter()221 .map(|token| token.0)222 .collect::<Vec<_>>()223 )224 }225 fn nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkNftChild>, DispatchError> {226 use up_data_structs::mapping::TokenAddressMapping;227228 let collection_id = CollectionId(collection_id);229 let nft_id = TokenId(nft_id);230 let cross_account_id = CrossAccountId::from_eth(231 EvmTokenAddressMapping::token_to_address(collection_id, nft_id)232 );233234 Ok(235 pallet_nonfungible::Owned::<Runtime>::iter_prefix((collection_id, cross_account_id))236 .map(|(child_id, _)| RmrkNftChild {237 collection_id: collection_id.0, // todo make sure they're always from this collection238 nft_id: child_id.0,239 })240 .collect()241 )242 }243 fn collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {244 use frame_support::BoundedVec;245246 let collection_id = CollectionId(collection_id);247 let properties = pallet_common::Pallet::<Runtime>::collection_properties(collection_id);248249 return Ok(match filter_keys {250 Some(keys) => {251 let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;252 let properties = keys253 .into_iter()254 .filter_map(|key| {255 properties.get(&key).map(|value| RmrkPropertyInfo {256 key: BoundedVec::try_from(key.into_inner()).unwrap(),257 value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),258 })259 })260 .collect();261262 properties263 }264 None => {265 properties266 .iter()267 .filter_map(|(key, value)| Some(RmrkPropertyInfo {268 key: BoundedVec::try_from(key.clone().into_inner()).unwrap(),269 value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),270 }))271 .collect()272 }273 });274 }275 fn nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Vec<RmrkPropertyInfo>, DispatchError> {276 use frame_support::BoundedVec;277278 let collection_id = CollectionId(collection_id);279 let token_id = TokenId(nft_id);280281 let properties = pallet_nonfungible::Pallet::<Runtime>::token_properties((collection_id, token_id)); // todo look into usage of pallet_nonfungible282283 // todo displace to a function? redundant code piece with collection props284 return Ok(match filter_keys {285 Some(keys) => {286 let keys = pallet_common::Pallet::<Runtime>::bytes_keys_to_property_keys(keys)?;287 let properties = keys288 .into_iter()289 .filter_map(|key| {290 properties.get(&key).map(|value| RmrkPropertyInfo {291 key: BoundedVec::try_from(key.into_inner()).unwrap(),292 value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),293 })294 })295 .collect();296297 properties298 }299 None => {300 properties301 .iter()302 .filter_map(|(key, value)| Some(RmrkPropertyInfo {303 key: BoundedVec::try_from(key.clone().into_inner()).unwrap(),304 value: BoundedVec::try_from(value.clone().into_inner()).unwrap(),305 }))306 .collect()307 }308 });309 }310 fn nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceInfo>, DispatchError> {311 use frame_support::BoundedVec;312 use pallet_proxy_rmrk_core::RmrkProperty;313314 let collection_id = CollectionId(collection_id);315 let nft_id = TokenId(nft_id);316317 // let keys = [318 // RmrkProperty::Royalty,319 // RmrkProperty::Metadata,320 // RmrkProperty::Equipped,321 // RmrkProperty::Pending,322 // // ?? "rmrk:recipient", "rmrk:nft-type", "rmrk:resource-collection", "rmrk:resource-priorities"323 // ];324325 /*let resources = keys.into_iter().map(326 |key| BoundedVec::try_from(327 <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_property(collection_id, nft_id, key).unwrap().into_inner()328 ).unwrap()329 )330 .collect::<Vec<RmrkString>>();*/331332 Ok(Vec::new(/*[RmrkResourceInfo {333334 }]*/))335 }336 fn nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Result<Vec<RmrkResourceId>, DispatchError> {337 todo!()338 }339 fn base(base_id: RmrkBaseId) -> Result<Option<RmrkBaseInfo<AccountId>>, DispatchError> {340 use frame_support::BoundedVec;341 use scale_info::prelude::string::String;342 use pallet_proxy_rmrk_core::RmrkProperty;343344 let collection_id = CollectionId(base_id);345 let collection = <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_collection(collection_id)?;346347 // todo export to macro? redundancy348 let keys = [349 RmrkProperty::BaseType,350 ];351352 let properties = keys.into_iter().map(353 |key| BoundedVec::try_from(354 <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_collection_property(collection_id, key).unwrap().into_inner()355 )356 )357 // todo not-a-rmrk-collection error358 .collect::<Result<Vec<_>, _>>()359 .map_err(|_| <pallet_proxy_rmrk_core::Error<Runtime>>::CollectionUnknown)?;360361 Ok(Some(RmrkBaseInfo {362 issuer: collection.owner.clone(),363 base_type: properties[0].clone(),364 symbol: BoundedVec::try_from(365 collection.token_prefix.clone().into_inner()366 ).map_err(|_| <pallet_common::Error<Runtime>>::PropertyKeyIsTooLong)?,367 }))368 }369 fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {370 use frame_support::BoundedVec;371 use pallet_proxy_rmrk_core::RmrkProperty;372373 let collection_id = CollectionId(base_id);374375 let keys = [376 //RmrkProperty::NftType)?,377 //RmrkProperty::PartId)?,378 RmrkProperty::Src,379 RmrkProperty::ZIndex,380 RmrkProperty::EquippableList,381 ];382383 let parts = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?384 .iter()385 .filter_map(|token_id| {386 /*let properties = keys.into_iter().map(387 |key| BoundedVec::try_from(388 <pallet_proxy_rmrk_core::Pallet<Runtime>>::get_nft_property(collection_id, *token_id, key).unwrap().into_inner()389 ).unwrap()390 ).collect::<Vec<RmrkString>>();*/391392 // todo ping properties for "rmrk:nft-type"393 // if none, skip, None394 let nft_type = "fixed-part";395396 match nft_type {397 "fixed-part" => Some(RmrkPartType::FixedPart(RmrkFixedPart {398 id: token_id.0,399 src: BoundedVec::default(), // "rmrk:src"400 z: 0, // "rmrk:z-index"401 })),402 "slot-part" => Some(RmrkPartType::SlotPart(RmrkSlotPart {403 id: token_id.0,404 equippable: RmrkEquippableList::Empty, // "rmrk:equippable-list" ?405 src: BoundedVec::default(), // "rmrk:src"406 z: 0, // "rmrk:z-index"407 })),408 _ => None409 }410411 })412 .collect();413414 Ok(parts)415 }416 fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {417 use frame_support::BoundedVec;418419 let collection_id = CollectionId(base_id);420421 let theme_names = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?422 .iter()423 .filter_map(|token_id| {424 let properties = pallet_nonfungible::Pallet::<Runtime>::token_properties((collection_id, token_id));425426 // todo ping property for "rmrk:nft-type"427 // if none or not "theme", skip, None428 let nft_type = "theme";429 // can't call dispatch_unique_runtime! from here??430 <pallet_nonfungible::TokenData<Runtime>>::get((collection_id, token_id))431 .map(|t| t.const_data.into_inner())432 //.unwrap_or_default()433 // todo rework to reduce independence434 })435 .collect();436437 Ok(theme_names)438 }439 fn theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Result<Option<RmrkTheme>, DispatchError> {440 use frame_support::BoundedVec;441442 let collection_id = CollectionId(base_id);443444 // todo one theme. filter collection tokens according to theme name, should result in one445 // (is it possible to search with iter_prefix for part of a struct that satisfies?..)446 // filter properties according to filter_keys and load them into resulting theme.properties447 let themes = (dispatch_unique_runtime!(collection_id.collection_tokens()) as Result<Vec<TokenId>, DispatchError>)?448 .iter()449 .filter_map(|token_id| {450 let properties = pallet_nonfungible::Pallet::<Runtime>::token_properties((collection_id, token_id));451452 // todo ping properties for "rmrk:nft-type"453 // if none, skip, None454 // ugh gonna go through ALL properties, searching for matches for "rmrk:theme-property-<key>"455 let nft_type = "theme";456 match nft_type {457 "theme" => Some(RmrkTheme {458 name: BoundedVec::try_from(459 <pallet_nonfungible::TokenData<Runtime>>::get((collection_id, token_id))460 .map(|t| t.const_data)461 .unwrap_or_default()462 .into_inner()463 ).unwrap(),464 // todo? (dispatch_unique_runtime!(collection_id.const_metadata(token_id)) as Result<Vec<u8>, DispatchError>)?,465 properties: Vec::new(), // pain in the ass466 inherit: false, // "rmrk:theme-inherit"467 }),468 _ => None469 }470 })471 .collect::<Vec<_>>();472473 // todo474 Ok(Some(themes[0].clone()))475 }476 }477478 impl sp_api::Core<Block> for Runtime {479 fn version() -> RuntimeVersion {480 VERSION481 }482483 fn execute_block(block: Block) {484 Executive::execute_block(block)485 }486487 fn initialize_block(header: &<Block as BlockT>::Header) {488 Executive::initialize_block(header)489 }490 }491492 impl sp_api::Metadata<Block> for Runtime {493 fn metadata() -> OpaqueMetadata {494 OpaqueMetadata::new(Runtime::metadata().into())495 }496 }497498 impl sp_block_builder::BlockBuilder<Block> for Runtime {499 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {500 Executive::apply_extrinsic(extrinsic)501 }502503 fn finalize_block() -> <Block as BlockT>::Header {504 Executive::finalize_block()505 }506507 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {508 data.create_extrinsics()509 }510511 fn check_inherents(512 block: Block,513 data: sp_inherents::InherentData,514 ) -> sp_inherents::CheckInherentsResult {515 data.check_extrinsics(&block)516 }517518 // fn random_seed() -> <Block as BlockT>::Hash {519 // RandomnessCollectiveFlip::random_seed().0520 // }521 }522523 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {524 fn validate_transaction(525 source: TransactionSource,526 tx: <Block as BlockT>::Extrinsic,527 hash: <Block as BlockT>::Hash,528 ) -> TransactionValidity {529 Executive::validate_transaction(source, tx, hash)530 }531 }532533 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {534 fn offchain_worker(header: &<Block as BlockT>::Header) {535 Executive::offchain_worker(header)536 }537 }538539 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {540 fn chain_id() -> u64 {541 <Runtime as pallet_evm::Config>::ChainId::get()542 }543544 fn account_basic(address: H160) -> EVMAccount {545 EVM::account_basic(&address)546 }547548 fn gas_price() -> U256 {549 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()550 }551552 fn account_code_at(address: H160) -> Vec<u8> {553 EVM::account_codes(address)554 }555556 fn author() -> H160 {557 <pallet_evm::Pallet<Runtime>>::find_author()558 }559560 fn storage_at(address: H160, index: U256) -> H256 {561 let mut tmp = [0u8; 32];562 index.to_big_endian(&mut tmp);563 EVM::account_storages(address, H256::from_slice(&tmp[..]))564 }565566 #[allow(clippy::redundant_closure)]567 fn call(568 from: H160,569 to: H160,570 data: Vec<u8>,571 value: U256,572 gas_limit: U256,573 max_fee_per_gas: Option<U256>,574 max_priority_fee_per_gas: Option<U256>,575 nonce: Option<U256>,576 estimate: bool,577 access_list: Option<Vec<(H160, Vec<H256>)>>,578 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {579 let config = if estimate {580 let mut config = <Runtime as pallet_evm::Config>::config().clone();581 config.estimate = true;582 Some(config)583 } else {584 None585 };586587 let is_transactional = false;588 <Runtime as pallet_evm::Config>::Runner::call(589 CrossAccountId::from_eth(from),590 to,591 data,592 value,593 gas_limit.low_u64(),594 max_fee_per_gas,595 max_priority_fee_per_gas,596 nonce,597 access_list.unwrap_or_default(),598 is_transactional,599 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),600 ).map_err(|err| err.into())601 }602603 #[allow(clippy::redundant_closure)]604 fn create(605 from: H160,606 data: Vec<u8>,607 value: U256,608 gas_limit: U256,609 max_fee_per_gas: Option<U256>,610 max_priority_fee_per_gas: Option<U256>,611 nonce: Option<U256>,612 estimate: bool,613 access_list: Option<Vec<(H160, Vec<H256>)>>,614 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {615 let config = if estimate {616 let mut config = <Runtime as pallet_evm::Config>::config().clone();617 config.estimate = true;618 Some(config)619 } else {620 None621 };622623 let is_transactional = false;624 <Runtime as pallet_evm::Config>::Runner::create(625 CrossAccountId::from_eth(from),626 data,627 value,628 gas_limit.low_u64(),629 max_fee_per_gas,630 max_priority_fee_per_gas,631 nonce,632 access_list.unwrap_or_default(),633 is_transactional,634 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),635 ).map_err(|err| err.into())636 }637638 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {639 Ethereum::current_transaction_statuses()640 }641642 fn current_block() -> Option<pallet_ethereum::Block> {643 Ethereum::current_block()644 }645646 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {647 Ethereum::current_receipts()648 }649650 fn current_all() -> (651 Option<pallet_ethereum::Block>,652 Option<Vec<pallet_ethereum::Receipt>>,653 Option<Vec<TransactionStatus>>654 ) {655 (656 Ethereum::current_block(),657 Ethereum::current_receipts(),658 Ethereum::current_transaction_statuses()659 )660 }661662 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {663 xts.into_iter().filter_map(|xt| match xt.0.function {664 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),665 _ => None666 }).collect()667 }668669 fn elasticity() -> Option<Permill> {670 None671 }672 }673674 impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {675 fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic {676 UncheckedExtrinsic::new_unsigned(677 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),678 )679 }680 }681682 impl sp_session::SessionKeys<Block> for Runtime {683 fn decode_session_keys(684 encoded: Vec<u8>,685 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {686 SessionKeys::decode_into_raw_public_keys(&encoded)687 }688689 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {690 SessionKeys::generate(seed)691 }692 }693694 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {695 fn slot_duration() -> sp_consensus_aura::SlotDuration {696 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())697 }698699 fn authorities() -> Vec<AuraId> {700 Aura::authorities().to_vec()701 }702 }703704 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {705 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {706 ParachainSystem::collect_collation_info(header)707 }708 }709710 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {711 fn account_nonce(account: AccountId) -> Index {712 System::account_nonce(account)713 }714 }715716 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {717 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {718 TransactionPayment::query_info(uxt, len)719 }720 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {721 TransactionPayment::query_fee_details(uxt, len)722 }723 }724725 /*726 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>727 for Runtime728 {729 fn call(730 origin: AccountId,731 dest: AccountId,732 value: Balance,733 gas_limit: u64,734 input_data: Vec<u8>,735 ) -> pallet_contracts_primitives::ContractExecResult {736 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)737 }738739 fn instantiate(740 origin: AccountId,741 endowment: Balance,742 gas_limit: u64,743 code: pallet_contracts_primitives::Code<Hash>,744 data: Vec<u8>,745 salt: Vec<u8>,746 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>747 {748 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)749 }750751 fn get_storage(752 address: AccountId,753 key: [u8; 32],754 ) -> pallet_contracts_primitives::GetStorageResult {755 Contracts::get_storage(address, key)756 }757758 fn rent_projection(759 address: AccountId,760 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {761 Contracts::rent_projection(address)762 }763 }764 */765766 #[cfg(feature = "runtime-benchmarks")]767 impl frame_benchmarking::Benchmark<Block> for Runtime {768 fn benchmark_metadata(extra: bool) -> (769 Vec<frame_benchmarking::BenchmarkList>,770 Vec<frame_support::traits::StorageInfo>,771 ) {772 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};773 use frame_support::traits::StorageInfoTrait;774775 let mut list = Vec::<BenchmarkList>::new();776777 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);778 list_benchmark!(list, extra, pallet_common, Common);779 list_benchmark!(list, extra, pallet_unique, Unique);780 list_benchmark!(list, extra, pallet_structure, Structure);781 list_benchmark!(list, extra, pallet_inflation, Inflation);782 list_benchmark!(list, extra, pallet_fungible, Fungible);783 list_benchmark!(list, extra, pallet_refungible, Refungible);784 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);785 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);786787 let storage_info = AllPalletsReversedWithSystemFirst::storage_info();788789 return (list, storage_info)790 }791792 fn dispatch_benchmark(793 config: frame_benchmarking::BenchmarkConfig794 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {795 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};796797 let allowlist: Vec<TrackedStorageKey> = vec![798 // Total Issuance799 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),800801 // Block Number802 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),803 // Execution Phase804 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),805 // Event Count806 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),807 // System Events808 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),809810 // Evm CurrentLogs811 hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),812813 // Transactional depth814 hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),815 ];816817 let mut batches = Vec::<BenchmarkBatch>::new();818 let params = (&config, &allowlist);819820 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);821 add_benchmark!(params, batches, pallet_common, Common);822 add_benchmark!(params, batches, pallet_unique, Unique);823 add_benchmark!(params, batches, pallet_structure, Structure);824 add_benchmark!(params, batches, pallet_inflation, Inflation);825 add_benchmark!(params, batches, pallet_fungible, Fungible);826 add_benchmark!(params, batches, pallet_refungible, Refungible);827 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);828 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);829830 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }831 Ok(batches)832 }833 }834835 #[cfg(feature = "try-runtime")]836 impl frame_try_runtime::TryRuntime<Block> for Runtime {837 fn on_runtime_upgrade() -> (Weight, Weight) {838 log::info!("try-runtime::on_runtime_upgrade unique-chain.");839 let weight = Executive::try_runtime_upgrade().unwrap();840 (weight, RuntimeBlockWeights::get().max_block)841 }842843 fn execute_block_no_check(block: Block) -> Weight {844 Executive::execute_block_no_check(block)845 }846 }847 }848 }849}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| 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(<pallet_common::CreatedCollectionCount<Runtime>>::get().0) // todo storage from proxy pallet146 }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)?;158 159 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);182 183 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>>();205 206 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()?;387 388 // 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 ];395 396 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()?;434 435 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}