difftreelog
Add pieces into token data. Add negative tests.
in: master
4 files changed
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -473,7 +473,11 @@
None
}
- fn total_pieces(&self, _token: TokenId) -> Option<u128> {
- Some(1)
+ fn total_pieces(&self, token: TokenId) -> Option<u128> {
+ if <TokenData<T>>::contains_key((self.id, token)) {
+ Some(1)
+ } else {
+ None
+ }
}
}
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -181,6 +181,7 @@
pub struct TokenData<CrossAccountId> {
pub properties: Vec<Property>,
pub owner: Option<CrossAccountId>,
+ pub pieces: Option<u128>,
}
pub struct OverflowError;
runtime/common/src/runtime_apis.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#[macro_export]18macro_rules! impl_common_runtime_apis {19 (20 $(21 #![custom_apis]2223 $($custom_apis:tt)+24 )?25 ) => {26 impl_runtime_apis! {27 $($($custom_apis)+)?2829 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {30 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {31 dispatch_unique_runtime!(collection.account_tokens(account))32 }33 fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {34 dispatch_unique_runtime!(collection.collection_tokens())35 }36 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {37 dispatch_unique_runtime!(collection.token_exists(token))38 }3940 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {41 dispatch_unique_runtime!(collection.token_owner(token))42 }43 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {44 let budget = up_data_structs::budget::Value::new(10);4546 Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))47 }48 fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {49 Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))50 }51 fn collection_properties(52 collection: CollectionId,53 keys: Option<Vec<Vec<u8>>>54 ) -> Result<Vec<Property>, DispatchError> {55 let keys = keys.map(56 |keys| Common::bytes_keys_to_property_keys(keys)57 ).transpose()?;5859 Common::filter_collection_properties(collection, keys)60 }6162 fn token_properties(63 collection: CollectionId,64 token_id: TokenId,65 keys: Option<Vec<Vec<u8>>>66 ) -> Result<Vec<Property>, DispatchError> {67 let keys = keys.map(68 |keys| Common::bytes_keys_to_property_keys(keys)69 ).transpose()?;7071 dispatch_unique_runtime!(collection.token_properties(token_id, keys))72 }7374 fn property_permissions(75 collection: CollectionId,76 keys: Option<Vec<Vec<u8>>>77 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {78 let keys = keys.map(79 |keys| Common::bytes_keys_to_property_keys(keys)80 ).transpose()?;8182 Common::filter_property_permissions(collection, keys)83 }8485 fn token_data(86 collection: CollectionId,87 token_id: TokenId,88 keys: Option<Vec<Vec<u8>>>89 ) -> Result<TokenData<CrossAccountId>, DispatchError> {90 let token_data = TokenData {91 properties: Self::token_properties(collection, token_id, keys)?,92 owner: Self::token_owner(collection, token_id)?93 };9495 Ok(token_data)96 }9798 fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {99 dispatch_unique_runtime!(collection.total_supply())100 }101 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {102 dispatch_unique_runtime!(collection.account_balance(account))103 }104 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {105 dispatch_unique_runtime!(collection.balance(account, token))106 }107 fn allowance(108 collection: CollectionId,109 sender: CrossAccountId,110 spender: CrossAccountId,111 token: TokenId,112 ) -> Result<u128, DispatchError> {113 dispatch_unique_runtime!(collection.allowance(sender, spender, token))114 }115116 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {117 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))118 }119 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {120 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))121 }122 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {123 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))124 }125 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {126 dispatch_unique_runtime!(collection.last_token_id())127 }128 fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {129 Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))130 }131 fn collection_stats() -> Result<CollectionStats, DispatchError> {132 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())133 }134 fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {135 Ok(<$crate::sponsoring::UniqueSponsorshipPredict<Runtime> as136 $crate::sponsoring::SponsorshipPredict<Runtime>>::predict(137 collection,138 account,139 token))140 }141142 fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {143 Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))144 }145146 fn total_pieces(collection: CollectionId, token_id: TokenId) -> Result<Option<u128>, DispatchError> {147 dispatch_unique_runtime!(collection.total_pieces(token_id))148 }149 }150151 impl sp_api::Core<Block> for Runtime {152 fn version() -> RuntimeVersion {153 VERSION154 }155156 fn execute_block(block: Block) {157 Executive::execute_block(block)158 }159160 fn initialize_block(header: &<Block as BlockT>::Header) {161 Executive::initialize_block(header)162 }163 }164165 impl sp_api::Metadata<Block> for Runtime {166 fn metadata() -> OpaqueMetadata {167 OpaqueMetadata::new(Runtime::metadata().into())168 }169 }170171 impl sp_block_builder::BlockBuilder<Block> for Runtime {172 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {173 Executive::apply_extrinsic(extrinsic)174 }175176 fn finalize_block() -> <Block as BlockT>::Header {177 Executive::finalize_block()178 }179180 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {181 data.create_extrinsics()182 }183184 fn check_inherents(185 block: Block,186 data: sp_inherents::InherentData,187 ) -> sp_inherents::CheckInherentsResult {188 data.check_extrinsics(&block)189 }190191 // fn random_seed() -> <Block as BlockT>::Hash {192 // RandomnessCollectiveFlip::random_seed().0193 // }194 }195196 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {197 fn validate_transaction(198 source: TransactionSource,199 tx: <Block as BlockT>::Extrinsic,200 hash: <Block as BlockT>::Hash,201 ) -> TransactionValidity {202 Executive::validate_transaction(source, tx, hash)203 }204 }205206 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {207 fn offchain_worker(header: &<Block as BlockT>::Header) {208 Executive::offchain_worker(header)209 }210 }211212 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {213 fn chain_id() -> u64 {214 <Runtime as pallet_evm::Config>::ChainId::get()215 }216217 fn account_basic(address: H160) -> EVMAccount {218 let (account, _) = EVM::account_basic(&address);219 account220 }221222 fn gas_price() -> U256 {223 let (price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();224 price225 }226227 fn account_code_at(address: H160) -> Vec<u8> {228 EVM::account_codes(address)229 }230231 fn author() -> H160 {232 <pallet_evm::Pallet<Runtime>>::find_author()233 }234235 fn storage_at(address: H160, index: U256) -> H256 {236 let mut tmp = [0u8; 32];237 index.to_big_endian(&mut tmp);238 EVM::account_storages(address, H256::from_slice(&tmp[..]))239 }240241 #[allow(clippy::redundant_closure)]242 fn call(243 from: H160,244 to: H160,245 data: Vec<u8>,246 value: U256,247 gas_limit: U256,248 max_fee_per_gas: Option<U256>,249 max_priority_fee_per_gas: Option<U256>,250 nonce: Option<U256>,251 estimate: bool,252 access_list: Option<Vec<(H160, Vec<H256>)>>,253 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {254 let config = if estimate {255 let mut config = <Runtime as pallet_evm::Config>::config().clone();256 config.estimate = true;257 Some(config)258 } else {259 None260 };261262 let is_transactional = false;263 <Runtime as pallet_evm::Config>::Runner::call(264 CrossAccountId::from_eth(from),265 to,266 data,267 value,268 gas_limit.low_u64(),269 max_fee_per_gas,270 max_priority_fee_per_gas,271 nonce,272 access_list.unwrap_or_default(),273 is_transactional,274 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),275 ).map_err(|err| err.error.into())276 }277278 #[allow(clippy::redundant_closure)]279 fn create(280 from: H160,281 data: Vec<u8>,282 value: U256,283 gas_limit: U256,284 max_fee_per_gas: Option<U256>,285 max_priority_fee_per_gas: Option<U256>,286 nonce: Option<U256>,287 estimate: bool,288 access_list: Option<Vec<(H160, Vec<H256>)>>,289 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {290 let config = if estimate {291 let mut config = <Runtime as pallet_evm::Config>::config().clone();292 config.estimate = true;293 Some(config)294 } else {295 None296 };297298 let is_transactional = false;299 <Runtime as pallet_evm::Config>::Runner::create(300 CrossAccountId::from_eth(from),301 data,302 value,303 gas_limit.low_u64(),304 max_fee_per_gas,305 max_priority_fee_per_gas,306 nonce,307 access_list.unwrap_or_default(),308 is_transactional,309 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),310 ).map_err(|err| err.error.into())311 }312313 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {314 Ethereum::current_transaction_statuses()315 }316317 fn current_block() -> Option<pallet_ethereum::Block> {318 Ethereum::current_block()319 }320321 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {322 Ethereum::current_receipts()323 }324325 fn current_all() -> (326 Option<pallet_ethereum::Block>,327 Option<Vec<pallet_ethereum::Receipt>>,328 Option<Vec<TransactionStatus>>329 ) {330 (331 Ethereum::current_block(),332 Ethereum::current_receipts(),333 Ethereum::current_transaction_statuses()334 )335 }336337 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {338 xts.into_iter().filter_map(|xt| match xt.0.function {339 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),340 _ => None341 }).collect()342 }343344 fn elasticity() -> Option<Permill> {345 None346 }347 }348349 impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {350 fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic {351 UncheckedExtrinsic::new_unsigned(352 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),353 )354 }355 }356357 impl sp_session::SessionKeys<Block> for Runtime {358 fn decode_session_keys(359 encoded: Vec<u8>,360 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {361 SessionKeys::decode_into_raw_public_keys(&encoded)362 }363364 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {365 SessionKeys::generate(seed)366 }367 }368369 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {370 fn slot_duration() -> sp_consensus_aura::SlotDuration {371 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())372 }373374 fn authorities() -> Vec<AuraId> {375 Aura::authorities().to_vec()376 }377 }378379 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {380 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {381 ParachainSystem::collect_collation_info(header)382 }383 }384385 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {386 fn account_nonce(account: AccountId) -> Index {387 System::account_nonce(account)388 }389 }390391 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {392 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {393 TransactionPayment::query_info(uxt, len)394 }395 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {396 TransactionPayment::query_fee_details(uxt, len)397 }398 }399400 /*401 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>402 for Runtime403 {404 fn call(405 origin: AccountId,406 dest: AccountId,407 value: Balance,408 gas_limit: u64,409 input_data: Vec<u8>,410 ) -> pallet_contracts_primitives::ContractExecResult {411 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)412 }413414 fn instantiate(415 origin: AccountId,416 endowment: Balance,417 gas_limit: u64,418 code: pallet_contracts_primitives::Code<Hash>,419 data: Vec<u8>,420 salt: Vec<u8>,421 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>422 {423 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)424 }425426 fn get_storage(427 address: AccountId,428 key: [u8; 32],429 ) -> pallet_contracts_primitives::GetStorageResult {430 Contracts::get_storage(address, key)431 }432433 fn rent_projection(434 address: AccountId,435 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {436 Contracts::rent_projection(address)437 }438 }439 */440441 #[cfg(feature = "runtime-benchmarks")]442 impl frame_benchmarking::Benchmark<Block> for Runtime {443 fn benchmark_metadata(extra: bool) -> (444 Vec<frame_benchmarking::BenchmarkList>,445 Vec<frame_support::traits::StorageInfo>,446 ) {447 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};448 use frame_support::traits::StorageInfoTrait;449450 let mut list = Vec::<BenchmarkList>::new();451452 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);453 list_benchmark!(list, extra, pallet_common, Common);454 list_benchmark!(list, extra, pallet_unique, Unique);455 list_benchmark!(list, extra, pallet_structure, Structure);456 list_benchmark!(list, extra, pallet_inflation, Inflation);457 list_benchmark!(list, extra, pallet_fungible, Fungible);458 list_benchmark!(list, extra, pallet_refungible, Refungible);459 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);460 list_benchmark!(list, extra, pallet_unique_scheduler, Scheduler);461462 #[cfg(not(feature = "unique-runtime"))]463 list_benchmark!(list, extra, pallet_proxy_rmrk_core, RmrkCore);464465 #[cfg(not(feature = "unique-runtime"))]466 list_benchmark!(list, extra, pallet_proxy_rmrk_equip, RmrkEquip);467468 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);469470 let storage_info = AllPalletsReversedWithSystemFirst::storage_info();471472 return (list, storage_info)473 }474475 fn dispatch_benchmark(476 config: frame_benchmarking::BenchmarkConfig477 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {478 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};479480 let allowlist: Vec<TrackedStorageKey> = vec![481 // Total Issuance482 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),483484 // Block Number485 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),486 // Execution Phase487 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),488 // Event Count489 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),490 // System Events491 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),492493 // Evm CurrentLogs494 hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),495496 // Transactional depth497 hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),498 ];499500 let mut batches = Vec::<BenchmarkBatch>::new();501 let params = (&config, &allowlist);502503 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);504 add_benchmark!(params, batches, pallet_common, Common);505 add_benchmark!(params, batches, pallet_unique, Unique);506 add_benchmark!(params, batches, pallet_structure, Structure);507 add_benchmark!(params, batches, pallet_inflation, Inflation);508 add_benchmark!(params, batches, pallet_fungible, Fungible);509 add_benchmark!(params, batches, pallet_refungible, Refungible);510 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);511 add_benchmark!(params, batches, pallet_unique_scheduler, Scheduler);512513 #[cfg(not(feature = "unique-runtime"))]514 add_benchmark!(params, batches, pallet_proxy_rmrk_core, RmrkCore);515516 #[cfg(not(feature = "unique-runtime"))]517 add_benchmark!(params, batches, pallet_proxy_rmrk_equip, RmrkEquip);518519 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);520521 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }522 Ok(batches)523 }524 }525526 #[cfg(feature = "try-runtime")]527 impl frame_try_runtime::TryRuntime<Block> for Runtime {528 fn on_runtime_upgrade() -> (Weight, Weight) {529 log::info!("try-runtime::on_runtime_upgrade unique-chain.");530 let weight = Executive::try_runtime_upgrade().unwrap();531 (weight, RuntimeBlockWeights::get().max_block)532 }533534 fn execute_block_no_check(block: Block) -> Weight {535 Executive::execute_block_no_check(block)536 }537 }538 }539 }540}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#[macro_export]18macro_rules! impl_common_runtime_apis {19 (20 $(21 #![custom_apis]2223 $($custom_apis:tt)+24 )?25 ) => {26 impl_runtime_apis! {27 $($($custom_apis)+)?2829 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {30 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {31 dispatch_unique_runtime!(collection.account_tokens(account))32 }33 fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {34 dispatch_unique_runtime!(collection.collection_tokens())35 }36 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {37 dispatch_unique_runtime!(collection.token_exists(token))38 }3940 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {41 dispatch_unique_runtime!(collection.token_owner(token))42 }43 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {44 let budget = up_data_structs::budget::Value::new(10);4546 Ok(Some(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?))47 }48 fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {49 Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))50 }51 fn collection_properties(52 collection: CollectionId,53 keys: Option<Vec<Vec<u8>>>54 ) -> Result<Vec<Property>, DispatchError> {55 let keys = keys.map(56 |keys| Common::bytes_keys_to_property_keys(keys)57 ).transpose()?;5859 Common::filter_collection_properties(collection, keys)60 }6162 fn token_properties(63 collection: CollectionId,64 token_id: TokenId,65 keys: Option<Vec<Vec<u8>>>66 ) -> Result<Vec<Property>, DispatchError> {67 let keys = keys.map(68 |keys| Common::bytes_keys_to_property_keys(keys)69 ).transpose()?;7071 dispatch_unique_runtime!(collection.token_properties(token_id, keys))72 }7374 fn property_permissions(75 collection: CollectionId,76 keys: Option<Vec<Vec<u8>>>77 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {78 let keys = keys.map(79 |keys| Common::bytes_keys_to_property_keys(keys)80 ).transpose()?;8182 Common::filter_property_permissions(collection, keys)83 }8485 fn token_data(86 collection: CollectionId,87 token_id: TokenId,88 keys: Option<Vec<Vec<u8>>>89 ) -> Result<TokenData<CrossAccountId>, DispatchError> {90 let token_data = TokenData {91 properties: Self::token_properties(collection, token_id, keys)?,92 owner: Self::token_owner(collection, token_id)?,93 pieces: Self::total_pieces(collection, token_id)?94 };9596 Ok(token_data)97 }9899 fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {100 dispatch_unique_runtime!(collection.total_supply())101 }102 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {103 dispatch_unique_runtime!(collection.account_balance(account))104 }105 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {106 dispatch_unique_runtime!(collection.balance(account, token))107 }108 fn allowance(109 collection: CollectionId,110 sender: CrossAccountId,111 spender: CrossAccountId,112 token: TokenId,113 ) -> Result<u128, DispatchError> {114 dispatch_unique_runtime!(collection.allowance(sender, spender, token))115 }116117 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {118 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))119 }120 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {121 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))122 }123 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {124 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))125 }126 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {127 dispatch_unique_runtime!(collection.last_token_id())128 }129 fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {130 Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))131 }132 fn collection_stats() -> Result<CollectionStats, DispatchError> {133 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())134 }135 fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {136 Ok(<$crate::sponsoring::UniqueSponsorshipPredict<Runtime> as137 $crate::sponsoring::SponsorshipPredict<Runtime>>::predict(138 collection,139 account,140 token))141 }142143 fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {144 Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))145 }146147 fn total_pieces(collection: CollectionId, token_id: TokenId) -> Result<Option<u128>, DispatchError> {148 dispatch_unique_runtime!(collection.total_pieces(token_id))149 }150 }151152 impl sp_api::Core<Block> for Runtime {153 fn version() -> RuntimeVersion {154 VERSION155 }156157 fn execute_block(block: Block) {158 Executive::execute_block(block)159 }160161 fn initialize_block(header: &<Block as BlockT>::Header) {162 Executive::initialize_block(header)163 }164 }165166 impl sp_api::Metadata<Block> for Runtime {167 fn metadata() -> OpaqueMetadata {168 OpaqueMetadata::new(Runtime::metadata().into())169 }170 }171172 impl sp_block_builder::BlockBuilder<Block> for Runtime {173 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {174 Executive::apply_extrinsic(extrinsic)175 }176177 fn finalize_block() -> <Block as BlockT>::Header {178 Executive::finalize_block()179 }180181 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {182 data.create_extrinsics()183 }184185 fn check_inherents(186 block: Block,187 data: sp_inherents::InherentData,188 ) -> sp_inherents::CheckInherentsResult {189 data.check_extrinsics(&block)190 }191192 // fn random_seed() -> <Block as BlockT>::Hash {193 // RandomnessCollectiveFlip::random_seed().0194 // }195 }196197 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {198 fn validate_transaction(199 source: TransactionSource,200 tx: <Block as BlockT>::Extrinsic,201 hash: <Block as BlockT>::Hash,202 ) -> TransactionValidity {203 Executive::validate_transaction(source, tx, hash)204 }205 }206207 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {208 fn offchain_worker(header: &<Block as BlockT>::Header) {209 Executive::offchain_worker(header)210 }211 }212213 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {214 fn chain_id() -> u64 {215 <Runtime as pallet_evm::Config>::ChainId::get()216 }217218 fn account_basic(address: H160) -> EVMAccount {219 let (account, _) = EVM::account_basic(&address);220 account221 }222223 fn gas_price() -> U256 {224 let (price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();225 price226 }227228 fn account_code_at(address: H160) -> Vec<u8> {229 EVM::account_codes(address)230 }231232 fn author() -> H160 {233 <pallet_evm::Pallet<Runtime>>::find_author()234 }235236 fn storage_at(address: H160, index: U256) -> H256 {237 let mut tmp = [0u8; 32];238 index.to_big_endian(&mut tmp);239 EVM::account_storages(address, H256::from_slice(&tmp[..]))240 }241242 #[allow(clippy::redundant_closure)]243 fn call(244 from: H160,245 to: H160,246 data: Vec<u8>,247 value: U256,248 gas_limit: U256,249 max_fee_per_gas: Option<U256>,250 max_priority_fee_per_gas: Option<U256>,251 nonce: Option<U256>,252 estimate: bool,253 access_list: Option<Vec<(H160, Vec<H256>)>>,254 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {255 let config = if estimate {256 let mut config = <Runtime as pallet_evm::Config>::config().clone();257 config.estimate = true;258 Some(config)259 } else {260 None261 };262263 let is_transactional = false;264 <Runtime as pallet_evm::Config>::Runner::call(265 CrossAccountId::from_eth(from),266 to,267 data,268 value,269 gas_limit.low_u64(),270 max_fee_per_gas,271 max_priority_fee_per_gas,272 nonce,273 access_list.unwrap_or_default(),274 is_transactional,275 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),276 ).map_err(|err| err.error.into())277 }278279 #[allow(clippy::redundant_closure)]280 fn create(281 from: H160,282 data: Vec<u8>,283 value: U256,284 gas_limit: U256,285 max_fee_per_gas: Option<U256>,286 max_priority_fee_per_gas: Option<U256>,287 nonce: Option<U256>,288 estimate: bool,289 access_list: Option<Vec<(H160, Vec<H256>)>>,290 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {291 let config = if estimate {292 let mut config = <Runtime as pallet_evm::Config>::config().clone();293 config.estimate = true;294 Some(config)295 } else {296 None297 };298299 let is_transactional = false;300 <Runtime as pallet_evm::Config>::Runner::create(301 CrossAccountId::from_eth(from),302 data,303 value,304 gas_limit.low_u64(),305 max_fee_per_gas,306 max_priority_fee_per_gas,307 nonce,308 access_list.unwrap_or_default(),309 is_transactional,310 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),311 ).map_err(|err| err.error.into())312 }313314 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {315 Ethereum::current_transaction_statuses()316 }317318 fn current_block() -> Option<pallet_ethereum::Block> {319 Ethereum::current_block()320 }321322 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {323 Ethereum::current_receipts()324 }325326 fn current_all() -> (327 Option<pallet_ethereum::Block>,328 Option<Vec<pallet_ethereum::Receipt>>,329 Option<Vec<TransactionStatus>>330 ) {331 (332 Ethereum::current_block(),333 Ethereum::current_receipts(),334 Ethereum::current_transaction_statuses()335 )336 }337338 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {339 xts.into_iter().filter_map(|xt| match xt.0.function {340 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),341 _ => None342 }).collect()343 }344345 fn elasticity() -> Option<Permill> {346 None347 }348 }349350 impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {351 fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic {352 UncheckedExtrinsic::new_unsigned(353 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),354 )355 }356 }357358 impl sp_session::SessionKeys<Block> for Runtime {359 fn decode_session_keys(360 encoded: Vec<u8>,361 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {362 SessionKeys::decode_into_raw_public_keys(&encoded)363 }364365 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {366 SessionKeys::generate(seed)367 }368 }369370 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {371 fn slot_duration() -> sp_consensus_aura::SlotDuration {372 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())373 }374375 fn authorities() -> Vec<AuraId> {376 Aura::authorities().to_vec()377 }378 }379380 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {381 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {382 ParachainSystem::collect_collation_info(header)383 }384 }385386 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {387 fn account_nonce(account: AccountId) -> Index {388 System::account_nonce(account)389 }390 }391392 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {393 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {394 TransactionPayment::query_info(uxt, len)395 }396 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {397 TransactionPayment::query_fee_details(uxt, len)398 }399 }400401 /*402 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>403 for Runtime404 {405 fn call(406 origin: AccountId,407 dest: AccountId,408 value: Balance,409 gas_limit: u64,410 input_data: Vec<u8>,411 ) -> pallet_contracts_primitives::ContractExecResult {412 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)413 }414415 fn instantiate(416 origin: AccountId,417 endowment: Balance,418 gas_limit: u64,419 code: pallet_contracts_primitives::Code<Hash>,420 data: Vec<u8>,421 salt: Vec<u8>,422 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>423 {424 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)425 }426427 fn get_storage(428 address: AccountId,429 key: [u8; 32],430 ) -> pallet_contracts_primitives::GetStorageResult {431 Contracts::get_storage(address, key)432 }433434 fn rent_projection(435 address: AccountId,436 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {437 Contracts::rent_projection(address)438 }439 }440 */441442 #[cfg(feature = "runtime-benchmarks")]443 impl frame_benchmarking::Benchmark<Block> for Runtime {444 fn benchmark_metadata(extra: bool) -> (445 Vec<frame_benchmarking::BenchmarkList>,446 Vec<frame_support::traits::StorageInfo>,447 ) {448 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};449 use frame_support::traits::StorageInfoTrait;450451 let mut list = Vec::<BenchmarkList>::new();452453 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);454 list_benchmark!(list, extra, pallet_common, Common);455 list_benchmark!(list, extra, pallet_unique, Unique);456 list_benchmark!(list, extra, pallet_structure, Structure);457 list_benchmark!(list, extra, pallet_inflation, Inflation);458 list_benchmark!(list, extra, pallet_fungible, Fungible);459 list_benchmark!(list, extra, pallet_refungible, Refungible);460 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);461 list_benchmark!(list, extra, pallet_unique_scheduler, Scheduler);462463 #[cfg(not(feature = "unique-runtime"))]464 list_benchmark!(list, extra, pallet_proxy_rmrk_core, RmrkCore);465466 #[cfg(not(feature = "unique-runtime"))]467 list_benchmark!(list, extra, pallet_proxy_rmrk_equip, RmrkEquip);468469 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);470471 let storage_info = AllPalletsReversedWithSystemFirst::storage_info();472473 return (list, storage_info)474 }475476 fn dispatch_benchmark(477 config: frame_benchmarking::BenchmarkConfig478 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {479 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};480481 let allowlist: Vec<TrackedStorageKey> = vec![482 // Total Issuance483 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),484485 // Block Number486 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),487 // Execution Phase488 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),489 // Event Count490 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),491 // System Events492 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),493494 // Evm CurrentLogs495 hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),496497 // Transactional depth498 hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),499 ];500501 let mut batches = Vec::<BenchmarkBatch>::new();502 let params = (&config, &allowlist);503504 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);505 add_benchmark!(params, batches, pallet_common, Common);506 add_benchmark!(params, batches, pallet_unique, Unique);507 add_benchmark!(params, batches, pallet_structure, Structure);508 add_benchmark!(params, batches, pallet_inflation, Inflation);509 add_benchmark!(params, batches, pallet_fungible, Fungible);510 add_benchmark!(params, batches, pallet_refungible, Refungible);511 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);512 add_benchmark!(params, batches, pallet_unique_scheduler, Scheduler);513514 #[cfg(not(feature = "unique-runtime"))]515 add_benchmark!(params, batches, pallet_proxy_rmrk_core, RmrkCore);516517 #[cfg(not(feature = "unique-runtime"))]518 add_benchmark!(params, batches, pallet_proxy_rmrk_equip, RmrkEquip);519520 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);521522 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }523 Ok(batches)524 }525 }526527 #[cfg(feature = "try-runtime")]528 impl frame_try_runtime::TryRuntime<Block> for Runtime {529 fn on_runtime_upgrade() -> (Weight, Weight) {530 log::info!("try-runtime::on_runtime_upgrade unique-chain.");531 let weight = Executive::try_runtime_upgrade().unwrap();532 (weight, RuntimeBlockWeights::get().max_block)533 }534535 fn execute_block_no_check(block: Block) -> Weight {536 Executive::execute_block_no_check(block)537 }538 }539 }540 }541}tests/src/createItem.test.tsdiffbeforeafterboth--- a/tests/src/createItem.test.ts
+++ b/tests/src/createItem.test.ts
@@ -98,47 +98,57 @@
await createItemWithPropsExpectSuccess(alice, newCollectionID, createMode, [{key: 'key1', value: 'val1'}]);
});
- it.only('Check total pieces of Fungible token', async () => {
+ it('Check total pieces of Fungible token', async () => {
await usingApi(async api => {
const createMode = 'Fungible';
const collectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0}});
+ const amountPieces = 10n;
const tokenId = await createItemExpectSuccess(alice, collectionId, createMode, bob.address);
{
const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);
expect(totalPieces.isSome).to.be.true;
- expect(totalPieces.unwrap().toBigInt()).to.be.eq(10n);
+ expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
}
await transferExpectSuccess(collectionId, tokenId, bob, alice, 1, createMode);
{
const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);
expect(totalPieces.isSome).to.be.true;
- expect(totalPieces.unwrap().toBigInt()).to.be.eq(10n);
+ expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
}
+
+ const totalPieces = (await api.rpc.unique.tokenData(collectionId, tokenId, [])).pieces;
+ expect(totalPieces.isSome).to.be.true;
+ expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
});
});
- it.only('Check total pieces of NFT token', async () => {
+ it('Check total pieces of NFT token', async () => {
await usingApi(async api => {
const createMode = 'NFT';
const collectionId = await createCollectionExpectSuccess({mode: {type: createMode}});
+ const amountPieces = 1n;
const tokenId = await createItemExpectSuccess(alice, collectionId, createMode, bob.address);
{
const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);
expect(totalPieces.isSome).to.be.true;
- expect(totalPieces.unwrap().toBigInt()).to.be.eq(1n);
+ expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
}
await transferExpectSuccess(collectionId, tokenId, bob, alice, 1, createMode);
{
const totalPieces = await api.rpc.unique.totalPieces(collectionId, tokenId);
expect(totalPieces.isSome).to.be.true;
- expect(totalPieces.unwrap().toBigInt()).to.be.eq(1n);
+ expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
}
+
+ const totalPieces = (await api.rpc.unique.tokenData(collectionId, tokenId, [])).pieces;
+ expect(totalPieces.isSome).to.be.true;
+ expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
});
});
- it.only('Check total pieces of ReFungible token', async () => {
+ it('Check total pieces of ReFungible token', async () => {
await usingApi(async api => {
const createMode = 'ReFungible';
const createCollectionResult = await createCollection(api, alice, {mode: {type: createMode}});
@@ -157,6 +167,10 @@
expect(totalPieces.isSome).to.be.true;
expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
}
+
+ const totalPieces = (await api.rpc.unique.tokenData(collectionId, tokenId, [])).pieces;
+ expect(totalPieces.isSome).to.be.true;
+ expect(totalPieces.unwrap().toBigInt()).to.be.eq(amountPieces);
});
});
});
@@ -233,4 +247,37 @@
await createItemWithPropsExpectFailure(alice, newCollectionID, 'NFT', [{key: 'k', value: 'vvvvvv'.repeat(5000)}, {key: 'k2', value: 'vvv'.repeat(5000)}]);
});
});
+
+ it('Check total pieces for invalid Fungible token', async () => {
+ await usingApi(async api => {
+ const createCollectionResult = await createCollection(api, alice, {mode: {type: 'Fungible', decimalPoints: 0}});
+ const collectionId = createCollectionResult.collectionId;
+ const invalidTokenId = 1000_000;
+
+ expect((await api.rpc.unique.totalPieces(collectionId, invalidTokenId)).isNone).to.be.true;
+ expect((await api.rpc.unique.tokenData(collectionId, invalidTokenId, [])).pieces.isNone).to.be.true;
+ });
+ });
+
+ it('Check total pieces for invalid NFT token', async () => {
+ await usingApi(async api => {
+ const createCollectionResult = await createCollection(api, alice, {mode: {type: 'NFT'}});
+ const collectionId = createCollectionResult.collectionId;
+ const invalidTokenId = 1000_000;
+
+ expect((await api.rpc.unique.totalPieces(collectionId, invalidTokenId)).isNone).to.be.true;
+ expect((await api.rpc.unique.tokenData(collectionId, invalidTokenId, [])).pieces.isNone).to.be.true;
+ });
+ });
+
+ it('Check total pieces for invalid Refungible token', async () => {
+ await usingApi(async api => {
+ const createCollectionResult = await createCollection(api, alice, {mode: {type: 'ReFungible'}});
+ const collectionId = createCollectionResult.collectionId;
+ const invalidTokenId = 1000_000;
+
+ expect((await api.rpc.unique.totalPieces(collectionId, invalidTokenId)).isNone).to.be.true;
+ expect((await api.rpc.unique.tokenData(collectionId, invalidTokenId, [])).pieces.isNone).to.be.true;
+ });
+ });
});