difftreelog
Merge pull request #337 from UniqueNetwork/CORE-178
in: master
feature/core-178
9 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -119,6 +119,15 @@
) -> Result<Option<Collection<AccountId>>>;
#[rpc(name = "unique_collectionStats")]
fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;
+
+ #[rpc(name = "unique_nextSponsored")]
+ fn next_sponsored(
+ &self,
+ collection: CollectionId,
+ account: CrossAccountId,
+ token: TokenId,
+ at: Option<BlockHash>,
+ ) -> Result<Option<u64>>;
#[rpc(name = "unique_effectiveCollectionLimits")]
fn effective_collection_limits(
&self,
@@ -228,5 +237,6 @@
pass_method!(last_token_id(collection: CollectionId) -> TokenId);
pass_method!(collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>>);
pass_method!(collection_stats() -> CollectionStats);
+ pass_method!(next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Option<u64>);
pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>);
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -67,7 +67,7 @@
mod eth;
mod sponsorship;
-pub use sponsorship::UniqueSponsorshipHandler;
+pub use sponsorship::{UniqueSponsorshipHandler, UniqueSponsorshipPredict};
pub use eth::sponsoring::UniqueEthSponsorshipHandler;
pub use eth::UniqueErcSupport;
@@ -82,6 +82,12 @@
pub mod weights;
use weights::WeightInfo;
+pub trait SponsorshipPredict<T: Config> {
+ fn predict(collection: CollectionId, account: T::CrossAccountId, token: TokenId) -> Option<u64>
+ where
+ u64: From<<T as frame_system::Config>::BlockNumber>;
+}
+
decl_error! {
/// Error for non-fungible-token module.
pub enum Error for Module<T: Config> {
pallets/unique/src/sponsorship.rsdiffbeforeafterboth--- a/pallets/unique/src/sponsorship.rs
+++ b/pallets/unique/src/sponsorship.rs
@@ -29,6 +29,7 @@
CollectionId, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MetaUpdatePermission,
NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, TokenId,
};
+use sp_runtime::traits::Saturating;
use pallet_common::{CollectionHandle};
use pallet_evm::account::CrossAccountId;
@@ -301,3 +302,65 @@
}
}
}
+
+use crate::SponsorshipPredict;
+use up_data_structs::SponsorshipState;
+pub struct UniqueSponsorshipPredict<T>(PhantomData<T>);
+
+impl<T> SponsorshipPredict<T> for UniqueSponsorshipPredict<T>
+where
+ T: Config,
+{
+ fn predict(collection_id: CollectionId, who: T::CrossAccountId, token: TokenId) -> Option<u64>
+ where
+ u64: From<<T as frame_system::Config>::BlockNumber>,
+ {
+ let collection = <CollectionHandle<T>>::try_get(collection_id).ok()?;
+ let _ = collection.sponsorship.sponsor()?;
+
+ // sponsor timeout
+ let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+ let limit = collection
+ .limits
+ .sponsor_transfer_timeout(match collection.mode {
+ CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,
+ CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+ CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
+ });
+
+ let last_tx_block = match collection.mode {
+ CollectionMode::NFT => <NftTransferBasket<T>>::get(collection.id, token),
+ CollectionMode::Fungible(_) => {
+ <FungibleTransferBasket<T>>::get(collection.id, who.as_sub())
+ }
+ CollectionMode::ReFungible => {
+ <ReFungibleTransferBasket<T>>::get((collection.id, token, who.as_sub()))
+ }
+ };
+
+ if let Some(last_tx_block) = last_tx_block {
+ return Some(
+ last_tx_block
+ .saturating_add(limit.into())
+ .saturating_sub(block_number)
+ .into(),
+ );
+ }
+
+ let token_exists = match collection.mode {
+ CollectionMode::NFT => {
+ <pallet_nonfungible::TokenData<T>>::contains_key((collection.id, token))
+ }
+ CollectionMode::Fungible(_) => true,
+ CollectionMode::ReFungible => {
+ <pallet_refungible::TotalSupply<T>>::contains_key((collection.id, token))
+ }
+ };
+
+ if token_exists {
+ Some(0)
+ } else {
+ None
+ }
+ }
+}
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -59,6 +59,7 @@
fn last_token_id(collection: CollectionId) -> Result<TokenId>;
fn collection_by_id(collection: CollectionId) -> Result<Option<Collection<AccountId>>>;
fn collection_stats() -> Result<CollectionStats>;
+ fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>>;
fn effective_collection_limits(collection_id: CollectionId) -> Result<Option<CollectionLimits>>;
}
}
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 token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {18 dispatch_unique_runtime!(collection.token_exists(token))19 }2021 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {22 dispatch_unique_runtime!(collection.token_owner(token))23 }24 fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {25 dispatch_unique_runtime!(collection.const_metadata(token))26 }27 fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {28 dispatch_unique_runtime!(collection.variable_metadata(token))29 }3031 fn collection_tokens(collection: CollectionId) -> Result<u32, DispatchError> {32 dispatch_unique_runtime!(collection.collection_tokens())33 }34 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {35 dispatch_unique_runtime!(collection.account_balance(account))36 }37 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {38 dispatch_unique_runtime!(collection.balance(account, token))39 }40 fn allowance(41 collection: CollectionId,42 sender: CrossAccountId,43 spender: CrossAccountId,44 token: TokenId,45 ) -> Result<u128, DispatchError> {46 dispatch_unique_runtime!(collection.allowance(sender, spender, token))47 }4849 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {50 <pallet_unique::UniqueErcSupport<Runtime>>::get_code(&account)51 .or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))52 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))53 }54 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {55 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))56 }57 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {58 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))59 }60 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {61 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))62 }63 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {64 dispatch_unique_runtime!(collection.last_token_id())65 }66 fn collection_by_id(collection: CollectionId) -> Result<Option<Collection<AccountId>>, DispatchError> {67 Ok(<pallet_common::CollectionById<Runtime>>::get(collection))68 }69 fn collection_stats() -> Result<CollectionStats, DispatchError> {70 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())71 }7273 fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {74 Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))75 }76 }7778 impl sp_api::Core<Block> for Runtime {79 fn version() -> RuntimeVersion {80 VERSION81 }8283 fn execute_block(block: Block) {84 Executive::execute_block(block)85 }8687 fn initialize_block(header: &<Block as BlockT>::Header) {88 Executive::initialize_block(header)89 }90 }9192 impl sp_api::Metadata<Block> for Runtime {93 fn metadata() -> OpaqueMetadata {94 OpaqueMetadata::new(Runtime::metadata().into())95 }96 }9798 impl sp_block_builder::BlockBuilder<Block> for Runtime {99 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {100 Executive::apply_extrinsic(extrinsic)101 }102103 fn finalize_block() -> <Block as BlockT>::Header {104 Executive::finalize_block()105 }106107 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {108 data.create_extrinsics()109 }110111 fn check_inherents(112 block: Block,113 data: sp_inherents::InherentData,114 ) -> sp_inherents::CheckInherentsResult {115 data.check_extrinsics(&block)116 }117118 // fn random_seed() -> <Block as BlockT>::Hash {119 // RandomnessCollectiveFlip::random_seed().0120 // }121 }122123 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {124 fn validate_transaction(125 source: TransactionSource,126 tx: <Block as BlockT>::Extrinsic,127 hash: <Block as BlockT>::Hash,128 ) -> TransactionValidity {129 Executive::validate_transaction(source, tx, hash)130 }131 }132133 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {134 fn offchain_worker(header: &<Block as BlockT>::Header) {135 Executive::offchain_worker(header)136 }137 }138139 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {140 fn chain_id() -> u64 {141 <Runtime as pallet_evm::Config>::ChainId::get()142 }143144 fn account_basic(address: H160) -> EVMAccount {145 EVM::account_basic(&address)146 }147148 fn gas_price() -> U256 {149 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()150 }151152 fn account_code_at(address: H160) -> Vec<u8> {153 EVM::account_codes(address)154 }155156 fn author() -> H160 {157 <pallet_evm::Pallet<Runtime>>::find_author()158 }159160 fn storage_at(address: H160, index: U256) -> H256 {161 let mut tmp = [0u8; 32];162 index.to_big_endian(&mut tmp);163 EVM::account_storages(address, H256::from_slice(&tmp[..]))164 }165166 #[allow(clippy::redundant_closure)]167 fn call(168 from: H160,169 to: H160,170 data: Vec<u8>,171 value: U256,172 gas_limit: U256,173 max_fee_per_gas: Option<U256>,174 max_priority_fee_per_gas: Option<U256>,175 nonce: Option<U256>,176 estimate: bool,177 access_list: Option<Vec<(H160, Vec<H256>)>>,178 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {179 let config = if estimate {180 let mut config = <Runtime as pallet_evm::Config>::config().clone();181 config.estimate = true;182 Some(config)183 } else {184 None185 };186187 <Runtime as pallet_evm::Config>::Runner::call(188 CrossAccountId::from_eth(from),189 to,190 data,191 value,192 gas_limit.low_u64(),193 max_fee_per_gas,194 max_priority_fee_per_gas,195 nonce,196 access_list.unwrap_or_default(),197 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),198 ).map_err(|err| err.into())199 }200201 #[allow(clippy::redundant_closure)]202 fn create(203 from: H160,204 data: Vec<u8>,205 value: U256,206 gas_limit: U256,207 max_fee_per_gas: Option<U256>,208 max_priority_fee_per_gas: Option<U256>,209 nonce: Option<U256>,210 estimate: bool,211 access_list: Option<Vec<(H160, Vec<H256>)>>,212 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {213 let config = if estimate {214 let mut config = <Runtime as pallet_evm::Config>::config().clone();215 config.estimate = true;216 Some(config)217 } else {218 None219 };220221 <Runtime as pallet_evm::Config>::Runner::create(222 CrossAccountId::from_eth(from),223 data,224 value,225 gas_limit.low_u64(),226 max_fee_per_gas,227 max_priority_fee_per_gas,228 nonce,229 access_list.unwrap_or_default(),230 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),231 ).map_err(|err| err.into())232 }233234 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {235 Ethereum::current_transaction_statuses()236 }237238 fn current_block() -> Option<pallet_ethereum::Block> {239 Ethereum::current_block()240 }241242 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {243 Ethereum::current_receipts()244 }245246 fn current_all() -> (247 Option<pallet_ethereum::Block>,248 Option<Vec<pallet_ethereum::Receipt>>,249 Option<Vec<TransactionStatus>>250 ) {251 (252 Ethereum::current_block(),253 Ethereum::current_receipts(),254 Ethereum::current_transaction_statuses()255 )256 }257258 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {259 xts.into_iter().filter_map(|xt| match xt.0.function {260 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),261 _ => None262 }).collect()263 }264265 fn elasticity() -> Option<Permill> {266 None267 }268 }269270 impl sp_session::SessionKeys<Block> for Runtime {271 fn decode_session_keys(272 encoded: Vec<u8>,273 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {274 SessionKeys::decode_into_raw_public_keys(&encoded)275 }276277 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {278 SessionKeys::generate(seed)279 }280 }281282 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {283 fn slot_duration() -> sp_consensus_aura::SlotDuration {284 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())285 }286287 fn authorities() -> Vec<AuraId> {288 Aura::authorities().to_vec()289 }290 }291292 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {293 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {294 ParachainSystem::collect_collation_info(header)295 }296 }297298 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {299 fn account_nonce(account: AccountId) -> Index {300 System::account_nonce(account)301 }302 }303304 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {305 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {306 TransactionPayment::query_info(uxt, len)307 }308 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {309 TransactionPayment::query_fee_details(uxt, len)310 }311 }312313 /*314 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>315 for Runtime316 {317 fn call(318 origin: AccountId,319 dest: AccountId,320 value: Balance,321 gas_limit: u64,322 input_data: Vec<u8>,323 ) -> pallet_contracts_primitives::ContractExecResult {324 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)325 }326327 fn instantiate(328 origin: AccountId,329 endowment: Balance,330 gas_limit: u64,331 code: pallet_contracts_primitives::Code<Hash>,332 data: Vec<u8>,333 salt: Vec<u8>,334 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>335 {336 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)337 }338339 fn get_storage(340 address: AccountId,341 key: [u8; 32],342 ) -> pallet_contracts_primitives::GetStorageResult {343 Contracts::get_storage(address, key)344 }345346 fn rent_projection(347 address: AccountId,348 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {349 Contracts::rent_projection(address)350 }351 }352 */353354 #[cfg(feature = "runtime-benchmarks")]355 impl frame_benchmarking::Benchmark<Block> for Runtime {356 fn benchmark_metadata(extra: bool) -> (357 Vec<frame_benchmarking::BenchmarkList>,358 Vec<frame_support::traits::StorageInfo>,359 ) {360 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};361 use frame_support::traits::StorageInfoTrait;362363 let mut list = Vec::<BenchmarkList>::new();364365 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);366 list_benchmark!(list, extra, pallet_unique, Unique);367 list_benchmark!(list, extra, pallet_inflation, Inflation);368 list_benchmark!(list, extra, pallet_fungible, Fungible);369 list_benchmark!(list, extra, pallet_refungible, Refungible);370 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);371 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);372373 let storage_info = AllPalletsReversedWithSystemFirst::storage_info();374375 return (list, storage_info)376 }377378 fn dispatch_benchmark(379 config: frame_benchmarking::BenchmarkConfig380 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {381 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};382383 let allowlist: Vec<TrackedStorageKey> = vec![384 // Block Number385 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),386 // Total Issuance387 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),388 // Execution Phase389 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),390 // Event Count391 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),392 // System Events393 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),394 ];395396 let mut batches = Vec::<BenchmarkBatch>::new();397 let params = (&config, &allowlist);398399 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);400 add_benchmark!(params, batches, pallet_unique, Unique);401 add_benchmark!(params, batches, pallet_inflation, Inflation);402 add_benchmark!(params, batches, pallet_fungible, Fungible);403 add_benchmark!(params, batches, pallet_refungible, Refungible);404 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);405 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);406407 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }408 Ok(batches)409 }410 }411 }412 }413}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 token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {18 dispatch_unique_runtime!(collection.token_exists(token))19 }2021 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {22 dispatch_unique_runtime!(collection.token_owner(token))23 }24 fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {25 dispatch_unique_runtime!(collection.const_metadata(token))26 }27 fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {28 dispatch_unique_runtime!(collection.variable_metadata(token))29 }3031 fn collection_tokens(collection: CollectionId) -> Result<u32, DispatchError> {32 dispatch_unique_runtime!(collection.collection_tokens())33 }34 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {35 dispatch_unique_runtime!(collection.account_balance(account))36 }37 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {38 dispatch_unique_runtime!(collection.balance(account, token))39 }40 fn allowance(41 collection: CollectionId,42 sender: CrossAccountId,43 spender: CrossAccountId,44 token: TokenId,45 ) -> Result<u128, DispatchError> {46 dispatch_unique_runtime!(collection.allowance(sender, spender, token))47 }4849 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {50 <pallet_unique::UniqueErcSupport<Runtime>>::get_code(&account)51 .or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))52 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))53 }54 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {55 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))56 }57 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {58 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))59 }60 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {61 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))62 }63 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {64 dispatch_unique_runtime!(collection.last_token_id())65 }66 fn collection_by_id(collection: CollectionId) -> Result<Option<Collection<AccountId>>, DispatchError> {67 Ok(<pallet_common::CollectionById<Runtime>>::get(collection))68 }69 fn collection_stats() -> Result<CollectionStats, DispatchError> {70 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())71 }72 fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {73 Ok(<pallet_unique::UniqueSponsorshipPredict<Runtime> as74 pallet_unique::SponsorshipPredict<Runtime>>::predict(75 collection,76 account,77 token))78 }7980 fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {81 Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))82 }83 }8485 impl sp_api::Core<Block> for Runtime {86 fn version() -> RuntimeVersion {87 VERSION88 }8990 fn execute_block(block: Block) {91 Executive::execute_block(block)92 }9394 fn initialize_block(header: &<Block as BlockT>::Header) {95 Executive::initialize_block(header)96 }97 }9899 impl sp_api::Metadata<Block> for Runtime {100 fn metadata() -> OpaqueMetadata {101 OpaqueMetadata::new(Runtime::metadata().into())102 }103 }104105 impl sp_block_builder::BlockBuilder<Block> for Runtime {106 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {107 Executive::apply_extrinsic(extrinsic)108 }109110 fn finalize_block() -> <Block as BlockT>::Header {111 Executive::finalize_block()112 }113114 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {115 data.create_extrinsics()116 }117118 fn check_inherents(119 block: Block,120 data: sp_inherents::InherentData,121 ) -> sp_inherents::CheckInherentsResult {122 data.check_extrinsics(&block)123 }124125 // fn random_seed() -> <Block as BlockT>::Hash {126 // RandomnessCollectiveFlip::random_seed().0127 // }128 }129130 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {131 fn validate_transaction(132 source: TransactionSource,133 tx: <Block as BlockT>::Extrinsic,134 hash: <Block as BlockT>::Hash,135 ) -> TransactionValidity {136 Executive::validate_transaction(source, tx, hash)137 }138 }139140 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {141 fn offchain_worker(header: &<Block as BlockT>::Header) {142 Executive::offchain_worker(header)143 }144 }145146 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {147 fn chain_id() -> u64 {148 <Runtime as pallet_evm::Config>::ChainId::get()149 }150151 fn account_basic(address: H160) -> EVMAccount {152 EVM::account_basic(&address)153 }154155 fn gas_price() -> U256 {156 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()157 }158159 fn account_code_at(address: H160) -> Vec<u8> {160 EVM::account_codes(address)161 }162163 fn author() -> H160 {164 <pallet_evm::Pallet<Runtime>>::find_author()165 }166167 fn storage_at(address: H160, index: U256) -> H256 {168 let mut tmp = [0u8; 32];169 index.to_big_endian(&mut tmp);170 EVM::account_storages(address, H256::from_slice(&tmp[..]))171 }172173 #[allow(clippy::redundant_closure)]174 fn call(175 from: H160,176 to: H160,177 data: Vec<u8>,178 value: U256,179 gas_limit: U256,180 max_fee_per_gas: Option<U256>,181 max_priority_fee_per_gas: Option<U256>,182 nonce: Option<U256>,183 estimate: bool,184 access_list: Option<Vec<(H160, Vec<H256>)>>,185 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {186 let config = if estimate {187 let mut config = <Runtime as pallet_evm::Config>::config().clone();188 config.estimate = true;189 Some(config)190 } else {191 None192 };193194 <Runtime as pallet_evm::Config>::Runner::call(195 CrossAccountId::from_eth(from),196 to,197 data,198 value,199 gas_limit.low_u64(),200 max_fee_per_gas,201 max_priority_fee_per_gas,202 nonce,203 access_list.unwrap_or_default(),204 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),205 ).map_err(|err| err.into())206 }207208 #[allow(clippy::redundant_closure)]209 fn create(210 from: H160,211 data: Vec<u8>,212 value: U256,213 gas_limit: U256,214 max_fee_per_gas: Option<U256>,215 max_priority_fee_per_gas: Option<U256>,216 nonce: Option<U256>,217 estimate: bool,218 access_list: Option<Vec<(H160, Vec<H256>)>>,219 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {220 let config = if estimate {221 let mut config = <Runtime as pallet_evm::Config>::config().clone();222 config.estimate = true;223 Some(config)224 } else {225 None226 };227228 <Runtime as pallet_evm::Config>::Runner::create(229 CrossAccountId::from_eth(from),230 data,231 value,232 gas_limit.low_u64(),233 max_fee_per_gas,234 max_priority_fee_per_gas,235 nonce,236 access_list.unwrap_or_default(),237 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),238 ).map_err(|err| err.into())239 }240241 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {242 Ethereum::current_transaction_statuses()243 }244245 fn current_block() -> Option<pallet_ethereum::Block> {246 Ethereum::current_block()247 }248249 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {250 Ethereum::current_receipts()251 }252253 fn current_all() -> (254 Option<pallet_ethereum::Block>,255 Option<Vec<pallet_ethereum::Receipt>>,256 Option<Vec<TransactionStatus>>257 ) {258 (259 Ethereum::current_block(),260 Ethereum::current_receipts(),261 Ethereum::current_transaction_statuses()262 )263 }264265 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {266 xts.into_iter().filter_map(|xt| match xt.0.function {267 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),268 _ => None269 }).collect()270 }271272 fn elasticity() -> Option<Permill> {273 None274 }275 }276277 impl sp_session::SessionKeys<Block> for Runtime {278 fn decode_session_keys(279 encoded: Vec<u8>,280 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {281 SessionKeys::decode_into_raw_public_keys(&encoded)282 }283284 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {285 SessionKeys::generate(seed)286 }287 }288289 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {290 fn slot_duration() -> sp_consensus_aura::SlotDuration {291 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())292 }293294 fn authorities() -> Vec<AuraId> {295 Aura::authorities().to_vec()296 }297 }298299 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {300 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {301 ParachainSystem::collect_collation_info(header)302 }303 }304305 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {306 fn account_nonce(account: AccountId) -> Index {307 System::account_nonce(account)308 }309 }310311 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {312 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {313 TransactionPayment::query_info(uxt, len)314 }315 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {316 TransactionPayment::query_fee_details(uxt, len)317 }318 }319320 /*321 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>322 for Runtime323 {324 fn call(325 origin: AccountId,326 dest: AccountId,327 value: Balance,328 gas_limit: u64,329 input_data: Vec<u8>,330 ) -> pallet_contracts_primitives::ContractExecResult {331 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)332 }333334 fn instantiate(335 origin: AccountId,336 endowment: Balance,337 gas_limit: u64,338 code: pallet_contracts_primitives::Code<Hash>,339 data: Vec<u8>,340 salt: Vec<u8>,341 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>342 {343 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)344 }345346 fn get_storage(347 address: AccountId,348 key: [u8; 32],349 ) -> pallet_contracts_primitives::GetStorageResult {350 Contracts::get_storage(address, key)351 }352353 fn rent_projection(354 address: AccountId,355 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {356 Contracts::rent_projection(address)357 }358 }359 */360361 #[cfg(feature = "runtime-benchmarks")]362 impl frame_benchmarking::Benchmark<Block> for Runtime {363 fn benchmark_metadata(extra: bool) -> (364 Vec<frame_benchmarking::BenchmarkList>,365 Vec<frame_support::traits::StorageInfo>,366 ) {367 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};368 use frame_support::traits::StorageInfoTrait;369370 let mut list = Vec::<BenchmarkList>::new();371372 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);373 list_benchmark!(list, extra, pallet_unique, Unique);374 list_benchmark!(list, extra, pallet_inflation, Inflation);375 list_benchmark!(list, extra, pallet_fungible, Fungible);376 list_benchmark!(list, extra, pallet_refungible, Refungible);377 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);378 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);379380 let storage_info = AllPalletsReversedWithSystemFirst::storage_info();381382 return (list, storage_info)383 }384385 fn dispatch_benchmark(386 config: frame_benchmarking::BenchmarkConfig387 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {388 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};389390 let allowlist: Vec<TrackedStorageKey> = vec![391 // Block Number392 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),393 // Total Issuance394 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),395 // Execution Phase396 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),397 // Event Count398 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),399 // System Events400 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),401 ];402403 let mut batches = Vec::<BenchmarkBatch>::new();404 let params = (&config, &allowlist);405406 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);407 add_benchmark!(params, batches, pallet_unique, Unique);408 add_benchmark!(params, batches, pallet_inflation, Inflation);409 add_benchmark!(params, batches, pallet_fungible, Fungible);410 add_benchmark!(params, batches, pallet_refungible, Refungible);411 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);412 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);413414 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }415 Ok(batches)416 }417 }418 }419 }420}tests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-rpc.ts
+++ b/tests/src/interfaces/augment-api-rpc.ts
@@ -623,6 +623,10 @@
* Get token variable metadata
**/
variableMetadata: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, tokenId: u32 | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Bytes>>;
+ /**
+ * nextSponsored transaction
+ **/
+ nextSponsored: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, account: AccountId | string | Uint8Array | { Substrate: any } | { Ethereum: any } | string | Uint8Array, tokenId: u32 | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<u64>>>;
};
web3: {
/**
tests/src/interfaces/unique/definitions.tsdiffbeforeafterboth--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -55,6 +55,7 @@
collectionById: fun('Get collection by specified id', [collectionParam], 'Option<UpDataStructsCollection>'),
collectionStats: fun('Get collection stats', [], 'UpDataStructsCollectionStats'),
allowed: fun('Check if user is allowed to use collection', [collectionParam, crossAccountParam()], 'bool'),
+ nextSponsored: fun('Get number of blocks when sponsored transaction is available', [collectionParam, crossAccountParam(), tokenParam], 'Option<u64>'),
effectiveCollectionLimits: fun('Get effective collection limits', [collectionParam], 'Option<UpDataStructsCollectionLimits>'),
},
};
tests/src/nextSponsoring.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/nextSponsoring.test.ts
@@ -0,0 +1,110 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {ApiPromise} from '@polkadot/api';
+import {IKeyringPair} from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from './substrate/privateKey';
+import {default as usingApi} from './substrate/substrate-api';
+import {
+ createCollectionExpectSuccess,
+ setCollectionSponsorExpectSuccess,
+ confirmSponsorshipExpectSuccess,
+ createItemExpectSuccess,
+ transferExpectSuccess,
+ normalizeAccountId,
+ getNextSponsored,
+} from './util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+
+
+describe('Integration Test getNextSponsored(collection_id, owner, item_id):', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
+ });
+
+ it('NFT', async () => {
+ await usingApi(async (api: ApiPromise) => {
+
+ // Not existing collection
+ expect(await getNextSponsored(api, 0, normalizeAccountId(alice), 0)).to.be.equal(-1);
+
+ const collectionId = await createCollectionExpectSuccess();
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ // Check with Disabled sponsoring state
+ expect(await getNextSponsored(api, collectionId, normalizeAccountId(alice), itemId)).to.be.equal(-1);
+ await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+
+ // Check with Unconfirmed sponsoring state
+ expect(await getNextSponsored(api, collectionId, normalizeAccountId(alice), itemId)).to.be.equal(-1);
+ await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ // Check with Confirmed sponsoring state
+ expect(await getNextSponsored(api, collectionId, normalizeAccountId(alice), itemId)).to.be.equal(0);
+
+ // After transfer
+ await transferExpectSuccess(collectionId, itemId, alice, bob, 1);
+ expect(await getNextSponsored(api, collectionId, normalizeAccountId(alice), itemId)).to.be.equal(5);
+
+ // Not existing token
+ expect(await getNextSponsored(api, collectionId, normalizeAccountId(alice), itemId+1)).to.be.equal(-1);
+ });
+ });
+
+ it('Fungible', async () => {
+ await usingApi(async (api: ApiPromise) => {
+
+ const createMode = 'Fungible';
+ const funCollectionId = await createCollectionExpectSuccess({mode: {type: createMode, decimalPoints: 0}});
+ await createItemExpectSuccess(alice, funCollectionId, createMode);
+ await setCollectionSponsorExpectSuccess(funCollectionId, bob.address);
+ await confirmSponsorshipExpectSuccess(funCollectionId, '//Bob');
+ expect(await getNextSponsored(api, funCollectionId, normalizeAccountId(alice), 0)).to.be.equal(0);
+
+ await transferExpectSuccess(funCollectionId, 0, alice, bob, 10, 'Fungible');
+ expect(await getNextSponsored(api, funCollectionId, normalizeAccountId(alice), 0)).to.be.equal(5);
+ });
+ });
+
+ it('ReFungible', async () => {
+ await usingApi(async (api: ApiPromise) => {
+
+ const createMode = 'ReFungible';
+ const refunCollectionId = await createCollectionExpectSuccess({mode: {type: createMode}});
+ const refunItemId = await createItemExpectSuccess(alice, refunCollectionId, createMode);
+ await setCollectionSponsorExpectSuccess(refunCollectionId, bob.address);
+ await confirmSponsorshipExpectSuccess(refunCollectionId, '//Bob');
+ expect(await getNextSponsored(api, refunCollectionId, normalizeAccountId(alice), refunItemId)).to.be.equal(0);
+
+ await transferExpectSuccess(refunCollectionId, refunItemId, alice, bob, 10, 'ReFungible');
+ expect(await getNextSponsored(api, refunCollectionId, normalizeAccountId(alice), refunItemId)).to.be.equal(5);
+
+ // Not existing token
+ expect(await getNextSponsored(api, refunCollectionId, normalizeAccountId(alice), refunItemId+1)).to.be.equal(-1);
+ });
+ });
+});
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -608,6 +608,15 @@
});
}
+export async function getNextSponsored(
+ api: ApiPromise,
+ collectionId: number,
+ account: string | CrossAccountId,
+ tokenId: number,
+): Promise<number> {
+ return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));
+}
+
export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {
await usingApi(async (api) => {
const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);