difftreelog
refactor upgrade code for new substrate
in: master
39 files changed
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -153,11 +153,12 @@
) => {{
use $runtime::*;
- GenesisConfig {
+ RuntimeGenesisConfig {
system: SystemConfig {
code: WASM_BINARY
.expect("WASM binary was not build, please build it!")
.to_vec(),
+ ..Default::default()
},
balances: BalancesConfig {
balances: $endowed_accounts
@@ -167,10 +168,6 @@
.map(|k| (k, 1 << 100))
.collect(),
},
- common: Default::default(),
- configuration: Default::default(),
- nonfungible: Default::default(),
- treasury: Default::default(),
tokens: TokensConfig { balances: vec![] },
sudo: SudoConfig {
key: Some($root_key),
@@ -179,8 +176,8 @@
vesting: VestingConfig { vesting: vec![] },
parachain_info: ParachainInfoConfig {
parachain_id: $id.into(),
+ ..Default::default()
},
- parachain_system: Default::default(),
collator_selection: CollatorSelectionConfig {
invulnerables: $initial_invulnerables
.iter()
@@ -200,14 +197,10 @@
})
.collect(),
},
- aura: Default::default(),
- aura_ext: Default::default(),
evm: EVMConfig {
accounts: BTreeMap::new(),
+ ..Default::default()
},
- ethereum: EthereumConfig {},
- polkadot_xcm: Default::default(),
- transaction_payment: Default::default(),
..Default::default()
}
}};
@@ -224,15 +217,13 @@
) => {{
use $runtime::*;
- GenesisConfig {
+ RuntimeGenesisConfig {
system: SystemConfig {
code: WASM_BINARY
.expect("WASM binary was not build, please build it!")
.to_vec(),
+ ..Default::default()
},
- common: Default::default(),
- configuration: Default::default(),
- nonfungible: Default::default(),
balances: BalancesConfig {
balances: $endowed_accounts
.iter()
@@ -241,7 +232,6 @@
.map(|k| (k, 1 << 100))
.collect(),
},
- treasury: Default::default(),
tokens: TokensConfig { balances: vec![] },
sudo: SudoConfig {
key: Some($root_key),
@@ -249,21 +239,19 @@
vesting: VestingConfig { vesting: vec![] },
parachain_info: ParachainInfoConfig {
parachain_id: $id.into(),
+ Default::default()
},
- parachain_system: Default::default(),
aura: AuraConfig {
authorities: $initial_invulnerables
.into_iter()
.map(|(_, aura)| aura)
.collect(),
},
- aura_ext: Default::default(),
evm: EVMConfig {
accounts: BTreeMap::new(),
+ ..Default::default()
},
- ethereum: EthereumConfig {},
- polkadot_xcm: Default::default(),
- transaction_payment: Default::default(),
+ ..Default::default()
}
}};
}
node/cli/src/command.rsdiffbeforeafterboth--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -135,19 +135,6 @@
fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
load_spec(id)
}
-
- fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
- match chain_spec.runtime_id() {
- #[cfg(feature = "unique-runtime")]
- RuntimeId::Unique => &unique_runtime::VERSION,
-
- #[cfg(feature = "quartz-runtime")]
- RuntimeId::Quartz => &quartz_runtime::VERSION,
-
- RuntimeId::Opal => &opal_runtime::VERSION,
- runtime_id => panic!("{}", no_runtime_err!(runtime_id)),
- }
- }
}
impl SubstrateCli for RelayChainCli {
@@ -184,25 +171,21 @@
fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)
- }
-
- fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
- polkadot_cli::Cli::native_runtime_version(chain_spec)
}
}
macro_rules! async_run_with_runtime {
(
- $runtime_api:path, $executor:path,
+ $runtime:path, $runtime_api:path, $executor:path,
$runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,
$( $code:tt )*
) => {
$runner.async_run(|$config| {
let $components = new_partial::<
- $runtime_api, $executor, _
+ $runtime, $runtime_api, $executor, _
>(
&$config,
- crate::service::parachain_build_import_queue,
+ crate::service::parachain_build_import_queue::<$runtime, _, _>,
)?;
let task_manager = $components.task_manager;
@@ -218,18 +201,18 @@
match runner.config().chain_spec.runtime_id() {
#[cfg(feature = "unique-runtime")]
RuntimeId::Unique => async_run_with_runtime!(
- unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
+ unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
runner, $components, $cli, $cmd, $config, $( $code )*
),
#[cfg(feature = "quartz-runtime")]
RuntimeId::Quartz => async_run_with_runtime!(
- quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
+ quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
runner, $components, $cli, $cmd, $config, $( $code )*
),
RuntimeId::Opal => async_run_with_runtime!(
- opal_runtime::RuntimeApi, OpalRuntimeExecutor,
+ opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,
runner, $components, $cli, $cmd, $config, $( $code )*
),
@@ -240,11 +223,18 @@
macro_rules! sync_run_with_runtime {
(
- $runtime_api:path, $executor:path,
+ $runtime:path, $runtime_api:path, $executor:path,
$runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,
$( $code:tt )*
) => {
$runner.sync_run(|$config| {
+ let $components = new_partial::<
+ $runtime, $runtime_api, $executor, _
+ >(
+ &$config,
+ crate::service::parachain_build_import_queue::<$runtime, _, _>,
+ )?;
+
$( $code )*
})
};
@@ -257,18 +247,18 @@
match runner.config().chain_spec.runtime_id() {
#[cfg(feature = "unique-runtime")]
RuntimeId::Unique => sync_run_with_runtime!(
- unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
+ unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
runner, $components, $cli, $cmd, $config, $( $code )*
),
#[cfg(feature = "quartz-runtime")]
RuntimeId::Quartz => sync_run_with_runtime!(
- quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
+ quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
runner, $components, $cli, $cmd, $config, $( $code )*
),
RuntimeId::Opal => sync_run_with_runtime!(
- opal_runtime::RuntimeApi, OpalRuntimeExecutor,
+ opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,
runner, $components, $cli, $cmd, $config, $( $code )*
),
@@ -362,12 +352,11 @@
Some(Subcommand::ExportGenesisState(cmd)) => {
construct_sync_run!(|components, cli, cmd, _config| {
let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;
- let state_version = Cli::native_runtime_version(&spec).state_version();
- cmd.run::<Block>(&*spec, state_version)
+ cmd.run(&*spec, &*components.client)
})
}
Some(Subcommand::ExportGenesisWasm(cmd)) => {
- construct_sync_run!(|components, cli, cmd, _config| {
+ construct_sync_run!(|_components, cli, cmd, _config| {
let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;
cmd.run(&*spec)
})
@@ -411,6 +400,7 @@
#[cfg(feature = "try-runtime")]
Some(Subcommand::TryRuntime(cmd)) => {
use std::{future::Future, pin::Pin};
+
use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch};
use try_runtime_cli::block_building_info::timestamp_with_aura_info;
@@ -506,12 +496,6 @@
AccountIdConversion::<polkadot_primitives::AccountId>::into_account_truncating(
¶_id,
);
-
- let state_version = Cli::native_runtime_version(&config.chain_spec).state_version();
- let block: Block = generate_genesis_block(&*config.chain_spec, state_version)
- .map_err(|e| format!("{e:?}"))?;
- let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));
- let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));
let polkadot_config = SubstrateCli::create_configuration(
&polkadot_cli,
@@ -522,9 +506,6 @@
info!("Parachain id: {:?}", para_id);
info!("Parachain Account: {}", parachain_account);
- info!("Parachain genesis state: {}", genesis_state);
- info!("Parachain genesis hash: {}", genesis_hash);
- debug!("Parachain genesis block: {:?}", block);
info!(
"Is collating: {}",
if config.role.is_authority() {
node/cli/src/service.rsdiffbeforeafterboth--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -185,7 +185,7 @@
}
}
-pub fn open_frontier_backend<Block: BlockT, C: HeaderBackend<Block>>(
+pub fn open_frontier_backend<C: HeaderBackend<Block>>(
client: Arc<C>,
config: &Configuration,
) -> Result<Arc<fc_db::kv::Backend<Block>>, String> {
@@ -210,12 +210,42 @@
type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =
TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;
+/// Generate a supertrait based on bounds, and blanket impl for it.
+macro_rules! ez_bounds {
+ ($vis:vis trait $name:ident$(<$($gen:ident $(: $($(+)? $bound:path)*)?),* $(,)?>)? $(:)? $($(+)? $super:path)* {}) => {
+ $vis trait $name $(<$($gen $(: $($bound+)*)?,)*>)?: $($super +)* {}
+ impl<T, $($($gen $(: $($bound+)*)?,)*)?> $name$(<$($gen,)*>)? for T
+ where T: $($super +)* {}
+ }
+}
+ez_bounds!(
+ pub trait RuntimeApiDep<Runtime: RuntimeInstance>:
+ sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
+ + sp_consensus_aura::AuraApi<Block, AuraId>
+ + fp_rpc::EthereumRuntimeRPCApi<Block>
+ + sp_session::SessionKeys<Block>
+ + sp_block_builder::BlockBuilder<Block>
+ + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
+ + sp_api::ApiExt<Block>
+ + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>
+ + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
+ + up_pov_estimate_rpc::PovEstimateApi<Block>
+ + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Nonce>
+ + sp_api::Metadata<Block>
+ + sp_offchain::OffchainWorkerApi<Block>
+ + cumulus_primitives_core::CollectCollationInfo<Block>
+ // Deprecated, not used.
+ + fp_rpc::ConvertTransactionRuntimeApi<Block>
+ {
+ }
+);
+
/// Starts a `ServiceBuilder` for a full service.
///
/// Use this macro if you don't actually need the full service, but just the builder in order to
/// be able to perform chain operations.
#[allow(clippy::type_complexity)]
-pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(
+pub fn new_partial<Runtime, RuntimeApi, ExecutorDispatch, BIQ>(
config: &Configuration,
build_import_queue: BIQ,
) -> Result<
@@ -223,7 +253,7 @@
FullClient<RuntimeApi, ExecutorDispatch>,
FullBackend,
FullSelectChain,
- sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
+ sc_consensus::DefaultImportQueue<Block>,
sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
OtherPartial,
>,
@@ -235,7 +265,8 @@
+ Send
+ Sync
+ 'static,
- RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,
+ RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
+ Runtime: RuntimeInstance,
ExecutorDispatch: NativeExecutionDispatch + 'static,
BIQ: FnOnce(
Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
@@ -243,10 +274,7 @@
&Configuration,
Option<TelemetryHandle>,
&TaskManager,
- ) -> Result<
- sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
- sc_service::Error,
- >,
+ ) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error>,
{
let telemetry = config
.telemetry_endpoints
@@ -317,35 +345,6 @@
};
Ok(params)
-}
-
-async fn build_relay_chain_interface(
- polkadot_config: Configuration,
- parachain_config: &Configuration,
- telemetry_worker_handle: Option<TelemetryWorkerHandle>,
- task_manager: &mut TaskManager,
- collator_options: CollatorOptions,
- hwbench: Option<sc_sysinfo::HwBench>,
-) -> RelayChainResult<(
- Arc<(dyn RelayChainInterface + 'static)>,
- Option<CollatorPair>,
-)> {
- if collator_options.relay_chain_rpc_urls.is_empty() {
- build_inprocess_relay_chain(
- polkadot_config,
- parachain_config,
- telemetry_worker_handle,
- task_manager,
- hwbench,
- )
- } else {
- build_minimal_relay_chain_node(
- polkadot_config,
- task_manager,
- collator_options.relay_chain_rpc_urls,
- )
- .await
- }
}
macro_rules! clone {
@@ -360,13 +359,11 @@
///
/// This is the actual implementation that is abstract over the executor and the runtime api.
#[sc_tracing::logging::prefix_logs_with("Parachain")]
-async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(
+pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(
parachain_config: Configuration,
polkadot_config: Configuration,
collator_options: CollatorOptions,
- id: ParaId,
- build_import_queue: BIQ,
- build_consensus: BIC,
+ para_id: ParaId,
hwbench: Option<sc_sysinfo::HwBench>,
) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>
where
@@ -378,48 +375,16 @@
+ Send
+ Sync
+ 'static,
- RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
- + fp_rpc::EthereumRuntimeRPCApi<Block>
- + fp_rpc::ConvertTransactionRuntimeApi<Block>
- + sp_session::SessionKeys<Block>
- + sp_block_builder::BlockBuilder<Block>
- + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
- + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>
- + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>
- + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
- + up_pov_estimate_rpc::PovEstimateApi<Block>
- + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
- + sp_api::Metadata<Block>
- + sp_offchain::OffchainWorkerApi<Block>
- + cumulus_primitives_core::CollectCollationInfo<Block>,
+ RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
+ Runtime: RuntimeInstance,
ExecutorDispatch: NativeExecutionDispatch + 'static,
- BIQ: FnOnce(
- Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
- Arc<FullBackend>,
- &Configuration,
- Option<TelemetryHandle>,
- &TaskManager,
- ) -> Result<
- sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
- sc_service::Error,
- >,
- BIC: FnOnce(
- Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
- Arc<FullBackend>,
- Option<&Registry>,
- Option<TelemetryHandle>,
- &TaskManager,
- Arc<dyn RelayChainInterface>,
- Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,
- Arc<SyncingService<Block>>,
- KeystorePtr,
- bool,
- ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,
{
let parachain_config = prepare_node_config(parachain_config);
- let params =
- new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(¶chain_config, build_import_queue)?;
+ let params = new_partial::<Runtime, RuntimeApi, ExecutorDispatch, _>(
+ ¶chain_config,
+ parachain_build_import_queue,
+ )?;
let OtherPartial {
mut telemetry,
telemetry_worker_handle,
@@ -443,9 +408,9 @@
.await
.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;
- let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);
+ let block_announce_validator =
+ RequireSecondedInBlockAnnounce::new(relay_chain_interface.clone(), para_id);
- let force_authoring = parachain_config.force_authoring;
let validator = parachain_config.role.is_authority();
let prometheus_registry = parachain_config.prometheus_registry().cloned();
let transaction_pool = params.transaction_pool.clone();
@@ -531,7 +496,7 @@
let mut rpc_handle = RpcModule::new(());
- let full_deps = unique_rpc::FullDeps {
+ let full_deps = FullDeps {
client: client.clone(),
runtime_id,
@@ -551,9 +516,9 @@
select_chain,
};
- unique_rpc::create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_handle, full_deps)?;
+ create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_handle, full_deps)?;
- let eth_deps = unique_rpc::EthDeps {
+ let eth_deps = EthDeps {
client,
graph: transaction_pool.pool().clone(),
pool: transaction_pool,
@@ -571,9 +536,18 @@
eth_pubsub_notification_sinks,
overrides,
sync: sync_service.clone(),
+ pending_create_inherent_data_providers: |_, ()| async move { Ok(()) },
};
- unique_rpc::create_eth(
+ create_eth::<
+ _,
+ _,
+ _,
+ _,
+ _,
+ _,
+ DefaultEthConfig<FullClient<RuntimeApi, ExecutorDispatch>>,
+ >(
&mut rpc_handle,
eth_deps,
subscription_task_executor.clone(),
@@ -624,8 +598,25 @@
.overseer_handle()
.map_err(|e| sc_service::Error::Application(Box::new(e)))?;
+ start_relay_chain_tasks(StartRelayChainTasksParams {
+ client: client.clone(),
+ announce_block: announce_block.clone(),
+ para_id,
+ relay_chain_interface: relay_chain_interface.clone(),
+ task_manager: &mut task_manager,
+ da_recovery_profile: if validator {
+ DARecoveryProfile::Collator
+ } else {
+ DARecoveryProfile::FullNode
+ },
+ import_queue: import_queue_service,
+ relay_chain_slot_duration,
+ recovery_handle: Box::new(overseer_handle.clone()),
+ sync_service: sync_service.clone(),
+ })?;
+
if validator {
- let parachain_consensus = build_consensus(
+ start_consensus(
client.clone(),
backend.clone(),
prometheus_registry.as_ref(),
@@ -635,42 +626,12 @@
transaction_pool,
sync_service.clone(),
params.keystore_container.keystore(),
- force_authoring,
- )?;
-
- let spawner = task_manager.spawn_handle();
-
- let params = StartCollatorParams {
- para_id: id,
- block_status: client.clone(),
- announce_block,
- client: client.clone(),
- task_manager: &mut task_manager,
- spawner,
- parachain_consensus,
- import_queue: import_queue_service,
- collator_key: collator_key.expect("Command line arguments do not allow this. qed"),
- relay_chain_interface,
+ overseer_handle,
relay_chain_slot_duration,
- recovery_handle: Box::new(overseer_handle),
- sync_service,
- };
-
- start_collator(params).await?;
- } else {
- let params = StartFullNodeParams {
- client: client.clone(),
+ para_id,
+ collator_key.expect("cli args do not allow this"),
announce_block,
- task_manager: &mut task_manager,
- para_id: id,
- import_queue: import_queue_service,
- relay_chain_interface,
- relay_chain_slot_duration,
- recovery_handle: Box::new(overseer_handle),
- sync_service,
- };
-
- start_full_node(params)?;
+ )?;
}
start_network.start_network();
@@ -679,25 +640,20 @@
}
/// Build the import queue for the the parachain runtime.
-pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(
+pub fn parachain_build_import_queue<Runtime, RuntimeApi, ExecutorDispatch>(
client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
backend: Arc<FullBackend>,
config: &Configuration,
telemetry: Option<TelemetryHandle>,
task_manager: &TaskManager,
-) -> Result<
- sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
- sc_service::Error,
->
+) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error>
where
RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>
+ Send
+ Sync
+ 'static,
- RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
- + sp_block_builder::BlockBuilder<Block>
- + sp_consensus_aura::AuraApi<Block, AuraId>
- + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,
+ RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
+ Runtime: RuntimeInstance,
ExecutorDispatch: NativeExecutionDispatch + 'static,
{
let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
@@ -732,120 +688,81 @@
.map_err(Into::into)
}
-/// Start a normal parachain node.
-pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(
- parachain_config: Configuration,
- polkadot_config: Configuration,
- collator_options: CollatorOptions,
- id: ParaId,
- hwbench: Option<sc_sysinfo::HwBench>,
-) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>
+pub fn start_consensus<ExecutorDispatch, RuntimeApi, Runtime>(
+ client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
+ backend: Arc<FullBackend>,
+ prometheus_registry: Option<&Registry>,
+ telemetry: Option<TelemetryHandle>,
+ task_manager: &TaskManager,
+ relay_chain_interface: Arc<dyn RelayChainInterface>,
+ transaction_pool: Arc<
+ sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
+ >,
+ sync_oracle: Arc<SyncingService<Block>>,
+ keystore: KeystorePtr,
+ overseer_handle: OverseerHandle,
+ relay_chain_slot_duration: Duration,
+ para_id: ParaId,
+ collator_key: CollatorPair,
+ announce_block: Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>,
+) -> Result<(), sc_service::Error>
where
- Runtime: RuntimeInstance + Send + Sync + 'static,
- <Runtime as RuntimeInstance>::CrossAccountId: Serialize,
- for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,
+ ExecutorDispatch: NativeExecutionDispatch + 'static,
RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>
+ Send
+ Sync
+ 'static,
- RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
- + fp_rpc::EthereumRuntimeRPCApi<Block>
- + fp_rpc::ConvertTransactionRuntimeApi<Block>
- + sp_session::SessionKeys<Block>
- + sp_block_builder::BlockBuilder<Block>
- + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
- + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>
- + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>
- + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
- + up_pov_estimate_rpc::PovEstimateApi<Block>
- + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
- + sp_api::Metadata<Block>
- + sp_offchain::OffchainWorkerApi<Block>
- + cumulus_primitives_core::CollectCollationInfo<Block>
- + sp_consensus_aura::AuraApi<Block, AuraId>,
- ExecutorDispatch: NativeExecutionDispatch + 'static,
+ RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
+ Runtime: RuntimeInstance,
{
- start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(
- parachain_config,
- polkadot_config,
- collator_options,
- id,
- parachain_build_import_queue,
- |client,
- backend,
- prometheus_registry,
- telemetry,
- task_manager,
- relay_chain_interface,
- transaction_pool,
- sync_oracle,
- keystore,
- force_authoring| {
- let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
+ let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
- let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(
- task_manager.spawn_handle(),
- client.clone(),
- transaction_pool,
- prometheus_registry,
- telemetry.clone(),
- );
+ let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(
+ task_manager.spawn_handle(),
+ client.clone(),
+ transaction_pool,
+ prometheus_registry,
+ telemetry.clone(),
+ );
+ let proposer = Proposer::new(proposer_factory);
- let block_import = ParachainBlockImport::new(client.clone(), backend);
+ let collator_service = CollatorService::new(
+ client.clone(),
+ Arc::new(task_manager.spawn_handle()),
+ announce_block,
+ client.clone(),
+ );
- Ok(AuraConsensus::build::<
- sp_consensus_aura::sr25519::AuthorityPair,
- _,
- _,
- _,
- _,
- _,
- _,
- >(BuildAuraConsensusParams {
- proposer_factory,
- create_inherent_data_providers: move |_, (relay_parent, validation_data)| {
- let relay_chain_interface = relay_chain_interface.clone();
- async move {
- let parachain_inherent =
- cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(
- relay_parent,
- &relay_chain_interface,
- &validation_data,
- id,
- ).await;
+ let block_import = ParachainBlockImport::new(client.clone(), backend);
- let time = sp_timestamp::InherentDataProvider::from_system_time();
+ let params = BuildAuraConsensusParams {
+ create_inherent_data_providers: move |_, ()| async move { Ok(()) },
+ block_import,
+ para_client: client,
+ #[cfg(feature = "lookahead")]
+ para_backend: backend,
+ para_id,
+ relay_client: relay_chain_interface,
+ sync_oracle,
+ keystore,
+ slot_duration,
+ proposer,
+ collator_service,
+ // With async-baking, we allowed to be both slower (longer authoring) and faster (multiple para blocks per relay block)
+ authoring_duration: Duration::from_millis(500),
+ overseer_handle,
+ #[cfg(feature = "lookahead")]
+ code_hash_provider: || {},
+ collator_key,
+ relay_chain_slot_duration,
+ };
- let slot =
- sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
- *time,
- slot_duration,
- );
-
- let parachain_inherent = parachain_inherent.ok_or_else(|| {
- Box::<dyn std::error::Error + Send + Sync>::from(
- "Failed to create parachain inherent",
- )
- })?;
- Ok((slot, time, parachain_inherent))
- }
- },
- block_import,
- para_client: client,
- backoff_authoring_blocks: Option::<()>::None,
- sync_oracle,
- keystore,
- force_authoring,
- slot_duration,
- // We got around 500ms for proposing
- block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),
- telemetry,
- max_block_proposal_slot_portion: None,
- }))
- },
- hwbench,
- )
- .await
+ task_manager.spawn_essential_handle().spawn(
+ "aura",
+ None,
+ run_aura::<_, AuraAuthorityPair, _, _, _, _, _, _, _>(params),
+ );
+ Ok(())
}
fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(
@@ -854,17 +771,14 @@
config: &Configuration,
_: Option<TelemetryHandle>,
task_manager: &TaskManager,
-) -> Result<
- sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
- sc_service::Error,
->
+) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error>
where
RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>
+ Send
+ Sync
+ 'static,
- RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
- + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,
+ RuntimeApi::RuntimeApi:
+ sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> + sp_api::ApiExt<Block>,
ExecutorDispatch: NativeExecutionDispatch + 'static,
{
Ok(sc_consensus_manual_seal::import_queue(
@@ -881,6 +795,15 @@
pub eth_backend: Arc<fc_db::kv::Backend<Block>>,
}
+struct DefaultEthConfig<C>(PhantomData<C>);
+impl<C> EthConfig<Block, C> for DefaultEthConfig<C>
+where
+ C: StorageProvider<Block, FullBackend> + Sync + Send + 'static,
+{
+ type EstimateGasAdapter = ();
+ type RuntimeStorageOverride = SystemAccountId32StorageOverride<Block, C, FullBackend>;
+}
+
/// Builds a new development service. This service uses instant seal, and mocks
/// the parachain inherent
pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(
@@ -897,28 +820,14 @@
+ Send
+ Sync
+ 'static,
- RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
- + fp_rpc::EthereumRuntimeRPCApi<Block>
- + fp_rpc::ConvertTransactionRuntimeApi<Block>
- + sp_session::SessionKeys<Block>
- + sp_block_builder::BlockBuilder<Block>
- + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
- + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>
- + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>
- + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
- + up_pov_estimate_rpc::PovEstimateApi<Block>
- + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
- + sp_api::Metadata<Block>
- + sp_offchain::OffchainWorkerApi<Block>
- + cumulus_primitives_core::CollectCollationInfo<Block>
- + sp_consensus_aura::AuraApi<Block, AuraId>,
+ RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
ExecutorDispatch: NativeExecutionDispatch + 'static,
{
+ use fc_consensus::FrontierBlockImport;
use sc_consensus_manual_seal::{
run_manual_seal, run_delayed_finalize, EngineCommand, ManualSealParams,
DelayedFinalizeParams,
};
- use fc_consensus::FrontierBlockImport;
let sc_service::PartialComponents {
client,
@@ -935,7 +844,7 @@
eth_backend,
telemetry_worker_handle: _,
},
- } = new_partial::<RuntimeApi, ExecutorDispatch, _>(
+ } = new_partial::<Runtime, RuntimeApi, ExecutorDispatch, _>(
&config,
dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,
)?;
@@ -953,15 +862,6 @@
block_announce_validator_builder: None,
warp_sync_params: None,
})?;
-
- if config.offchain_worker.enabled {
- sc_service::build_offchain_workers(
- &config,
- task_manager.spawn_handle(),
- client.clone(),
- network.clone(),
- );
- }
let collator = config.role.is_authority();
@@ -1141,7 +1041,7 @@
let mut rpc_module = RpcModule::new(());
- let full_deps = unique_rpc::FullDeps {
+ let full_deps = FullDeps {
runtime_id,
#[cfg(feature = "pov-estimate")]
@@ -1161,9 +1061,9 @@
select_chain,
};
- unique_rpc::create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_module, full_deps)?;
+ create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_module, full_deps)?;
- let eth_deps = unique_rpc::EthDeps {
+ let eth_deps = EthDeps {
client,
graph: transaction_pool.pool().clone(),
pool: transaction_pool,
@@ -1181,9 +1081,19 @@
eth_pubsub_notification_sinks,
overrides,
sync: sync_service.clone(),
+ // We don't have any inherents except parachain built-ins, which we can't even extract from inside `run_aura`.
+ pending_create_inherent_data_providers: |_, ()| async move { Ok(()) },
};
- unique_rpc::create_eth(
+ create_eth::<
+ _,
+ _,
+ _,
+ _,
+ _,
+ _,
+ DefaultEthConfig<FullClient<RuntimeApi, ExecutorDispatch>>,
+ >(
&mut rpc_module,
eth_deps,
subscription_task_executor.clone(),
@@ -1241,37 +1151,35 @@
})
}
-pub struct FrontierTaskParams<'a, B: BlockT, C, BE> {
+pub struct FrontierTaskParams<'a, C, B> {
pub task_manager: &'a TaskManager,
pub client: Arc<C>,
- pub substrate_backend: Arc<BE>,
- pub eth_backend: Arc<fc_db::kv::Backend<B>>,
+ pub substrate_backend: Arc<B>,
+ pub eth_backend: Arc<fc_db::kv::Backend<Block>>,
pub eth_filter_pool: Option<FilterPool>,
- pub overrides: Arc<OverrideHandle<B>>,
+ pub overrides: Arc<OverrideHandle<Block>>,
pub fee_history_limit: u64,
pub fee_history_cache: FeeHistoryCache,
pub sync_strategy: SyncStrategy,
pub prometheus_registry: Option<Registry>,
}
-pub fn spawn_frontier_tasks<B, C, BE>(
- params: FrontierTaskParams<B, C, BE>,
- sync: Arc<SyncingService<B>>,
+pub fn spawn_frontier_tasks<C, B>(
+ params: FrontierTaskParams<C, B>,
+ sync: Arc<SyncingService<Block>>,
pubsub_notification_sinks: Arc<
- EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<B>>,
+ EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<Block>>,
>,
-) -> Arc<EthBlockDataCacheTask<B>>
+) -> Arc<EthBlockDataCacheTask<Block>>
where
- C: ProvideRuntimeApi<B> + BlockOf,
- C: HeaderBackend<B> + HeaderMetadata<B, Error = BlockChainError> + 'static,
- C: BlockchainEvents<B> + StorageProvider<B, BE>,
+ C: ProvideRuntimeApi<Block> + BlockOf,
+ C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,
+ C: BlockchainEvents<Block> + StorageProvider<Block, B>,
C: Send + Sync + 'static,
- C::Api: EthereumRuntimeRPCApi<B>,
- C::Api: BlockBuilder<B>,
- B: BlockT<Hash = H256> + Send + Sync + 'static,
- B::Header: HeaderT<Number = u32>,
- BE: Backend<B> + 'static,
- BE::State: StateBackend<BlakeTwo256>,
+ C::Api: EthereumRuntimeRPCApi<Block>,
+ C::Api: BlockBuilder<Block>,
+ B: Backend<Block> + 'static,
+ B::State: StateBackend<BlakeTwo256>,
{
let FrontierTaskParams {
task_manager,
pallets/app-promotion/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/benchmarking.rs
+++ b/pallets/app-promotion/src/benchmarking.rs
@@ -32,7 +32,7 @@
fn set_admin<T>() -> Result<T::AccountId, sp_runtime::DispatchError>
where
T: Config + pallet_unique::Config + pallet_evm_migration::Config,
- T::BlockNumber: From<u32> + Into<u32>,
+ BlockNumberFor<T>: From<u32> + Into<u32>,
BalanceOf<T>: Sum + From<u128>,
{
let pallet_admin = account::<T::AccountId>("admin", 0, SEED);
@@ -53,7 +53,7 @@
benchmarks! {
where_clause{
where T: Config + pallet_unique::Config + pallet_evm_migration::Config ,
- T::BlockNumber: From<u32> + Into<u32>,
+ BlockNumberFor<T>: From<u32> + Into<u32>,
BalanceOf<T>: Sum + From<u128>
}
pallets/app-promotion/src/lib.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -125,11 +125,11 @@
/// In relay blocks.
#[pallet::constant]
- type RecalculationInterval: Get<Self::BlockNumber>;
+ type RecalculationInterval: Get<BlockNumberFor<Self>>;
/// In parachain blocks.
#[pallet::constant]
- type PendingInterval: Get<Self::BlockNumber>;
+ type PendingInterval: Get<BlockNumberFor<Self>>;
/// Rate of return for interval in blocks defined in `RecalculationInterval`.
#[pallet::constant]
@@ -146,7 +146,7 @@
type WeightInfo: WeightInfo;
// The relay block number provider
- type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;
+ type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
/// Events compatible with [`frame_system::Config::Event`].
type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;
@@ -230,9 +230,9 @@
pub type Staked<T: Config> = StorageNMap<
Key = (
Key<Blake2_128Concat, T::AccountId>,
- Key<Twox64Concat, T::BlockNumber>,
+ Key<Twox64Concat, BlockNumberFor<T>>,
),
- Value = (BalanceOf<T>, T::BlockNumber),
+ Value = (BalanceOf<T>, BlockNumberFor<T>),
QueryKind = ValueQuery,
>;
@@ -252,7 +252,7 @@
pub type PendingUnstake<T: Config> = StorageMap<
_,
Twox64Concat,
- T::BlockNumber,
+ BlockNumberFor<T>,
BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,
ValueQuery,
>;
@@ -262,16 +262,16 @@
#[pallet::storage]
#[pallet::getter(fn get_next_calculated_record)]
pub type PreviousCalculatedRecord<T: Config> =
- StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;
+ StorageValue<Value = (T::AccountId, BlockNumberFor<T>), QueryKind = OptionQuery>;
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize
/// implies the execution of a strictly limited number of relatively lightweight operations.
/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.
- fn on_initialize(current_block_number: T::BlockNumber) -> Weight
+ fn on_initialize(current_block_number: BlockNumberFor<T>) -> Weight
where
- <T as frame_system::Config>::BlockNumber: From<u32>,
+ BlockNumberFor<T>: From<u32>,
{
if T::IsMaintenanceModeEnabled::get() {
return T::DbWeight::get().reads_writes(1, 0);
@@ -302,7 +302,7 @@
#[pallet::call]
impl<T: Config> Pallet<T>
where
- T::BlockNumber: From<u32> + Into<u32>,
+ BlockNumberFor<T>: From<u32> + Into<u32>,
<<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,
{
/// Sets an address as the the admin.
@@ -369,7 +369,7 @@
// Calculation of the number of recalculation periods,
// after how much the first interest calculation should be performed for the stake
- let recalculate_after_interval: T::BlockNumber =
+ let recalculate_after_interval: BlockNumberFor<T> =
if block_number % config.recalculation_interval == 0u32.into() {
1u32.into()
} else {
@@ -705,7 +705,7 @@
#[pallet::weight(<T as Config>::WeightInfo::on_initialize(PENDING_LIMIT_PER_BLOCK*pending_blocks.len() as u32))]
pub fn force_unstake(
origin: OriginFor<T>,
- pending_blocks: Vec<T::BlockNumber>,
+ pending_blocks: Vec<BlockNumberFor<T>>,
) -> DispatchResult {
ensure_root(origin)?;
@@ -917,7 +917,7 @@
/// - `staker`: staker account.
pub fn total_staked_by_id_per_block(
staker: impl EncodeLike<T::AccountId>,
- ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {
+ ) -> Option<Vec<(BlockNumberFor<T>, BalanceOf<T>)>> {
let mut staked = Staked::<T>::iter_prefix((staker,))
.map(|(block, (amount, _))| (block, amount))
.collect::<Vec<_>>();
@@ -944,14 +944,14 @@
/// - `staker`: staker account.
pub fn cross_id_total_staked_per_block(
staker: T::CrossAccountId,
- ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {
+ ) -> Vec<(BlockNumberFor<T>, BalanceOf<T>)> {
Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()
}
fn recalculate_and_insert_stake(
staker: &T::AccountId,
- staked_block: T::BlockNumber,
- next_recalc_block: T::BlockNumber,
+ staked_block: BlockNumberFor<T>,
+ next_recalc_block: BlockNumberFor<T>,
base: BalanceOf<T>,
iters: u32,
income_acc: &mut BalanceOf<T>,
@@ -979,9 +979,9 @@
/// Get relay block number rounded down to multiples of config.recalculation_interval.
/// We need it to reward stakers in integer parts of recalculation_interval
fn get_current_recalc_block(
- current_relay_block: T::BlockNumber,
+ current_relay_block: BlockNumberFor<T>,
config: &PalletConfiguration<T>,
- ) -> T::BlockNumber {
+ ) -> BlockNumberFor<T> {
(current_relay_block / config.recalculation_interval) * config.recalculation_interval
}
@@ -1028,7 +1028,7 @@
/// - `staker`: staker account.
pub fn cross_id_pending_unstake_per_block(
staker: T::CrossAccountId,
- ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {
+ ) -> Vec<(BlockNumberFor<T>, BalanceOf<T>)> {
let mut unsorted_res = vec![];
PendingUnstake::<T>::iter().for_each(|(block, pendings)| {
pendings.into_iter().for_each(|(id, amount)| {
pallets/app-promotion/src/types.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/types.rs
+++ b/pallets/app-promotion/src/types.rs
@@ -114,9 +114,9 @@
}
pub(crate) struct PalletConfiguration<T: crate::Config> {
/// In relay blocks.
- pub recalculation_interval: T::BlockNumber,
+ pub recalculation_interval: BlockNumberFor<T>,
/// In parachain blocks.
- pub pending_interval: T::BlockNumber,
+ pub pending_interval: BlockNumberFor<T>,
/// Value for `RecalculationInterval` based on 0.05% per 24h.
pub interval_income: Perbill,
/// Maximum allowable number of stakers calculated per call of the `app-promotion::PayoutStakers` extrinsic.
pallets/collator-selection/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/collator-selection/src/benchmarking.rs
+++ b/pallets/collator-selection/src/benchmarking.rs
@@ -51,6 +51,10 @@
use pallet_session::{self as session, SessionManager};
use sp_std::prelude::*;
+use super::*;
+#[allow(unused)]
+use crate::{BalanceOf, Pallet as CollatorSelection};
+
const SEED: u32 = 0;
// TODO: remove if this is given in substrate commit.
@@ -317,7 +321,7 @@
balance_unit::<T>() * 4u32.into(),
);
let author = account("author", 0, SEED);
- let new_block: T::BlockNumber = 10u32.into();
+ let new_block: BlockNumberFor<T>= 10u32.into();
frame_system::Pallet::<T>::set_block_number(new_block);
assert!(T::Currency::balance(&author) == 0u32.into());
@@ -338,7 +342,7 @@
register_validators::<T>(c);
register_candidates::<T>(c);
- let new_block: T::BlockNumber = 1800u32.into();
+ let new_block: BlockNumberFor<T>= 1800u32.into();
let zero_block: T::BlockNumber = 0u32.into();
let candidates = <Candidates<T>>::get();
pallets/collator-selection/src/lib.rsdiffbeforeafterboth--- a/pallets/collator-selection/src/lib.rs
+++ b/pallets/collator-selection/src/lib.rs
@@ -131,8 +131,11 @@
pub trait Config: frame_system::Config {
/// Overarching event type.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
+ /// Overarching hold reason.
+ type RuntimeHoldReason: From<HoldReason>;
+
type Currency: Mutate<Self::AccountId>
- + MutateHold<Self::AccountId>
+ + MutateHold<Self::AccountId, Reason = Self::RuntimeHoldReason>
+ BalancedHold<Self::AccountId>;
/// Origin that can dictate updating parameters of this pallet.
@@ -164,14 +167,17 @@
/// The weight information of this pallet.
type WeightInfo: WeightInfo;
- #[pallet::constant]
- type LicenceBondIdentifier: Get<<Self::Currency as InspectHold<Self::AccountId>>::Reason>;
-
type DesiredCollators: Get<u32>;
type LicenseBond: Get<BalanceOf<Self>>;
- type KickThreshold: Get<Self::BlockNumber>;
+ type KickThreshold: Get<BlockNumberFor<Self>>;
+ }
+
+ #[pallet::composite_enum]
+ pub enum HoldReason {
+ /// The funds are held as the license bond.
+ LicenseBond,
}
#[pallet::pallet]
@@ -199,14 +205,13 @@
#[pallet::storage]
#[pallet::getter(fn last_authored_block)]
pub type LastAuthoredBlock<T: Config> =
- StorageMap<_, Twox64Concat, T::AccountId, T::BlockNumber, ValueQuery>;
+ StorageMap<_, Twox64Concat, T::AccountId, BlockNumberFor<T>, ValueQuery>;
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub invulnerables: Vec<T::AccountId>,
}
- #[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self {
@@ -216,12 +221,11 @@
}
#[pallet::genesis_build]
- impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
+ impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
- let duplicate_invulnerables = self
- .invulnerables
- .iter()
- .collect::<std::collections::BTreeSet<_>>();
+ use sp_std::collections::btree_set::BTreeSet;
+
+ let duplicate_invulnerables = self.invulnerables.iter().collect::<BTreeSet<_>>();
assert!(
duplicate_invulnerables.len() == self.invulnerables.len(),
"duplicate invulnerables in genesis."
@@ -375,7 +379,7 @@
let deposit = T::LicenseBond::get();
- T::Currency::hold(&T::LicenceBondIdentifier::get(), &who, deposit)?;
+ T::Currency::hold(&HoldReason::LicenseBond.into(), &who, deposit)?;
LicenseDepositOf::<T>::insert(who.clone(), deposit);
Self::deposit_event(Event::LicenseObtained {
@@ -538,7 +542,7 @@
let remaining = deposit - slashed;
let (imbalance, _) =
- T::Currency::slash(&T::LicenceBondIdentifier::get(), who, slashed);
+ T::Currency::slash(&HoldReason::LicenseBond.into(), who, slashed);
deposit_returned = remaining;
T::Currency::resolve(&T::TreasuryAccountId::get(), imbalance)
@@ -548,7 +552,7 @@
}
T::Currency::release(
- &T::LicenceBondIdentifier::get(),
+ &HoldReason::LicenseBond.into(),
who,
deposit_returned,
Precision::Exact,
@@ -608,7 +612,7 @@
/// Keep track of number of authored blocks per authority, uncles are counted as well since
/// they're a valid proof of being online.
impl<T: Config + pallet_authorship::Config>
- pallet_authorship::EventHandler<T::AccountId, T::BlockNumber> for Pallet<T>
+ pallet_authorship::EventHandler<T::AccountId, BlockNumberFor<T>> for Pallet<T>
{
fn note_author(author: T::AccountId) {
let pot = Self::account_id();
pallets/collator-selection/src/mock.rsdiffbeforeafterboth--- a/pallets/collator-selection/src/mock.rs
+++ b/pallets/collator-selection/src/mock.rs
@@ -51,18 +51,14 @@
// Configure a mock runtime to test the pallet.
frame_support::construct_runtime!(
- pub enum Test where
- Block = Block,
- NodeBlock = Block,
- UncheckedExtrinsic = UncheckedExtrinsic,
- {
- System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
- Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
- Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>},
- Aura: pallet_aura::{Pallet, Storage, Config<T>},
- Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
- CollatorSelection: collator_selection::{Pallet, Call, Storage, Event<T>},
- Authorship: pallet_authorship::{Pallet, Storage},
+ pub enum Test {
+ System: frame_system,
+ Timestamp: pallet_timestamp,
+ Session: pallet_session,
+ Aura: pallet_aura,
+ Balances: pallet_balances,
+ CollatorSelection: collator_selection,
+ Authorship: pallet_authorship,
}
);
@@ -78,13 +74,11 @@
type DbWeight = ();
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
- type Index = u64;
- type BlockNumber = u64;
+ type Nonce = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
- type Header = Header;
type RuntimeEvent = RuntimeEvent;
type BlockHashCount = BlockHashCount;
type Version = ();
@@ -115,7 +109,6 @@
type MaxLocks = ();
type MaxReserves = MaxReserves;
type ReserveIdentifier = [u8; 8];
- type HoldIdentifier = [u8; 16];
type FreezeIdentifier = [u8; 16];
type MaxHolds = MaxHolds;
type MaxFreezes = MaxFreezes;
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -463,7 +463,6 @@
#[pallet::genesis_config]
pub struct GenesisConfig<T>(PhantomData<T>);
- #[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self(Default::default())
@@ -471,7 +470,7 @@
}
#[pallet::genesis_build]
- impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
+ impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
StorageVersion::new(1).put::<Pallet<T>>();
}
pallets/configuration/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/configuration/src/benchmarking.rs
+++ b/pallets/configuration/src/benchmarking.rs
@@ -52,7 +52,7 @@
}
set_app_promotion_configuration_override {
- let configuration: AppPromotionConfiguration<T::BlockNumber> = Default::default();
+ let configuration: AppPromotionConfiguration<BlockNumberFor<T>> = Default::default();
}: {
assert_ok!(
<Pallet<T>>::set_app_promotion_configuration_override(RawOrigin::Root.into(), configuration)
@@ -82,7 +82,7 @@
}
set_collator_selection_kick_threshold {
- let threshold: Option<T::BlockNumber> = Some(900u32.into());
+ let threshold: Option<BlockNumberFor<T>> = Some(900u32.into());
}: {
assert_ok!(
<Pallet<T>>::set_collator_selection_kick_threshold(RawOrigin::Root.into(), threshold)
pallets/configuration/src/lib.rsdiffbeforeafterboth--- a/pallets/configuration/src/lib.rs
+++ b/pallets/configuration/src/lib.rs
@@ -80,14 +80,14 @@
#[pallet::constant]
type AppPromotionDailyRate: Get<Perbill>;
#[pallet::constant]
- type DayRelayBlocks: Get<Self::BlockNumber>;
+ type DayRelayBlocks: Get<BlockNumberFor<Self>>;
#[pallet::constant]
type DefaultCollatorSelectionMaxCollators: Get<u32>;
#[pallet::constant]
type DefaultCollatorSelectionLicenseBond: Get<Self::Balance>;
#[pallet::constant]
- type DefaultCollatorSelectionKickThreshold: Get<Self::BlockNumber>;
+ type DefaultCollatorSelectionKickThreshold: Get<BlockNumberFor<Self>>;
/// The weight information of this pallet.
type WeightInfo: WeightInfo;
@@ -103,7 +103,7 @@
bond_cost: Option<T::Balance>,
},
NewCollatorKickThreshold {
- length_in_blocks: Option<T::BlockNumber>,
+ length_in_blocks: Option<BlockNumberFor<T>>,
},
}
@@ -134,7 +134,6 @@
#[pallet::genesis_config]
pub struct GenesisConfig<T>(PhantomData<T>);
- #[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self(Default::default())
@@ -142,7 +141,7 @@
}
#[pallet::genesis_build]
- impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
+ impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
update_base_fee::<T>();
}
@@ -166,7 +165,7 @@
#[pallet::storage]
pub type AppPromomotionConfigurationOverride<T: Config> =
- StorageValue<Value = AppPromotionConfiguration<T::BlockNumber>, QueryKind = ValueQuery>;
+ StorageValue<Value = AppPromotionConfiguration<BlockNumberFor<T>>, QueryKind = ValueQuery>;
#[pallet::storage]
pub type CollatorSelectionDesiredCollatorsOverride<T: Config> = StorageValue<
@@ -184,7 +183,7 @@
#[pallet::storage]
pub type CollatorSelectionKickThresholdOverride<T: Config> = StorageValue<
- Value = T::BlockNumber,
+ Value = BlockNumberFor<T>,
QueryKind = ValueQuery,
OnEmpty = T::DefaultCollatorSelectionKickThreshold,
>;
@@ -228,7 +227,7 @@
#[pallet::weight(T::WeightInfo::set_app_promotion_configuration_override())]
pub fn set_app_promotion_configuration_override(
origin: OriginFor<T>,
- mut configuration: AppPromotionConfiguration<T::BlockNumber>,
+ mut configuration: AppPromotionConfiguration<BlockNumberFor<T>>,
) -> DispatchResult {
ensure_root(origin)?;
if configuration.interval_income.is_some() {
@@ -287,7 +286,7 @@
#[pallet::weight(T::WeightInfo::set_collator_selection_kick_threshold())]
pub fn set_collator_selection_kick_threshold(
origin: OriginFor<T>,
- threshold: Option<T::BlockNumber>,
+ threshold: Option<BlockNumberFor<T>>,
) -> DispatchResult {
ensure_root(origin)?;
if let Some(threshold) = threshold {
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -422,7 +422,7 @@
{
return None;
}
- let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+ let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {
let limit = <SponsoringRateLimit<T>>::get(contract_address);
pallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/lib.rs
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -53,7 +53,7 @@
/// In case of enabled sponsoring, but no sponsoring rate limit set,
/// this value will be used implicitly
- type DefaultSponsoringRateLimit: Get<Self::BlockNumber>;
+ type DefaultSponsoringRateLimit: Get<BlockNumberFor<Self>>;
}
#[pallet::error]
@@ -115,7 +115,7 @@
pub(super) type SponsoringRateLimit<T: Config> = StorageMap<
Hasher = Twox128,
Key = H160,
- Value = T::BlockNumber,
+ Value = BlockNumberFor<T>,
QueryKind = ValueQuery,
OnEmpty = T::DefaultSponsoringRateLimit,
>;
@@ -139,7 +139,7 @@
Key1 = H160,
Hasher2 = Twox128,
Key2 = H160,
- Value = T::BlockNumber,
+ Value = BlockNumberFor<T>,
QueryKind = OptionQuery,
>;
@@ -393,7 +393,7 @@
}
/// Set duration between two sponsored contract calls
- pub fn set_sponsoring_rate_limit(contract: H160, rate_limit: T::BlockNumber) {
+ pub fn set_sponsoring_rate_limit(contract: H160, rate_limit: BlockNumberFor<T>) {
<SponsoringRateLimit<T>>::insert(contract, rate_limit);
}
pallets/evm-migration/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/evm-migration/src/benchmarking.rs
+++ b/pallets/evm-migration/src/benchmarking.rs
@@ -23,7 +23,7 @@
use sp_std::{vec::Vec, vec};
benchmarks! {
- where_clause { where <T as Config>::RuntimeEvent: codec::Encode }
+ where_clause { where <T as Config>::RuntimeEvent: parity_scale_codec::Encode }
begin {
}: _(RawOrigin::Root, H160::default())
@@ -59,7 +59,7 @@
insert_events {
let b in 0..200;
- use codec::Encode;
+ use parity_scale_codec::Encode;
let logs = (0..b).map(|_| <T as Config>::RuntimeEvent::from(crate::Event::<T>::TestEvent).encode()).collect::<Vec<_>>();
}: _(RawOrigin::Root, logs)
}
pallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/impl_fungibles.rs
+++ b/pallets/foreign-assets/src/impl_fungibles.rs
@@ -30,30 +30,30 @@
impl<T: Config> fungibles::Inspect<<T as SystemConfig>::AccountId> for Pallet<T>
where
- T: orml_tokens::Config<CurrencyId = AssetIds>,
+ T: orml_tokens::Config<CurrencyId = AssetId>,
BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
<T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
<T as orml_tokens::Config>::Balance: From<BalanceOf<T>>,
{
- type AssetId = AssetIds;
+ type AssetId = AssetId;
type Balance = BalanceOf<T>;
fn total_issuance(asset: Self::AssetId) -> Self::Balance {
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible total_issuance");
match asset {
- AssetIds::NativeAssetId(NativeCurrency::Here) => {
+ AssetId::NativeAssetId(NativeCurrency::Here) => {
<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::total_issuance()
.into()
}
- AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+ AssetId::NativeAssetId(NativeCurrency::Parent) => {
<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::total_issuance(
- AssetIds::NativeAssetId(NativeCurrency::Parent),
+ AssetId::NativeAssetId(NativeCurrency::Parent),
)
.into()
}
- AssetIds::ForeignAssetId(fid) => {
+ AssetId::ForeignAssetId(fid) => {
let target_collection_id = match <AssetBinding<T>>::get(fid) {
Some(v) => v,
None => return Zero::zero(),
@@ -71,38 +71,36 @@
fn minimum_balance(asset: Self::AssetId) -> Self::Balance {
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible minimum_balance");
match asset {
- AssetIds::NativeAssetId(NativeCurrency::Here) => {
+ AssetId::NativeAssetId(NativeCurrency::Here) => {
<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::minimum_balance()
.into()
}
- AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+ AssetId::NativeAssetId(NativeCurrency::Parent) => {
<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::minimum_balance(
- AssetIds::NativeAssetId(NativeCurrency::Parent),
+ AssetId::NativeAssetId(NativeCurrency::Parent),
)
.into()
}
- AssetIds::ForeignAssetId(fid) => {
- AssetMetadatas::<T>::get(AssetIds::ForeignAssetId(fid))
- .map(|x| x.minimal_balance)
- .unwrap_or_else(Zero::zero)
- }
+ AssetId::ForeignAssetId(fid) => AssetMetadatas::<T>::get(AssetId::ForeignAssetId(fid))
+ .map(|x| x.minimal_balance)
+ .unwrap_or_else(Zero::zero),
}
}
fn balance(asset: Self::AssetId, who: &<T as SystemConfig>::AccountId) -> Self::Balance {
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible balance");
match asset {
- AssetIds::NativeAssetId(NativeCurrency::Here) => {
+ AssetId::NativeAssetId(NativeCurrency::Here) => {
<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::balance(who).into()
}
- AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+ AssetId::NativeAssetId(NativeCurrency::Parent) => {
<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::balance(
- AssetIds::NativeAssetId(NativeCurrency::Parent),
+ AssetId::NativeAssetId(NativeCurrency::Parent),
who,
)
.into()
}
- AssetIds::ForeignAssetId(fid) => {
+ AssetId::ForeignAssetId(fid) => {
let target_collection_id = match <AssetBinding<T>>::get(fid) {
Some(v) => v,
None => return Zero::zero(),
@@ -133,7 +131,7 @@
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible reducible_balance");
match asset {
- AssetIds::NativeAssetId(NativeCurrency::Here) => {
+ AssetId::NativeAssetId(NativeCurrency::Here) => {
<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::reducible_balance(
who,
preservation,
@@ -141,9 +139,9 @@
)
.into()
}
- AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+ AssetId::NativeAssetId(NativeCurrency::Parent) => {
<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::reducible_balance(
- AssetIds::NativeAssetId(NativeCurrency::Parent),
+ AssetId::NativeAssetId(NativeCurrency::Parent),
who,
preservation,
fortitude,
@@ -163,16 +161,16 @@
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible can_deposit");
match asset {
- AssetIds::NativeAssetId(NativeCurrency::Here) => {
+ AssetId::NativeAssetId(NativeCurrency::Here) => {
<pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::can_deposit(
who,
amount.into(),
provenance,
)
}
- AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+ AssetId::NativeAssetId(NativeCurrency::Parent) => {
<orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_deposit(
- AssetIds::NativeAssetId(NativeCurrency::Parent),
+ AssetId::NativeAssetId(NativeCurrency::Parent),
who,
amount.into(),
provenance,
@@ -219,7 +217,7 @@
};
match asset {
- AssetIds::NativeAssetId(NativeCurrency::Here) => {
+ AssetId::NativeAssetId(NativeCurrency::Here) => {
let this_amount: <T as pallet_balances::Config>::Balance = match value.try_into() {
Ok(val) => val,
Err(_) => {
@@ -240,7 +238,7 @@
_ => WithdrawConsequence::BalanceLow,
}
}
- AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+ AssetId::NativeAssetId(NativeCurrency::Parent) => {
let parent_amount: <T as orml_tokens::Config>::Balance = match value.try_into() {
Ok(val) => val,
Err(_) => {
@@ -248,7 +246,7 @@
}
};
match <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_withdraw(
- AssetIds::NativeAssetId(NativeCurrency::Parent),
+ AssetId::NativeAssetId(NativeCurrency::Parent),
who,
parent_amount,
) {
@@ -269,17 +267,17 @@
}
}
- fn asset_exists(asset: AssetIds) -> bool {
+ fn asset_exists(asset: AssetId) -> bool {
match asset {
- AssetIds::NativeAssetId(_) => true,
- AssetIds::ForeignAssetId(fid) => <AssetBinding<T>>::contains_key(fid),
+ AssetId::NativeAssetId(_) => true,
+ AssetId::ForeignAssetId(fid) => <AssetBinding<T>>::contains_key(fid),
}
}
}
impl<T: Config> fungibles::Mutate<<T as SystemConfig>::AccountId> for Pallet<T>
where
- T: orml_tokens::Config<CurrencyId = AssetIds>,
+ T: orml_tokens::Config<CurrencyId = AssetId>,
BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
<T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
@@ -295,22 +293,22 @@
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible mint_into {:?}", asset);
match asset {
- AssetIds::NativeAssetId(NativeCurrency::Here) => {
+ AssetId::NativeAssetId(NativeCurrency::Here) => {
<pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::mint_into(
who,
amount.into(),
)
.map(Into::into)
}
- AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+ AssetId::NativeAssetId(NativeCurrency::Parent) => {
<orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::mint_into(
- AssetIds::NativeAssetId(NativeCurrency::Parent),
+ AssetId::NativeAssetId(NativeCurrency::Parent),
who,
amount.into(),
)
.map(Into::into)
}
- AssetIds::ForeignAssetId(fid) => {
+ AssetId::ForeignAssetId(fid) => {
let target_collection_id = match <AssetBinding<T>>::get(fid) {
Some(v) => v,
None => {
@@ -349,7 +347,7 @@
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible burn_from");
match asset {
- AssetIds::NativeAssetId(NativeCurrency::Here) => {
+ AssetId::NativeAssetId(NativeCurrency::Here) => {
<pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::burn_from(
who,
amount.into(),
@@ -358,9 +356,9 @@
)
.map(Into::into)
}
- AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+ AssetId::NativeAssetId(NativeCurrency::Parent) => {
<orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::burn_from(
- AssetIds::NativeAssetId(NativeCurrency::Parent),
+ AssetId::NativeAssetId(NativeCurrency::Parent),
who,
amount.into(),
precision,
@@ -368,7 +366,7 @@
)
.map(Into::into)
}
- AssetIds::ForeignAssetId(fid) => {
+ AssetId::ForeignAssetId(fid) => {
let target_collection_id = match <AssetBinding<T>>::get(fid) {
Some(v) => v,
None => {
@@ -401,7 +399,7 @@
log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible transfer");
match asset {
- AssetIds::NativeAssetId(NativeCurrency::Here) => {
+ AssetId::NativeAssetId(NativeCurrency::Here) => {
match <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::transfer(
source,
dest,
@@ -414,9 +412,9 @@
)),
}
}
- AssetIds::NativeAssetId(NativeCurrency::Parent) => {
+ AssetId::NativeAssetId(NativeCurrency::Parent) => {
match <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::transfer(
- AssetIds::NativeAssetId(NativeCurrency::Parent),
+ AssetId::NativeAssetId(NativeCurrency::Parent),
source,
dest,
amount.into(),
@@ -426,7 +424,7 @@
Err(e) => Err(e),
}
}
- AssetIds::ForeignAssetId(fid) => {
+ AssetId::ForeignAssetId(fid) => {
let target_collection_id = match <AssetBinding<T>>::get(fid) {
Some(v) => v,
None => {
@@ -479,7 +477,7 @@
impl<T: Config> fungibles::Unbalanced<<T as SystemConfig>::AccountId> for Pallet<T>
where
- T: orml_tokens::Config<CurrencyId = AssetIds>,
+ T: orml_tokens::Config<CurrencyId = AssetId>,
BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
<T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
pallets/foreign-assets/src/lib.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -79,8 +79,9 @@
Encode,
Decode,
TypeInfo,
+ Serialize,
+ Deserialize,
)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum NativeCurrency {
Here = 0,
Parent = 1,
@@ -98,9 +99,10 @@
Encode,
Decode,
TypeInfo,
+ Serialize,
+ Deserialize,
)]
-#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
-pub enum AssetIds {
+pub enum AssetId {
ForeignAssetId(ForeignAssetId),
NativeAssetId(NativeCurrency),
}
@@ -109,17 +111,17 @@
fn try_as_foreign(asset: T) -> Option<F>;
}
-impl TryAsForeign<AssetIds, ForeignAssetId> for AssetIds {
- fn try_as_foreign(asset: AssetIds) -> Option<ForeignAssetId> {
+impl TryAsForeign<AssetId, ForeignAssetId> for AssetId {
+ fn try_as_foreign(asset: AssetId) -> Option<ForeignAssetId> {
match asset {
- AssetIds::ForeignAssetId(id) => Some(id),
+ Self::ForeignAssetId(id) => Some(id),
_ => None,
}
}
}
pub type ForeignAssetId = u32;
-pub type CurrencyId = AssetIds;
+pub type CurrencyId = AssetId;
mod impl_fungibles;
pub mod weights;
@@ -151,7 +153,7 @@
{
fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata<BalanceOf<T>>> {
log::trace!(target: "fassets::asset_metadatas", "call");
- Pallet::<T>::asset_metadatas(AssetIds::ForeignAssetId(foreign_asset_id))
+ Pallet::<T>::asset_metadatas(AssetId::ForeignAssetId(foreign_asset_id))
}
fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation> {
@@ -161,7 +163,7 @@
fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {
log::trace!(target: "fassets::get_currency_id", "call");
- Pallet::<T>::location_to_currency_ids(multi_location).map(AssetIds::ForeignAssetId)
+ Pallet::<T>::location_to_currency_ids(multi_location).map(AssetId::ForeignAssetId)
}
}
@@ -231,12 +233,12 @@
},
/// The asset registered.
AssetRegistered {
- asset_id: AssetIds,
+ asset_id: AssetId,
metadata: AssetMetadata<BalanceOf<T>>,
},
/// The asset updated.
AssetUpdated {
- asset_id: AssetIds,
+ asset_id: AssetId,
metadata: AssetMetadata<BalanceOf<T>>,
},
}
@@ -253,7 +255,7 @@
#[pallet::storage]
#[pallet::getter(fn foreign_asset_locations)]
pub type ForeignAssetLocations<T: Config> =
- StorageMap<_, Twox64Concat, ForeignAssetId, xcm::v3::MultiLocation, OptionQuery>;
+ StorageMap<_, Twox64Concat, ForeignAssetId, staging_xcm::v3::MultiLocation, OptionQuery>;
/// The storages for CurrencyIds.
///
@@ -261,7 +263,7 @@
#[pallet::storage]
#[pallet::getter(fn location_to_currency_ids)]
pub type LocationToCurrencyIds<T: Config> =
- StorageMap<_, Twox64Concat, xcm::v3::MultiLocation, ForeignAssetId, OptionQuery>;
+ StorageMap<_, Twox64Concat, staging_xcm::v3::MultiLocation, ForeignAssetId, OptionQuery>;
/// The storages for AssetMetadatas.
///
@@ -269,7 +271,7 @@
#[pallet::storage]
#[pallet::getter(fn asset_metadatas)]
pub type AssetMetadatas<T: Config> =
- StorageMap<_, Twox64Concat, AssetIds, AssetMetadata<BalanceOf<T>>, OptionQuery>;
+ StorageMap<_, Twox64Concat, AssetId, AssetMetadata<BalanceOf<T>>, OptionQuery>;
/// The storages for assets to fungible collection binding
///
@@ -381,7 +383,7 @@
*maybe_location = Some(*location);
AssetMetadatas::<T>::try_mutate(
- AssetIds::ForeignAssetId(foreign_asset_id),
+ AssetId::ForeignAssetId(foreign_asset_id),
|maybe_asset_metadatas| -> DispatchResult {
ensure!(maybe_asset_metadatas.is_none(), Error::<T>::AssetIdExisted);
*maybe_asset_metadatas = Some(metadata.clone());
@@ -413,7 +415,7 @@
.ok_or(Error::<T>::AssetIdNotExists)?;
AssetMetadatas::<T>::try_mutate(
- AssetIds::ForeignAssetId(foreign_asset_id),
+ AssetId::ForeignAssetId(foreign_asset_id),
|maybe_asset_metadatas| -> DispatchResult {
ensure!(
maybe_asset_metadatas.is_some(),
@@ -450,7 +452,7 @@
traits::{
fungibles::Balanced, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT,
},
- weights::{WeightToFeePolynomial, WeightToFee},
+ weights::{WeightToFee, WeightToFeePolynomial},
};
pub struct FreeForAll<
@@ -477,7 +479,12 @@
Self(Weight::default(), Zero::zero(), PhantomData)
}
- fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {
+ fn buy_weight(
+ &mut self,
+ weight: Weight,
+ payment: Assets,
+ _xcm: &XcmContext,
+ ) -> Result<Assets, XcmError> {
log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);
Ok(payment)
}
pallets/identity/src/tests.rsdiffbeforeafterboth--- a/pallets/identity/src/tests.rs
+++ b/pallets/identity/src/tests.rs
@@ -54,14 +54,10 @@
type Block = frame_system::mocking::MockBlock<Test>;
frame_support::construct_runtime!(
- pub enum Test where
- Block = Block,
- NodeBlock = Block,
- UncheckedExtrinsic = UncheckedExtrinsic,
- {
- System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
- Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
- Identity: pallet_identity::{Pallet, Call, Storage, Event<T>},
+ pub enum Test {
+ System: frame_system,
+ Balances: pallet_balances,
+ Identity: pallet_identity,
}
);
@@ -71,17 +67,16 @@
}
impl frame_system::Config for Test {
type BaseCallFilter = frame_support::traits::Everything;
+ type Block = Block;
type BlockWeights = ();
type BlockLength = ();
type RuntimeOrigin = RuntimeOrigin;
- type Index = u64;
- type BlockNumber = u64;
+ type Nonce = u64;
type Hash = H256;
type RuntimeCall = RuntimeCall;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
- type Header = Header;
type RuntimeEvent = RuntimeEvent;
type BlockHashCount = ConstU64<250>;
type DbWeight = ();
@@ -106,7 +101,7 @@
type MaxReserves = ();
type ReserveIdentifier = [u8; 8];
type WeightInfo = ();
- type HoldIdentifier = ();
+ type RuntimeHoldReason = RuntimeHoldReason;
type FreezeIdentifier = ();
type MaxHolds = ();
type MaxFreezes = ();
@@ -139,8 +134,8 @@
}
pub fn new_test_ext() -> sp_io::TestExternalities {
- let mut t = frame_system::GenesisConfig::default()
- .build_storage::<Test>()
+ let mut t = <frame_system::GenesisConfig<Test>>::default()
+ .build_storage()
.unwrap();
pallet_balances::GenesisConfig::<Test> {
balances: vec![(1, 10), (2, 10), (3, 10), (10, 100), (20, 100), (30, 100)],
pallets/identity/src/types.rsdiffbeforeafterboth--- a/pallets/identity/src/types.rs
+++ b/pallets/identity/src/types.rs
@@ -77,7 +77,9 @@
}
impl Decode for Data {
- fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
+ fn decode<I: parity_scale_codec::Input>(
+ input: &mut I,
+ ) -> sp_std::result::Result<Self, parity_scale_codec::Error> {
let b = input.read_byte()?;
Ok(match b {
0 => Data::None,
@@ -92,7 +94,7 @@
35 => Data::Sha256(<[u8; 32]>::decode(input)?),
36 => Data::Keccak256(<[u8; 32]>::decode(input)?),
37 => Data::ShaThree256(<[u8; 32]>::decode(input)?),
- _ => return Err(codec::Error::from("invalid leading byte")),
+ _ => return Err(parity_scale_codec::Error::from("invalid leading byte")),
})
}
}
@@ -114,7 +116,7 @@
}
}
}
-impl codec::EncodeLike for Data {}
+impl parity_scale_codec::EncodeLike for Data {}
/// Add a Raw variant with the given index and a fixed sized byte array
macro_rules! data_raw_variants {
@@ -284,7 +286,9 @@
}
}
impl Decode for IdentityFields {
- fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
+ fn decode<I: parity_scale_codec::Input>(
+ input: &mut I,
+ ) -> sp_std::result::Result<Self, parity_scale_codec::Error> {
let field = u64::decode(input)?;
Ok(Self(
<BitFlags<IdentityField>>::from_bits(field).map_err(|_| "invalid value")?,
@@ -445,7 +449,9 @@
MaxAdditionalFields: Get<u32>,
> Decode for Registration<Balance, MaxJudgements, MaxAdditionalFields>
{
- fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
+ fn decode<I: parity_scale_codec::Input>(
+ input: &mut I,
+ ) -> sp_std::result::Result<Self, parity_scale_codec::Error> {
let (judgements, deposit, info) = Decode::decode(&mut AppendZerosInput::new(input))?;
Ok(Self {
judgements,
pallets/inflation/src/lib.rsdiffbeforeafterboth--- a/pallets/inflation/src/lib.rs
+++ b/pallets/inflation/src/lib.rs
@@ -73,11 +73,11 @@
type TreasuryAccountId: Get<Self::AccountId>;
// The block number provider
- type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;
+ type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
/// Number of blocks that pass between treasury balance updates due to inflation
#[pallet::constant]
- type InflationBlockInterval: Get<Self::BlockNumber>;
+ type InflationBlockInterval: Get<BlockNumberFor<Self>>;
}
#[pallet::pallet]
@@ -95,22 +95,23 @@
/// Next target (relay) block when inflation will be applied
#[pallet::storage]
pub type NextInflationBlock<T: Config> =
- StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
+ StorageValue<Value = BlockNumberFor<T>, QueryKind = ValueQuery>;
/// Next target (relay) block when inflation is recalculated
#[pallet::storage]
pub type NextRecalculationBlock<T: Config> =
- StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
+ StorageValue<Value = BlockNumberFor<T>, QueryKind = ValueQuery>;
/// Relay block when inflation has started
#[pallet::storage]
- pub type StartBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
+ pub type StartBlock<T: Config> =
+ StorageValue<Value = BlockNumberFor<T>, QueryKind = ValueQuery>;
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
- fn on_initialize(_: T::BlockNumber) -> Weight
+ fn on_initialize(_: BlockNumberFor<T>) -> Weight
where
- <T as frame_system::Config>::BlockNumber: From<u32>,
+ BlockNumberFor<T>: From<u32>,
{
let mut consumed_weight = Weight::zero();
let mut add_weight = |reads, writes, weight| {
@@ -120,7 +121,7 @@
let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
let current_relay_block = T::BlockNumberProvider::current_block_number();
- let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();
+ let next_inflation: BlockNumberFor<T> = <NextInflationBlock<T>>::get();
add_weight(1, 0, Weight::from_parts(5_000_000, 0));
// Apply inflation every InflationBlockInterval blocks
@@ -129,7 +130,7 @@
// Recalculate inflation on the first block of the year (or if it is not initialized yet)
// Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation"
// block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.
- let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();
+ let next_recalculation: BlockNumberFor<T> = <NextRecalculationBlock<T>>::get();
add_weight(1, 0, Weight::zero());
if current_relay_block >= next_recalculation {
Self::recalculate_inflation(next_recalculation);
@@ -169,10 +170,10 @@
#[pallet::weight(Weight::from_parts(0, 0))]
pub fn start_inflation(
origin: OriginFor<T>,
- inflation_start_relay_block: T::BlockNumber,
+ inflation_start_relay_block: BlockNumberFor<T>,
) -> DispatchResult
where
- <T as frame_system::Config>::BlockNumber: From<u32>,
+ BlockNumberFor<T>: From<u32>,
{
ensure_root(origin)?;
@@ -200,9 +201,9 @@
}
impl<T: Config> Pallet<T> {
- pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {
+ pub fn recalculate_inflation(recalculation_block: BlockNumberFor<T>) {
let current_year: u32 = ((recalculation_block - <StartBlock<T>>::get())
- / T::BlockNumber::from(YEAR))
+ / BlockNumberFor::<T>::from(YEAR))
.try_into()
.unwrap_or(0);
let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
pallets/inflation/src/tests.rsdiffbeforeafterboth--- a/pallets/inflation/src/tests.rs
+++ b/pallets/inflation/src/tests.rs
@@ -57,21 +57,16 @@
type MaxLocks = MaxLocks;
type MaxReserves = ();
type ReserveIdentifier = ();
- type HoldIdentifier = ();
type FreezeIdentifier = ();
type MaxHolds = ();
type MaxFreezes = ();
}
frame_support::construct_runtime!(
- pub enum Test where
- Block = Block,
- NodeBlock = Block,
- UncheckedExtrinsic = UncheckedExtrinsic,
- {
- Balances: pallet_balances::{Pallet, Call, Storage},
- System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
- Inflation: pallet_inflation::{Pallet, Call, Storage},
+ pub enum Test {
+ Balances: pallet_balances,
+ System: frame_system,
+ Inflation: pallet_inflation,
}
);
@@ -89,13 +84,11 @@
type DbWeight = ();
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
- type Index = u64;
- type BlockNumber = u64;
+ type Nonce = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
- type Header = Header;
type RuntimeEvent = ();
type BlockHashCount = BlockHashCount;
type Version = ();
@@ -112,11 +105,11 @@
parameter_types! {
pub TreasuryAccountId: u64 = 1234;
pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied
- pub static MockBlockNumberProvider: u64 = 0;
+ pub static MockBlockNumberProvider: u32 = 0;
}
impl BlockNumberProvider for MockBlockNumberProvider {
- type BlockNumber = u64;
+ type BlockNumber = u32;
fn current_block_number() -> Self::BlockNumber {
Self::get()
@@ -131,8 +124,8 @@
}
pub fn new_test_ext() -> sp_io::TestExternalities {
- frame_system::GenesisConfig::default()
- .build_storage::<Test>()
+ <frame_system::GenesisConfig<Test>>::default()
+ .build_storage()
.unwrap()
.into()
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -90,37 +90,37 @@
#![cfg_attr(not(feature = "std"), no_std)]
+use core::ops::Deref;
+
use erc::ERC721Events;
use evm_coder::ToLog;
use frame_support::{
- BoundedVec, ensure, fail, transactional,
+ dispatch::{Pays, PostDispatchInfo},
+ ensure, fail,
+ pallet_prelude::*,
storage::with_transaction,
- pallet_prelude::DispatchResultWithPostInfo,
- pallet_prelude::Weight,
- dispatch::{PostDispatchInfo, Pays},
-};
-use up_data_structs::{
- AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
- mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,
- PropertyKeyPermission, PropertyScope, TokenChild, AuxPropertyValue, PropertiesPermissionMap,
- TokenProperties as TokenPropertiesT,
+ transactional, BoundedVec,
};
-use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
+pub use pallet::*;
use pallet_common::{
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,
weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,
};
-use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
+use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
+use pallet_structure::{Error as StructureError, Pallet as PalletStructure};
+use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
+use scale_info::TypeInfo;
use sp_core::{Get, H160};
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
-use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
-use core::ops::Deref;
-use codec::{Encode, Decode, MaxEncodedLen};
-use scale_info::TypeInfo;
-
-pub use pallet::*;
+use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};
+use up_data_structs::{
+ AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
+ mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,
+ PropertyKeyPermission, PropertyScope, TokenChild, AuxPropertyValue, PropertiesPermissionMap,
+ TokenProperties as TokenPropertiesT,
+};
use weights::WeightInfo;
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
@@ -147,13 +147,13 @@
#[frame_support::pallet]
pub mod pallet {
- use super::*;
use frame_support::{
- Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,
+ pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128Concat, Twox64Concat,
};
use up_data_structs::{CollectionId, TokenId};
- use super::weights::WeightInfo;
+ use super::{weights::WeightInfo, *};
+
#[pallet::error]
pub enum Error<T> {
/// Not Nonfungible item data used to mint in Nonfungible collection.
@@ -285,7 +285,6 @@
#[pallet::genesis_config]
pub struct GenesisConfig<T>(PhantomData<T>);
- #[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self(Default::default())
@@ -293,7 +292,7 @@
}
#[pallet::genesis_build]
- impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
+ impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
StorageVersion::new(1).put::<Pallet<T>>();
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -174,7 +174,7 @@
pub type CreateItemBasket<T: Config> = StorageMap<
Hasher = Blake2_128Concat,
Key = (CollectionId, T::AccountId),
- Value = T::BlockNumber,
+ Value = BlockNumberFor<T>,
QueryKind = OptionQuery,
>;
/// Collection id (controlled?2), token id (controlled?2)
@@ -185,7 +185,7 @@
Key1 = CollectionId,
Hasher2 = Blake2_128Concat,
Key2 = TokenId,
- Value = T::BlockNumber,
+ Value = BlockNumberFor<T>,
QueryKind = OptionQuery,
>;
/// Collection id (controlled?2), owning user (real)
@@ -196,7 +196,7 @@
Key1 = CollectionId,
Hasher2 = Twox64Concat,
Key2 = T::AccountId,
- Value = T::BlockNumber,
+ Value = BlockNumberFor<T>,
QueryKind = OptionQuery,
>;
/// Collection id (controlled?2), token id (controlled?2)
@@ -208,7 +208,7 @@
Key<Blake2_128Concat, TokenId>,
Key<Twox64Concat, T::AccountId>,
),
- Value = T::BlockNumber,
+ Value = BlockNumberFor<T>,
QueryKind = OptionQuery,
>;
//#endregion
@@ -221,7 +221,7 @@
Key1 = CollectionId,
Hasher2 = Blake2_128Concat,
Key2 = TokenId,
- Value = T::BlockNumber,
+ Value = BlockNumberFor<T>,
QueryKind = OptionQuery,
>;
@@ -233,7 +233,7 @@
Key1 = CollectionId,
Hasher2 = Blake2_128Concat,
Key2 = TokenId,
- Value = T::BlockNumber,
+ Value = BlockNumberFor<T>,
QueryKind = OptionQuery,
>;
/// Last sponsoring of fungible tokens approval in a collection
@@ -244,7 +244,7 @@
Key1 = CollectionId,
Hasher2 = Twox64Concat,
Key2 = T::AccountId,
- Value = T::BlockNumber,
+ Value = BlockNumberFor<T>,
QueryKind = OptionQuery,
>;
/// Last sponsoring of RFT approval in a collection
@@ -256,7 +256,7 @@
Key<Blake2_128Concat, TokenId>,
Key<Twox64Concat, T::AccountId>,
),
- Value = T::BlockNumber,
+ Value = BlockNumberFor<T>,
QueryKind = OptionQuery,
>;
primitives/common/src/constants.rsdiffbeforeafterboth--- a/primitives/common/src/constants.rs
+++ b/primitives/common/src/constants.rs
@@ -28,14 +28,14 @@
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
// These time units are defined in number of blocks.
-pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
-pub const HOURS: BlockNumber = MINUTES * 60;
-pub const DAYS: BlockNumber = HOURS * 24;
+pub const MINUTES: u32 = 60_000 / (MILLISECS_PER_BLOCK as u32);
+pub const HOURS: u32 = MINUTES * 60;
+pub const DAYS: u32 = HOURS * 24;
// These time units are defined in number of relay blocks.
-pub const RELAY_MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_RELAY_BLOCK as BlockNumber);
-pub const RELAY_HOURS: BlockNumber = RELAY_MINUTES * 60;
-pub const RELAY_DAYS: BlockNumber = RELAY_HOURS * 24;
+pub const RELAY_MINUTES: u32 = 60_000 / (MILLISECS_PER_RELAY_BLOCK as u32);
+pub const RELAY_HOURS: u32 = RELAY_MINUTES * 60;
+pub const RELAY_DAYS: u32 = RELAY_HOURS * 24;
pub const MICROUNIQUE: Balance = 1_000_000_000_000;
pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;
primitives/common/src/types.rsdiffbeforeafterboth--- a/primitives/common/src/types.rs
+++ b/primitives/common/src/types.rs
@@ -37,10 +37,8 @@
Unknown(sp_std::vec::Vec<u8>),
}
- /// Opaque block header type.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
- /// Opaque block type.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
pub trait RuntimeInstance {
@@ -71,7 +69,7 @@
pub type Balance = u128;
/// Index of a transaction in the chain.
-pub type Index = u32;
+pub type Nonce = u32;
/// A hash of some data used by the chain.
pub type Hash = sp_core::H256;
primitives/data-structs/src/bondrewd_codec.rsdiffbeforeafterboth--- a/primitives/data-structs/src/bondrewd_codec.rs
+++ b/primitives/data-structs/src/bondrewd_codec.rs
@@ -5,12 +5,14 @@
macro_rules! bondrewd_codec {
($T:ty) => {
impl Encode for $T {
- fn encode_to<O: codec::Output + ?Sized>(&self, dest: &mut O) {
+ fn encode_to<O: parity_scale_codec::Output + ?Sized>(&self, dest: &mut O) {
dest.write(&self.into_bytes())
}
}
- impl codec::Decode for $T {
- fn decode<I: codec::Input + ?Sized>(from: &mut I) -> Result<Self, codec::Error> {
+ impl parity_scale_codec::Decode for $T {
+ fn decode<I: parity_scale_codec::Input + ?Sized>(
+ from: &mut I,
+ ) -> Result<Self, parity_scale_codec::Error> {
let mut bytes = [0; Self::BYTE_SIZE];
from.read(&mut bytes)?;
Ok(Self::from_bytes(bytes))
primitives/data-structs/src/bounded.rsdiffbeforeafterboth--- a/primitives/data-structs/src/bounded.rs
+++ b/primitives/data-structs/src/bounded.rs
@@ -26,13 +26,13 @@
};
/// [`serde`] implementations for [`BoundedVec`].
-#[cfg(feature = "serde1")]
pub mod vec_serde {
use core::convert::TryFrom;
- use frame_support::{BoundedVec, traits::Get};
+
+ use frame_support::{traits::Get, BoundedVec};
use serde::{
- ser::{self, Serialize},
de::{self, Deserialize, Error},
+ ser::{self, Serialize},
};
use sp_std::vec::Vec;
@@ -66,17 +66,17 @@
(v as &Vec<V>).fmt(f)
}
-#[cfg(feature = "serde1")]
#[allow(dead_code)]
/// [`serde`] implementations for [`BoundedBTreeMap`].
pub mod map_serde {
use core::convert::TryFrom;
- use sp_std::collections::btree_map::BTreeMap;
- use frame_support::{traits::Get, storage::bounded_btree_map::BoundedBTreeMap};
+
+ use frame_support::{storage::bounded_btree_map::BoundedBTreeMap, traits::Get};
use serde::{
+ de::{self, Deserialize, Error},
ser::{self, Serialize},
- de::{self, Deserialize, Error},
};
+ use sp_std::collections::btree_map::BTreeMap;
pub fn serialize<D, K, V, S>(
value: &BoundedBTreeMap<K, V, S>,
serializer: D,
@@ -117,17 +117,17 @@
(v as &BTreeMap<K, V>).fmt(f)
}
-#[cfg(feature = "serde1")]
#[allow(dead_code)]
/// [`serde`] implementations for [`BoundedBTreeSet`].
pub mod set_serde {
use core::convert::TryFrom;
- use sp_std::collections::btree_set::BTreeSet;
- use frame_support::{traits::Get, storage::bounded_btree_set::BoundedBTreeSet};
+
+ use frame_support::{storage::bounded_btree_set::BoundedBTreeSet, traits::Get};
use serde::{
- ser::{self, Serialize},
de::{self, Deserialize, Error},
+ ser::{self, Serialize},
};
+ use sp_std::collections::btree_set::BTreeSet;
pub fn serialize<D, K, S>(
value: &BoundedBTreeSet<K, S>,
serializer: D,
primitives/data-structs/src/lib.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//! # Primitives crate.18//!19//! This crate contains types, traits and constants.2021#![cfg_attr(not(feature = "std"), no_std)]2223use core::{24 convert::{TryFrom, TryInto},25 fmt,26 ops::Deref,27};28use frame_support::storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet};2930#[cfg(feature = "serde")]31use serde::{Serialize, Deserialize};3233use sp_core::U256;34use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};35use sp_std::collections::btree_set::BTreeSet;36use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};37use frame_support::{BoundedVec, traits::ConstU32};38use derivative::Derivative;39use scale_info::TypeInfo;40use evm_coder::AbiCoderFlags;41use bondrewd::Bitfields;4243mod bondrewd_codec;44mod bounded;45pub mod budget;46pub mod mapping;47mod migration;4849/// Maximum of decimal points.50pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;5152/// Maximum pieces for refungible token.53pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;54pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;5556/// Maximum tokens for user.57pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {58 100_00059} else {60 1061};6263/// Maximum for collections can be created.64pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {65 100_00066} else {67 1068};6970/// Maximum for various custom data of token.71pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {72 204873} else {74 1075};7677/// Maximum admins per collection.78pub const COLLECTION_ADMINS_LIMIT: u32 = 5;7980/// Maximum tokens per collection.81pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;8283/// Maximum tokens per account.84pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {85 1_000_00086} else {87 1088};8990/// Default timeout for transfer sponsoring NFT item.91pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;92/// Default timeout for transfer sponsoring fungible item.93pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;94/// Default timeout for transfer sponsoring refungible item.95pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;9697/// Default timeout for sponsored approving.98pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;99100// Schema limits101pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;102pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;103pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;104105// TODO: not used. Delete?106pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;107108/// Maximal length of a collection name.109pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;110111/// Maximal length of a collection description.112pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;113114/// Maximal length of a token prefix.115pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;116117/// Maximal length of a property key.118pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;119120/// Maximal length of a property value.121pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;122123/// A maximum number of token properties.124pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;125126/// Maximal lenght of extended property value.127pub const MAX_AUX_PROPERTY_VALUE_LENGTH: u32 = 2048;128129/// Maximum size for all collection properties.130pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;131132/// Maximum size of all token properties.133pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;134135/// How much items can be created per single136/// create_many call.137pub const MAX_ITEMS_PER_BATCH: u32 = 200;138139/// Used for limit bounded types of token custom data.140pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;141142/// Collection id.143#[derive(144 Encode,145 Decode,146 PartialEq,147 Eq,148 PartialOrd,149 Ord,150 Clone,151 Copy,152 Debug,153 Default,154 TypeInfo,155 MaxEncodedLen,156)]157#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]158pub struct CollectionId(pub u32);159impl EncodeLike<u32> for CollectionId {}160impl EncodeLike<CollectionId> for u32 {}161162impl From<u32> for CollectionId {163 fn from(value: u32) -> Self {164 Self(value)165 }166}167168impl Deref for CollectionId {169 type Target = u32;170171 fn deref(&self) -> &Self::Target {172 &self.0173 }174}175176/// Token id.177#[derive(178 Encode,179 Decode,180 PartialEq,181 Eq,182 PartialOrd,183 Ord,184 Clone,185 Copy,186 Debug,187 Default,188 TypeInfo,189 MaxEncodedLen,190)]191#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]192pub struct TokenId(pub u32);193impl EncodeLike<u32> for TokenId {}194impl EncodeLike<TokenId> for u32 {}195196impl TokenId {197 /// Try to get next token id.198 ///199 /// If next id cause overflow, then [`ArithmeticError::Overflow`] returned.200 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {201 self.0202 .checked_add(1)203 .ok_or(ArithmeticError::Overflow)204 .map(Self)205 }206}207208impl From<TokenId> for U256 {209 fn from(t: TokenId) -> Self {210 t.0.into()211 }212}213214impl TryFrom<U256> for TokenId {215 type Error = &'static str;216217 fn try_from(value: U256) -> Result<Self, Self::Error> {218 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))219 }220}221222/// Token data.223#[struct_versioning::versioned(version = 2, upper)]224#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]225#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]226pub struct TokenData<CrossAccountId> {227 /// Properties of token.228 pub properties: Vec<Property>,229230 /// Token owner.231 pub owner: Option<CrossAccountId>,232233 /// Token pieces.234 #[version(2.., upper(0))]235 pub pieces: u128,236}237238// TODO: unused type239pub struct OverflowError;240impl From<OverflowError> for &'static str {241 fn from(_: OverflowError) -> Self {242 "overflow occured"243 }244}245246/// Alias for decimal points type.247pub type DecimalPoints = u8;248249/// Collection mode.250///251/// Collection can represent various types of tokens.252/// Each collection can contain only one type of tokens at a time.253/// This type helps to understand which tokens the collection contains.254#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]255#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]256pub enum CollectionMode {257 /// Non fungible tokens.258 NFT,259 /// Fungible tokens.260 Fungible(DecimalPoints),261 /// Refungible tokens.262 ReFungible,263}264265impl CollectionMode {266 /// Get collection mod as number.267 pub fn id(&self) -> u8 {268 match self {269 CollectionMode::NFT => 1,270 CollectionMode::Fungible(_) => 2,271 CollectionMode::ReFungible => 3,272 }273 }274}275276// TODO: unused trait277pub trait SponsoringResolve<AccountId, Call> {278 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;279}280281/// Access mode for some token operations.282#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]283#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]284pub enum AccessMode {285 /// Access grant for owner and admins. Used as default.286 Normal,287 /// Like a [`Normal`](AccessMode::Normal) but also users in allow list.288 AllowList,289}290impl Default for AccessMode {291 fn default() -> Self {292 Self::Normal293 }294}295296// TODO: remove in future.297#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]298#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]299pub enum SchemaVersion {300 ImageURL,301 Unique,302}303impl Default for SchemaVersion {304 fn default() -> Self {305 Self::ImageURL306 }307}308309// TODO: unused type310#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]311#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]312pub struct Ownership<AccountId> {313 pub owner: AccountId,314 pub fraction: u128,315}316317/// The state of collection sponsorship.318#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]319#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]320pub enum SponsorshipState<AccountId> {321 /// The fees are applied to the transaction sender.322 Disabled,323 /// The sponsor is under consideration. Until the sponsor gives his consent,324 /// the fee will still be charged to sender.325 Unconfirmed(AccountId),326 /// Transactions are sponsored by specified account.327 Confirmed(AccountId),328}329330impl<AccountId> SponsorshipState<AccountId> {331 /// Get a sponsor of the collection who has confirmed his status.332 pub fn sponsor(&self) -> Option<&AccountId> {333 match self {334 Self::Confirmed(sponsor) => Some(sponsor),335 _ => None,336 }337 }338339 /// Get a sponsor of the collection who has pending or confirmed status.340 pub fn pending_sponsor(&self) -> Option<&AccountId> {341 match self {342 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),343 _ => None,344 }345 }346347 /// Whether the sponsorship is confirmed.348 pub fn confirmed(&self) -> bool {349 matches!(self, Self::Confirmed(_))350 }351}352353impl<T> Default for SponsorshipState<T> {354 fn default() -> Self {355 Self::Disabled356 }357}358359pub type CollectionName = BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>;360pub type CollectionDescription = BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>;361pub type CollectionTokenPrefix = BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>;362363#[derive(AbiCoderFlags, Bitfields, Clone, Copy, PartialEq, Eq, Debug, Default)]364#[bondrewd(enforce_bytes = 1)]365pub struct CollectionFlags {366 /// Tokens in foreign collections can be transferred, but not burnt367 #[bondrewd(bits = "0..1")]368 pub foreign: bool,369 /// Supports ERC721Metadata370 #[bondrewd(bits = "1..2")]371 pub erc721metadata: bool,372 /// External collections can't be managed using `unique` api373 #[bondrewd(bits = "7..8")]374 pub external: bool,375 /// Reserved flags376 #[bondrewd(bits = "2..7")]377 pub reserved: u8,378}379bondrewd_codec!(CollectionFlags);380381impl CollectionFlags {382 pub fn is_allowed_for_user(self) -> bool {383 !self.foreign && !self.external && self.reserved == 0384 }385}386387/// Base structure for represent collection.388///389/// Used to provide basic functionality for all types of collections.390///391/// #### Note392/// Collection parameters, used in storage (see [`RpcCollection`] for the RPC version).393#[struct_versioning::versioned(version = 2, upper)]394#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]395pub struct Collection<AccountId> {396 /// Collection owner account.397 pub owner: AccountId,398399 /// Collection mode.400 pub mode: CollectionMode,401402 /// Access mode.403 #[version(..2)]404 pub access: AccessMode,405406 /// Collection name.407 pub name: CollectionName,408409 /// Collection description.410 pub description: CollectionDescription,411412 /// Token prefix.413 pub token_prefix: CollectionTokenPrefix,414415 #[version(..2)]416 pub mint_mode: bool,417418 #[version(..2)]419 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,420421 #[version(..2)]422 pub schema_version: SchemaVersion,423424 /// The state of sponsorship of the collection.425 pub sponsorship: SponsorshipState<AccountId>,426427 /// Collection limits.428 pub limits: CollectionLimits,429430 /// Collection permissions.431 #[version(2.., upper(Default::default()))]432 pub permissions: CollectionPermissions,433434 #[version(2.., upper(Default::default()))]435 pub flags: CollectionFlags,436437 #[version(..2)]438 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,439440 #[version(..2)]441 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,442443 #[version(..2)]444 pub meta_update_permission: MetaUpdatePermission,445}446447#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo)]448#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]449pub struct RpcCollectionFlags {450 /// Is collection is foreign.451 pub foreign: bool,452 /// Collection supports ERC721Metadata.453 pub erc721metadata: bool,454}455456/// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).457#[struct_versioning::versioned(version = 2, upper)]458#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo)]459#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]460pub struct RpcCollection<AccountId> {461 /// Collection owner account.462 pub owner: AccountId,463464 /// Collection mode.465 pub mode: CollectionMode,466467 /// Collection name.468 pub name: Vec<u16>,469470 /// Collection description.471 pub description: Vec<u16>,472473 /// Token prefix.474 pub token_prefix: Vec<u8>,475476 /// The state of sponsorship of the collection.477 pub sponsorship: SponsorshipState<AccountId>,478479 /// Collection limits.480 pub limits: CollectionLimits,481482 /// Collection permissions.483 pub permissions: CollectionPermissions,484485 /// Token property permissions.486 pub token_property_permissions: Vec<PropertyKeyPermission>,487488 /// Collection properties.489 pub properties: Vec<Property>,490491 /// Is collection read only.492 pub read_only: bool,493494 /// Extra collection flags495 #[version(2.., upper(RpcCollectionFlags {foreign: false, erc721metadata: false}))]496 pub flags: RpcCollectionFlags,497}498499impl<AccountId> From<CollectionVersion1<AccountId>> for RpcCollection<AccountId> {500 fn from(value: CollectionVersion1<AccountId>) -> Self {501 let CollectionVersion1 {502 name,503 description,504 owner,505 mode,506 access,507 token_prefix,508 mint_mode,509 sponsorship,510 limits,511 ..512 } = value;513514 RpcCollection {515 name: name.into_inner(),516 description: description.into_inner(),517 owner,518 mode,519 token_prefix: token_prefix.into_inner(),520 sponsorship,521 limits,522 permissions: CollectionPermissions {523 access: Some(access),524 mint_mode: Some(mint_mode),525 nesting: None,526 },527 token_property_permissions: Vec::default(),528 properties: Vec::default(),529 read_only: true,530531 flags: RpcCollectionFlags {532 foreign: false,533 erc721metadata: false,534 },535 }536 }537}538539pub struct RawEncoded(Vec<u8>);540541impl codec::Decode for RawEncoded {542 fn decode<I: codec::Input>(input: &mut I) -> Result<Self, codec::Error> {543 let mut out = Vec::new();544 while let Ok(v) = input.read_byte() {545 out.push(v);546 }547 Ok(Self(out))548 }549}550551impl Deref for RawEncoded {552 type Target = Vec<u8>;553554 fn deref(&self) -> &Self::Target {555 &self.0556 }557}558559/// Data used for create collection.560///561/// All fields are wrapped in [`Option`], where `None` means chain default.562#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]563#[derivative(Debug, Default(bound = ""))]564pub struct CreateCollectionData<CrossAccountId> {565 /// Collection mode.566 #[derivative(Default(value = "CollectionMode::NFT"))]567 pub mode: CollectionMode,568569 /// Access mode.570 pub access: Option<AccessMode>,571572 /// Collection name.573 pub name: CollectionName,574575 /// Collection description.576 pub description: CollectionDescription,577578 /// Token prefix.579 pub token_prefix: CollectionTokenPrefix,580581 /// Collection limits.582 pub limits: Option<CollectionLimits>,583584 /// Collection permissions.585 pub permissions: Option<CollectionPermissions>,586587 /// Token property permissions.588 pub token_property_permissions: CollectionPropertiesPermissionsVec,589590 /// Collection properties.591 pub properties: CollectionPropertiesVec,592593 pub admin_list: Vec<CrossAccountId>,594595 /// Pending collection sponsor.596 pub pending_sponsor: Option<CrossAccountId>,597598 pub flags: CollectionFlags,599}600601/// Bounded vector of properties permissions. Max length is [`MAX_PROPERTIES_PER_ITEM`].602// TODO: maybe rename to PropertiesPermissionsVec603pub type CollectionPropertiesPermissionsVec =604 BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;605606/// Bounded vector of properties. Max length is [`MAX_PROPERTIES_PER_ITEM`].607pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;608609/// Limits and restrictions of a collection.610///611/// All fields are wrapped in [`Option`], where `None` means chain default.612///613/// Update with `pallet_common::Pallet::clamp_limits`.614// IMPORTANT: When adding/removing fields from this struct - don't forget to also615#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]616#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]617// When adding/removing fields from this struct - don't forget to also update with `pallet_common::Pallet::clamp_limits`.618// TODO: move `pallet_common::Pallet::clamp_limits` into `impl CollectionLimits`.619// TODO: may be remove [`Option`] and **pub** from fields and create struct with default values.620pub struct CollectionLimits {621 /// How many tokens can a user have on one account.622 /// * Default - [`ACCOUNT_TOKEN_OWNERSHIP_LIMIT`].623 /// * Limit - [`MAX_TOKEN_OWNERSHIP`].624 pub account_token_ownership_limit: Option<u32>,625626 /// How many bytes of data are available for sponsorship.627 /// * Default - [`CUSTOM_DATA_LIMIT`].628 /// * Limit - [`CUSTOM_DATA_LIMIT`].629 pub sponsored_data_size: Option<u32>,630631 // FIXME should we delete this or repurpose it?632 /// Times in how many blocks we sponsor data.633 ///634 /// If is `Some(v)` then **setVariableMetadata** is sponsored if there is `v` block between transactions.635 ///636 /// * Default - [`SponsoringDisabled`](SponsoringRateLimit::SponsoringDisabled).637 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].638 ///639 /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]640 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,641 /// Maximum amount of tokens inside the collection. Chain default: [`COLLECTION_TOKEN_LIMIT`]642643 /// How many tokens can be mined into this collection.644 ///645 /// * Default - [`COLLECTION_TOKEN_LIMIT`].646 /// * Limit - [`COLLECTION_TOKEN_LIMIT`].647 pub token_limit: Option<u32>,648649 /// Timeouts for transfer sponsoring.650 ///651 /// * Default652 /// - **Fungible** - [`FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]653 /// - **NFT** - [`NFT_SPONSOR_TRANSFER_TIMEOUT`]654 /// - **Refungible** - [`REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]655 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].656 pub sponsor_transfer_timeout: Option<u32>,657658 /// Timeout for sponsoring an approval in passed blocks.659 ///660 /// * Default - [`SPONSOR_APPROVE_TIMEOUT`].661 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].662 pub sponsor_approve_timeout: Option<u32>,663664 /// Whether the collection owner of the collection can send tokens (which belong to other users).665 ///666 /// * Default - **false**.667 pub owner_can_transfer: Option<bool>,668669 /// Can the collection owner burn other people's tokens.670 ///671 /// * Default - **true**.672 pub owner_can_destroy: Option<bool>,673674 /// Is it possible to send tokens from this collection between users.675 ///676 /// * Default - **true**.677 pub transfers_enabled: Option<bool>,678}679680impl CollectionLimits {681 pub fn with_default_limits(collection_type: CollectionMode) -> Self {682 CollectionLimits {683 account_token_ownership_limit: Some(ACCOUNT_TOKEN_OWNERSHIP_LIMIT),684 sponsored_data_size: Some(CUSTOM_DATA_LIMIT),685 sponsored_data_rate_limit: Some(SponsoringRateLimit::SponsoringDisabled),686 token_limit: Some(COLLECTION_TOKEN_LIMIT),687 sponsor_transfer_timeout: match collection_type {688 CollectionMode::NFT => Some(NFT_SPONSOR_TRANSFER_TIMEOUT),689 CollectionMode::ReFungible => Some(REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT),690 CollectionMode::Fungible(_) => Some(FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT),691 },692 sponsor_approve_timeout: Some(SPONSOR_APPROVE_TIMEOUT),693 owner_can_transfer: Some(false),694 owner_can_destroy: Some(true),695 transfers_enabled: Some(true),696 }697 }698699 /// Get effective value for [`account_token_ownership_limit`](self.account_token_ownership_limit).700 pub fn account_token_ownership_limit(&self) -> u32 {701 self.account_token_ownership_limit702 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)703 .min(MAX_TOKEN_OWNERSHIP)704 }705706 /// Get effective value for [`sponsored_data_size`](self.sponsored_data_size).707 pub fn sponsored_data_size(&self) -> u32 {708 self.sponsored_data_size709 .unwrap_or(CUSTOM_DATA_LIMIT)710 .min(CUSTOM_DATA_LIMIT)711 }712713 /// Get effective value for [`token_limit`](self.token_limit).714 pub fn token_limit(&self) -> u32 {715 self.token_limit716 .unwrap_or(COLLECTION_TOKEN_LIMIT)717 .min(COLLECTION_TOKEN_LIMIT)718 }719720 // TODO: may be replace u32 to mode?721 /// Get effective value for [`sponsor_transfer_timeout`](self.sponsor_transfer_timeout).722 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {723 self.sponsor_transfer_timeout724 .unwrap_or(default)725 .min(MAX_SPONSOR_TIMEOUT)726 }727728 /// Get effective value for [`sponsor_approve_timeout`](self.sponsor_approve_timeout).729 pub fn sponsor_approve_timeout(&self) -> u32 {730 self.sponsor_approve_timeout731 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)732 .min(MAX_SPONSOR_TIMEOUT)733 }734735 /// Get effective value for [`owner_can_transfer`](self.owner_can_transfer).736 pub fn owner_can_transfer(&self) -> bool {737 self.owner_can_transfer.unwrap_or(false)738 }739740 /// Get effective value for [`owner_can_transfer_instaled`](self.owner_can_transfer_instaled).741 pub fn owner_can_transfer_instaled(&self) -> bool {742 self.owner_can_transfer.is_some()743 }744745 /// Get effective value for [`owner_can_destroy`](self.owner_can_destroy).746 pub fn owner_can_destroy(&self) -> bool {747 self.owner_can_destroy.unwrap_or(true)748 }749750 /// Get effective value for [`transfers_enabled`](self.transfers_enabled).751 pub fn transfers_enabled(&self) -> bool {752 self.transfers_enabled.unwrap_or(true)753 }754755 /// Get effective value for [`sponsored_data_rate_limit`](self.sponsored_data_rate_limit).756 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {757 match self758 .sponsored_data_rate_limit759 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)760 {761 SponsoringRateLimit::SponsoringDisabled => None,762 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),763 }764 }765}766767/// Permissions on certain operations within a collection.768///769/// Some fields are wrapped in [`Option`], where `None` means chain default.770///771/// Update with `pallet_common::Pallet::clamp_permissions`.772#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]773#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]774// When adding/removing fields from this struct - don't forget to also update `pallet_common::Pallet::clamp_permissions`.775// TODO: move `pallet_common::Pallet::clamp_permissions` into `impl CollectionPermissions`.776pub struct CollectionPermissions {777 /// Access mode.778 ///779 /// * Default - [`AccessMode::Normal`].780 pub access: Option<AccessMode>,781782 /// Minting allowance.783 ///784 /// * Default - **false**.785 pub mint_mode: Option<bool>,786787 /// Permissions for nesting.788 ///789 /// * Default790 /// - `token_owner` - **false**791 /// - `collection_admin` - **false**792 /// - `restricted` - **None**793 pub nesting: Option<NestingPermissions>,794}795796impl CollectionPermissions {797 /// Get effective value for [`access`](self.access).798 pub fn access(&self) -> AccessMode {799 self.access.unwrap_or(AccessMode::Normal)800 }801802 /// Get effective value for [`mint_mode`](self.mint_mode).803 pub fn mint_mode(&self) -> bool {804 self.mint_mode.unwrap_or(false)805 }806807 /// Get effective value for [`nesting`](self.nesting).808 pub fn nesting(&self) -> &NestingPermissions {809 static DEFAULT: NestingPermissions = NestingPermissions {810 token_owner: false,811 collection_admin: false,812 restricted: None,813 #[cfg(feature = "runtime-benchmarks")]814 permissive: false,815 };816 self.nesting.as_ref().unwrap_or(&DEFAULT)817 }818}819820/// Inner set for collections allowed to nest.821type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;822823/// Wraper for collections set allowing nest.824#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]825#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]826#[derivative(Debug)]827pub struct OwnerRestrictedSet(828 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]829 #[derivative(Debug(format_with = "bounded::set_debug"))]830 pub OwnerRestrictedSetInner,831);832833impl OwnerRestrictedSet {834 /// Create new set.835 pub fn new() -> Self {836 Self(Default::default())837 }838}839impl Default for OwnerRestrictedSet {840 fn default() -> Self {841 Self::new()842 }843}844impl core::ops::Deref for OwnerRestrictedSet {845 type Target = OwnerRestrictedSetInner;846 fn deref(&self) -> &Self::Target {847 &self.0848 }849}850impl core::ops::DerefMut for OwnerRestrictedSet {851 fn deref_mut(&mut self) -> &mut Self::Target {852 &mut self.0853 }854}855856impl TryFrom<BTreeSet<CollectionId>> for OwnerRestrictedSet {857 type Error = ();858859 fn try_from(value: BTreeSet<CollectionId>) -> Result<Self, Self::Error> {860 Ok(Self(value.try_into()?))861 }862}863864/// Part of collection permissions, if set, defines who is able to nest tokens into other tokens.865#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]866#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]867#[derivative(Debug)]868pub struct NestingPermissions {869 /// Owner of token can nest tokens under it.870 pub token_owner: bool,871 /// Admin of token collection can nest tokens under token.872 pub collection_admin: bool,873 /// If set - only tokens from specified collections can be nested.874 pub restricted: Option<OwnerRestrictedSet>,875876 #[cfg(feature = "runtime-benchmarks")]877 /// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`.878 pub permissive: bool,879}880881/// Enum denominating how often can sponsoring occur if it is enabled.882///883/// Used for [`collection limits`](CollectionLimits).884#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]885#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]886pub enum SponsoringRateLimit {887 /// Sponsoring is disabled, and the collection sponsor will not pay for transactions888 SponsoringDisabled,889 /// Once per how many blocks can sponsorship of a transaction type occur890 Blocks(u32),891}892893/// Data used to describe an NFT at creation.894#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]895#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]896#[derivative(Debug)]897pub struct CreateNftData {898 /// Key-value pairs used to describe the token as metadata899 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]900 #[derivative(Debug(format_with = "bounded::vec_debug"))]901 /// Properties that wil be assignet to created item.902 pub properties: CollectionPropertiesVec,903}904905/// Data used to describe a Fungible token at creation.906#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]907#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]908pub struct CreateFungibleData {909 /// Number of fungible coins minted910 pub value: u128,911}912913/// Data used to describe a Refungible token at creation.914#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]915#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]916#[derivative(Debug)]917pub struct CreateReFungibleData {918 /// Number of pieces the RFT is split into919 pub pieces: u128,920921 /// Key-value pairs used to describe the token as metadata922 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]923 #[derivative(Debug(format_with = "bounded::vec_debug"))]924 pub properties: CollectionPropertiesVec,925}926927// TODO: remove this.928#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]929#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]930pub enum MetaUpdatePermission {931 ItemOwner,932 Admin,933 None,934}935936/// Enum holding data used for creation of all three item types.937/// Unified data for create item.938#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]939#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]940pub enum CreateItemData {941 /// Data for create NFT.942 NFT(CreateNftData),943 /// Data for create Fungible item.944 Fungible(CreateFungibleData),945 /// Data for create ReFungible item.946 ReFungible(CreateReFungibleData),947}948949/// Extended data for create NFT.950#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]951#[derivative(Debug)]952pub struct CreateNftExData<CrossAccountId> {953 /// Properties that wil be assignet to created item.954 #[derivative(Debug(format_with = "bounded::vec_debug"))]955 pub properties: CollectionPropertiesVec,956957 /// Owner of creating item.958 pub owner: CrossAccountId,959}960961/// Extended data for create ReFungible item.962#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]963#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]964pub struct CreateRefungibleExMultipleOwners<CrossAccountId> {965 #[derivative(Debug(format_with = "bounded::map_debug"))]966 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,967 #[derivative(Debug(format_with = "bounded::vec_debug"))]968 pub properties: CollectionPropertiesVec,969}970971/// Extended data for create ReFungible item.972#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]973#[derivative(Debug(bound = "CrossAccountId: fmt::Debug"))]974pub struct CreateRefungibleExSingleOwner<CrossAccountId> {975 pub user: CrossAccountId,976 pub pieces: u128,977 #[derivative(Debug(format_with = "bounded::vec_debug"))]978 pub properties: CollectionPropertiesVec,979}980981/// Unified extended data for creating item.982#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]983#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]984pub enum CreateItemExData<CrossAccountId> {985 /// Extended data for create NFT.986 NFT(987 #[derivative(Debug(format_with = "bounded::vec_debug"))]988 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,989 ),990991 /// Extended data for create Fungible item.992 Fungible(993 #[derivative(Debug(format_with = "bounded::map_debug"))]994 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,995 ),996997 /// Extended data for create ReFungible item in case of998 /// many tokens, each may have only one owner999 RefungibleMultipleItems(1000 #[derivative(Debug(format_with = "bounded::vec_debug"))]1001 BoundedVec<CreateRefungibleExSingleOwner<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,1002 ),10031004 /// Extended data for create ReFungible item in case of1005 /// single token, which may have many owners1006 RefungibleMultipleOwners(CreateRefungibleExMultipleOwners<CrossAccountId>),1007}10081009impl From<CreateNftData> for CreateItemData {1010 fn from(item: CreateNftData) -> Self {1011 CreateItemData::NFT(item)1012 }1013}10141015impl From<CreateReFungibleData> for CreateItemData {1016 fn from(item: CreateReFungibleData) -> Self {1017 CreateItemData::ReFungible(item)1018 }1019}10201021impl From<CreateFungibleData> for CreateItemData {1022 fn from(item: CreateFungibleData) -> Self {1023 CreateItemData::Fungible(item)1024 }1025}10261027/// Token's address, dictated by its collection and token IDs.1028#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]1029#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1030// todo possibly rename to be used generally as an address pair1031pub struct TokenChild {1032 /// Token id.1033 pub token: TokenId,10341035 /// Collection id.1036 pub collection: CollectionId,1037}10381039/// Collection statistics.1040#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]1041#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1042pub struct CollectionStats {1043 /// Number of created items.1044 pub created: u32,10451046 /// Number of burned items.1047 pub destroyed: u32,10481049 /// Number of current items.1050 pub alive: u32,1051}10521053/// This type works like [`PhantomData`] but supports generating _scale-info_ descriptions to generate node metadata.1054#[derive(Encode, Decode, Clone, Debug)]1055#[cfg_attr(feature = "std", derive(PartialEq))]1056pub struct PhantomType<T>(core::marker::PhantomData<T>);10571058impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {1059 type Identity = PhantomType<T>;10601061 fn type_info() -> scale_info::Type {1062 use scale_info::{1063 Type, Path,1064 build::{FieldsBuilder, UnnamedFields},1065 form::MetaForm,1066 type_params,1067 };1068 Type::builder()1069 .path(Path::new("up_data_structs", "PhantomType"))1070 .type_params(type_params!(T))1071 .composite(1072 <FieldsBuilder<MetaForm, UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()),1073 )1074 }1075}1076impl<T> MaxEncodedLen for PhantomType<T> {1077 fn max_encoded_len() -> usize {1078 01079 }1080}10811082/// Bounded vector of bytes.1083pub type BoundedBytes<S> = BoundedVec<u8, S>;10841085/// Extra properties for external collections.1086pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;10871088/// Property key.1089pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;10901091/// Property value.1092pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;10931094/// Property permission.1095#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone, Default)]1096#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1097pub struct PropertyPermission {1098 /// Permission to change the property and property permission.1099 ///1100 /// If it **false** then you can not change corresponding property even if [`collection_admin`] and [`token_owner`] are **true**.1101 pub mutable: bool,11021103 /// Change permission for the collection administrator.1104 pub collection_admin: bool,11051106 /// Permission to change the property for the owner of the token.1107 pub token_owner: bool,1108}11091110impl PropertyPermission {1111 /// Creates mutable property permission but changes restricted for collection admin and token owner.1112 pub fn none() -> Self {1113 Self {1114 mutable: true,1115 collection_admin: false,1116 token_owner: false,1117 }1118 }1119}11201121/// Property is simpl key-value record.1122#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]1123#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1124pub struct Property {1125 /// Property key.1126 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1127 pub key: PropertyKey,11281129 /// Property value.1130 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1131 pub value: PropertyValue,1132}11331134impl From<Property> for (PropertyKey, PropertyValue) {1135 fn from(value: Property) -> Self {1136 (value.key, value.value)1137 }1138}11391140/// Record for proprty key permission.1141#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]1142#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1143pub struct PropertyKeyPermission {1144 /// Key.1145 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1146 pub key: PropertyKey,11471148 /// Permission.1149 pub permission: PropertyPermission,1150}11511152impl From<PropertyKeyPermission> for (PropertyKey, PropertyPermission) {1153 fn from(value: PropertyKeyPermission) -> Self {1154 (value.key, value.permission)1155 }1156}11571158/// Errors for properties actions.1159#[derive(Debug)]1160pub enum PropertiesError {1161 /// The space allocated for properties has run out.1162 ///1163 /// * Limit for colection - [`MAX_COLLECTION_PROPERTIES_SIZE`].1164 /// * Limit for token - [`MAX_TOKEN_PROPERTIES_SIZE`].1165 NoSpaceForProperty,11661167 /// The property limit has been reached.1168 ///1169 /// * Limit - [`MAX_PROPERTIES_PER_ITEM`].1170 PropertyLimitReached,11711172 /// Property key contains not allowed character.1173 InvalidCharacterInPropertyKey,11741175 /// Property key length is too long.1176 ///1177 /// * Limit - [`MAX_PROPERTY_KEY_LENGTH`].1178 PropertyKeyIsTooLong,11791180 /// Property key is empty.1181 EmptyPropertyKey,1182}11831184/// Token owner error: it could be either `NotFound` ot `MultipleOwners`.1185#[derive(Debug)]1186pub enum TokenOwnerError {1187 NotFound,1188 MultipleOwners,1189}11901191/// Marker for scope of property.1192///1193/// Scoped property can't be changed by user. Used for external collections.1194#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]1195pub enum PropertyScope {1196 None,1197 Rmrk,1198}11991200impl PropertyScope {1201 pub fn prefix(&self) -> &'static [u8] {1202 match self {1203 Self::None => b"",1204 Self::Rmrk => b"rmrk:",1205 }1206 }1207 /// Apply scope to property key.1208 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {1209 let prefix = self.prefix();1210 if prefix == b"" {1211 return Ok(key);1212 }1213 [prefix, key.as_slice()]1214 .concat()1215 .try_into()1216 .map_err(|_| PropertiesError::PropertyKeyIsTooLong)1217 }1218}12191220/// Trait for operate with properties.1221pub trait TrySetProperty: Sized {1222 type Value;12231224 /// Try to set property with scope.1225 fn try_scoped_set(1226 &mut self,1227 scope: PropertyScope,1228 key: PropertyKey,1229 value: Self::Value,1230 ) -> Result<Option<Self::Value>, PropertiesError>;12311232 /// Try to set property with scope from iterator.1233 fn try_scoped_set_from_iter<I, KV>(1234 &mut self,1235 scope: PropertyScope,1236 iter: I,1237 ) -> Result<(), PropertiesError>1238 where1239 I: Iterator<Item = KV>,1240 KV: Into<(PropertyKey, Self::Value)>,1241 {1242 for kv in iter {1243 let (key, value) = kv.into();1244 self.try_scoped_set(scope, key, value)?;1245 }12461247 Ok(())1248 }12491250 /// Try to set property.1251 fn try_set(1252 &mut self,1253 key: PropertyKey,1254 value: Self::Value,1255 ) -> Result<Option<Self::Value>, PropertiesError> {1256 self.try_scoped_set(PropertyScope::None, key, value)1257 }12581259 /// Try to set property from iterator.1260 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>1261 where1262 I: Iterator<Item = KV>,1263 KV: Into<(PropertyKey, Self::Value)>,1264 {1265 self.try_scoped_set_from_iter(PropertyScope::None, iter)1266 }1267}12681269/// Wrapped map for storing properties.1270#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]1271#[derivative(Default(bound = ""))]1272pub struct PropertiesMap<Value>(1273 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,1274);12751276impl<Value> PropertiesMap<Value> {1277 /// Create new property map.1278 pub fn new() -> Self {1279 Self(BoundedBTreeMap::new())1280 }12811282 /// Remove property from map.1283 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {1284 Self::check_property_key(key)?;12851286 Ok(self.0.remove(key))1287 }12881289 /// Get property with appropriate key from map.1290 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {1291 self.0.get(key)1292 }12931294 /// Check if map contains key.1295 pub fn contains_key(&self, key: &PropertyKey) -> bool {1296 self.0.contains_key(key)1297 }12981299 /// Check if map contains key with key validation.1300 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {1301 if key.is_empty() {1302 return Err(PropertiesError::EmptyPropertyKey);1303 }13041305 for byte in key.as_slice().iter() {1306 let byte = *byte;13071308 if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' && byte != b'.' {1309 return Err(PropertiesError::InvalidCharacterInPropertyKey);1310 }1311 }13121313 Ok(())1314 }13151316 pub fn values(&self) -> impl Iterator<Item = &Value> {1317 self.0.values()1318 }13191320 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &Value)> {1321 self.0.iter()1322 }1323}13241325impl<Value> IntoIterator for PropertiesMap<Value> {1326 type Item = (PropertyKey, Value);1327 type IntoIter = <1328 BoundedBTreeMap<1329 PropertyKey,1330 Value,1331 ConstU32<MAX_PROPERTIES_PER_ITEM>1332 > as IntoIterator1333 >::IntoIter;13341335 fn into_iter(self) -> Self::IntoIter {1336 self.0.into_iter()1337 }1338}13391340impl<Value> TrySetProperty for PropertiesMap<Value> {1341 type Value = Value;13421343 fn try_scoped_set(1344 &mut self,1345 scope: PropertyScope,1346 key: PropertyKey,1347 value: Self::Value,1348 ) -> Result<Option<Self::Value>, PropertiesError> {1349 Self::check_property_key(&key)?;13501351 let key = scope.apply(key)?;1352 self.01353 .try_insert(key, value)1354 .map_err(|_| PropertiesError::PropertyLimitReached)1355 }1356}13571358/// Alias for property permissions map.1359pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;13601361fn slice_size(data: &[u8]) -> u32 {1362 scoped_slice_size(PropertyScope::None, data)1363}1364fn scoped_slice_size(scope: PropertyScope, data: &[u8]) -> u32 {1365 use codec::Compact;1366 let prefix = scope.prefix();1367 <Compact<u32>>::encoded_size(&Compact(data.len() as u32 + prefix.len() as u32)) as u321368 + data.len() as u321369 + prefix.len() as u321370}13711372/// Wrapper for properties map with consumed space control.1373#[derive(Encode, Decode, TypeInfo, Clone, PartialEq)]1374pub struct Properties<const S: u32> {1375 map: PropertiesMap<PropertyValue>,1376 consumed_space: u32,1377 // May be not zero, previously served as a current S generic1378 _reserved: u32,1379}13801381impl<const S: u32> MaxEncodedLen for Properties<S> {1382 fn max_encoded_len() -> usize {1383 // len of map + len of consumed_space + len of space_limit1384 u32::max_encoded_len() * 3 + S as usize1385 }1386}13871388impl<const S: u32> Default for Properties<S> {1389 fn default() -> Self {1390 Self::new()1391 }1392}13931394impl<const S: u32> Properties<S> {1395 /// Create new properies container.1396 pub fn new() -> Self {1397 Self {1398 map: PropertiesMap::new(),1399 consumed_space: 0,1400 _reserved: 0,1401 }1402 }14031404 /// Remove propery with appropiate key.1405 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {1406 let value = self.map.remove(key)?;14071408 if let Some(ref value) = value {1409 let kv_len = slice_size(key) + slice_size(value);1410 self.consumed_space = self.consumed_space.saturating_sub(kv_len);1411 }14121413 Ok(value)1414 }14151416 /// Get property with appropriate key.1417 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {1418 self.map.get(key)1419 }14201421 /// Recomputes the consumed space for the current properties state.1422 /// Needed to repair a token due to a bug fixed in the [PR #733](https://github.com/UniqueNetwork/unique-chain/pull/773).1423 pub fn recompute_consumed_space(&mut self) {1424 self.consumed_space = self1425 .map1426 .iter()1427 .map(|(key, value)| slice_size(key) + slice_size(value))1428 .sum();1429 }1430}14311432impl<const S: u32> IntoIterator for Properties<S> {1433 type Item = (PropertyKey, PropertyValue);1434 type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;14351436 fn into_iter(self) -> Self::IntoIter {1437 self.map.into_iter()1438 }1439}14401441impl<const S: u32> TrySetProperty for Properties<S> {1442 type Value = PropertyValue;14431444 fn try_scoped_set(1445 &mut self,1446 scope: PropertyScope,1447 key: PropertyKey,1448 value: Self::Value,1449 ) -> Result<Option<Self::Value>, PropertiesError> {1450 let key_size = scoped_slice_size(scope, &key);1451 let value_size = slice_size(&value);14521453 if self.consumed_space + value_size + key_size > S && !cfg!(feature = "runtime-benchmarks")1454 {1455 return Err(PropertiesError::NoSpaceForProperty);1456 }14571458 let old_value = self.map.try_scoped_set(scope, key, value)?;14591460 if let Some(old_value) = old_value.as_ref() {1461 let old_value_size = slice_size(old_value);1462 self.consumed_space = self.consumed_space.saturating_sub(old_value_size) + value_size;1463 } else {1464 self.consumed_space += key_size + value_size;1465 }14661467 Ok(old_value)1468 }1469}14701471pub type CollectionProperties = Properties<MAX_COLLECTION_PROPERTIES_SIZE>;1472pub type TokenProperties = Properties<MAX_TOKEN_PROPERTIES_SIZE>;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//! # Primitives crate.18//!19//! This crate contains types, traits and constants.2021#![cfg_attr(not(feature = "std"), no_std)]2223use core::{24 convert::{TryFrom, TryInto},25 fmt,26 ops::Deref,27};28use frame_support::storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet};2930#[cfg(feature = "serde")]31use serde::{Serialize, Deserialize};3233use sp_core::U256;34use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};35use sp_std::collections::btree_set::BTreeSet;36use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};37use frame_support::{BoundedVec, traits::ConstU32};38use derivative::Derivative;39use scale_info::TypeInfo;40use evm_coder::AbiCoderFlags;41use bondrewd::Bitfields;4243mod bondrewd_codec;44mod bounded;45pub mod budget;46pub mod mapping;47mod migration;4849/// Maximum of decimal points.50pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;5152/// Maximum pieces for refungible token.53pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;54pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;5556/// Maximum tokens for user.57pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {58 100_00059} else {60 1061};6263/// Maximum for collections can be created.64pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {65 100_00066} else {67 1068};6970/// Maximum for various custom data of token.71pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {72 204873} else {74 1075};7677/// Maximum admins per collection.78pub const COLLECTION_ADMINS_LIMIT: u32 = 5;7980/// Maximum tokens per collection.81pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;8283/// Maximum tokens per account.84pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {85 1_000_00086} else {87 1088};8990/// Default timeout for transfer sponsoring NFT item.91pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;92/// Default timeout for transfer sponsoring fungible item.93pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;94/// Default timeout for transfer sponsoring refungible item.95pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;9697/// Default timeout for sponsored approving.98pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;99100// Schema limits101pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;102pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;103pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;104105// TODO: not used. Delete?106pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;107108/// Maximal length of a collection name.109pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;110111/// Maximal length of a collection description.112pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;113114/// Maximal length of a token prefix.115pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;116117/// Maximal length of a property key.118pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;119120/// Maximal length of a property value.121pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;122123/// A maximum number of token properties.124pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;125126/// Maximal lenght of extended property value.127pub const MAX_AUX_PROPERTY_VALUE_LENGTH: u32 = 2048;128129/// Maximum size for all collection properties.130pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;131132/// Maximum size of all token properties.133pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;134135/// How much items can be created per single136/// create_many call.137pub const MAX_ITEMS_PER_BATCH: u32 = 200;138139/// Used for limit bounded types of token custom data.140pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;141142/// Collection id.143#[derive(144 Encode,145 Decode,146 PartialEq,147 Eq,148 PartialOrd,149 Ord,150 Clone,151 Copy,152 Debug,153 Default,154 TypeInfo,155 MaxEncodedLen,156 Serialize,157 Deserialize,158)]159pub struct CollectionId(pub u32);160impl EncodeLike<u32> for CollectionId {}161impl EncodeLike<CollectionId> for u32 {}162163impl From<u32> for CollectionId {164 fn from(value: u32) -> Self {165 Self(value)166 }167}168169impl Deref for CollectionId {170 type Target = u32;171172 fn deref(&self) -> &Self::Target {173 &self.0174 }175}176177/// Token id.178#[derive(179 Encode,180 Decode,181 PartialEq,182 Eq,183 PartialOrd,184 Ord,185 Clone,186 Copy,187 Debug,188 Default,189 TypeInfo,190 MaxEncodedLen,191 Serialize,192 Deserialize,193)]194pub struct TokenId(pub u32);195impl EncodeLike<u32> for TokenId {}196impl EncodeLike<TokenId> for u32 {}197198impl TokenId {199 /// Try to get next token id.200 ///201 /// If next id cause overflow, then [`ArithmeticError::Overflow`] returned.202 pub fn try_next(self) -> Result<TokenId, ArithmeticError> {203 self.0204 .checked_add(1)205 .ok_or(ArithmeticError::Overflow)206 .map(Self)207 }208}209210impl From<TokenId> for U256 {211 fn from(t: TokenId) -> Self {212 t.0.into()213 }214}215216impl TryFrom<U256> for TokenId {217 type Error = &'static str;218219 fn try_from(value: U256) -> Result<Self, Self::Error> {220 Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))221 }222}223224/// Token data.225#[struct_versioning::versioned(version = 2, upper)]226#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]227pub struct TokenData<CrossAccountId> {228 /// Properties of token.229 pub properties: Vec<Property>,230231 /// Token owner.232 pub owner: Option<CrossAccountId>,233234 /// Token pieces.235 #[version(2.., upper(0))]236 pub pieces: u128,237}238239// TODO: unused type240pub struct OverflowError;241impl From<OverflowError> for &'static str {242 fn from(_: OverflowError) -> Self {243 "overflow occured"244 }245}246247/// Alias for decimal points type.248pub type DecimalPoints = u8;249250/// Collection mode.251///252/// Collection can represent various types of tokens.253/// Each collection can contain only one type of tokens at a time.254/// This type helps to understand which tokens the collection contains.255#[derive(256 Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,257)]258pub enum CollectionMode {259 /// Non fungible tokens.260 NFT,261 /// Fungible tokens.262 Fungible(DecimalPoints),263 /// Refungible tokens.264 ReFungible,265}266267impl CollectionMode {268 /// Get collection mod as number.269 pub fn id(&self) -> u8 {270 match self {271 CollectionMode::NFT => 1,272 CollectionMode::Fungible(_) => 2,273 CollectionMode::ReFungible => 3,274 }275 }276}277278// TODO: unused trait279pub trait SponsoringResolve<AccountId, Call> {280 fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;281}282283/// Access mode for some token operations.284#[derive(285 Encode,286 Decode,287 Eq,288 Debug,289 Clone,290 Copy,291 PartialEq,292 TypeInfo,293 MaxEncodedLen,294 Serialize,295 Deserialize,296)]297pub enum AccessMode {298 /// Access grant for owner and admins. Used as default.299 Normal,300 /// Like a [`Normal`](AccessMode::Normal) but also users in allow list.301 AllowList,302}303impl Default for AccessMode {304 fn default() -> Self {305 Self::Normal306 }307}308309// TODO: remove in future.310#[derive(311 Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,312)]313pub enum SchemaVersion {314 ImageURL,315 Unique,316}317impl Default for SchemaVersion {318 fn default() -> Self {319 Self::ImageURL320 }321}322323// TODO: unused type324#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]325pub struct Ownership<AccountId> {326 pub owner: AccountId,327 pub fraction: u128,328}329330/// The state of collection sponsorship.331#[derive(332 Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,333)]334pub enum SponsorshipState<AccountId> {335 /// The fees are applied to the transaction sender.336 Disabled,337 /// The sponsor is under consideration. Until the sponsor gives his consent,338 /// the fee will still be charged to sender.339 Unconfirmed(AccountId),340 /// Transactions are sponsored by specified account.341 Confirmed(AccountId),342}343344impl<AccountId> SponsorshipState<AccountId> {345 /// Get a sponsor of the collection who has confirmed his status.346 pub fn sponsor(&self) -> Option<&AccountId> {347 match self {348 Self::Confirmed(sponsor) => Some(sponsor),349 _ => None,350 }351 }352353 /// Get a sponsor of the collection who has pending or confirmed status.354 pub fn pending_sponsor(&self) -> Option<&AccountId> {355 match self {356 Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),357 _ => None,358 }359 }360361 /// Whether the sponsorship is confirmed.362 pub fn confirmed(&self) -> bool {363 matches!(self, Self::Confirmed(_))364 }365}366367impl<T> Default for SponsorshipState<T> {368 fn default() -> Self {369 Self::Disabled370 }371}372373pub type CollectionName = BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>;374pub type CollectionDescription = BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>;375pub type CollectionTokenPrefix = BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>;376377#[derive(AbiCoderFlags, Bitfields, Clone, Copy, PartialEq, Eq, Debug, Default)]378#[bondrewd(enforce_bytes = 1)]379pub struct CollectionFlags {380 /// Tokens in foreign collections can be transferred, but not burnt381 #[bondrewd(bits = "0..1")]382 pub foreign: bool,383 /// Supports ERC721Metadata384 #[bondrewd(bits = "1..2")]385 pub erc721metadata: bool,386 /// External collections can't be managed using `unique` api387 #[bondrewd(bits = "7..8")]388 pub external: bool,389 /// Reserved flags390 #[bondrewd(bits = "2..7")]391 pub reserved: u8,392}393bondrewd_codec!(CollectionFlags);394395impl CollectionFlags {396 pub fn is_allowed_for_user(self) -> bool {397 !self.foreign && !self.external && self.reserved == 0398 }399}400401/// Base structure for represent collection.402///403/// Used to provide basic functionality for all types of collections.404///405/// #### Note406/// Collection parameters, used in storage (see [`RpcCollection`] for the RPC version).407#[struct_versioning::versioned(version = 2, upper)]408#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]409pub struct Collection<AccountId> {410 /// Collection owner account.411 pub owner: AccountId,412413 /// Collection mode.414 pub mode: CollectionMode,415416 /// Access mode.417 #[version(..2)]418 pub access: AccessMode,419420 /// Collection name.421 pub name: CollectionName,422423 /// Collection description.424 pub description: CollectionDescription,425426 /// Token prefix.427 pub token_prefix: CollectionTokenPrefix,428429 #[version(..2)]430 pub mint_mode: bool,431432 #[version(..2)]433 pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,434435 #[version(..2)]436 pub schema_version: SchemaVersion,437438 /// The state of sponsorship of the collection.439 pub sponsorship: SponsorshipState<AccountId>,440441 /// Collection limits.442 pub limits: CollectionLimits,443444 /// Collection permissions.445 #[version(2.., upper(Default::default()))]446 pub permissions: CollectionPermissions,447448 #[version(2.., upper(Default::default()))]449 pub flags: CollectionFlags,450451 #[version(..2)]452 pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,453454 #[version(..2)]455 pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,456457 #[version(..2)]458 pub meta_update_permission: MetaUpdatePermission,459}460461#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]462pub struct RpcCollectionFlags {463 /// Is collection is foreign.464 pub foreign: bool,465 /// Collection supports ERC721Metadata.466 pub erc721metadata: bool,467}468469/// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).470#[struct_versioning::versioned(version = 2, upper)]471#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]472pub struct RpcCollection<AccountId> {473 /// Collection owner account.474 pub owner: AccountId,475476 /// Collection mode.477 pub mode: CollectionMode,478479 /// Collection name.480 pub name: Vec<u16>,481482 /// Collection description.483 pub description: Vec<u16>,484485 /// Token prefix.486 pub token_prefix: Vec<u8>,487488 /// The state of sponsorship of the collection.489 pub sponsorship: SponsorshipState<AccountId>,490491 /// Collection limits.492 pub limits: CollectionLimits,493494 /// Collection permissions.495 pub permissions: CollectionPermissions,496497 /// Token property permissions.498 pub token_property_permissions: Vec<PropertyKeyPermission>,499500 /// Collection properties.501 pub properties: Vec<Property>,502503 /// Is collection read only.504 pub read_only: bool,505506 /// Extra collection flags507 #[version(2.., upper(RpcCollectionFlags {foreign: false, erc721metadata: false}))]508 pub flags: RpcCollectionFlags,509}510511impl<AccountId> From<CollectionVersion1<AccountId>> for RpcCollection<AccountId> {512 fn from(value: CollectionVersion1<AccountId>) -> Self {513 let CollectionVersion1 {514 name,515 description,516 owner,517 mode,518 access,519 token_prefix,520 mint_mode,521 sponsorship,522 limits,523 ..524 } = value;525526 RpcCollection {527 name: name.into_inner(),528 description: description.into_inner(),529 owner,530 mode,531 token_prefix: token_prefix.into_inner(),532 sponsorship,533 limits,534 permissions: CollectionPermissions {535 access: Some(access),536 mint_mode: Some(mint_mode),537 nesting: None,538 },539 token_property_permissions: Vec::default(),540 properties: Vec::default(),541 read_only: true,542543 flags: RpcCollectionFlags {544 foreign: false,545 erc721metadata: false,546 },547 }548 }549}550551pub struct RawEncoded(Vec<u8>);552553impl parity_scale_codec::Decode for RawEncoded {554 fn decode<I: parity_scale_codec::Input>(555 input: &mut I,556 ) -> Result<Self, parity_scale_codec::Error> {557 let mut out = Vec::new();558 while let Ok(v) = input.read_byte() {559 out.push(v);560 }561 Ok(Self(out))562 }563}564565impl Deref for RawEncoded {566 type Target = Vec<u8>;567568 fn deref(&self) -> &Self::Target {569 &self.0570 }571}572573/// Data used for create collection.574///575/// All fields are wrapped in [`Option`], where `None` means chain default.576#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]577#[derivative(Debug, Default(bound = ""))]578pub struct CreateCollectionData<CrossAccountId> {579 /// Collection mode.580 #[derivative(Default(value = "CollectionMode::NFT"))]581 pub mode: CollectionMode,582583 /// Access mode.584 pub access: Option<AccessMode>,585586 /// Collection name.587 pub name: CollectionName,588589 /// Collection description.590 pub description: CollectionDescription,591592 /// Token prefix.593 pub token_prefix: CollectionTokenPrefix,594595 /// Collection limits.596 pub limits: Option<CollectionLimits>,597598 /// Collection permissions.599 pub permissions: Option<CollectionPermissions>,600601 /// Token property permissions.602 pub token_property_permissions: CollectionPropertiesPermissionsVec,603604 /// Collection properties.605 pub properties: CollectionPropertiesVec,606607 pub admin_list: Vec<CrossAccountId>,608609 /// Pending collection sponsor.610 pub pending_sponsor: Option<CrossAccountId>,611612 pub flags: CollectionFlags,613}614615/// Bounded vector of properties permissions. Max length is [`MAX_PROPERTIES_PER_ITEM`].616// TODO: maybe rename to PropertiesPermissionsVec617pub type CollectionPropertiesPermissionsVec =618 BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;619620/// Bounded vector of properties. Max length is [`MAX_PROPERTIES_PER_ITEM`].621pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;622623/// Limits and restrictions of a collection.624///625/// All fields are wrapped in [`Option`], where `None` means chain default.626///627/// Update with `pallet_common::Pallet::clamp_limits`.628// IMPORTANT: When adding/removing fields from this struct - don't forget to also629#[derive(630 Encode,631 Decode,632 Debug,633 Default,634 Clone,635 PartialEq,636 TypeInfo,637 MaxEncodedLen,638 Serialize,639 Deserialize,640)]641// When adding/removing fields from this struct - don't forget to also update with `pallet_common::Pallet::clamp_limits`.642// TODO: move `pallet_common::Pallet::clamp_limits` into `impl CollectionLimits`.643// TODO: may be remove [`Option`] and **pub** from fields and create struct with default values.644pub struct CollectionLimits {645 /// How many tokens can a user have on one account.646 /// * Default - [`ACCOUNT_TOKEN_OWNERSHIP_LIMIT`].647 /// * Limit - [`MAX_TOKEN_OWNERSHIP`].648 pub account_token_ownership_limit: Option<u32>,649650 /// How many bytes of data are available for sponsorship.651 /// * Default - [`CUSTOM_DATA_LIMIT`].652 /// * Limit - [`CUSTOM_DATA_LIMIT`].653 pub sponsored_data_size: Option<u32>,654655 // FIXME should we delete this or repurpose it?656 /// Times in how many blocks we sponsor data.657 ///658 /// If is `Some(v)` then **setVariableMetadata** is sponsored if there is `v` block between transactions.659 ///660 /// * Default - [`SponsoringDisabled`](SponsoringRateLimit::SponsoringDisabled).661 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].662 ///663 /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]664 pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,665 /// Maximum amount of tokens inside the collection. Chain default: [`COLLECTION_TOKEN_LIMIT`]666667 /// How many tokens can be mined into this collection.668 ///669 /// * Default - [`COLLECTION_TOKEN_LIMIT`].670 /// * Limit - [`COLLECTION_TOKEN_LIMIT`].671 pub token_limit: Option<u32>,672673 /// Timeouts for transfer sponsoring.674 ///675 /// * Default676 /// - **Fungible** - [`FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]677 /// - **NFT** - [`NFT_SPONSOR_TRANSFER_TIMEOUT`]678 /// - **Refungible** - [`REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]679 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].680 pub sponsor_transfer_timeout: Option<u32>,681682 /// Timeout for sponsoring an approval in passed blocks.683 ///684 /// * Default - [`SPONSOR_APPROVE_TIMEOUT`].685 /// * Limit - [`MAX_SPONSOR_TIMEOUT`].686 pub sponsor_approve_timeout: Option<u32>,687688 /// Whether the collection owner of the collection can send tokens (which belong to other users).689 ///690 /// * Default - **false**.691 pub owner_can_transfer: Option<bool>,692693 /// Can the collection owner burn other people's tokens.694 ///695 /// * Default - **true**.696 pub owner_can_destroy: Option<bool>,697698 /// Is it possible to send tokens from this collection between users.699 ///700 /// * Default - **true**.701 pub transfers_enabled: Option<bool>,702}703704impl CollectionLimits {705 pub fn with_default_limits(collection_type: CollectionMode) -> Self {706 CollectionLimits {707 account_token_ownership_limit: Some(ACCOUNT_TOKEN_OWNERSHIP_LIMIT),708 sponsored_data_size: Some(CUSTOM_DATA_LIMIT),709 sponsored_data_rate_limit: Some(SponsoringRateLimit::SponsoringDisabled),710 token_limit: Some(COLLECTION_TOKEN_LIMIT),711 sponsor_transfer_timeout: match collection_type {712 CollectionMode::NFT => Some(NFT_SPONSOR_TRANSFER_TIMEOUT),713 CollectionMode::ReFungible => Some(REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT),714 CollectionMode::Fungible(_) => Some(FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT),715 },716 sponsor_approve_timeout: Some(SPONSOR_APPROVE_TIMEOUT),717 owner_can_transfer: Some(false),718 owner_can_destroy: Some(true),719 transfers_enabled: Some(true),720 }721 }722723 /// Get effective value for [`account_token_ownership_limit`](self.account_token_ownership_limit).724 pub fn account_token_ownership_limit(&self) -> u32 {725 self.account_token_ownership_limit726 .unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)727 .min(MAX_TOKEN_OWNERSHIP)728 }729730 /// Get effective value for [`sponsored_data_size`](self.sponsored_data_size).731 pub fn sponsored_data_size(&self) -> u32 {732 self.sponsored_data_size733 .unwrap_or(CUSTOM_DATA_LIMIT)734 .min(CUSTOM_DATA_LIMIT)735 }736737 /// Get effective value for [`token_limit`](self.token_limit).738 pub fn token_limit(&self) -> u32 {739 self.token_limit740 .unwrap_or(COLLECTION_TOKEN_LIMIT)741 .min(COLLECTION_TOKEN_LIMIT)742 }743744 // TODO: may be replace u32 to mode?745 /// Get effective value for [`sponsor_transfer_timeout`](self.sponsor_transfer_timeout).746 pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {747 self.sponsor_transfer_timeout748 .unwrap_or(default)749 .min(MAX_SPONSOR_TIMEOUT)750 }751752 /// Get effective value for [`sponsor_approve_timeout`](self.sponsor_approve_timeout).753 pub fn sponsor_approve_timeout(&self) -> u32 {754 self.sponsor_approve_timeout755 .unwrap_or(SPONSOR_APPROVE_TIMEOUT)756 .min(MAX_SPONSOR_TIMEOUT)757 }758759 /// Get effective value for [`owner_can_transfer`](self.owner_can_transfer).760 pub fn owner_can_transfer(&self) -> bool {761 self.owner_can_transfer.unwrap_or(false)762 }763764 /// Get effective value for [`owner_can_transfer_instaled`](self.owner_can_transfer_instaled).765 pub fn owner_can_transfer_instaled(&self) -> bool {766 self.owner_can_transfer.is_some()767 }768769 /// Get effective value for [`owner_can_destroy`](self.owner_can_destroy).770 pub fn owner_can_destroy(&self) -> bool {771 self.owner_can_destroy.unwrap_or(true)772 }773774 /// Get effective value for [`transfers_enabled`](self.transfers_enabled).775 pub fn transfers_enabled(&self) -> bool {776 self.transfers_enabled.unwrap_or(true)777 }778779 /// Get effective value for [`sponsored_data_rate_limit`](self.sponsored_data_rate_limit).780 pub fn sponsored_data_rate_limit(&self) -> Option<u32> {781 match self782 .sponsored_data_rate_limit783 .unwrap_or(SponsoringRateLimit::SponsoringDisabled)784 {785 SponsoringRateLimit::SponsoringDisabled => None,786 SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),787 }788 }789}790791/// Permissions on certain operations within a collection.792///793/// Some fields are wrapped in [`Option`], where `None` means chain default.794///795/// Update with `pallet_common::Pallet::clamp_permissions`.796#[derive(797 Encode,798 Decode,799 Debug,800 Default,801 Clone,802 PartialEq,803 TypeInfo,804 MaxEncodedLen,805 Serialize,806 Deserialize,807)]808// When adding/removing fields from this struct - don't forget to also update `pallet_common::Pallet::clamp_permissions`.809// TODO: move `pallet_common::Pallet::clamp_permissions` into `impl CollectionPermissions`.810pub struct CollectionPermissions {811 /// Access mode.812 ///813 /// * Default - [`AccessMode::Normal`].814 pub access: Option<AccessMode>,815816 /// Minting allowance.817 ///818 /// * Default - **false**.819 pub mint_mode: Option<bool>,820821 /// Permissions for nesting.822 ///823 /// * Default824 /// - `token_owner` - **false**825 /// - `collection_admin` - **false**826 /// - `restricted` - **None**827 pub nesting: Option<NestingPermissions>,828}829830impl CollectionPermissions {831 /// Get effective value for [`access`](self.access).832 pub fn access(&self) -> AccessMode {833 self.access.unwrap_or(AccessMode::Normal)834 }835836 /// Get effective value for [`mint_mode`](self.mint_mode).837 pub fn mint_mode(&self) -> bool {838 self.mint_mode.unwrap_or(false)839 }840841 /// Get effective value for [`nesting`](self.nesting).842 pub fn nesting(&self) -> &NestingPermissions {843 static DEFAULT: NestingPermissions = NestingPermissions {844 token_owner: false,845 collection_admin: false,846 restricted: None,847 #[cfg(feature = "runtime-benchmarks")]848 permissive: false,849 };850 self.nesting.as_ref().unwrap_or(&DEFAULT)851 }852}853854/// Inner set for collections allowed to nest.855type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;856857/// Wraper for collections set allowing nest.858#[derive(859 Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative, Serialize, Deserialize,860)]861#[derivative(Debug)]862pub struct OwnerRestrictedSet(863 #[serde(with = "bounded::set_serde")]864 #[derivative(Debug(format_with = "bounded::set_debug"))]865 pub OwnerRestrictedSetInner,866);867868impl OwnerRestrictedSet {869 /// Create new set.870 pub fn new() -> Self {871 Self(Default::default())872 }873}874impl Default for OwnerRestrictedSet {875 fn default() -> Self {876 Self::new()877 }878}879impl core::ops::Deref for OwnerRestrictedSet {880 type Target = OwnerRestrictedSetInner;881 fn deref(&self) -> &Self::Target {882 &self.0883 }884}885impl core::ops::DerefMut for OwnerRestrictedSet {886 fn deref_mut(&mut self) -> &mut Self::Target {887 &mut self.0888 }889}890891impl TryFrom<BTreeSet<CollectionId>> for OwnerRestrictedSet {892 type Error = ();893894 fn try_from(value: BTreeSet<CollectionId>) -> Result<Self, Self::Error> {895 Ok(Self(value.try_into()?))896 }897}898899/// Part of collection permissions, if set, defines who is able to nest tokens into other tokens.900#[derive(901 Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative, Serialize, Deserialize,902)]903#[derivative(Debug)]904pub struct NestingPermissions {905 /// Owner of token can nest tokens under it.906 pub token_owner: bool,907 /// Admin of token collection can nest tokens under token.908 pub collection_admin: bool,909 /// If set - only tokens from specified collections can be nested.910 pub restricted: Option<OwnerRestrictedSet>,911912 #[cfg(feature = "runtime-benchmarks")]913 /// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`.914 pub permissive: bool,915}916917/// Enum denominating how often can sponsoring occur if it is enabled.918///919/// Used for [`collection limits`](CollectionLimits).920#[derive(921 Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,922)]923pub enum SponsoringRateLimit {924 /// Sponsoring is disabled, and the collection sponsor will not pay for transactions925 SponsoringDisabled,926 /// Once per how many blocks can sponsorship of a transaction type occur927 Blocks(u32),928}929930/// Data used to describe an NFT at creation.931#[derive(932 Encode,933 Decode,934 MaxEncodedLen,935 Default,936 PartialEq,937 Clone,938 Derivative,939 TypeInfo,940 Serialize,941 Deserialize,942)]943#[derivative(Debug)]944pub struct CreateNftData {945 /// Key-value pairs used to describe the token as metadata946 #[serde(with = "bounded::vec_serde")]947 #[derivative(Debug(format_with = "bounded::vec_debug"))]948 /// Properties that wil be assignet to created item.949 pub properties: CollectionPropertiesVec,950}951952/// Data used to describe a Fungible token at creation.953#[derive(954 Encode,955 Decode,956 MaxEncodedLen,957 Default,958 Debug,959 Clone,960 PartialEq,961 TypeInfo,962 Serialize,963 Deserialize,964)]965pub struct CreateFungibleData {966 /// Number of fungible coins minted967 pub value: u128,968}969970/// Data used to describe a Refungible token at creation.971#[derive(972 Encode,973 Decode,974 MaxEncodedLen,975 Default,976 PartialEq,977 Clone,978 Derivative,979 TypeInfo,980 Serialize,981 Deserialize,982)]983#[derivative(Debug)]984pub struct CreateReFungibleData {985 /// Number of pieces the RFT is split into986 pub pieces: u128,987988 /// Key-value pairs used to describe the token as metadata989 #[serde(with = "bounded::vec_serde")]990 #[derivative(Debug(format_with = "bounded::vec_debug"))]991 pub properties: CollectionPropertiesVec,992}993994// TODO: remove this.995#[derive(996 Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,997)]998pub enum MetaUpdatePermission {999 ItemOwner,1000 Admin,1001 None,1002}10031004/// Enum holding data used for creation of all three item types.1005/// Unified data for create item.1006#[derive(1007 Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo, Serialize, Deserialize,1008)]1009pub enum CreateItemData {1010 /// Data for create NFT.1011 NFT(CreateNftData),1012 /// Data for create Fungible item.1013 Fungible(CreateFungibleData),1014 /// Data for create ReFungible item.1015 ReFungible(CreateReFungibleData),1016}10171018/// Extended data for create NFT.1019#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]1020#[derivative(Debug)]1021pub struct CreateNftExData<CrossAccountId> {1022 /// Properties that wil be assignet to created item.1023 #[derivative(Debug(format_with = "bounded::vec_debug"))]1024 pub properties: CollectionPropertiesVec,10251026 /// Owner of creating item.1027 pub owner: CrossAccountId,1028}10291030/// Extended data for create ReFungible item.1031#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]1032#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]1033pub struct CreateRefungibleExMultipleOwners<CrossAccountId> {1034 #[derivative(Debug(format_with = "bounded::map_debug"))]1035 pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,1036 #[derivative(Debug(format_with = "bounded::vec_debug"))]1037 pub properties: CollectionPropertiesVec,1038}10391040/// Extended data for create ReFungible item.1041#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]1042#[derivative(Debug(bound = "CrossAccountId: fmt::Debug"))]1043pub struct CreateRefungibleExSingleOwner<CrossAccountId> {1044 pub user: CrossAccountId,1045 pub pieces: u128,1046 #[derivative(Debug(format_with = "bounded::vec_debug"))]1047 pub properties: CollectionPropertiesVec,1048}10491050/// Unified extended data for creating item.1051#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]1052#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]1053pub enum CreateItemExData<CrossAccountId> {1054 /// Extended data for create NFT.1055 NFT(1056 #[derivative(Debug(format_with = "bounded::vec_debug"))]1057 BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,1058 ),10591060 /// Extended data for create Fungible item.1061 Fungible(1062 #[derivative(Debug(format_with = "bounded::map_debug"))]1063 BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,1064 ),10651066 /// Extended data for create ReFungible item in case of1067 /// many tokens, each may have only one owner1068 RefungibleMultipleItems(1069 #[derivative(Debug(format_with = "bounded::vec_debug"))]1070 BoundedVec<CreateRefungibleExSingleOwner<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,1071 ),10721073 /// Extended data for create ReFungible item in case of1074 /// single token, which may have many owners1075 RefungibleMultipleOwners(CreateRefungibleExMultipleOwners<CrossAccountId>),1076}10771078impl From<CreateNftData> for CreateItemData {1079 fn from(item: CreateNftData) -> Self {1080 CreateItemData::NFT(item)1081 }1082}10831084impl From<CreateReFungibleData> for CreateItemData {1085 fn from(item: CreateReFungibleData) -> Self {1086 CreateItemData::ReFungible(item)1087 }1088}10891090impl From<CreateFungibleData> for CreateItemData {1091 fn from(item: CreateFungibleData) -> Self {1092 CreateItemData::Fungible(item)1093 }1094}10951096/// Token's address, dictated by its collection and token IDs.1097#[derive(1098 Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo, Serialize, Deserialize,1099)]1100// todo possibly rename to be used generally as an address pair1101pub struct TokenChild {1102 /// Token id.1103 pub token: TokenId,11041105 /// Collection id.1106 pub collection: CollectionId,1107}11081109/// Collection statistics.1110#[derive(1111 Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo, Serialize, Deserialize,1112)]1113pub struct CollectionStats {1114 /// Number of created items.1115 pub created: u32,11161117 /// Number of burned items.1118 pub destroyed: u32,11191120 /// Number of current items.1121 pub alive: u32,1122}11231124/// This type works like [`PhantomData`] but supports generating _scale-info_ descriptions to generate node metadata.1125#[derive(Encode, Decode, Clone, Debug)]1126#[cfg_attr(feature = "std", derive(PartialEq))]1127pub struct PhantomType<T>(core::marker::PhantomData<T>);11281129impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {1130 type Identity = PhantomType<T>;11311132 fn type_info() -> scale_info::Type {1133 use scale_info::{1134 build::{FieldsBuilder, UnnamedFields},1135 form::MetaForm,1136 type_params, Path, Type,1137 };1138 Type::builder()1139 .path(Path::new("up_data_structs", "PhantomType"))1140 .type_params(type_params!(T))1141 .composite(1142 <FieldsBuilder<MetaForm, UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()),1143 )1144 }1145}1146impl<T> MaxEncodedLen for PhantomType<T> {1147 fn max_encoded_len() -> usize {1148 01149 }1150}11511152/// Bounded vector of bytes.1153pub type BoundedBytes<S> = BoundedVec<u8, S>;11541155/// Extra properties for external collections.1156pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;11571158/// Property key.1159pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;11601161/// Property value.1162pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;11631164/// Property permission.1165#[derive(1166 Encode,1167 Decode,1168 TypeInfo,1169 Debug,1170 MaxEncodedLen,1171 PartialEq,1172 Clone,1173 Default,1174 Serialize,1175 Deserialize,1176)]1177pub struct PropertyPermission {1178 /// Permission to change the property and property permission.1179 ///1180 /// If it **false** then you can not change corresponding property even if [`collection_admin`] and [`token_owner`] are **true**.1181 pub mutable: bool,11821183 /// Change permission for the collection administrator.1184 pub collection_admin: bool,11851186 /// Permission to change the property for the owner of the token.1187 pub token_owner: bool,1188}11891190impl PropertyPermission {1191 /// Creates mutable property permission but changes restricted for collection admin and token owner.1192 pub fn none() -> Self {1193 Self {1194 mutable: true,1195 collection_admin: false,1196 token_owner: false,1197 }1198 }1199}12001201/// Property is simpl key-value record.1202#[derive(1203 Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen, Serialize, Deserialize,1204)]1205pub struct Property {1206 /// Property key.1207 #[serde(with = "bounded::vec_serde")]1208 pub key: PropertyKey,12091210 /// Property value.1211 #[serde(with = "bounded::vec_serde")]1212 pub value: PropertyValue,1213}12141215impl From<Property> for (PropertyKey, PropertyValue) {1216 fn from(value: Property) -> Self {1217 (value.key, value.value)1218 }1219}12201221/// Record for proprty key permission.1222#[derive(1223 Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone, Serialize, Deserialize,1224)]1225pub struct PropertyKeyPermission {1226 /// Key.1227 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1228 pub key: PropertyKey,12291230 /// Permission.1231 pub permission: PropertyPermission,1232}12331234impl From<PropertyKeyPermission> for (PropertyKey, PropertyPermission) {1235 fn from(value: PropertyKeyPermission) -> Self {1236 (value.key, value.permission)1237 }1238}12391240/// Errors for properties actions.1241#[derive(Debug)]1242pub enum PropertiesError {1243 /// The space allocated for properties has run out.1244 ///1245 /// * Limit for colection - [`MAX_COLLECTION_PROPERTIES_SIZE`].1246 /// * Limit for token - [`MAX_TOKEN_PROPERTIES_SIZE`].1247 NoSpaceForProperty,12481249 /// The property limit has been reached.1250 ///1251 /// * Limit - [`MAX_PROPERTIES_PER_ITEM`].1252 PropertyLimitReached,12531254 /// Property key contains not allowed character.1255 InvalidCharacterInPropertyKey,12561257 /// Property key length is too long.1258 ///1259 /// * Limit - [`MAX_PROPERTY_KEY_LENGTH`].1260 PropertyKeyIsTooLong,12611262 /// Property key is empty.1263 EmptyPropertyKey,1264}12651266/// Token owner error: it could be either `NotFound` ot `MultipleOwners`.1267#[derive(Debug)]1268pub enum TokenOwnerError {1269 NotFound,1270 MultipleOwners,1271}12721273/// Marker for scope of property.1274///1275/// Scoped property can't be changed by user. Used for external collections.1276#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]1277pub enum PropertyScope {1278 None,1279 Rmrk,1280}12811282impl PropertyScope {1283 pub fn prefix(&self) -> &'static [u8] {1284 match self {1285 Self::None => b"",1286 Self::Rmrk => b"rmrk:",1287 }1288 }1289 /// Apply scope to property key.1290 pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {1291 let prefix = self.prefix();1292 if prefix == b"" {1293 return Ok(key);1294 }1295 [prefix, key.as_slice()]1296 .concat()1297 .try_into()1298 .map_err(|_| PropertiesError::PropertyKeyIsTooLong)1299 }1300}13011302/// Trait for operate with properties.1303pub trait TrySetProperty: Sized {1304 type Value;13051306 /// Try to set property with scope.1307 fn try_scoped_set(1308 &mut self,1309 scope: PropertyScope,1310 key: PropertyKey,1311 value: Self::Value,1312 ) -> Result<Option<Self::Value>, PropertiesError>;13131314 /// Try to set property with scope from iterator.1315 fn try_scoped_set_from_iter<I, KV>(1316 &mut self,1317 scope: PropertyScope,1318 iter: I,1319 ) -> Result<(), PropertiesError>1320 where1321 I: Iterator<Item = KV>,1322 KV: Into<(PropertyKey, Self::Value)>,1323 {1324 for kv in iter {1325 let (key, value) = kv.into();1326 self.try_scoped_set(scope, key, value)?;1327 }13281329 Ok(())1330 }13311332 /// Try to set property.1333 fn try_set(1334 &mut self,1335 key: PropertyKey,1336 value: Self::Value,1337 ) -> Result<Option<Self::Value>, PropertiesError> {1338 self.try_scoped_set(PropertyScope::None, key, value)1339 }13401341 /// Try to set property from iterator.1342 fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>1343 where1344 I: Iterator<Item = KV>,1345 KV: Into<(PropertyKey, Self::Value)>,1346 {1347 self.try_scoped_set_from_iter(PropertyScope::None, iter)1348 }1349}13501351/// Wrapped map for storing properties.1352#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]1353#[derivative(Default(bound = ""))]1354pub struct PropertiesMap<Value>(1355 BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,1356);13571358impl<Value> PropertiesMap<Value> {1359 /// Create new property map.1360 pub fn new() -> Self {1361 Self(BoundedBTreeMap::new())1362 }13631364 /// Remove property from map.1365 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {1366 Self::check_property_key(key)?;13671368 Ok(self.0.remove(key))1369 }13701371 /// Get property with appropriate key from map.1372 pub fn get(&self, key: &PropertyKey) -> Option<&Value> {1373 self.0.get(key)1374 }13751376 /// Check if map contains key.1377 pub fn contains_key(&self, key: &PropertyKey) -> bool {1378 self.0.contains_key(key)1379 }13801381 /// Check if map contains key with key validation.1382 fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {1383 if key.is_empty() {1384 return Err(PropertiesError::EmptyPropertyKey);1385 }13861387 for byte in key.as_slice().iter() {1388 let byte = *byte;13891390 if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' && byte != b'.' {1391 return Err(PropertiesError::InvalidCharacterInPropertyKey);1392 }1393 }13941395 Ok(())1396 }13971398 pub fn values(&self) -> impl Iterator<Item = &Value> {1399 self.0.values()1400 }14011402 pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &Value)> {1403 self.0.iter()1404 }1405}14061407impl<Value> IntoIterator for PropertiesMap<Value> {1408 type Item = (PropertyKey, Value);1409 type IntoIter = <1410 BoundedBTreeMap<1411 PropertyKey,1412 Value,1413 ConstU32<MAX_PROPERTIES_PER_ITEM>1414 > as IntoIterator1415 >::IntoIter;14161417 fn into_iter(self) -> Self::IntoIter {1418 self.0.into_iter()1419 }1420}14211422impl<Value> TrySetProperty for PropertiesMap<Value> {1423 type Value = Value;14241425 fn try_scoped_set(1426 &mut self,1427 scope: PropertyScope,1428 key: PropertyKey,1429 value: Self::Value,1430 ) -> Result<Option<Self::Value>, PropertiesError> {1431 Self::check_property_key(&key)?;14321433 let key = scope.apply(key)?;1434 self.01435 .try_insert(key, value)1436 .map_err(|_| PropertiesError::PropertyLimitReached)1437 }1438}14391440/// Alias for property permissions map.1441pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;14421443fn slice_size(data: &[u8]) -> u32 {1444 scoped_slice_size(PropertyScope::None, data)1445}1446fn scoped_slice_size(scope: PropertyScope, data: &[u8]) -> u32 {1447 use parity_scale_codec::Compact;1448 let prefix = scope.prefix();1449 <Compact<u32>>::encoded_size(&Compact(data.len() as u32 + prefix.len() as u32)) as u321450 + data.len() as u321451 + prefix.len() as u321452}14531454/// Wrapper for properties map with consumed space control.1455#[derive(Encode, Decode, TypeInfo, Clone, PartialEq)]1456pub struct Properties<const S: u32> {1457 map: PropertiesMap<PropertyValue>,1458 consumed_space: u32,1459 // May be not zero, previously served as a current S generic1460 _reserved: u32,1461}14621463impl<const S: u32> MaxEncodedLen for Properties<S> {1464 fn max_encoded_len() -> usize {1465 // len of map + len of consumed_space + len of space_limit1466 u32::max_encoded_len() * 3 + S as usize1467 }1468}14691470impl<const S: u32> Default for Properties<S> {1471 fn default() -> Self {1472 Self::new()1473 }1474}14751476impl<const S: u32> Properties<S> {1477 /// Create new properies container.1478 pub fn new() -> Self {1479 Self {1480 map: PropertiesMap::new(),1481 consumed_space: 0,1482 _reserved: 0,1483 }1484 }14851486 /// Remove propery with appropiate key.1487 pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {1488 let value = self.map.remove(key)?;14891490 if let Some(ref value) = value {1491 let kv_len = slice_size(key) + slice_size(value);1492 self.consumed_space = self.consumed_space.saturating_sub(kv_len);1493 }14941495 Ok(value)1496 }14971498 /// Get property with appropriate key.1499 pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {1500 self.map.get(key)1501 }15021503 /// Recomputes the consumed space for the current properties state.1504 /// Needed to repair a token due to a bug fixed in the [PR #733](https://github.com/UniqueNetwork/unique-chain/pull/773).1505 pub fn recompute_consumed_space(&mut self) {1506 self.consumed_space = self1507 .map1508 .iter()1509 .map(|(key, value)| slice_size(key) + slice_size(value))1510 .sum();1511 }1512}15131514impl<const S: u32> IntoIterator for Properties<S> {1515 type Item = (PropertyKey, PropertyValue);1516 type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;15171518 fn into_iter(self) -> Self::IntoIter {1519 self.map.into_iter()1520 }1521}15221523impl<const S: u32> TrySetProperty for Properties<S> {1524 type Value = PropertyValue;15251526 fn try_scoped_set(1527 &mut self,1528 scope: PropertyScope,1529 key: PropertyKey,1530 value: Self::Value,1531 ) -> Result<Option<Self::Value>, PropertiesError> {1532 let key_size = scoped_slice_size(scope, &key);1533 let value_size = slice_size(&value);15341535 if self.consumed_space + value_size + key_size > S && !cfg!(feature = "runtime-benchmarks")1536 {1537 return Err(PropertiesError::NoSpaceForProperty);1538 }15391540 let old_value = self.map.try_scoped_set(scope, key, value)?;15411542 if let Some(old_value) = old_value.as_ref() {1543 let old_value_size = slice_size(old_value);1544 self.consumed_space = self.consumed_space.saturating_sub(old_value_size) + value_size;1545 } else {1546 self.consumed_space += key_size + value_size;1547 }15481549 Ok(old_value)1550 }1551}15521553pub type CollectionProperties = Properties<MAX_COLLECTION_PROPERTIES_SIZE>;1554pub type TokenProperties = Properties<MAX_TOKEN_PROPERTIES_SIZE>;primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -82,7 +82,7 @@
collection: CollectionId,
token_id: TokenId,
keys: Option<Vec<Vec<u8>>>
- ) -> Result<TokenDataVersion1<CrossAccountId>>;
+ ) -> Result<up_data_structs::TokenDataVersion1<CrossAccountId>>;
/// Total number of tokens in collection.
fn total_supply(collection: CollectionId) -> Result<u32>;
@@ -117,7 +117,7 @@
fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>>;
#[changed_in(3)]
- fn collection_by_id(collection: CollectionId) -> Result<Option<RawEncoded>>;
+ fn collection_by_id(collection: CollectionId) -> Result<Option<up_data_structs::RawEncoded>>;
/// Get collection stats.
fn collection_stats() -> Result<CollectionStats>;
runtime/common/config/pallets/collator_selection.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/collator_selection.rs
+++ b/runtime/common/config/pallets/collator_selection.rs
@@ -107,6 +107,7 @@
impl pallet_collator_selection::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
+ type RuntimeHoldReason = RuntimeHoldReason;
type Currency = Balances;
// We allow root only to execute privileged collator selection operations.
@@ -128,7 +129,6 @@
type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
type ValidatorRegistration = Session;
type WeightInfo = pallet_collator_selection::weights::SubstrateWeight<Runtime>;
- type LicenceBondIdentifier = LicenceBondIdentifier;
type DesiredCollators = DesiredCollators;
type LicenseBond = LicenseBond;
type KickThreshold = KickThreshold;
runtime/common/config/substrate.rsdiffbeforeafterboth--- a/runtime/common/config/substrate.rs
+++ b/runtime/common/config/substrate.rs
@@ -76,10 +76,10 @@
type BaseCallFilter = Everything;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = BlockHashCount;
+ /// The block type.
+ type Block = Block;
/// The maximum length of a block (in bytes).
type BlockLength = RuntimeBlockLength;
- /// The index type for blocks.
- type BlockNumber = BlockNumber;
/// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.
type BlockWeights = RuntimeBlockWeights;
/// The aggregated dispatch type that is available for extrinsics.
@@ -92,10 +92,8 @@
type Hash = Hash;
/// The hashing algorithm used.
type Hashing = BlakeTwo256;
- /// The header type.
- type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// The index type for storing how many extrinsics an account has signed.
- type Index = Index;
+ type Nonce = Nonce;
/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
type Lookup = AccountIdLookup<AccountId, ()>;
/// What to do if an account is fully reaped from the system.
@@ -171,7 +169,7 @@
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;
- type HoldIdentifier = [u8; 16];
+ type RuntimeHoldReason = RuntimeHoldReason;
type FreezeIdentifier = [u8; 16];
type MaxHolds = MaxHolds;
type MaxFreezes = MaxFreezes;
@@ -247,6 +245,7 @@
type AuthorityId = AuraId;
type DisabledValidators = ();
type MaxAuthorities = MaxAuthorities;
+ type AllowMultipleBlocksPerSlot = ConstBool<true>;
}
impl pallet_utility::Config for Runtime {
runtime/common/config/xcm/foreignassets.rsdiffbeforeafterboth--- a/runtime/common/config/xcm/foreignassets.rs
+++ b/runtime/common/config/xcm/foreignassets.rs
@@ -36,17 +36,11 @@
pub CheckingAccount: AccountId = PolkadotXcm::check_account();
}
-pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);
-impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>
- ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>
-where
- AssetId: Borrow<AssetId>,
- AssetId: TryAsForeign<AssetId, ForeignAssetId>,
- AssetIds: Borrow<AssetId>,
+pub struct AsInnerId<ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);
+impl<ConvertAssetId: MaybeEquivalence<AssetId, AssetId>> MaybeEquivalence<MultiLocation, AssetId>
+ for AsInnerId<ConvertAssetId>
{
- fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {
- let id = id.borrow();
-
+ fn convert(id: &MultiLocation) -> Option<AssetId> {
log::trace!(
target: "xcm::AsInnerId::Convert",
"AsInnerId {:?}",
@@ -58,52 +52,46 @@
let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
if *id == parent {
- return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));
+ return ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Parent));
}
if *id == here || *id == self_location {
- return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));
+ return ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Here));
}
match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(*id) {
- Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {
- ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))
+ Some(AssetId::ForeignAssetId(foreign_asset_id)) => {
+ ConvertAssetId::convert(&AssetId::ForeignAssetId(foreign_asset_id))
}
- _ => Err(()),
+ _ => None,
}
}
- fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {
+ fn convert_back(asset_id: &AssetId) -> Option<MultiLocation> {
log::trace!(
target: "xcm::AsInnerId::Reverse",
"AsInnerId",
);
-
- let asset_id = what.borrow();
let parent_id =
- ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();
+ ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Parent)).unwrap();
let here_id =
- ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();
+ ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Here)).unwrap();
if asset_id.clone() == parent_id {
- return Ok(MultiLocation::parent());
+ return Some(MultiLocation::parent());
}
if asset_id.clone() == here_id {
- return Ok(MultiLocation::new(
+ return Some(MultiLocation::new(
1,
X1(Parachain(ParachainInfo::get().into())),
));
}
- match <AssetId as TryAsForeign<AssetId, ForeignAssetId>>::try_as_foreign(asset_id.clone()) {
- Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {
- Some(location) => Ok(location),
- None => Err(()),
- },
- None => Err(()),
- }
+ let fid =
+ <AssetId as TryAsForeign<AssetId, ForeignAssetId>>::try_as_foreign(asset_id.clone())?;
+ XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid)
}
}
@@ -112,7 +100,7 @@
// Use this fungibles implementation:
ForeignAssets,
// Use this currency when it is a fungible asset matching the given location or name:
- ConvertedConcreteId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,
+ ConvertedConcreteId<AssetId, Balance, AsInnerId<JustTry>, JustTry>,
// Convert an XCM MultiLocation into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
@@ -154,7 +142,7 @@
what: &MultiAsset,
who: &MultiLocation,
maybe_context: Option<&XcmContext>,
- ) -> Result<xcm_executor::Assets, XcmError> {
+ ) -> Result<staging_xcm_executor::Assets, XcmError> {
FungiblesTransactor::withdraw_asset(what, who, maybe_context)
}
@@ -163,7 +151,7 @@
from: &MultiLocation,
to: &MultiLocation,
context: &XcmContext,
- ) -> Result<xcm_executor::Assets, XcmError> {
+ ) -> Result<staging_xcm_executor::Assets, XcmError> {
FungiblesTransactor::internal_transfer_asset(what, from, to, context)
}
}
@@ -179,15 +167,15 @@
>;
pub struct CurrencyIdConvert;
-impl Convert<AssetIds, Option<MultiLocation>> for CurrencyIdConvert {
- fn convert(id: AssetIds) -> Option<MultiLocation> {
+impl Convert<AssetId, Option<MultiLocation>> for CurrencyIdConvert {
+ fn convert(id: AssetId) -> Option<MultiLocation> {
match id {
- AssetIds::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
+ AssetId::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
1,
X1(Parachain(ParachainInfo::get().into())),
)),
- AssetIds::NativeAssetId(NativeCurrency::Parent) => Some(MultiLocation::parent()),
- AssetIds::ForeignAssetId(foreign_asset_id) => {
+ AssetId::NativeAssetId(NativeCurrency::Parent) => Some(MultiLocation::parent()),
+ AssetId::ForeignAssetId(foreign_asset_id) => {
XcmForeignAssetIdMapping::<Runtime>::get_multi_location(foreign_asset_id)
}
}
@@ -199,11 +187,11 @@
if location == MultiLocation::here()
|| location == MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())))
{
- return Some(AssetIds::NativeAssetId(NativeCurrency::Here));
+ return Some(AssetId::NativeAssetId(NativeCurrency::Here));
}
if location == MultiLocation::parent() {
- return Some(AssetIds::NativeAssetId(NativeCurrency::Parent));
+ return Some(AssetId::NativeAssetId(NativeCurrency::Parent));
}
if let Some(currency_id) = XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location) {
runtime/common/config/xcm/mod.rsdiffbeforeafterboth--- a/runtime/common/config/xcm/mod.rs
+++ b/runtime/common/config/xcm/mod.rs
@@ -153,10 +153,10 @@
origin: &MultiLocation,
message: &mut [Instruction<Call>],
max_weight: Weight,
- weight_credit: &mut Weight,
+ properties: &mut Properties,
) -> Result<(), ProcessMessageError> {
Deny::try_pass(origin, message)?;
- Allow::should_execute(origin, message, max_weight, weight_credit)
+ Allow::should_execute(origin, message, max_weight, properties)
}
}
@@ -211,7 +211,7 @@
}
pub struct XcmExecutorConfig<T>(PhantomData<T>);
-impl<T> xcm_executor::Config for XcmExecutorConfig<T>
+impl<T> staging_xcm_executor::Config for XcmExecutorConfig<T>
where
T: pallet_configuration::Config,
{
@@ -240,6 +240,7 @@
type UniversalAliases = Nothing;
type CallDispatcher = RuntimeCall;
type SafeCallFilter = XcmCallFilter;
+ type Aliasers = Nothing;
}
#[cfg(feature = "runtime-benchmarks")]
runtime/common/config/xcm/nativeassets.rsdiffbeforeafterboth--- a/runtime/common/config/xcm/nativeassets.rs
+++ b/runtime/common/config/xcm/nativeassets.rs
@@ -106,7 +106,12 @@
Self(Weight::from_parts(0, 0), Zero::zero(), PhantomData)
}
- fn buy_weight(&mut self, _weight: Weight, payment: Assets) -> Result<Assets, XcmError> {
+ fn buy_weight(
+ &mut self,
+ _weight: Weight,
+ payment: Assets,
+ _xcm: &XcmContext,
+ ) -> Result<Assets, XcmError> {
Ok(payment)
}
}
runtime/common/construct_runtime.rsdiffbeforeafterboth--- a/runtime/common/construct_runtime.rs
+++ b/runtime/common/construct_runtime.rs
@@ -19,11 +19,7 @@
() => {
frame_support::construct_runtime! {
- pub enum Runtime where
- Block = Block,
- NodeBlock = opaque::Block,
- UncheckedExtrinsic = UncheckedExtrinsic
- {
+ pub enum Runtime {
System: frame_system = 0,
StateTrieMigration: pallet_state_trie_migration = 1,
runtime/common/mod.rsdiffbeforeafterboth--- a/runtime/common/mod.rs
+++ b/runtime/common/mod.rs
@@ -63,12 +63,15 @@
/// The address format for describing accounts.
pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
-/// Block header type as expected by this runtime.
-pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
-/// Block type as expected by this runtime.
-pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// A Block signed with a Justification
pub type SignedBlock = generic::SignedBlock<Block>;
+/// Frontier wrapped extrinsic
+pub type UncheckedExtrinsic =
+ fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
+/// Header type.
+pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
+/// Block type.
+pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// BlockId type as expected by this runtime.
pub type BlockId = generic::BlockId<Block>;
@@ -102,14 +105,6 @@
//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
pallet_ethereum::FakeTransactionFinalizer<Runtime>,
);
-
-/// Unchecked extrinsic type as expected by this runtime.
-pub type UncheckedExtrinsic =
- fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
-
-/// Extrinsic type that has already been checked.
-pub type CheckedExtrinsic =
- fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra, H160>;
/// Executive: handles dispatch to the various modules.
pub type Executive = frame_executive::Executive<
runtime/common/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/sponsoring.rs
+++ b/runtime/common/sponsoring.rs
@@ -79,7 +79,7 @@
return None;
}
- let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+ let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
let limit = collection.limits.sponsored_data_rate_limit()?;
if let Some(last_tx_block) = TokenPropertyBasket::<T>::get(collection.id, item_id) {
@@ -123,7 +123,7 @@
}
// sponsor timeout
- let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+ let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
let limit = collection
.limits
.sponsor_transfer_timeout(match collection.mode {
@@ -169,7 +169,7 @@
properties: &CreateItemData,
) -> Option<()> {
// sponsor timeout
- let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+ let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
let limit = collection
.limits
.sponsor_transfer_timeout(match properties {
@@ -195,7 +195,7 @@
item_id: &TokenId,
) -> Option<()> {
// sponsor timeout
- let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;
+ let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
let limit = collection.limits.sponsor_approve_timeout();
let last_tx_block = match collection.mode {
@@ -307,7 +307,7 @@
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>;
+ u64: From<BlockNumberFor<T>>;
}
pub struct UniqueSponsorshipPredict<T>(PhantomData<T>);
@@ -315,13 +315,13 @@
impl<T: Config> SponsorshipPredict<T> for UniqueSponsorshipPredict<T> {
fn predict(collection_id: CollectionId, who: T::CrossAccountId, token: TokenId) -> Option<u64>
where
- u64: From<<T as frame_system::Config>::BlockNumber>,
+ u64: From<BlockNumberFor<T>>,
{
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 block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
let limit = collection
.limits
.sponsor_transfer_timeout(match collection.mode {
runtime/common/tests/mod.rsdiffbeforeafterboth--- a/runtime/common/tests/mod.rs
+++ b/runtime/common/tests/mod.rs
@@ -51,8 +51,8 @@
fn new_test_ext(balances: Vec<(AccountId, Balance)>) -> sp_io::TestExternalities {
let mut storage = make_basic_storage();
- pallet_balances::GenesisConfig::<Runtime> { balances }
- .assimilate_storage(&mut storage)
+ pallet_balances::BuildGenesisConfig::<Runtime> { balances }
+ .build_storage(&mut storage)
.unwrap();
let mut ext = sp_io::TestExternalities::new(storage);
@@ -94,13 +94,14 @@
.map(|acc| get_account_id_from_seed::<sr25519::Public>(acc))
.collect::<Vec<_>>();
- let cfg = GenesisConfig {
+ let cfg = BuildGenesisConfig {
collator_selection: CollatorSelectionConfig { invulnerables },
session: SessionConfig { keys },
parachain_info: ParachainInfoConfig {
parachain_id: PARA_ID.into(),
+ ..Default::default()
},
- ..GenesisConfig::default()
+ ..Default::default()
};
cfg.build_storage().unwrap()
@@ -110,7 +111,7 @@
fn make_basic_storage() -> Storage {
use crate::AuraConfig;
- let cfg = GenesisConfig {
+ let cfg = BuildGenesisConfig {
aura: AuraConfig {
authorities: vec![
get_from_seed::<AuraId>("Alice"),
@@ -119,8 +120,9 @@
},
parachain_info: ParachainInfoConfig {
parachain_id: PARA_ID.into(),
+ ..Default::default()
},
- ..GenesisConfig::default()
+ ..Default::default()
};
cfg.build_storage().unwrap().into()
runtime/tests/src/lib.rsdiffbeforeafterboth--- a/runtime/tests/src/lib.rs
+++ b/runtime/tests/src/lib.rs
@@ -57,23 +57,19 @@
// Configure a mock runtime to test the pallet.
frame_support::construct_runtime!(
- pub enum Test where
- Block = Block,
- NodeBlock = Block,
- UncheckedExtrinsic = UncheckedExtrinsic,
- {
+ pub enum Test {
System: frame_system,
Timestamp: pallet_timestamp,
- Unique: pallet_unique::{Pallet, Call, Storage},
- Balances: pallet_balances::{Pallet, Call, Storage, Event<T>},
- Common: pallet_common::{Pallet, Storage, Event<T>},
- Fungible: pallet_fungible::{Pallet, Storage},
- Refungible: pallet_refungible::{Pallet, Storage},
- Nonfungible: pallet_nonfungible::{Pallet, Storage},
- Structure: pallet_structure::{Pallet, Storage, Event<T>},
- TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event<T>},
- Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin},
- EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>},
+ Unique: pallet_unique,
+ Balances: pallet_balances,
+ Common: pallet_common,
+ Fungible: pallet_fungible,
+ Refungible: pallet_refungible,
+ Nonfungible: pallet_nonfungible,
+ Structure: pallet_structure,
+ TransactionPayment: pallet_transaction_payment,
+ Ethereum: pallet_ethereum,
+ EVM: pallet_evm,
}
);
@@ -90,13 +86,11 @@
type DbWeight = ();
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
- type Index = u64;
- type BlockNumber = u64;
+ type Nonce = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
- type Header = Header;
type BlockHashCount = BlockHashCount;
type Version = ();
type PalletInfo = PalletInfo;
@@ -127,7 +121,6 @@
type MaxFreezes = MaxLocks;
type FreezeIdentifier = [u8; 8];
type MaxHolds = MaxLocks;
- type HoldIdentifier = [u8; 8];
}
parameter_types! {
@@ -242,7 +235,6 @@
type OnChargeTransaction = ();
type FindAuthor = ();
type BlockHashMapping = SubstrateBlockHashMapping<Self>;
- type TransactionValidityHack = ();
type Timestamp = Timestamp;
type GasLimitPovSizeRatio = ConstU64<0>;
}