git.delta.rocks / unique-network / refs/commits / a64769ff6bff

difftreelog

refactor upgrade code for new substrate

Yaroslav Bolyukin2023-10-02parent: #c318883.patch.diff
in: master

39 files changed

modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
153 ) => {{153 ) => {{
154 use $runtime::*;154 use $runtime::*;
155155
156 GenesisConfig {156 RuntimeGenesisConfig {
157 system: SystemConfig {157 system: SystemConfig {
158 code: WASM_BINARY158 code: WASM_BINARY
159 .expect("WASM binary was not build, please build it!")159 .expect("WASM binary was not build, please build it!")
160 .to_vec(),160 .to_vec(),
161 ..Default::default()
161 },162 },
162 balances: BalancesConfig {163 balances: BalancesConfig {
163 balances: $endowed_accounts164 balances: $endowed_accounts
167 .map(|k| (k, 1 << 100))168 .map(|k| (k, 1 << 100))
168 .collect(),169 .collect(),
169 },170 },
170 common: Default::default(),
171 configuration: Default::default(),
172 nonfungible: Default::default(),
173 treasury: Default::default(),
174 tokens: TokensConfig { balances: vec![] },171 tokens: TokensConfig { balances: vec![] },
175 sudo: SudoConfig {172 sudo: SudoConfig {
176 key: Some($root_key),173 key: Some($root_key),
177 },174 },
178175
179 vesting: VestingConfig { vesting: vec![] },176 vesting: VestingConfig { vesting: vec![] },
180 parachain_info: ParachainInfoConfig {177 parachain_info: ParachainInfoConfig {
181 parachain_id: $id.into(),178 parachain_id: $id.into(),
182 },
183 parachain_system: Default::default(),179 ..Default::default()
180 },
184 collator_selection: CollatorSelectionConfig {181 collator_selection: CollatorSelectionConfig {
185 invulnerables: $initial_invulnerables182 invulnerables: $initial_invulnerables
186 .iter()183 .iter()
200 })197 })
201 .collect(),198 .collect(),
202 },199 },
203 aura: Default::default(),
204 aura_ext: Default::default(),
205 evm: EVMConfig {200 evm: EVMConfig {
206 accounts: BTreeMap::new(),201 accounts: BTreeMap::new(),
207 },
208 ethereum: EthereumConfig {},
209 polkadot_xcm: Default::default(),202 ..Default::default()
210 transaction_payment: Default::default(),203 },
211 ..Default::default()204 ..Default::default()
212 }205 }
213 }};206 }};
224 ) => {{217 ) => {{
225 use $runtime::*;218 use $runtime::*;
226219
227 GenesisConfig {220 RuntimeGenesisConfig {
228 system: SystemConfig {221 system: SystemConfig {
229 code: WASM_BINARY222 code: WASM_BINARY
230 .expect("WASM binary was not build, please build it!")223 .expect("WASM binary was not build, please build it!")
231 .to_vec(),224 .to_vec(),
232 },
233 common: Default::default(),225 ..Default::default()
234 configuration: Default::default(),226 },
235 nonfungible: Default::default(),
236 balances: BalancesConfig {227 balances: BalancesConfig {
237 balances: $endowed_accounts228 balances: $endowed_accounts
238 .iter()229 .iter()
241 .map(|k| (k, 1 << 100))232 .map(|k| (k, 1 << 100))
242 .collect(),233 .collect(),
243 },234 },
244 treasury: Default::default(),
245 tokens: TokensConfig { balances: vec![] },235 tokens: TokensConfig { balances: vec![] },
246 sudo: SudoConfig {236 sudo: SudoConfig {
247 key: Some($root_key),237 key: Some($root_key),
248 },238 },
249 vesting: VestingConfig { vesting: vec![] },239 vesting: VestingConfig { vesting: vec![] },
250 parachain_info: ParachainInfoConfig {240 parachain_info: ParachainInfoConfig {
251 parachain_id: $id.into(),241 parachain_id: $id.into(),
252 },
253 parachain_system: Default::default(),242 Default::default()
243 },
254 aura: AuraConfig {244 aura: AuraConfig {
255 authorities: $initial_invulnerables245 authorities: $initial_invulnerables
256 .into_iter()246 .into_iter()
257 .map(|(_, aura)| aura)247 .map(|(_, aura)| aura)
258 .collect(),248 .collect(),
259 },249 },
260 aura_ext: Default::default(),
261 evm: EVMConfig {250 evm: EVMConfig {
262 accounts: BTreeMap::new(),251 accounts: BTreeMap::new(),
263 },
264 ethereum: EthereumConfig {},
265 polkadot_xcm: Default::default(),252 ..Default::default()
253 },
266 transaction_payment: Default::default(),254 ..Default::default()
267 }255 }
268 }};256 }};
269}257}
modifiednode/cli/src/command.rsdiffbeforeafterboth
136 load_spec(id)136 load_spec(id)
137 }137 }
138
139 fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
140 match chain_spec.runtime_id() {
141 #[cfg(feature = "unique-runtime")]
142 RuntimeId::Unique => &unique_runtime::VERSION,
143
144 #[cfg(feature = "quartz-runtime")]
145 RuntimeId::Quartz => &quartz_runtime::VERSION,
146
147 RuntimeId::Opal => &opal_runtime::VERSION,
148 runtime_id => panic!("{}", no_runtime_err!(runtime_id)),
149 }
150 }
151}138}
152139
153impl SubstrateCli for RelayChainCli {140impl SubstrateCli for RelayChainCli {
186 polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)173 polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)
187 }174 }
188
189 fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
190 polkadot_cli::Cli::native_runtime_version(chain_spec)
191 }
192}175}
193176
194macro_rules! async_run_with_runtime {177macro_rules! async_run_with_runtime {
195 (178 (
196 $runtime_api:path, $executor:path,179 $runtime:path, $runtime_api:path, $executor:path,
197 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,180 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,
198 $( $code:tt )*181 $( $code:tt )*
199 ) => {182 ) => {
200 $runner.async_run(|$config| {183 $runner.async_run(|$config| {
201 let $components = new_partial::<184 let $components = new_partial::<
202 $runtime_api, $executor, _185 $runtime, $runtime_api, $executor, _
203 >(186 >(
204 &$config,187 &$config,
205 crate::service::parachain_build_import_queue,188 crate::service::parachain_build_import_queue::<$runtime, _, _>,
206 )?;189 )?;
207 let task_manager = $components.task_manager;190 let task_manager = $components.task_manager;
208191
218 match runner.config().chain_spec.runtime_id() {201 match runner.config().chain_spec.runtime_id() {
219 #[cfg(feature = "unique-runtime")]202 #[cfg(feature = "unique-runtime")]
220 RuntimeId::Unique => async_run_with_runtime!(203 RuntimeId::Unique => async_run_with_runtime!(
221 unique_runtime::RuntimeApi, UniqueRuntimeExecutor,204 unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
222 runner, $components, $cli, $cmd, $config, $( $code )*205 runner, $components, $cli, $cmd, $config, $( $code )*
223 ),206 ),
224207
225 #[cfg(feature = "quartz-runtime")]208 #[cfg(feature = "quartz-runtime")]
226 RuntimeId::Quartz => async_run_with_runtime!(209 RuntimeId::Quartz => async_run_with_runtime!(
227 quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,210 quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
228 runner, $components, $cli, $cmd, $config, $( $code )*211 runner, $components, $cli, $cmd, $config, $( $code )*
229 ),212 ),
230213
231 RuntimeId::Opal => async_run_with_runtime!(214 RuntimeId::Opal => async_run_with_runtime!(
232 opal_runtime::RuntimeApi, OpalRuntimeExecutor,215 opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,
233 runner, $components, $cli, $cmd, $config, $( $code )*216 runner, $components, $cli, $cmd, $config, $( $code )*
234 ),217 ),
235218
240223
241macro_rules! sync_run_with_runtime {224macro_rules! sync_run_with_runtime {
242 (225 (
243 $runtime_api:path, $executor:path,226 $runtime:path, $runtime_api:path, $executor:path,
244 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,227 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,
245 $( $code:tt )*228 $( $code:tt )*
246 ) => {229 ) => {
247 $runner.sync_run(|$config| {230 $runner.sync_run(|$config| {
231 let $components = new_partial::<
232 $runtime, $runtime_api, $executor, _
233 >(
234 &$config,
235 crate::service::parachain_build_import_queue::<$runtime, _, _>,
236 )?;
237
248 $( $code )*238 $( $code )*
249 })239 })
257 match runner.config().chain_spec.runtime_id() {247 match runner.config().chain_spec.runtime_id() {
258 #[cfg(feature = "unique-runtime")]248 #[cfg(feature = "unique-runtime")]
259 RuntimeId::Unique => sync_run_with_runtime!(249 RuntimeId::Unique => sync_run_with_runtime!(
260 unique_runtime::RuntimeApi, UniqueRuntimeExecutor,250 unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
261 runner, $components, $cli, $cmd, $config, $( $code )*251 runner, $components, $cli, $cmd, $config, $( $code )*
262 ),252 ),
263253
264 #[cfg(feature = "quartz-runtime")]254 #[cfg(feature = "quartz-runtime")]
265 RuntimeId::Quartz => sync_run_with_runtime!(255 RuntimeId::Quartz => sync_run_with_runtime!(
266 quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,256 quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
267 runner, $components, $cli, $cmd, $config, $( $code )*257 runner, $components, $cli, $cmd, $config, $( $code )*
268 ),258 ),
269259
270 RuntimeId::Opal => sync_run_with_runtime!(260 RuntimeId::Opal => sync_run_with_runtime!(
271 opal_runtime::RuntimeApi, OpalRuntimeExecutor,261 opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,
272 runner, $components, $cli, $cmd, $config, $( $code )*262 runner, $components, $cli, $cmd, $config, $( $code )*
273 ),263 ),
274264
362 Some(Subcommand::ExportGenesisState(cmd)) => {352 Some(Subcommand::ExportGenesisState(cmd)) => {
363 construct_sync_run!(|components, cli, cmd, _config| {353 construct_sync_run!(|components, cli, cmd, _config| {
364 let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;354 let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;
365 let state_version = Cli::native_runtime_version(&spec).state_version();
366 cmd.run::<Block>(&*spec, state_version)355 cmd.run(&*spec, &*components.client)
367 })356 })
368 }357 }
369 Some(Subcommand::ExportGenesisWasm(cmd)) => {358 Some(Subcommand::ExportGenesisWasm(cmd)) => {
370 construct_sync_run!(|components, cli, cmd, _config| {359 construct_sync_run!(|_components, cli, cmd, _config| {
371 let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;360 let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;
372 cmd.run(&*spec)361 cmd.run(&*spec)
373 })362 })
507 &para_id,497 &para_id,
508 );498 );
509
510 let state_version = Cli::native_runtime_version(&config.chain_spec).state_version();
511 let block: Block = generate_genesis_block(&*config.chain_spec, state_version)
512 .map_err(|e| format!("{e:?}"))?;
513 let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));
514 let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));
515499
516 let polkadot_config = SubstrateCli::create_configuration(500 let polkadot_config = SubstrateCli::create_configuration(
517 &polkadot_cli,501 &polkadot_cli,
522506
523 info!("Parachain id: {:?}", para_id);507 info!("Parachain id: {:?}", para_id);
524 info!("Parachain Account: {}", parachain_account);508 info!("Parachain Account: {}", parachain_account);
525 info!("Parachain genesis state: {}", genesis_state);
526 info!("Parachain genesis hash: {}", genesis_hash);
527 debug!("Parachain genesis block: {:?}", block);
528 info!(509 info!(
529 "Is collating: {}",510 "Is collating: {}",
530 if config.role.is_authority() {511 if config.role.is_authority() {
modifiednode/cli/src/service.rsdiffbeforeafterboth
185 }185 }
186}186}
187187
188pub fn open_frontier_backend<Block: BlockT, C: HeaderBackend<Block>>(188pub fn open_frontier_backend<C: HeaderBackend<Block>>(
189 client: Arc<C>,189 client: Arc<C>,
190 config: &Configuration,190 config: &Configuration,
191) -> Result<Arc<fc_db::kv::Backend<Block>>, String> {191) -> Result<Arc<fc_db::kv::Backend<Block>>, String> {
210type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =210type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =
211 TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;211 TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;
212212
213/// Generate a supertrait based on bounds, and blanket impl for it.
214macro_rules! ez_bounds {
215 ($vis:vis trait $name:ident$(<$($gen:ident $(: $($(+)? $bound:path)*)?),* $(,)?>)? $(:)? $($(+)? $super:path)* {}) => {
216 $vis trait $name $(<$($gen $(: $($bound+)*)?,)*>)?: $($super +)* {}
217 impl<T, $($($gen $(: $($bound+)*)?,)*)?> $name$(<$($gen,)*>)? for T
218 where T: $($super +)* {}
219 }
220}
221ez_bounds!(
222 pub trait RuntimeApiDep<Runtime: RuntimeInstance>:
223 sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>
224 + sp_consensus_aura::AuraApi<Block, AuraId>
225 + fp_rpc::EthereumRuntimeRPCApi<Block>
226 + sp_session::SessionKeys<Block>
227 + sp_block_builder::BlockBuilder<Block>
228 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
229 + sp_api::ApiExt<Block>
230 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>
231 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
232 + up_pov_estimate_rpc::PovEstimateApi<Block>
233 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Nonce>
234 + sp_api::Metadata<Block>
235 + sp_offchain::OffchainWorkerApi<Block>
236 + cumulus_primitives_core::CollectCollationInfo<Block>
237 // Deprecated, not used.
238 + fp_rpc::ConvertTransactionRuntimeApi<Block>
239 {
240 }
241);
242
213/// Starts a `ServiceBuilder` for a full service.243/// Starts a `ServiceBuilder` for a full service.
214///244///
215/// Use this macro if you don't actually need the full service, but just the builder in order to245/// Use this macro if you don't actually need the full service, but just the builder in order to
216/// be able to perform chain operations.246/// be able to perform chain operations.
217#[allow(clippy::type_complexity)]247#[allow(clippy::type_complexity)]
218pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(248pub fn new_partial<Runtime, RuntimeApi, ExecutorDispatch, BIQ>(
219 config: &Configuration,249 config: &Configuration,
220 build_import_queue: BIQ,250 build_import_queue: BIQ,
221) -> Result<251) -> Result<
222 PartialComponents<252 PartialComponents<
223 FullClient<RuntimeApi, ExecutorDispatch>,253 FullClient<RuntimeApi, ExecutorDispatch>,
224 FullBackend,254 FullBackend,
225 FullSelectChain,255 FullSelectChain,
226 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,256 sc_consensus::DefaultImportQueue<Block>,
227 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,257 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
228 OtherPartial,258 OtherPartial,
229 >,259 >,
235 + Send265 + Send
236 + Sync266 + Sync
237 + 'static,267 + 'static,
238 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,268 RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
269 Runtime: RuntimeInstance,
239 ExecutorDispatch: NativeExecutionDispatch + 'static,270 ExecutorDispatch: NativeExecutionDispatch + 'static,
240 BIQ: FnOnce(271 BIQ: FnOnce(
241 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,272 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
242 Arc<FullBackend>,273 Arc<FullBackend>,
243 &Configuration,274 &Configuration,
244 Option<TelemetryHandle>,275 Option<TelemetryHandle>,
245 &TaskManager,276 &TaskManager,
246 ) -> Result<277 ) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error>,
247 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
248 sc_service::Error,
249 >,
250{278{
251 let telemetry = config279 let telemetry = config
252 .telemetry_endpoints280 .telemetry_endpoints
319 Ok(params)347 Ok(params)
320}348}
321349
322async fn build_relay_chain_interface(
323 polkadot_config: Configuration,
324 parachain_config: &Configuration,
325 telemetry_worker_handle: Option<TelemetryWorkerHandle>,
326 task_manager: &mut TaskManager,
327 collator_options: CollatorOptions,
328 hwbench: Option<sc_sysinfo::HwBench>,
329) -> RelayChainResult<(
330 Arc<(dyn RelayChainInterface + 'static)>,
331 Option<CollatorPair>,
332)> {
333 if collator_options.relay_chain_rpc_urls.is_empty() {
334 build_inprocess_relay_chain(
335 polkadot_config,
336 parachain_config,
337 telemetry_worker_handle,
338 task_manager,
339 hwbench,
340 )
341 } else {
342 build_minimal_relay_chain_node(
343 polkadot_config,
344 task_manager,
345 collator_options.relay_chain_rpc_urls,
346 )
347 .await
348 }
349}
350
351macro_rules! clone {350macro_rules! clone {
352 ($($i:ident),* $(,)?) => {351 ($($i:ident),* $(,)?) => {
353 $(352 $(
360///359///
361/// This is the actual implementation that is abstract over the executor and the runtime api.360/// This is the actual implementation that is abstract over the executor and the runtime api.
362#[sc_tracing::logging::prefix_logs_with("Parachain")]361#[sc_tracing::logging::prefix_logs_with("Parachain")]
363async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(362pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(
364 parachain_config: Configuration,363 parachain_config: Configuration,
365 polkadot_config: Configuration,364 polkadot_config: Configuration,
366 collator_options: CollatorOptions,365 collator_options: CollatorOptions,
367 id: ParaId,366 para_id: ParaId,
368 build_import_queue: BIQ,
369 build_consensus: BIC,
370 hwbench: Option<sc_sysinfo::HwBench>,367 hwbench: Option<sc_sysinfo::HwBench>,
371) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>368) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>
372where369where
378 + Send375 + Send
379 + Sync376 + Sync
380 + 'static,377 + 'static,
381 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>378 RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
382 + fp_rpc::EthereumRuntimeRPCApi<Block>
383 + fp_rpc::ConvertTransactionRuntimeApi<Block>
384 + sp_session::SessionKeys<Block>
385 + sp_block_builder::BlockBuilder<Block>
386 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
387 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>379 Runtime: RuntimeInstance,
388 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>
389 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
390 + up_pov_estimate_rpc::PovEstimateApi<Block>
391 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
392 + sp_api::Metadata<Block>
393 + sp_offchain::OffchainWorkerApi<Block>
394 + cumulus_primitives_core::CollectCollationInfo<Block>,
395 ExecutorDispatch: NativeExecutionDispatch + 'static,380 ExecutorDispatch: NativeExecutionDispatch + 'static,
396 BIQ: FnOnce(
397 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
398 Arc<FullBackend>,
399 &Configuration,
400 Option<TelemetryHandle>,
401 &TaskManager,
402 ) -> Result<
403 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
404 sc_service::Error,
405 >,
406 BIC: FnOnce(
407 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
408 Arc<FullBackend>,
409 Option<&Registry>,
410 Option<TelemetryHandle>,
411 &TaskManager,
412 Arc<dyn RelayChainInterface>,
413 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,
414 Arc<SyncingService<Block>>,
415 KeystorePtr,
416 bool,
417 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,
418{381{
419 let parachain_config = prepare_node_config(parachain_config);382 let parachain_config = prepare_node_config(parachain_config);
420383
421 let params =384 let params = new_partial::<Runtime, RuntimeApi, ExecutorDispatch, _>(
422 new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;385 &parachain_config,
386 parachain_build_import_queue,
387 )?;
423 let OtherPartial {388 let OtherPartial {
424 mut telemetry,389 mut telemetry,
425 telemetry_worker_handle,390 telemetry_worker_handle,
443 .await408 .await
444 .map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;409 .map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;
445410
446 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);411 let block_announce_validator =
412 RequireSecondedInBlockAnnounce::new(relay_chain_interface.clone(), para_id);
447413
448 let force_authoring = parachain_config.force_authoring;
449 let validator = parachain_config.role.is_authority();414 let validator = parachain_config.role.is_authority();
450 let prometheus_registry = parachain_config.prometheus_registry().cloned();415 let prometheus_registry = parachain_config.prometheus_registry().cloned();
451 let transaction_pool = params.transaction_pool.clone();416 let transaction_pool = params.transaction_pool.clone();
531496
532 let mut rpc_handle = RpcModule::new(());497 let mut rpc_handle = RpcModule::new(());
533498
534 let full_deps = unique_rpc::FullDeps {499 let full_deps = FullDeps {
535 client: client.clone(),500 client: client.clone(),
536 runtime_id,501 runtime_id,
537502
551 select_chain,516 select_chain,
552 };517 };
553518
554 unique_rpc::create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_handle, full_deps)?;519 create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_handle, full_deps)?;
555520
556 let eth_deps = unique_rpc::EthDeps {521 let eth_deps = EthDeps {
557 client,522 client,
558 graph: transaction_pool.pool().clone(),523 graph: transaction_pool.pool().clone(),
559 pool: transaction_pool,524 pool: transaction_pool,
571 eth_pubsub_notification_sinks,536 eth_pubsub_notification_sinks,
572 overrides,537 overrides,
573 sync: sync_service.clone(),538 sync: sync_service.clone(),
539 pending_create_inherent_data_providers: |_, ()| async move { Ok(()) },
574 };540 };
575541
576 unique_rpc::create_eth(542 create_eth::<
543 _,
544 _,
545 _,
546 _,
547 _,
548 _,
549 DefaultEthConfig<FullClient<RuntimeApi, ExecutorDispatch>>,
550 >(
577 &mut rpc_handle,551 &mut rpc_handle,
578 eth_deps,552 eth_deps,
579 subscription_task_executor.clone(),553 subscription_task_executor.clone(),
624 .overseer_handle()598 .overseer_handle()
625 .map_err(|e| sc_service::Error::Application(Box::new(e)))?;599 .map_err(|e| sc_service::Error::Application(Box::new(e)))?;
626600
601 start_relay_chain_tasks(StartRelayChainTasksParams {
602 client: client.clone(),
603 announce_block: announce_block.clone(),
604 para_id,
605 relay_chain_interface: relay_chain_interface.clone(),
606 task_manager: &mut task_manager,
607 da_recovery_profile: if validator {
608 DARecoveryProfile::Collator
609 } else {
610 DARecoveryProfile::FullNode
611 },
612 import_queue: import_queue_service,
613 relay_chain_slot_duration,
614 recovery_handle: Box::new(overseer_handle.clone()),
615 sync_service: sync_service.clone(),
616 })?;
617
627 if validator {618 if validator {
628 let parachain_consensus = build_consensus(619 start_consensus(
629 client.clone(),620 client.clone(),
630 backend.clone(),621 backend.clone(),
631 prometheus_registry.as_ref(),622 prometheus_registry.as_ref(),
635 transaction_pool,626 transaction_pool,
636 sync_service.clone(),627 sync_service.clone(),
637 params.keystore_container.keystore(),628 params.keystore_container.keystore(),
638 force_authoring,629 overseer_handle,
639 )?;
640
641 let spawner = task_manager.spawn_handle();
642
643 let params = StartCollatorParams {
644 para_id: id,
645 block_status: client.clone(),
646 announce_block,
647 client: client.clone(),
648 task_manager: &mut task_manager,
649 spawner,
650 parachain_consensus,
651 import_queue: import_queue_service,
652 collator_key: collator_key.expect("Command line arguments do not allow this. qed"),
653 relay_chain_interface,
654 relay_chain_slot_duration,630 relay_chain_slot_duration,
655 recovery_handle: Box::new(overseer_handle),631 para_id,
656 sync_service,632 collator_key.expect("cli args do not allow this"),
657 };
658
659 start_collator(params).await?;
660 } else {
661 let params = StartFullNodeParams {
662 client: client.clone(),
663 announce_block,633 announce_block,
664 task_manager: &mut task_manager,634 )?;
665 para_id: id,
666 import_queue: import_queue_service,
667 relay_chain_interface,
668 relay_chain_slot_duration,
669 recovery_handle: Box::new(overseer_handle),
670 sync_service,
671 };
672
673 start_full_node(params)?;
674 }635 }
675636
676 start_network.start_network();637 start_network.start_network();
679}640}
680641
681/// Build the import queue for the the parachain runtime.642/// Build the import queue for the the parachain runtime.
682pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(643pub fn parachain_build_import_queue<Runtime, RuntimeApi, ExecutorDispatch>(
683 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,644 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
684 backend: Arc<FullBackend>,645 backend: Arc<FullBackend>,
685 config: &Configuration,646 config: &Configuration,
686 telemetry: Option<TelemetryHandle>,647 telemetry: Option<TelemetryHandle>,
687 task_manager: &TaskManager,648 task_manager: &TaskManager,
688) -> Result<649) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error>
689 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
690 sc_service::Error,
691>
692where650where
693 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>651 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>
694 + Send652 + Send
695 + Sync653 + Sync
696 + 'static,654 + 'static,
697 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>655 RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
698 + sp_block_builder::BlockBuilder<Block>
699 + sp_consensus_aura::AuraApi<Block, AuraId>
700 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,656 Runtime: RuntimeInstance,
701 ExecutorDispatch: NativeExecutionDispatch + 'static,657 ExecutorDispatch: NativeExecutionDispatch + 'static,
702{658{
703 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;659 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
732 .map_err(Into::into)688 .map_err(Into::into)
733}689}
734690
735/// Start a normal parachain node.
736pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(691pub fn start_consensus<ExecutorDispatch, RuntimeApi, Runtime>(
737 parachain_config: Configuration,692 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
738 polkadot_config: Configuration,693 backend: Arc<FullBackend>,
739 collator_options: CollatorOptions,694 prometheus_registry: Option<&Registry>,
740 id: ParaId,695 telemetry: Option<TelemetryHandle>,
741 hwbench: Option<sc_sysinfo::HwBench>,696 task_manager: &TaskManager,
697 relay_chain_interface: Arc<dyn RelayChainInterface>,
698 transaction_pool: Arc<
699 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
700 >,
742) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>701 sync_oracle: Arc<SyncingService<Block>>,
702 keystore: KeystorePtr,
703 overseer_handle: OverseerHandle,
704 relay_chain_slot_duration: Duration,
705 para_id: ParaId,
706 collator_key: CollatorPair,
707 announce_block: Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>,
708) -> Result<(), sc_service::Error>
743where709where
744 Runtime: RuntimeInstance + Send + Sync + 'static,710 ExecutorDispatch: NativeExecutionDispatch + 'static,
745 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,
746 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,
747 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>711 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>
748 + Send712 + Send
749 + Sync713 + Sync
750 + 'static,714 + 'static,
751 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>715 RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
752 + fp_rpc::EthereumRuntimeRPCApi<Block>
753 + fp_rpc::ConvertTransactionRuntimeApi<Block>
754 + sp_session::SessionKeys<Block>
755 + sp_block_builder::BlockBuilder<Block>
756 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
757 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>716 Runtime: RuntimeInstance,
758 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>
759 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
760 + up_pov_estimate_rpc::PovEstimateApi<Block>
761 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
762 + sp_api::Metadata<Block>
763 + sp_offchain::OffchainWorkerApi<Block>
764 + cumulus_primitives_core::CollectCollationInfo<Block>
765 + sp_consensus_aura::AuraApi<Block, AuraId>,
766 ExecutorDispatch: NativeExecutionDispatch + 'static,
767{717{
768 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(718 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
769 parachain_config,
770 polkadot_config,
771 collator_options,
772 id,
773 parachain_build_import_queue,
774 |client,
775 backend,
776 prometheus_registry,
777 telemetry,
778 task_manager,
779 relay_chain_interface,
780 transaction_pool,
781 sync_oracle,
782 keystore,
783 force_authoring| {
784 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
785719
786 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(720 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(
787 task_manager.spawn_handle(),721 task_manager.spawn_handle(),
788 client.clone(),722 client.clone(),
789 transaction_pool,723 transaction_pool,
790 prometheus_registry,724 prometheus_registry,
791 telemetry.clone(),725 telemetry.clone(),
792 );726 );
727 let proposer = Proposer::new(proposer_factory);
793728
794 let block_import = ParachainBlockImport::new(client.clone(), backend);729 let collator_service = CollatorService::new(
730 client.clone(),
731 Arc::new(task_manager.spawn_handle()),
732 announce_block,
733 client.clone(),
734 );
795735
796 Ok(AuraConsensus::build::<736 let block_import = ParachainBlockImport::new(client.clone(), backend);
797 sp_consensus_aura::sr25519::AuthorityPair,
798 _,
799 _,
800 _,
801 _,
802 _,
803 _,
804 >(BuildAuraConsensusParams {
805 proposer_factory,
806 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {
807 let relay_chain_interface = relay_chain_interface.clone();
808 async move {
809 let parachain_inherent =
810 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(
811 relay_parent,
812 &relay_chain_interface,
813 &validation_data,
814 id,
815 ).await;
816737
817 let time = sp_timestamp::InherentDataProvider::from_system_time();738 let params = BuildAuraConsensusParams {
739 create_inherent_data_providers: move |_, ()| async move { Ok(()) },
740 block_import,
741 para_client: client,
742 #[cfg(feature = "lookahead")]
743 para_backend: backend,
744 para_id,
745 relay_client: relay_chain_interface,
746 sync_oracle,
747 keystore,
748 slot_duration,
749 proposer,
750 collator_service,
751 // With async-baking, we allowed to be both slower (longer authoring) and faster (multiple para blocks per relay block)
752 authoring_duration: Duration::from_millis(500),
753 overseer_handle,
754 #[cfg(feature = "lookahead")]
755 code_hash_provider: || {},
756 collator_key,
757 relay_chain_slot_duration,
758 };
818759
819 let slot =760 task_manager.spawn_essential_handle().spawn(
820 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
821 *time,
822 slot_duration,
823 );
824
825 let parachain_inherent = parachain_inherent.ok_or_else(|| {
826 Box::<dyn std::error::Error + Send + Sync>::from(761 "aura",
827 "Failed to create parachain inherent",
828 )762 None,
829 })?;763 run_aura::<_, AuraAuthorityPair, _, _, _, _, _, _, _>(params),
830 Ok((slot, time, parachain_inherent))
831 }
832 },
833 block_import,
834 para_client: client,
835 backoff_authoring_blocks: Option::<()>::None,
836 sync_oracle,
837 keystore,
838 force_authoring,
839 slot_duration,
840 // We got around 500ms for proposing
841 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),
842 telemetry,764 );
843 max_block_proposal_slot_portion: None,
844 }))
845 },765 Ok(())
846 hwbench,
847 )
848 .await
849}766}
850767
851fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(768fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(
854 config: &Configuration,771 config: &Configuration,
855 _: Option<TelemetryHandle>,772 _: Option<TelemetryHandle>,
856 task_manager: &TaskManager,773 task_manager: &TaskManager,
857) -> Result<774) -> Result<sc_consensus::DefaultImportQueue<Block>, sc_service::Error>
858 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,
859 sc_service::Error,
860>
861where775where
862 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>776 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>
863 + Send777 + Send
864 + Sync778 + Sync
865 + 'static,779 + 'static,
866 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>780 RuntimeApi::RuntimeApi:
867 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,781 sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> + sp_api::ApiExt<Block>,
868 ExecutorDispatch: NativeExecutionDispatch + 'static,782 ExecutorDispatch: NativeExecutionDispatch + 'static,
869{783{
870 Ok(sc_consensus_manual_seal::import_queue(784 Ok(sc_consensus_manual_seal::import_queue(
881 pub eth_backend: Arc<fc_db::kv::Backend<Block>>,795 pub eth_backend: Arc<fc_db::kv::Backend<Block>>,
882}796}
883797
798struct DefaultEthConfig<C>(PhantomData<C>);
799impl<C> EthConfig<Block, C> for DefaultEthConfig<C>
800where
801 C: StorageProvider<Block, FullBackend> + Sync + Send + 'static,
802{
803 type EstimateGasAdapter = ();
804 type RuntimeStorageOverride = SystemAccountId32StorageOverride<Block, C, FullBackend>;
805}
806
884/// Builds a new development service. This service uses instant seal, and mocks807/// Builds a new development service. This service uses instant seal, and mocks
885/// the parachain inherent808/// the parachain inherent
886pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(809pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(
897 + Send820 + Send
898 + Sync821 + Sync
899 + 'static,822 + 'static,
900 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>823 RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
901 + fp_rpc::EthereumRuntimeRPCApi<Block>
902 + fp_rpc::ConvertTransactionRuntimeApi<Block>
903 + sp_session::SessionKeys<Block>
904 + sp_block_builder::BlockBuilder<Block>
905 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
906 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>
907 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>
908 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>
909 + up_pov_estimate_rpc::PovEstimateApi<Block>
910 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>
911 + sp_api::Metadata<Block>
912 + sp_offchain::OffchainWorkerApi<Block>
913 + cumulus_primitives_core::CollectCollationInfo<Block>
914 + sp_consensus_aura::AuraApi<Block, AuraId>,
915 ExecutorDispatch: NativeExecutionDispatch + 'static,824 ExecutorDispatch: NativeExecutionDispatch + 'static,
916{825{
826 use fc_consensus::FrontierBlockImport;
917 use sc_consensus_manual_seal::{827 use sc_consensus_manual_seal::{
918 run_manual_seal, run_delayed_finalize, EngineCommand, ManualSealParams,828 run_manual_seal, run_delayed_finalize, EngineCommand, ManualSealParams,
919 DelayedFinalizeParams,829 DelayedFinalizeParams,
920 };830 };
921 use fc_consensus::FrontierBlockImport;
922831
923 let sc_service::PartialComponents {832 let sc_service::PartialComponents {
924 client,833 client,
935 eth_backend,844 eth_backend,
936 telemetry_worker_handle: _,845 telemetry_worker_handle: _,
937 },846 },
938 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(847 } = new_partial::<Runtime, RuntimeApi, ExecutorDispatch, _>(
939 &config,848 &config,
940 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,849 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,
941 )?;850 )?;
954 warp_sync_params: None,863 warp_sync_params: None,
955 })?;864 })?;
956865
957 if config.offchain_worker.enabled {
958 sc_service::build_offchain_workers(
959 &config,
960 task_manager.spawn_handle(),
961 client.clone(),
962 network.clone(),
963 );
964 }
965
966 let collator = config.role.is_authority();866 let collator = config.role.is_authority();
967867
968 let select_chain = maybe_select_chain;868 let select_chain = maybe_select_chain;
11411041
1142 let mut rpc_module = RpcModule::new(());1042 let mut rpc_module = RpcModule::new(());
11431043
1144 let full_deps = unique_rpc::FullDeps {1044 let full_deps = FullDeps {
1145 runtime_id,1045 runtime_id,
11461046
1147 #[cfg(feature = "pov-estimate")]1047 #[cfg(feature = "pov-estimate")]
1161 select_chain,1061 select_chain,
1162 };1062 };
11631063
1164 unique_rpc::create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_module, full_deps)?;1064 create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_module, full_deps)?;
11651065
1166 let eth_deps = unique_rpc::EthDeps {1066 let eth_deps = EthDeps {
1167 client,1067 client,
1168 graph: transaction_pool.pool().clone(),1068 graph: transaction_pool.pool().clone(),
1169 pool: transaction_pool,1069 pool: transaction_pool,
1181 eth_pubsub_notification_sinks,1081 eth_pubsub_notification_sinks,
1182 overrides,1082 overrides,
1183 sync: sync_service.clone(),1083 sync: sync_service.clone(),
1084 // We don't have any inherents except parachain built-ins, which we can't even extract from inside `run_aura`.
1085 pending_create_inherent_data_providers: |_, ()| async move { Ok(()) },
1184 };1086 };
11851087
1186 unique_rpc::create_eth(1088 create_eth::<
1089 _,
1090 _,
1091 _,
1092 _,
1093 _,
1094 _,
1095 DefaultEthConfig<FullClient<RuntimeApi, ExecutorDispatch>>,
1096 >(
1187 &mut rpc_module,1097 &mut rpc_module,
1188 eth_deps,1098 eth_deps,
1189 subscription_task_executor.clone(),1099 subscription_task_executor.clone(),
1241 })1151 })
1242}1152}
12431153
1244pub struct FrontierTaskParams<'a, B: BlockT, C, BE> {1154pub struct FrontierTaskParams<'a, C, B> {
1245 pub task_manager: &'a TaskManager,1155 pub task_manager: &'a TaskManager,
1246 pub client: Arc<C>,1156 pub client: Arc<C>,
1247 pub substrate_backend: Arc<BE>,1157 pub substrate_backend: Arc<B>,
1248 pub eth_backend: Arc<fc_db::kv::Backend<B>>,1158 pub eth_backend: Arc<fc_db::kv::Backend<Block>>,
1249 pub eth_filter_pool: Option<FilterPool>,1159 pub eth_filter_pool: Option<FilterPool>,
1250 pub overrides: Arc<OverrideHandle<B>>,1160 pub overrides: Arc<OverrideHandle<Block>>,
1251 pub fee_history_limit: u64,1161 pub fee_history_limit: u64,
1252 pub fee_history_cache: FeeHistoryCache,1162 pub fee_history_cache: FeeHistoryCache,
1253 pub sync_strategy: SyncStrategy,1163 pub sync_strategy: SyncStrategy,
1254 pub prometheus_registry: Option<Registry>,1164 pub prometheus_registry: Option<Registry>,
1255}1165}
12561166
1257pub fn spawn_frontier_tasks<B, C, BE>(1167pub fn spawn_frontier_tasks<C, B>(
1258 params: FrontierTaskParams<B, C, BE>,1168 params: FrontierTaskParams<C, B>,
1259 sync: Arc<SyncingService<B>>,1169 sync: Arc<SyncingService<Block>>,
1260 pubsub_notification_sinks: Arc<1170 pubsub_notification_sinks: Arc<
1261 EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<B>>,1171 EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<Block>>,
1262 >,1172 >,
1263) -> Arc<EthBlockDataCacheTask<B>>1173) -> Arc<EthBlockDataCacheTask<Block>>
1264where1174where
1265 C: ProvideRuntimeApi<B> + BlockOf,1175 C: ProvideRuntimeApi<Block> + BlockOf,
1266 C: HeaderBackend<B> + HeaderMetadata<B, Error = BlockChainError> + 'static,1176 C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,
1267 C: BlockchainEvents<B> + StorageProvider<B, BE>,1177 C: BlockchainEvents<Block> + StorageProvider<Block, B>,
1268 C: Send + Sync + 'static,1178 C: Send + Sync + 'static,
1269 C::Api: EthereumRuntimeRPCApi<B>,1179 C::Api: EthereumRuntimeRPCApi<Block>,
1270 C::Api: BlockBuilder<B>,1180 C::Api: BlockBuilder<Block>,
1271 B: BlockT<Hash = H256> + Send + Sync + 'static,1181 B: Backend<Block> + 'static,
1272 B::Header: HeaderT<Number = u32>,
1273 BE: Backend<B> + 'static,
1274 BE::State: StateBackend<BlakeTwo256>,1182 B::State: StateBackend<BlakeTwo256>,
1275{1183{
1276 let FrontierTaskParams {1184 let FrontierTaskParams {
1277 task_manager,1185 task_manager,
modifiedpallets/app-promotion/src/benchmarking.rsdiffbeforeafterboth
32fn set_admin<T>() -> Result<T::AccountId, sp_runtime::DispatchError>32fn set_admin<T>() -> Result<T::AccountId, sp_runtime::DispatchError>
33where33where
34 T: Config + pallet_unique::Config + pallet_evm_migration::Config,34 T: Config + pallet_unique::Config + pallet_evm_migration::Config,
35 T::BlockNumber: From<u32> + Into<u32>,35 BlockNumberFor<T>: From<u32> + Into<u32>,
36 BalanceOf<T>: Sum + From<u128>,36 BalanceOf<T>: Sum + From<u128>,
37{37{
38 let pallet_admin = account::<T::AccountId>("admin", 0, SEED);38 let pallet_admin = account::<T::AccountId>("admin", 0, SEED);
53benchmarks! {53benchmarks! {
54 where_clause{54 where_clause{
55 where T: Config + pallet_unique::Config + pallet_evm_migration::Config ,55 where T: Config + pallet_unique::Config + pallet_evm_migration::Config ,
56 T::BlockNumber: From<u32> + Into<u32>,56 BlockNumberFor<T>: From<u32> + Into<u32>,
57 BalanceOf<T>: Sum + From<u128>57 BalanceOf<T>: Sum + From<u128>
58 }58 }
5959
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
125125
126 /// In relay blocks.126 /// In relay blocks.
127 #[pallet::constant]127 #[pallet::constant]
128 type RecalculationInterval: Get<Self::BlockNumber>;128 type RecalculationInterval: Get<BlockNumberFor<Self>>;
129129
130 /// In parachain blocks.130 /// In parachain blocks.
131 #[pallet::constant]131 #[pallet::constant]
132 type PendingInterval: Get<Self::BlockNumber>;132 type PendingInterval: Get<BlockNumberFor<Self>>;
133133
134 /// Rate of return for interval in blocks defined in `RecalculationInterval`.134 /// Rate of return for interval in blocks defined in `RecalculationInterval`.
135 #[pallet::constant]135 #[pallet::constant]
146 type WeightInfo: WeightInfo;146 type WeightInfo: WeightInfo;
147147
148 // The relay block number provider148 // The relay block number provider
149 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;149 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
150150
151 /// Events compatible with [`frame_system::Config::Event`].151 /// Events compatible with [`frame_system::Config::Event`].
152 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;152 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;
230 pub type Staked<T: Config> = StorageNMap<230 pub type Staked<T: Config> = StorageNMap<
231 Key = (231 Key = (
232 Key<Blake2_128Concat, T::AccountId>,232 Key<Blake2_128Concat, T::AccountId>,
233 Key<Twox64Concat, T::BlockNumber>,233 Key<Twox64Concat, BlockNumberFor<T>>,
234 ),234 ),
235 Value = (BalanceOf<T>, T::BlockNumber),235 Value = (BalanceOf<T>, BlockNumberFor<T>),
236 QueryKind = ValueQuery,236 QueryKind = ValueQuery,
237 >;237 >;
238238
252 pub type PendingUnstake<T: Config> = StorageMap<252 pub type PendingUnstake<T: Config> = StorageMap<
253 _,253 _,
254 Twox64Concat,254 Twox64Concat,
255 T::BlockNumber,255 BlockNumberFor<T>,
256 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,256 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,
257 ValueQuery,257 ValueQuery,
258 >;258 >;
262 #[pallet::storage]262 #[pallet::storage]
263 #[pallet::getter(fn get_next_calculated_record)]263 #[pallet::getter(fn get_next_calculated_record)]
264 pub type PreviousCalculatedRecord<T: Config> =264 pub type PreviousCalculatedRecord<T: Config> =
265 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;265 StorageValue<Value = (T::AccountId, BlockNumberFor<T>), QueryKind = OptionQuery>;
266266
267 #[pallet::hooks]267 #[pallet::hooks]
268 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {268 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
269 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize269 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize
270 /// implies the execution of a strictly limited number of relatively lightweight operations.270 /// implies the execution of a strictly limited number of relatively lightweight operations.
271 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.271 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.
272 fn on_initialize(current_block_number: T::BlockNumber) -> Weight272 fn on_initialize(current_block_number: BlockNumberFor<T>) -> Weight
273 where273 where
274 <T as frame_system::Config>::BlockNumber: From<u32>,274 BlockNumberFor<T>: From<u32>,
275 {275 {
276 if T::IsMaintenanceModeEnabled::get() {276 if T::IsMaintenanceModeEnabled::get() {
277 return T::DbWeight::get().reads_writes(1, 0);277 return T::DbWeight::get().reads_writes(1, 0);
302 #[pallet::call]302 #[pallet::call]
303 impl<T: Config> Pallet<T>303 impl<T: Config> Pallet<T>
304 where304 where
305 T::BlockNumber: From<u32> + Into<u32>,305 BlockNumberFor<T>: From<u32> + Into<u32>,
306 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,306 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,
307 {307 {
308 /// Sets an address as the the admin.308 /// Sets an address as the the admin.
369369
370 // Calculation of the number of recalculation periods,370 // Calculation of the number of recalculation periods,
371 // after how much the first interest calculation should be performed for the stake371 // after how much the first interest calculation should be performed for the stake
372 let recalculate_after_interval: T::BlockNumber =372 let recalculate_after_interval: BlockNumberFor<T> =
373 if block_number % config.recalculation_interval == 0u32.into() {373 if block_number % config.recalculation_interval == 0u32.into() {
374 1u32.into()374 1u32.into()
375 } else {375 } else {
705 #[pallet::weight(<T as Config>::WeightInfo::on_initialize(PENDING_LIMIT_PER_BLOCK*pending_blocks.len() as u32))]705 #[pallet::weight(<T as Config>::WeightInfo::on_initialize(PENDING_LIMIT_PER_BLOCK*pending_blocks.len() as u32))]
706 pub fn force_unstake(706 pub fn force_unstake(
707 origin: OriginFor<T>,707 origin: OriginFor<T>,
708 pending_blocks: Vec<T::BlockNumber>,708 pending_blocks: Vec<BlockNumberFor<T>>,
709 ) -> DispatchResult {709 ) -> DispatchResult {
710 ensure_root(origin)?;710 ensure_root(origin)?;
711711
917 /// - `staker`: staker account.917 /// - `staker`: staker account.
918 pub fn total_staked_by_id_per_block(918 pub fn total_staked_by_id_per_block(
919 staker: impl EncodeLike<T::AccountId>,919 staker: impl EncodeLike<T::AccountId>,
920 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {920 ) -> Option<Vec<(BlockNumberFor<T>, BalanceOf<T>)>> {
921 let mut staked = Staked::<T>::iter_prefix((staker,))921 let mut staked = Staked::<T>::iter_prefix((staker,))
922 .map(|(block, (amount, _))| (block, amount))922 .map(|(block, (amount, _))| (block, amount))
923 .collect::<Vec<_>>();923 .collect::<Vec<_>>();
944 /// - `staker`: staker account.944 /// - `staker`: staker account.
945 pub fn cross_id_total_staked_per_block(945 pub fn cross_id_total_staked_per_block(
946 staker: T::CrossAccountId,946 staker: T::CrossAccountId,
947 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {947 ) -> Vec<(BlockNumberFor<T>, BalanceOf<T>)> {
948 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()948 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()
949 }949 }
950950
951 fn recalculate_and_insert_stake(951 fn recalculate_and_insert_stake(
952 staker: &T::AccountId,952 staker: &T::AccountId,
953 staked_block: T::BlockNumber,953 staked_block: BlockNumberFor<T>,
954 next_recalc_block: T::BlockNumber,954 next_recalc_block: BlockNumberFor<T>,
955 base: BalanceOf<T>,955 base: BalanceOf<T>,
956 iters: u32,956 iters: u32,
957 income_acc: &mut BalanceOf<T>,957 income_acc: &mut BalanceOf<T>,
979 /// Get relay block number rounded down to multiples of config.recalculation_interval.979 /// Get relay block number rounded down to multiples of config.recalculation_interval.
980 /// We need it to reward stakers in integer parts of recalculation_interval980 /// We need it to reward stakers in integer parts of recalculation_interval
981 fn get_current_recalc_block(981 fn get_current_recalc_block(
982 current_relay_block: T::BlockNumber,982 current_relay_block: BlockNumberFor<T>,
983 config: &PalletConfiguration<T>,983 config: &PalletConfiguration<T>,
984 ) -> T::BlockNumber {984 ) -> BlockNumberFor<T> {
985 (current_relay_block / config.recalculation_interval) * config.recalculation_interval985 (current_relay_block / config.recalculation_interval) * config.recalculation_interval
986 }986 }
987987
1028 /// - `staker`: staker account.1028 /// - `staker`: staker account.
1029 pub fn cross_id_pending_unstake_per_block(1029 pub fn cross_id_pending_unstake_per_block(
1030 staker: T::CrossAccountId,1030 staker: T::CrossAccountId,
1031 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1031 ) -> Vec<(BlockNumberFor<T>, BalanceOf<T>)> {
1032 let mut unsorted_res = vec![];1032 let mut unsorted_res = vec![];
1033 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1033 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {
1034 pendings.into_iter().for_each(|(id, amount)| {1034 pendings.into_iter().for_each(|(id, amount)| {
modifiedpallets/app-promotion/src/types.rsdiffbeforeafterboth
114}114}
115pub(crate) struct PalletConfiguration<T: crate::Config> {115pub(crate) struct PalletConfiguration<T: crate::Config> {
116 /// In relay blocks.116 /// In relay blocks.
117 pub recalculation_interval: T::BlockNumber,117 pub recalculation_interval: BlockNumberFor<T>,
118 /// In parachain blocks.118 /// In parachain blocks.
119 pub pending_interval: T::BlockNumber,119 pub pending_interval: BlockNumberFor<T>,
120 /// Value for `RecalculationInterval` based on 0.05% per 24h.120 /// Value for `RecalculationInterval` based on 0.05% per 24h.
121 pub interval_income: Perbill,121 pub interval_income: Perbill,
122 /// Maximum allowable number of stakers calculated per call of the `app-promotion::PayoutStakers` extrinsic.122 /// Maximum allowable number of stakers calculated per call of the `app-promotion::PayoutStakers` extrinsic.
modifiedpallets/collator-selection/src/benchmarking.rsdiffbeforeafterboth
51use pallet_session::{self as session, SessionManager};51use pallet_session::{self as session, SessionManager};
52use sp_std::prelude::*;52use sp_std::prelude::*;
53
54use super::*;
55#[allow(unused)]
56use crate::{BalanceOf, Pallet as CollatorSelection};
5357
54const SEED: u32 = 0;58const SEED: u32 = 0;
5559
317 balance_unit::<T>() * 4u32.into(),321 balance_unit::<T>() * 4u32.into(),
318 );322 );
319 let author = account("author", 0, SEED);323 let author = account("author", 0, SEED);
320 let new_block: T::BlockNumber = 10u32.into();324 let new_block: BlockNumberFor<T>= 10u32.into();
321325
322 frame_system::Pallet::<T>::set_block_number(new_block);326 frame_system::Pallet::<T>::set_block_number(new_block);
323 assert!(T::Currency::balance(&author) == 0u32.into());327 assert!(T::Currency::balance(&author) == 0u32.into());
338 register_validators::<T>(c);342 register_validators::<T>(c);
339 register_candidates::<T>(c);343 register_candidates::<T>(c);
340344
341 let new_block: T::BlockNumber = 1800u32.into();345 let new_block: BlockNumberFor<T>= 1800u32.into();
342 let zero_block: T::BlockNumber = 0u32.into();346 let zero_block: T::BlockNumber = 0u32.into();
343 let candidates = <Candidates<T>>::get();347 let candidates = <Candidates<T>>::get();
344348
modifiedpallets/collator-selection/src/lib.rsdiffbeforeafterboth
131 pub trait Config: frame_system::Config {131 pub trait Config: frame_system::Config {
132 /// Overarching event type.132 /// Overarching event type.
133 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;133 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
134 /// Overarching hold reason.
135 type RuntimeHoldReason: From<HoldReason>;
136
134 type Currency: Mutate<Self::AccountId>137 type Currency: Mutate<Self::AccountId>
135 + MutateHold<Self::AccountId>138 + MutateHold<Self::AccountId, Reason = Self::RuntimeHoldReason>
136 + BalancedHold<Self::AccountId>;139 + BalancedHold<Self::AccountId>;
137140
138 /// Origin that can dictate updating parameters of this pallet.141 /// Origin that can dictate updating parameters of this pallet.
164 /// The weight information of this pallet.167 /// The weight information of this pallet.
165 type WeightInfo: WeightInfo;168 type WeightInfo: WeightInfo;
166
167 #[pallet::constant]
168 type LicenceBondIdentifier: Get<<Self::Currency as InspectHold<Self::AccountId>>::Reason>;
169169
170 type DesiredCollators: Get<u32>;170 type DesiredCollators: Get<u32>;
171171
172 type LicenseBond: Get<BalanceOf<Self>>;172 type LicenseBond: Get<BalanceOf<Self>>;
173173
174 type KickThreshold: Get<Self::BlockNumber>;174 type KickThreshold: Get<BlockNumberFor<Self>>;
175 }175 }
176
177 #[pallet::composite_enum]
178 pub enum HoldReason {
179 /// The funds are held as the license bond.
180 LicenseBond,
181 }
176182
177 #[pallet::pallet]183 #[pallet::pallet]
178 pub struct Pallet<T>(_);184 pub struct Pallet<T>(_);
199 #[pallet::storage]205 #[pallet::storage]
200 #[pallet::getter(fn last_authored_block)]206 #[pallet::getter(fn last_authored_block)]
201 pub type LastAuthoredBlock<T: Config> =207 pub type LastAuthoredBlock<T: Config> =
202 StorageMap<_, Twox64Concat, T::AccountId, T::BlockNumber, ValueQuery>;208 StorageMap<_, Twox64Concat, T::AccountId, BlockNumberFor<T>, ValueQuery>;
203209
204 #[pallet::genesis_config]210 #[pallet::genesis_config]
205 pub struct GenesisConfig<T: Config> {211 pub struct GenesisConfig<T: Config> {
206 pub invulnerables: Vec<T::AccountId>,212 pub invulnerables: Vec<T::AccountId>,
207 }213 }
208214
209 #[cfg(feature = "std")]
210 impl<T: Config> Default for GenesisConfig<T> {215 impl<T: Config> Default for GenesisConfig<T> {
211 fn default() -> Self {216 fn default() -> Self {
212 Self {217 Self {
216 }221 }
217222
218 #[pallet::genesis_build]223 #[pallet::genesis_build]
219 impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {224 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
220 fn build(&self) {225 fn build(&self) {
226 use sp_std::collections::btree_set::BTreeSet;
227
221 let duplicate_invulnerables = self228 let duplicate_invulnerables = self.invulnerables.iter().collect::<BTreeSet<_>>();
222 .invulnerables
223 .iter()
224 .collect::<std::collections::BTreeSet<_>>();
225 assert!(229 assert!(
226 duplicate_invulnerables.len() == self.invulnerables.len(),230 duplicate_invulnerables.len() == self.invulnerables.len(),
227 "duplicate invulnerables in genesis."231 "duplicate invulnerables in genesis."
375379
376 let deposit = T::LicenseBond::get();380 let deposit = T::LicenseBond::get();
377381
378 T::Currency::hold(&T::LicenceBondIdentifier::get(), &who, deposit)?;382 T::Currency::hold(&HoldReason::LicenseBond.into(), &who, deposit)?;
379 LicenseDepositOf::<T>::insert(who.clone(), deposit);383 LicenseDepositOf::<T>::insert(who.clone(), deposit);
380384
381 Self::deposit_event(Event::LicenseObtained {385 Self::deposit_event(Event::LicenseObtained {
538 let remaining = deposit - slashed;542 let remaining = deposit - slashed;
539543
540 let (imbalance, _) =544 let (imbalance, _) =
541 T::Currency::slash(&T::LicenceBondIdentifier::get(), who, slashed);545 T::Currency::slash(&HoldReason::LicenseBond.into(), who, slashed);
542 deposit_returned = remaining;546 deposit_returned = remaining;
543547
544 T::Currency::resolve(&T::TreasuryAccountId::get(), imbalance)548 T::Currency::resolve(&T::TreasuryAccountId::get(), imbalance)
548 }552 }
549553
550 T::Currency::release(554 T::Currency::release(
551 &T::LicenceBondIdentifier::get(),555 &HoldReason::LicenseBond.into(),
552 who,556 who,
553 deposit_returned,557 deposit_returned,
554 Precision::Exact,558 Precision::Exact,
608 /// Keep track of number of authored blocks per authority, uncles are counted as well since612 /// Keep track of number of authored blocks per authority, uncles are counted as well since
609 /// they're a valid proof of being online.613 /// they're a valid proof of being online.
610 impl<T: Config + pallet_authorship::Config>614 impl<T: Config + pallet_authorship::Config>
611 pallet_authorship::EventHandler<T::AccountId, T::BlockNumber> for Pallet<T>615 pallet_authorship::EventHandler<T::AccountId, BlockNumberFor<T>> for Pallet<T>
612 {616 {
613 fn note_author(author: T::AccountId) {617 fn note_author(author: T::AccountId) {
614 let pot = Self::account_id();618 let pot = Self::account_id();
modifiedpallets/collator-selection/src/mock.rsdiffbeforeafterboth
5151
52// Configure a mock runtime to test the pallet.52// Configure a mock runtime to test the pallet.
53frame_support::construct_runtime!(53frame_support::construct_runtime!(
54 pub enum Test where54 pub enum Test {
55 Block = Block,
56 NodeBlock = Block,
57 UncheckedExtrinsic = UncheckedExtrinsic,
58 {
59 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},55 System: frame_system,
60 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},56 Timestamp: pallet_timestamp,
61 Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>},57 Session: pallet_session,
62 Aura: pallet_aura::{Pallet, Storage, Config<T>},58 Aura: pallet_aura,
63 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},59 Balances: pallet_balances,
64 CollatorSelection: collator_selection::{Pallet, Call, Storage, Event<T>},60 CollatorSelection: collator_selection,
65 Authorship: pallet_authorship::{Pallet, Storage},61 Authorship: pallet_authorship,
66 }62 }
67);63);
6864
78 type DbWeight = ();74 type DbWeight = ();
79 type RuntimeOrigin = RuntimeOrigin;75 type RuntimeOrigin = RuntimeOrigin;
80 type RuntimeCall = RuntimeCall;76 type RuntimeCall = RuntimeCall;
81 type Index = u64;77 type Nonce = u64;
82 type BlockNumber = u64;
83 type Hash = H256;78 type Hash = H256;
84 type Hashing = BlakeTwo256;79 type Hashing = BlakeTwo256;
85 type AccountId = u64;80 type AccountId = u64;
86 type Lookup = IdentityLookup<Self::AccountId>;81 type Lookup = IdentityLookup<Self::AccountId>;
87 type Header = Header;
88 type RuntimeEvent = RuntimeEvent;82 type RuntimeEvent = RuntimeEvent;
89 type BlockHashCount = BlockHashCount;83 type BlockHashCount = BlockHashCount;
90 type Version = ();84 type Version = ();
115 type MaxLocks = ();109 type MaxLocks = ();
116 type MaxReserves = MaxReserves;110 type MaxReserves = MaxReserves;
117 type ReserveIdentifier = [u8; 8];111 type ReserveIdentifier = [u8; 8];
118 type HoldIdentifier = [u8; 16];
119 type FreezeIdentifier = [u8; 16];112 type FreezeIdentifier = [u8; 16];
120 type MaxHolds = MaxHolds;113 type MaxHolds = MaxHolds;
121 type MaxFreezes = MaxFreezes;114 type MaxFreezes = MaxFreezes;
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
463 #[pallet::genesis_config]463 #[pallet::genesis_config]
464 pub struct GenesisConfig<T>(PhantomData<T>);464 pub struct GenesisConfig<T>(PhantomData<T>);
465465
466 #[cfg(feature = "std")]
467 impl<T: Config> Default for GenesisConfig<T> {466 impl<T: Config> Default for GenesisConfig<T> {
468 fn default() -> Self {467 fn default() -> Self {
469 Self(Default::default())468 Self(Default::default())
470 }469 }
471 }470 }
472471
473 #[pallet::genesis_build]472 #[pallet::genesis_build]
474 impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {473 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
475 fn build(&self) {474 fn build(&self) {
476 StorageVersion::new(1).put::<Pallet<T>>();475 StorageVersion::new(1).put::<Pallet<T>>();
477 }476 }
modifiedpallets/configuration/src/benchmarking.rsdiffbeforeafterboth
52 }52 }
5353
54 set_app_promotion_configuration_override {54 set_app_promotion_configuration_override {
55 let configuration: AppPromotionConfiguration<T::BlockNumber> = Default::default();55 let configuration: AppPromotionConfiguration<BlockNumberFor<T>> = Default::default();
56 }: {56 }: {
57 assert_ok!(57 assert_ok!(
58 <Pallet<T>>::set_app_promotion_configuration_override(RawOrigin::Root.into(), configuration)58 <Pallet<T>>::set_app_promotion_configuration_override(RawOrigin::Root.into(), configuration)
82 }82 }
8383
84 set_collator_selection_kick_threshold {84 set_collator_selection_kick_threshold {
85 let threshold: Option<T::BlockNumber> = Some(900u32.into());85 let threshold: Option<BlockNumberFor<T>> = Some(900u32.into());
86 }: {86 }: {
87 assert_ok!(87 assert_ok!(
88 <Pallet<T>>::set_collator_selection_kick_threshold(RawOrigin::Root.into(), threshold)88 <Pallet<T>>::set_collator_selection_kick_threshold(RawOrigin::Root.into(), threshold)
modifiedpallets/configuration/src/lib.rsdiffbeforeafterboth
80 #[pallet::constant]80 #[pallet::constant]
81 type AppPromotionDailyRate: Get<Perbill>;81 type AppPromotionDailyRate: Get<Perbill>;
82 #[pallet::constant]82 #[pallet::constant]
83 type DayRelayBlocks: Get<Self::BlockNumber>;83 type DayRelayBlocks: Get<BlockNumberFor<Self>>;
8484
85 #[pallet::constant]85 #[pallet::constant]
86 type DefaultCollatorSelectionMaxCollators: Get<u32>;86 type DefaultCollatorSelectionMaxCollators: Get<u32>;
87 #[pallet::constant]87 #[pallet::constant]
88 type DefaultCollatorSelectionLicenseBond: Get<Self::Balance>;88 type DefaultCollatorSelectionLicenseBond: Get<Self::Balance>;
89 #[pallet::constant]89 #[pallet::constant]
90 type DefaultCollatorSelectionKickThreshold: Get<Self::BlockNumber>;90 type DefaultCollatorSelectionKickThreshold: Get<BlockNumberFor<Self>>;
9191
92 /// The weight information of this pallet.92 /// The weight information of this pallet.
93 type WeightInfo: WeightInfo;93 type WeightInfo: WeightInfo;
103 bond_cost: Option<T::Balance>,103 bond_cost: Option<T::Balance>,
104 },104 },
105 NewCollatorKickThreshold {105 NewCollatorKickThreshold {
106 length_in_blocks: Option<T::BlockNumber>,106 length_in_blocks: Option<BlockNumberFor<T>>,
107 },107 },
108 }108 }
109109
134 #[pallet::genesis_config]134 #[pallet::genesis_config]
135 pub struct GenesisConfig<T>(PhantomData<T>);135 pub struct GenesisConfig<T>(PhantomData<T>);
136136
137 #[cfg(feature = "std")]
138 impl<T: Config> Default for GenesisConfig<T> {137 impl<T: Config> Default for GenesisConfig<T> {
139 fn default() -> Self {138 fn default() -> Self {
140 Self(Default::default())139 Self(Default::default())
141 }140 }
142 }141 }
143142
144 #[pallet::genesis_build]143 #[pallet::genesis_build]
145 impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {144 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
146 fn build(&self) {145 fn build(&self) {
147 update_base_fee::<T>();146 update_base_fee::<T>();
148 }147 }
166165
167 #[pallet::storage]166 #[pallet::storage]
168 pub type AppPromomotionConfigurationOverride<T: Config> =167 pub type AppPromomotionConfigurationOverride<T: Config> =
169 StorageValue<Value = AppPromotionConfiguration<T::BlockNumber>, QueryKind = ValueQuery>;168 StorageValue<Value = AppPromotionConfiguration<BlockNumberFor<T>>, QueryKind = ValueQuery>;
170169
171 #[pallet::storage]170 #[pallet::storage]
172 pub type CollatorSelectionDesiredCollatorsOverride<T: Config> = StorageValue<171 pub type CollatorSelectionDesiredCollatorsOverride<T: Config> = StorageValue<
184183
185 #[pallet::storage]184 #[pallet::storage]
186 pub type CollatorSelectionKickThresholdOverride<T: Config> = StorageValue<185 pub type CollatorSelectionKickThresholdOverride<T: Config> = StorageValue<
187 Value = T::BlockNumber,186 Value = BlockNumberFor<T>,
188 QueryKind = ValueQuery,187 QueryKind = ValueQuery,
189 OnEmpty = T::DefaultCollatorSelectionKickThreshold,188 OnEmpty = T::DefaultCollatorSelectionKickThreshold,
190 >;189 >;
228 #[pallet::weight(T::WeightInfo::set_app_promotion_configuration_override())]227 #[pallet::weight(T::WeightInfo::set_app_promotion_configuration_override())]
229 pub fn set_app_promotion_configuration_override(228 pub fn set_app_promotion_configuration_override(
230 origin: OriginFor<T>,229 origin: OriginFor<T>,
231 mut configuration: AppPromotionConfiguration<T::BlockNumber>,230 mut configuration: AppPromotionConfiguration<BlockNumberFor<T>>,
232 ) -> DispatchResult {231 ) -> DispatchResult {
233 ensure_root(origin)?;232 ensure_root(origin)?;
234 if configuration.interval_income.is_some() {233 if configuration.interval_income.is_some() {
287 #[pallet::weight(T::WeightInfo::set_collator_selection_kick_threshold())]286 #[pallet::weight(T::WeightInfo::set_collator_selection_kick_threshold())]
288 pub fn set_collator_selection_kick_threshold(287 pub fn set_collator_selection_kick_threshold(
289 origin: OriginFor<T>,288 origin: OriginFor<T>,
290 threshold: Option<T::BlockNumber>,289 threshold: Option<BlockNumberFor<T>>,
291 ) -> DispatchResult {290 ) -> DispatchResult {
292 ensure_root(origin)?;291 ensure_root(origin)?;
293 if let Some(threshold) = threshold {292 if let Some(threshold) = threshold {
modifiedpallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
422 {422 {
423 return None;423 return None;
424 }424 }
425 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;425 let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
426426
427 if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {427 if let Some(last_tx_block) = <SponsorBasket<T>>::get(contract_address, who.as_eth()) {
428 let limit = <SponsoringRateLimit<T>>::get(contract_address);428 let limit = <SponsoringRateLimit<T>>::get(contract_address);
modifiedpallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth
5353
54 /// In case of enabled sponsoring, but no sponsoring rate limit set,54 /// In case of enabled sponsoring, but no sponsoring rate limit set,
55 /// this value will be used implicitly55 /// this value will be used implicitly
56 type DefaultSponsoringRateLimit: Get<Self::BlockNumber>;56 type DefaultSponsoringRateLimit: Get<BlockNumberFor<Self>>;
57 }57 }
5858
59 #[pallet::error]59 #[pallet::error]
115 pub(super) type SponsoringRateLimit<T: Config> = StorageMap<115 pub(super) type SponsoringRateLimit<T: Config> = StorageMap<
116 Hasher = Twox128,116 Hasher = Twox128,
117 Key = H160,117 Key = H160,
118 Value = T::BlockNumber,118 Value = BlockNumberFor<T>,
119 QueryKind = ValueQuery,119 QueryKind = ValueQuery,
120 OnEmpty = T::DefaultSponsoringRateLimit,120 OnEmpty = T::DefaultSponsoringRateLimit,
121 >;121 >;
139 Key1 = H160,139 Key1 = H160,
140 Hasher2 = Twox128,140 Hasher2 = Twox128,
141 Key2 = H160,141 Key2 = H160,
142 Value = T::BlockNumber,142 Value = BlockNumberFor<T>,
143 QueryKind = OptionQuery,143 QueryKind = OptionQuery,
144 >;144 >;
145145
393 }393 }
394394
395 /// Set duration between two sponsored contract calls395 /// Set duration between two sponsored contract calls
396 pub fn set_sponsoring_rate_limit(contract: H160, rate_limit: T::BlockNumber) {396 pub fn set_sponsoring_rate_limit(contract: H160, rate_limit: BlockNumberFor<T>) {
397 <SponsoringRateLimit<T>>::insert(contract, rate_limit);397 <SponsoringRateLimit<T>>::insert(contract, rate_limit);
398 }398 }
399399
modifiedpallets/evm-migration/src/benchmarking.rsdiffbeforeafterboth
23use sp_std::{vec::Vec, vec};23use sp_std::{vec::Vec, vec};
2424
25benchmarks! {25benchmarks! {
26 where_clause { where <T as Config>::RuntimeEvent: codec::Encode }26 where_clause { where <T as Config>::RuntimeEvent: parity_scale_codec::Encode }
2727
28 begin {28 begin {
29 }: _(RawOrigin::Root, H160::default())29 }: _(RawOrigin::Root, H160::default())
5959
60 insert_events {60 insert_events {
61 let b in 0..200;61 let b in 0..200;
62 use codec::Encode;62 use parity_scale_codec::Encode;
63 let logs = (0..b).map(|_| <T as Config>::RuntimeEvent::from(crate::Event::<T>::TestEvent).encode()).collect::<Vec<_>>();63 let logs = (0..b).map(|_| <T as Config>::RuntimeEvent::from(crate::Event::<T>::TestEvent).encode()).collect::<Vec<_>>();
64 }: _(RawOrigin::Root, logs)64 }: _(RawOrigin::Root, logs)
65}65}
modifiedpallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth
3030
31impl<T: Config> fungibles::Inspect<<T as SystemConfig>::AccountId> for Pallet<T>31impl<T: Config> fungibles::Inspect<<T as SystemConfig>::AccountId> for Pallet<T>
32where32where
33 T: orml_tokens::Config<CurrencyId = AssetIds>,33 T: orml_tokens::Config<CurrencyId = AssetId>,
34 BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,34 BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
35 BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,35 BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
36 <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,36 <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
37 <T as orml_tokens::Config>::Balance: From<BalanceOf<T>>,37 <T as orml_tokens::Config>::Balance: From<BalanceOf<T>>,
38{38{
39 type AssetId = AssetIds;39 type AssetId = AssetId;
40 type Balance = BalanceOf<T>;40 type Balance = BalanceOf<T>;
4141
42 fn total_issuance(asset: Self::AssetId) -> Self::Balance {42 fn total_issuance(asset: Self::AssetId) -> Self::Balance {
43 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible total_issuance");43 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible total_issuance");
4444
45 match asset {45 match asset {
46 AssetIds::NativeAssetId(NativeCurrency::Here) => {46 AssetId::NativeAssetId(NativeCurrency::Here) => {
47 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::total_issuance()47 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::total_issuance()
48 .into()48 .into()
49 }49 }
50 AssetIds::NativeAssetId(NativeCurrency::Parent) => {50 AssetId::NativeAssetId(NativeCurrency::Parent) => {
51 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::total_issuance(51 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::total_issuance(
52 AssetIds::NativeAssetId(NativeCurrency::Parent),52 AssetId::NativeAssetId(NativeCurrency::Parent),
53 )53 )
54 .into()54 .into()
55 }55 }
56 AssetIds::ForeignAssetId(fid) => {56 AssetId::ForeignAssetId(fid) => {
57 let target_collection_id = match <AssetBinding<T>>::get(fid) {57 let target_collection_id = match <AssetBinding<T>>::get(fid) {
58 Some(v) => v,58 Some(v) => v,
59 None => return Zero::zero(),59 None => return Zero::zero(),
71 fn minimum_balance(asset: Self::AssetId) -> Self::Balance {71 fn minimum_balance(asset: Self::AssetId) -> Self::Balance {
72 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible minimum_balance");72 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible minimum_balance");
73 match asset {73 match asset {
74 AssetIds::NativeAssetId(NativeCurrency::Here) => {74 AssetId::NativeAssetId(NativeCurrency::Here) => {
75 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::minimum_balance()75 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::minimum_balance()
76 .into()76 .into()
77 }77 }
78 AssetIds::NativeAssetId(NativeCurrency::Parent) => {78 AssetId::NativeAssetId(NativeCurrency::Parent) => {
79 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::minimum_balance(79 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::minimum_balance(
80 AssetIds::NativeAssetId(NativeCurrency::Parent),80 AssetId::NativeAssetId(NativeCurrency::Parent),
81 )81 )
82 .into()82 .into()
83 }83 }
84 AssetIds::ForeignAssetId(fid) => {84 AssetId::ForeignAssetId(fid) => AssetMetadatas::<T>::get(AssetId::ForeignAssetId(fid))
85 AssetMetadatas::<T>::get(AssetIds::ForeignAssetId(fid))
86 .map(|x| x.minimal_balance)85 .map(|x| x.minimal_balance)
87 .unwrap_or_else(Zero::zero)86 .unwrap_or_else(Zero::zero),
88 }
89 }87 }
90 }88 }
9189
92 fn balance(asset: Self::AssetId, who: &<T as SystemConfig>::AccountId) -> Self::Balance {90 fn balance(asset: Self::AssetId, who: &<T as SystemConfig>::AccountId) -> Self::Balance {
93 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible balance");91 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible balance");
94 match asset {92 match asset {
95 AssetIds::NativeAssetId(NativeCurrency::Here) => {93 AssetId::NativeAssetId(NativeCurrency::Here) => {
96 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::balance(who).into()94 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::balance(who).into()
97 }95 }
98 AssetIds::NativeAssetId(NativeCurrency::Parent) => {96 AssetId::NativeAssetId(NativeCurrency::Parent) => {
99 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::balance(97 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::balance(
100 AssetIds::NativeAssetId(NativeCurrency::Parent),98 AssetId::NativeAssetId(NativeCurrency::Parent),
101 who,99 who,
102 )100 )
103 .into()101 .into()
104 }102 }
105 AssetIds::ForeignAssetId(fid) => {103 AssetId::ForeignAssetId(fid) => {
106 let target_collection_id = match <AssetBinding<T>>::get(fid) {104 let target_collection_id = match <AssetBinding<T>>::get(fid) {
107 Some(v) => v,105 Some(v) => v,
108 None => return Zero::zero(),106 None => return Zero::zero(),
133 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible reducible_balance");131 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible reducible_balance");
134132
135 match asset {133 match asset {
136 AssetIds::NativeAssetId(NativeCurrency::Here) => {134 AssetId::NativeAssetId(NativeCurrency::Here) => {
137 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::reducible_balance(135 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::reducible_balance(
138 who,136 who,
139 preservation,137 preservation,
140 fortitude,138 fortitude,
141 )139 )
142 .into()140 .into()
143 }141 }
144 AssetIds::NativeAssetId(NativeCurrency::Parent) => {142 AssetId::NativeAssetId(NativeCurrency::Parent) => {
145 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::reducible_balance(143 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::reducible_balance(
146 AssetIds::NativeAssetId(NativeCurrency::Parent),144 AssetId::NativeAssetId(NativeCurrency::Parent),
147 who,145 who,
148 preservation,146 preservation,
149 fortitude,147 fortitude,
163 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible can_deposit");161 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible can_deposit");
164162
165 match asset {163 match asset {
166 AssetIds::NativeAssetId(NativeCurrency::Here) => {164 AssetId::NativeAssetId(NativeCurrency::Here) => {
167 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::can_deposit(165 <pallet_balances::Pallet<T> as fungible::Inspect<T::AccountId>>::can_deposit(
168 who,166 who,
169 amount.into(),167 amount.into(),
170 provenance,168 provenance,
171 )169 )
172 }170 }
173 AssetIds::NativeAssetId(NativeCurrency::Parent) => {171 AssetId::NativeAssetId(NativeCurrency::Parent) => {
174 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_deposit(172 <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_deposit(
175 AssetIds::NativeAssetId(NativeCurrency::Parent),173 AssetId::NativeAssetId(NativeCurrency::Parent),
176 who,174 who,
177 amount.into(),175 amount.into(),
178 provenance,176 provenance,
219 };217 };
220218
221 match asset {219 match asset {
222 AssetIds::NativeAssetId(NativeCurrency::Here) => {220 AssetId::NativeAssetId(NativeCurrency::Here) => {
223 let this_amount: <T as pallet_balances::Config>::Balance = match value.try_into() {221 let this_amount: <T as pallet_balances::Config>::Balance = match value.try_into() {
224 Ok(val) => val,222 Ok(val) => val,
225 Err(_) => {223 Err(_) => {
240 _ => WithdrawConsequence::BalanceLow,238 _ => WithdrawConsequence::BalanceLow,
241 }239 }
242 }240 }
243 AssetIds::NativeAssetId(NativeCurrency::Parent) => {241 AssetId::NativeAssetId(NativeCurrency::Parent) => {
244 let parent_amount: <T as orml_tokens::Config>::Balance = match value.try_into() {242 let parent_amount: <T as orml_tokens::Config>::Balance = match value.try_into() {
245 Ok(val) => val,243 Ok(val) => val,
246 Err(_) => {244 Err(_) => {
247 return WithdrawConsequence::UnknownAsset;245 return WithdrawConsequence::UnknownAsset;
248 }246 }
249 };247 };
250 match <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_withdraw(248 match <orml_tokens::Pallet<T> as fungibles::Inspect<T::AccountId>>::can_withdraw(
251 AssetIds::NativeAssetId(NativeCurrency::Parent),249 AssetId::NativeAssetId(NativeCurrency::Parent),
252 who,250 who,
253 parent_amount,251 parent_amount,
254 ) {252 ) {
269 }267 }
270 }268 }
271269
272 fn asset_exists(asset: AssetIds) -> bool {270 fn asset_exists(asset: AssetId) -> bool {
273 match asset {271 match asset {
274 AssetIds::NativeAssetId(_) => true,272 AssetId::NativeAssetId(_) => true,
275 AssetIds::ForeignAssetId(fid) => <AssetBinding<T>>::contains_key(fid),273 AssetId::ForeignAssetId(fid) => <AssetBinding<T>>::contains_key(fid),
276 }274 }
277 }275 }
278}276}
279277
280impl<T: Config> fungibles::Mutate<<T as SystemConfig>::AccountId> for Pallet<T>278impl<T: Config> fungibles::Mutate<<T as SystemConfig>::AccountId> for Pallet<T>
281where279where
282 T: orml_tokens::Config<CurrencyId = AssetIds>,280 T: orml_tokens::Config<CurrencyId = AssetId>,
283 BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,281 BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
284 BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,282 BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
285 <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,283 <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
295 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible mint_into {:?}", asset);293 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible mint_into {:?}", asset);
296294
297 match asset {295 match asset {
298 AssetIds::NativeAssetId(NativeCurrency::Here) => {296 AssetId::NativeAssetId(NativeCurrency::Here) => {
299 <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::mint_into(297 <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::mint_into(
300 who,298 who,
301 amount.into(),299 amount.into(),
302 )300 )
303 .map(Into::into)301 .map(Into::into)
304 }302 }
305 AssetIds::NativeAssetId(NativeCurrency::Parent) => {303 AssetId::NativeAssetId(NativeCurrency::Parent) => {
306 <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::mint_into(304 <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::mint_into(
307 AssetIds::NativeAssetId(NativeCurrency::Parent),305 AssetId::NativeAssetId(NativeCurrency::Parent),
308 who,306 who,
309 amount.into(),307 amount.into(),
310 )308 )
311 .map(Into::into)309 .map(Into::into)
312 }310 }
313 AssetIds::ForeignAssetId(fid) => {311 AssetId::ForeignAssetId(fid) => {
314 let target_collection_id = match <AssetBinding<T>>::get(fid) {312 let target_collection_id = match <AssetBinding<T>>::get(fid) {
315 Some(v) => v,313 Some(v) => v,
316 None => {314 None => {
349 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible burn_from");347 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible burn_from");
350348
351 match asset {349 match asset {
352 AssetIds::NativeAssetId(NativeCurrency::Here) => {350 AssetId::NativeAssetId(NativeCurrency::Here) => {
353 <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::burn_from(351 <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::burn_from(
354 who,352 who,
355 amount.into(),353 amount.into(),
358 )356 )
359 .map(Into::into)357 .map(Into::into)
360 }358 }
361 AssetIds::NativeAssetId(NativeCurrency::Parent) => {359 AssetId::NativeAssetId(NativeCurrency::Parent) => {
362 <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::burn_from(360 <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::burn_from(
363 AssetIds::NativeAssetId(NativeCurrency::Parent),361 AssetId::NativeAssetId(NativeCurrency::Parent),
364 who,362 who,
365 amount.into(),363 amount.into(),
366 precision,364 precision,
367 fortitude,365 fortitude,
368 )366 )
369 .map(Into::into)367 .map(Into::into)
370 }368 }
371 AssetIds::ForeignAssetId(fid) => {369 AssetId::ForeignAssetId(fid) => {
372 let target_collection_id = match <AssetBinding<T>>::get(fid) {370 let target_collection_id = match <AssetBinding<T>>::get(fid) {
373 Some(v) => v,371 Some(v) => v,
374 None => {372 None => {
401 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible transfer");399 log::trace!(target: "fassets::impl_foreign_assets", "impl_fungible transfer");
402400
403 match asset {401 match asset {
404 AssetIds::NativeAssetId(NativeCurrency::Here) => {402 AssetId::NativeAssetId(NativeCurrency::Here) => {
405 match <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::transfer(403 match <pallet_balances::Pallet<T> as fungible::Mutate<T::AccountId>>::transfer(
406 source,404 source,
407 dest,405 dest,
414 )),412 )),
415 }413 }
416 }414 }
417 AssetIds::NativeAssetId(NativeCurrency::Parent) => {415 AssetId::NativeAssetId(NativeCurrency::Parent) => {
418 match <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::transfer(416 match <orml_tokens::Pallet<T> as fungibles::Mutate<T::AccountId>>::transfer(
419 AssetIds::NativeAssetId(NativeCurrency::Parent),417 AssetId::NativeAssetId(NativeCurrency::Parent),
420 source,418 source,
421 dest,419 dest,
422 amount.into(),420 amount.into(),
426 Err(e) => Err(e),424 Err(e) => Err(e),
427 }425 }
428 }426 }
429 AssetIds::ForeignAssetId(fid) => {427 AssetId::ForeignAssetId(fid) => {
430 let target_collection_id = match <AssetBinding<T>>::get(fid) {428 let target_collection_id = match <AssetBinding<T>>::get(fid) {
431 Some(v) => v,429 Some(v) => v,
432 None => {430 None => {
479477
480impl<T: Config> fungibles::Unbalanced<<T as SystemConfig>::AccountId> for Pallet<T>478impl<T: Config> fungibles::Unbalanced<<T as SystemConfig>::AccountId> for Pallet<T>
481where479where
482 T: orml_tokens::Config<CurrencyId = AssetIds>,480 T: orml_tokens::Config<CurrencyId = AssetId>,
483 BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,481 BalanceOf<T>: From<<T as pallet_balances::Config>::Balance>,
484 BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,482 BalanceOf<T>: From<<T as orml_tokens::Config>::Balance>,
485 <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,483 <T as pallet_balances::Config>::Balance: From<BalanceOf<T>>,
modifiedpallets/foreign-assets/src/lib.rsdiffbeforeafterboth
79 Encode,79 Encode,
80 Decode,80 Decode,
81 TypeInfo,81 TypeInfo,
82 Serialize,
83 Deserialize,
82)]84)]
83#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
84pub enum NativeCurrency {85pub enum NativeCurrency {
85 Here = 0,86 Here = 0,
86 Parent = 1,87 Parent = 1,
98 Encode,99 Encode,
99 Decode,100 Decode,
100 TypeInfo,101 TypeInfo,
102 Serialize,
103 Deserialize,
101)]104)]
102#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
103pub enum AssetIds {105pub enum AssetId {
104 ForeignAssetId(ForeignAssetId),106 ForeignAssetId(ForeignAssetId),
105 NativeAssetId(NativeCurrency),107 NativeAssetId(NativeCurrency),
106}108}
109 fn try_as_foreign(asset: T) -> Option<F>;111 fn try_as_foreign(asset: T) -> Option<F>;
110}112}
111113
112impl TryAsForeign<AssetIds, ForeignAssetId> for AssetIds {114impl TryAsForeign<AssetId, ForeignAssetId> for AssetId {
113 fn try_as_foreign(asset: AssetIds) -> Option<ForeignAssetId> {115 fn try_as_foreign(asset: AssetId) -> Option<ForeignAssetId> {
114 match asset {116 match asset {
115 AssetIds::ForeignAssetId(id) => Some(id),117 Self::ForeignAssetId(id) => Some(id),
116 _ => None,118 _ => None,
117 }119 }
118 }120 }
119}121}
120122
121pub type ForeignAssetId = u32;123pub type ForeignAssetId = u32;
122pub type CurrencyId = AssetIds;124pub type CurrencyId = AssetId;
123125
124mod impl_fungibles;126mod impl_fungibles;
125pub mod weights;127pub mod weights;
151{153{
152 fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata<BalanceOf<T>>> {154 fn get_asset_metadata(foreign_asset_id: ForeignAssetId) -> Option<AssetMetadata<BalanceOf<T>>> {
153 log::trace!(target: "fassets::asset_metadatas", "call");155 log::trace!(target: "fassets::asset_metadatas", "call");
154 Pallet::<T>::asset_metadatas(AssetIds::ForeignAssetId(foreign_asset_id))156 Pallet::<T>::asset_metadatas(AssetId::ForeignAssetId(foreign_asset_id))
155 }157 }
156158
157 fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation> {159 fn get_multi_location(foreign_asset_id: ForeignAssetId) -> Option<MultiLocation> {
161163
162 fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {164 fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {
163 log::trace!(target: "fassets::get_currency_id", "call");165 log::trace!(target: "fassets::get_currency_id", "call");
164 Pallet::<T>::location_to_currency_ids(multi_location).map(AssetIds::ForeignAssetId)166 Pallet::<T>::location_to_currency_ids(multi_location).map(AssetId::ForeignAssetId)
165 }167 }
166}168}
167169
231 },233 },
232 /// The asset registered.234 /// The asset registered.
233 AssetRegistered {235 AssetRegistered {
234 asset_id: AssetIds,236 asset_id: AssetId,
235 metadata: AssetMetadata<BalanceOf<T>>,237 metadata: AssetMetadata<BalanceOf<T>>,
236 },238 },
237 /// The asset updated.239 /// The asset updated.
238 AssetUpdated {240 AssetUpdated {
239 asset_id: AssetIds,241 asset_id: AssetId,
240 metadata: AssetMetadata<BalanceOf<T>>,242 metadata: AssetMetadata<BalanceOf<T>>,
241 },243 },
242 }244 }
253 #[pallet::storage]255 #[pallet::storage]
254 #[pallet::getter(fn foreign_asset_locations)]256 #[pallet::getter(fn foreign_asset_locations)]
255 pub type ForeignAssetLocations<T: Config> =257 pub type ForeignAssetLocations<T: Config> =
256 StorageMap<_, Twox64Concat, ForeignAssetId, xcm::v3::MultiLocation, OptionQuery>;258 StorageMap<_, Twox64Concat, ForeignAssetId, staging_xcm::v3::MultiLocation, OptionQuery>;
257259
258 /// The storages for CurrencyIds.260 /// The storages for CurrencyIds.
259 ///261 ///
260 /// LocationToCurrencyIds: map MultiLocation => Option<ForeignAssetId>262 /// LocationToCurrencyIds: map MultiLocation => Option<ForeignAssetId>
261 #[pallet::storage]263 #[pallet::storage]
262 #[pallet::getter(fn location_to_currency_ids)]264 #[pallet::getter(fn location_to_currency_ids)]
263 pub type LocationToCurrencyIds<T: Config> =265 pub type LocationToCurrencyIds<T: Config> =
264 StorageMap<_, Twox64Concat, xcm::v3::MultiLocation, ForeignAssetId, OptionQuery>;266 StorageMap<_, Twox64Concat, staging_xcm::v3::MultiLocation, ForeignAssetId, OptionQuery>;
265267
266 /// The storages for AssetMetadatas.268 /// The storages for AssetMetadatas.
267 ///269 ///
268 /// AssetMetadatas: map AssetIds => Option<AssetMetadata>270 /// AssetMetadatas: map AssetIds => Option<AssetMetadata>
269 #[pallet::storage]271 #[pallet::storage]
270 #[pallet::getter(fn asset_metadatas)]272 #[pallet::getter(fn asset_metadatas)]
271 pub type AssetMetadatas<T: Config> =273 pub type AssetMetadatas<T: Config> =
272 StorageMap<_, Twox64Concat, AssetIds, AssetMetadata<BalanceOf<T>>, OptionQuery>;274 StorageMap<_, Twox64Concat, AssetId, AssetMetadata<BalanceOf<T>>, OptionQuery>;
273275
274 /// The storages for assets to fungible collection binding276 /// The storages for assets to fungible collection binding
275 ///277 ///
381 *maybe_location = Some(*location);383 *maybe_location = Some(*location);
382384
383 AssetMetadatas::<T>::try_mutate(385 AssetMetadatas::<T>::try_mutate(
384 AssetIds::ForeignAssetId(foreign_asset_id),386 AssetId::ForeignAssetId(foreign_asset_id),
385 |maybe_asset_metadatas| -> DispatchResult {387 |maybe_asset_metadatas| -> DispatchResult {
386 ensure!(maybe_asset_metadatas.is_none(), Error::<T>::AssetIdExisted);388 ensure!(maybe_asset_metadatas.is_none(), Error::<T>::AssetIdExisted);
387 *maybe_asset_metadatas = Some(metadata.clone());389 *maybe_asset_metadatas = Some(metadata.clone());
413 .ok_or(Error::<T>::AssetIdNotExists)?;415 .ok_or(Error::<T>::AssetIdNotExists)?;
414416
415 AssetMetadatas::<T>::try_mutate(417 AssetMetadatas::<T>::try_mutate(
416 AssetIds::ForeignAssetId(foreign_asset_id),418 AssetId::ForeignAssetId(foreign_asset_id),
417 |maybe_asset_metadatas| -> DispatchResult {419 |maybe_asset_metadatas| -> DispatchResult {
418 ensure!(420 ensure!(
419 maybe_asset_metadatas.is_some(),421 maybe_asset_metadatas.is_some(),
450 traits::{452 traits::{
451 fungibles::Balanced, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT,453 fungibles::Balanced, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT,
452 },454 },
453 weights::{WeightToFeePolynomial, WeightToFee},455 weights::{WeightToFee, WeightToFeePolynomial},
454};456};
455457
456pub struct FreeForAll<458pub struct FreeForAll<
480 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {482 fn buy_weight(
483 &mut self,
484 weight: Weight,
485 payment: Assets,
486 _xcm: &XcmContext,
487 ) -> Result<Assets, XcmError> {
481 log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);488 log::trace!(target: "fassets::weight", "buy_weight weight: {:?}, payment: {:?}", weight, payment);
482 Ok(payment)489 Ok(payment)
modifiedpallets/identity/src/tests.rsdiffbeforeafterboth
54type Block = frame_system::mocking::MockBlock<Test>;54type Block = frame_system::mocking::MockBlock<Test>;
5555
56frame_support::construct_runtime!(56frame_support::construct_runtime!(
57 pub enum Test where57 pub enum Test {
58 Block = Block,
59 NodeBlock = Block,
60 UncheckedExtrinsic = UncheckedExtrinsic,
61 {
62 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},58 System: frame_system,
63 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},59 Balances: pallet_balances,
64 Identity: pallet_identity::{Pallet, Call, Storage, Event<T>},60 Identity: pallet_identity,
65 }61 }
66);62);
6763
71}67}
72impl frame_system::Config for Test {68impl frame_system::Config for Test {
73 type BaseCallFilter = frame_support::traits::Everything;69 type BaseCallFilter = frame_support::traits::Everything;
70 type Block = Block;
74 type BlockWeights = ();71 type BlockWeights = ();
75 type BlockLength = ();72 type BlockLength = ();
76 type RuntimeOrigin = RuntimeOrigin;73 type RuntimeOrigin = RuntimeOrigin;
77 type Index = u64;74 type Nonce = u64;
78 type BlockNumber = u64;
79 type Hash = H256;75 type Hash = H256;
80 type RuntimeCall = RuntimeCall;76 type RuntimeCall = RuntimeCall;
81 type Hashing = BlakeTwo256;77 type Hashing = BlakeTwo256;
82 type AccountId = u64;78 type AccountId = u64;
83 type Lookup = IdentityLookup<Self::AccountId>;79 type Lookup = IdentityLookup<Self::AccountId>;
84 type Header = Header;
85 type RuntimeEvent = RuntimeEvent;80 type RuntimeEvent = RuntimeEvent;
86 type BlockHashCount = ConstU64<250>;81 type BlockHashCount = ConstU64<250>;
87 type DbWeight = ();82 type DbWeight = ();
106 type MaxReserves = ();101 type MaxReserves = ();
107 type ReserveIdentifier = [u8; 8];102 type ReserveIdentifier = [u8; 8];
108 type WeightInfo = ();103 type WeightInfo = ();
109 type HoldIdentifier = ();104 type RuntimeHoldReason = RuntimeHoldReason;
110 type FreezeIdentifier = ();105 type FreezeIdentifier = ();
111 type MaxHolds = ();106 type MaxHolds = ();
112 type MaxFreezes = ();107 type MaxFreezes = ();
139}134}
140135
141pub fn new_test_ext() -> sp_io::TestExternalities {136pub fn new_test_ext() -> sp_io::TestExternalities {
142 let mut t = frame_system::GenesisConfig::default()137 let mut t = <frame_system::GenesisConfig<Test>>::default()
143 .build_storage::<Test>()138 .build_storage()
144 .unwrap();139 .unwrap();
145 pallet_balances::GenesisConfig::<Test> {140 pallet_balances::GenesisConfig::<Test> {
146 balances: vec![(1, 10), (2, 10), (3, 10), (10, 100), (20, 100), (30, 100)],141 balances: vec![(1, 10), (2, 10), (3, 10), (10, 100), (20, 100), (30, 100)],
modifiedpallets/identity/src/types.rsdiffbeforeafterboth
77}77}
7878
79impl Decode for Data {79impl Decode for Data {
80 fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {80 fn decode<I: parity_scale_codec::Input>(
81 input: &mut I,
82 ) -> sp_std::result::Result<Self, parity_scale_codec::Error> {
81 let b = input.read_byte()?;83 let b = input.read_byte()?;
82 Ok(match b {84 Ok(match b {
83 0 => Data::None,85 0 => Data::None,
92 35 => Data::Sha256(<[u8; 32]>::decode(input)?),94 35 => Data::Sha256(<[u8; 32]>::decode(input)?),
93 36 => Data::Keccak256(<[u8; 32]>::decode(input)?),95 36 => Data::Keccak256(<[u8; 32]>::decode(input)?),
94 37 => Data::ShaThree256(<[u8; 32]>::decode(input)?),96 37 => Data::ShaThree256(<[u8; 32]>::decode(input)?),
95 _ => return Err(codec::Error::from("invalid leading byte")),97 _ => return Err(parity_scale_codec::Error::from("invalid leading byte")),
96 })98 })
97 }99 }
98}100}
114 }116 }
115 }117 }
116}118}
117impl codec::EncodeLike for Data {}119impl parity_scale_codec::EncodeLike for Data {}
118120
119/// Add a Raw variant with the given index and a fixed sized byte array121/// Add a Raw variant with the given index and a fixed sized byte array
120macro_rules! data_raw_variants {122macro_rules! data_raw_variants {
284 }286 }
285}287}
286impl Decode for IdentityFields {288impl Decode for IdentityFields {
287 fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {289 fn decode<I: parity_scale_codec::Input>(
290 input: &mut I,
291 ) -> sp_std::result::Result<Self, parity_scale_codec::Error> {
288 let field = u64::decode(input)?;292 let field = u64::decode(input)?;
289 Ok(Self(293 Ok(Self(
290 <BitFlags<IdentityField>>::from_bits(field).map_err(|_| "invalid value")?,294 <BitFlags<IdentityField>>::from_bits(field).map_err(|_| "invalid value")?,
445 MaxAdditionalFields: Get<u32>,449 MaxAdditionalFields: Get<u32>,
446 > Decode for Registration<Balance, MaxJudgements, MaxAdditionalFields>450 > Decode for Registration<Balance, MaxJudgements, MaxAdditionalFields>
447{451{
448 fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {452 fn decode<I: parity_scale_codec::Input>(
453 input: &mut I,
454 ) -> sp_std::result::Result<Self, parity_scale_codec::Error> {
449 let (judgements, deposit, info) = Decode::decode(&mut AppendZerosInput::new(input))?;455 let (judgements, deposit, info) = Decode::decode(&mut AppendZerosInput::new(input))?;
450 Ok(Self {456 Ok(Self {
451 judgements,457 judgements,
modifiedpallets/inflation/src/lib.rsdiffbeforeafterboth
73 type TreasuryAccountId: Get<Self::AccountId>;73 type TreasuryAccountId: Get<Self::AccountId>;
7474
75 // The block number provider75 // The block number provider
76 type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;76 type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
7777
78 /// Number of blocks that pass between treasury balance updates due to inflation78 /// Number of blocks that pass between treasury balance updates due to inflation
79 #[pallet::constant]79 #[pallet::constant]
80 type InflationBlockInterval: Get<Self::BlockNumber>;80 type InflationBlockInterval: Get<BlockNumberFor<Self>>;
81 }81 }
8282
83 #[pallet::pallet]83 #[pallet::pallet]
95 /// Next target (relay) block when inflation will be applied95 /// Next target (relay) block when inflation will be applied
96 #[pallet::storage]96 #[pallet::storage]
97 pub type NextInflationBlock<T: Config> =97 pub type NextInflationBlock<T: Config> =
98 StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;98 StorageValue<Value = BlockNumberFor<T>, QueryKind = ValueQuery>;
9999
100 /// Next target (relay) block when inflation is recalculated100 /// Next target (relay) block when inflation is recalculated
101 #[pallet::storage]101 #[pallet::storage]
102 pub type NextRecalculationBlock<T: Config> =102 pub type NextRecalculationBlock<T: Config> =
103 StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;103 StorageValue<Value = BlockNumberFor<T>, QueryKind = ValueQuery>;
104104
105 /// Relay block when inflation has started105 /// Relay block when inflation has started
106 #[pallet::storage]106 #[pallet::storage]
107 pub type StartBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;107 pub type StartBlock<T: Config> =
108 StorageValue<Value = BlockNumberFor<T>, QueryKind = ValueQuery>;
108109
109 #[pallet::hooks]110 #[pallet::hooks]
110 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {111 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
111 fn on_initialize(_: T::BlockNumber) -> Weight112 fn on_initialize(_: BlockNumberFor<T>) -> Weight
112 where113 where
113 <T as frame_system::Config>::BlockNumber: From<u32>,114 BlockNumberFor<T>: From<u32>,
114 {115 {
115 let mut consumed_weight = Weight::zero();116 let mut consumed_weight = Weight::zero();
116 let mut add_weight = |reads, writes, weight| {117 let mut add_weight = |reads, writes, weight| {
120121
121 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);122 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
122 let current_relay_block = T::BlockNumberProvider::current_block_number();123 let current_relay_block = T::BlockNumberProvider::current_block_number();
123 let next_inflation: T::BlockNumber = <NextInflationBlock<T>>::get();124 let next_inflation: BlockNumberFor<T> = <NextInflationBlock<T>>::get();
124 add_weight(1, 0, Weight::from_parts(5_000_000, 0));125 add_weight(1, 0, Weight::from_parts(5_000_000, 0));
125126
126 // Apply inflation every InflationBlockInterval blocks127 // Apply inflation every InflationBlockInterval blocks
129 // Recalculate inflation on the first block of the year (or if it is not initialized yet)130 // Recalculate inflation on the first block of the year (or if it is not initialized yet)
130 // Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation"131 // Do the "current_relay_block >= next_recalculation" check in the "current_relay_block >= next_inflation"
131 // block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.132 // block because it saves InflationBlockInterval DB reads for NextRecalculationBlock.
132 let next_recalculation: T::BlockNumber = <NextRecalculationBlock<T>>::get();133 let next_recalculation: BlockNumberFor<T> = <NextRecalculationBlock<T>>::get();
133 add_weight(1, 0, Weight::zero());134 add_weight(1, 0, Weight::zero());
134 if current_relay_block >= next_recalculation {135 if current_relay_block >= next_recalculation {
135 Self::recalculate_inflation(next_recalculation);136 Self::recalculate_inflation(next_recalculation);
169 #[pallet::weight(Weight::from_parts(0, 0))]170 #[pallet::weight(Weight::from_parts(0, 0))]
170 pub fn start_inflation(171 pub fn start_inflation(
171 origin: OriginFor<T>,172 origin: OriginFor<T>,
172 inflation_start_relay_block: T::BlockNumber,173 inflation_start_relay_block: BlockNumberFor<T>,
173 ) -> DispatchResult174 ) -> DispatchResult
174 where175 where
175 <T as frame_system::Config>::BlockNumber: From<u32>,176 BlockNumberFor<T>: From<u32>,
176 {177 {
177 ensure_root(origin)?;178 ensure_root(origin)?;
178179
200}201}
201202
202impl<T: Config> Pallet<T> {203impl<T: Config> Pallet<T> {
203 pub fn recalculate_inflation(recalculation_block: T::BlockNumber) {204 pub fn recalculate_inflation(recalculation_block: BlockNumberFor<T>) {
204 let current_year: u32 = ((recalculation_block - <StartBlock<T>>::get())205 let current_year: u32 = ((recalculation_block - <StartBlock<T>>::get())
205 / T::BlockNumber::from(YEAR))206 / BlockNumberFor::<T>::from(YEAR))
206 .try_into()207 .try_into()
207 .unwrap_or(0);208 .unwrap_or(0);
208 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);209 let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
modifiedpallets/inflation/src/tests.rsdiffbeforeafterboth
57 type MaxLocks = MaxLocks;57 type MaxLocks = MaxLocks;
58 type MaxReserves = ();58 type MaxReserves = ();
59 type ReserveIdentifier = ();59 type ReserveIdentifier = ();
60 type HoldIdentifier = ();
61 type FreezeIdentifier = ();60 type FreezeIdentifier = ();
62 type MaxHolds = ();61 type MaxHolds = ();
63 type MaxFreezes = ();62 type MaxFreezes = ();
64}63}
6564
66frame_support::construct_runtime!(65frame_support::construct_runtime!(
67 pub enum Test where66 pub enum Test {
68 Block = Block,
69 NodeBlock = Block,
70 UncheckedExtrinsic = UncheckedExtrinsic,
71 {
72 Balances: pallet_balances::{Pallet, Call, Storage},67 Balances: pallet_balances,
73 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},68 System: frame_system,
74 Inflation: pallet_inflation::{Pallet, Call, Storage},69 Inflation: pallet_inflation,
75 }70 }
76);71);
7772
89 type DbWeight = ();84 type DbWeight = ();
90 type RuntimeOrigin = RuntimeOrigin;85 type RuntimeOrigin = RuntimeOrigin;
91 type RuntimeCall = RuntimeCall;86 type RuntimeCall = RuntimeCall;
92 type Index = u64;87 type Nonce = u64;
93 type BlockNumber = u64;
94 type Hash = H256;88 type Hash = H256;
95 type Hashing = BlakeTwo256;89 type Hashing = BlakeTwo256;
96 type AccountId = u64;90 type AccountId = u64;
97 type Lookup = IdentityLookup<Self::AccountId>;91 type Lookup = IdentityLookup<Self::AccountId>;
98 type Header = Header;
99 type RuntimeEvent = ();92 type RuntimeEvent = ();
100 type BlockHashCount = BlockHashCount;93 type BlockHashCount = BlockHashCount;
101 type Version = ();94 type Version = ();
112parameter_types! {105parameter_types! {
113 pub TreasuryAccountId: u64 = 1234;106 pub TreasuryAccountId: u64 = 1234;
114 pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied107 pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied
115 pub static MockBlockNumberProvider: u64 = 0;108 pub static MockBlockNumberProvider: u32 = 0;
116}109}
117110
118impl BlockNumberProvider for MockBlockNumberProvider {111impl BlockNumberProvider for MockBlockNumberProvider {
119 type BlockNumber = u64;112 type BlockNumber = u32;
120113
121 fn current_block_number() -> Self::BlockNumber {114 fn current_block_number() -> Self::BlockNumber {
122 Self::get()115 Self::get()
131}124}
132125
133pub fn new_test_ext() -> sp_io::TestExternalities {126pub fn new_test_ext() -> sp_io::TestExternalities {
134 frame_system::GenesisConfig::default()127 <frame_system::GenesisConfig<Test>>::default()
135 .build_storage::<Test>()128 .build_storage()
136 .unwrap()129 .unwrap()
137 .into()130 .into()
138}131}
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
9090
91#![cfg_attr(not(feature = "std"), no_std)]91#![cfg_attr(not(feature = "std"), no_std)]
92
93use core::ops::Deref;
9294
93use erc::ERC721Events;95use erc::ERC721Events;
94use evm_coder::ToLog;96use evm_coder::ToLog;
95use frame_support::{97use frame_support::{
96 BoundedVec, ensure, fail, transactional,98 dispatch::{Pays, PostDispatchInfo},
97 storage::with_transaction,99 ensure, fail,
98 pallet_prelude::DispatchResultWithPostInfo,100 pallet_prelude::*,
99 pallet_prelude::Weight,101 storage::with_transaction,
100 dispatch::{PostDispatchInfo, Pays},102 transactional, BoundedVec,
101};103};
102use up_data_structs::{104pub use pallet::*;
103 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
104 mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,
105 PropertyKeyPermission, PropertyScope, TokenChild, AuxPropertyValue, PropertiesPermissionMap,
106 TokenProperties as TokenPropertiesT,
107};
108use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
109use pallet_common::{105use pallet_common::{
110 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,106 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
111 eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,107 eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,
112 weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,108 weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,
113};109};
114use pallet_structure::{Pallet as PalletStructure, Error as StructureError};110use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
115use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};111use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
112use pallet_structure::{Error as StructureError, Pallet as PalletStructure};
113use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
114use scale_info::TypeInfo;
116use sp_core::{Get, H160};115use sp_core::{Get, H160};
117use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};116use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
118use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};117use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};
119use core::ops::Deref;118use up_data_structs::{
119 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
120use codec::{Encode, Decode, MaxEncodedLen};120 mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,
121use scale_info::TypeInfo;121 PropertyKeyPermission, PropertyScope, TokenChild, AuxPropertyValue, PropertiesPermissionMap,
122122 TokenProperties as TokenPropertiesT,
123pub use pallet::*;123};
124use weights::WeightInfo;124use weights::WeightInfo;
125#[cfg(feature = "runtime-benchmarks")]125#[cfg(feature = "runtime-benchmarks")]
126pub mod benchmarking;126pub mod benchmarking;
147147
148#[frame_support::pallet]148#[frame_support::pallet]
149pub mod pallet {149pub mod pallet {
150 use super::*;
151 use frame_support::{150 use frame_support::{
152 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,151 pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128Concat, Twox64Concat,
153 };152 };
154 use up_data_structs::{CollectionId, TokenId};153 use up_data_structs::{CollectionId, TokenId};
154
155 use super::weights::WeightInfo;155 use super::{weights::WeightInfo, *};
156156
157 #[pallet::error]157 #[pallet::error]
158 pub enum Error<T> {158 pub enum Error<T> {
285 #[pallet::genesis_config]285 #[pallet::genesis_config]
286 pub struct GenesisConfig<T>(PhantomData<T>);286 pub struct GenesisConfig<T>(PhantomData<T>);
287287
288 #[cfg(feature = "std")]
289 impl<T: Config> Default for GenesisConfig<T> {288 impl<T: Config> Default for GenesisConfig<T> {
290 fn default() -> Self {289 fn default() -> Self {
291 Self(Default::default())290 Self(Default::default())
292 }291 }
293 }292 }
294293
295 #[pallet::genesis_build]294 #[pallet::genesis_build]
296 impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {295 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
297 fn build(&self) {296 fn build(&self) {
298 StorageVersion::new(1).put::<Pallet<T>>();297 StorageVersion::new(1).put::<Pallet<T>>();
299 }298 }
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
174 pub type CreateItemBasket<T: Config> = StorageMap<174 pub type CreateItemBasket<T: Config> = StorageMap<
175 Hasher = Blake2_128Concat,175 Hasher = Blake2_128Concat,
176 Key = (CollectionId, T::AccountId),176 Key = (CollectionId, T::AccountId),
177 Value = T::BlockNumber,177 Value = BlockNumberFor<T>,
178 QueryKind = OptionQuery,178 QueryKind = OptionQuery,
179 >;179 >;
180 /// Collection id (controlled?2), token id (controlled?2)180 /// Collection id (controlled?2), token id (controlled?2)
185 Key1 = CollectionId,185 Key1 = CollectionId,
186 Hasher2 = Blake2_128Concat,186 Hasher2 = Blake2_128Concat,
187 Key2 = TokenId,187 Key2 = TokenId,
188 Value = T::BlockNumber,188 Value = BlockNumberFor<T>,
189 QueryKind = OptionQuery,189 QueryKind = OptionQuery,
190 >;190 >;
191 /// Collection id (controlled?2), owning user (real)191 /// Collection id (controlled?2), owning user (real)
196 Key1 = CollectionId,196 Key1 = CollectionId,
197 Hasher2 = Twox64Concat,197 Hasher2 = Twox64Concat,
198 Key2 = T::AccountId,198 Key2 = T::AccountId,
199 Value = T::BlockNumber,199 Value = BlockNumberFor<T>,
200 QueryKind = OptionQuery,200 QueryKind = OptionQuery,
201 >;201 >;
202 /// Collection id (controlled?2), token id (controlled?2)202 /// Collection id (controlled?2), token id (controlled?2)
208 Key<Blake2_128Concat, TokenId>,208 Key<Blake2_128Concat, TokenId>,
209 Key<Twox64Concat, T::AccountId>,209 Key<Twox64Concat, T::AccountId>,
210 ),210 ),
211 Value = T::BlockNumber,211 Value = BlockNumberFor<T>,
212 QueryKind = OptionQuery,212 QueryKind = OptionQuery,
213 >;213 >;
214 //#endregion214 //#endregion
221 Key1 = CollectionId,221 Key1 = CollectionId,
222 Hasher2 = Blake2_128Concat,222 Hasher2 = Blake2_128Concat,
223 Key2 = TokenId,223 Key2 = TokenId,
224 Value = T::BlockNumber,224 Value = BlockNumberFor<T>,
225 QueryKind = OptionQuery,225 QueryKind = OptionQuery,
226 >;226 >;
227227
233 Key1 = CollectionId,233 Key1 = CollectionId,
234 Hasher2 = Blake2_128Concat,234 Hasher2 = Blake2_128Concat,
235 Key2 = TokenId,235 Key2 = TokenId,
236 Value = T::BlockNumber,236 Value = BlockNumberFor<T>,
237 QueryKind = OptionQuery,237 QueryKind = OptionQuery,
238 >;238 >;
239 /// Last sponsoring of fungible tokens approval in a collection239 /// Last sponsoring of fungible tokens approval in a collection
244 Key1 = CollectionId,244 Key1 = CollectionId,
245 Hasher2 = Twox64Concat,245 Hasher2 = Twox64Concat,
246 Key2 = T::AccountId,246 Key2 = T::AccountId,
247 Value = T::BlockNumber,247 Value = BlockNumberFor<T>,
248 QueryKind = OptionQuery,248 QueryKind = OptionQuery,
249 >;249 >;
250 /// Last sponsoring of RFT approval in a collection250 /// Last sponsoring of RFT approval in a collection
256 Key<Blake2_128Concat, TokenId>,256 Key<Blake2_128Concat, TokenId>,
257 Key<Twox64Concat, T::AccountId>,257 Key<Twox64Concat, T::AccountId>,
258 ),258 ),
259 Value = T::BlockNumber,259 Value = BlockNumberFor<T>,
260 QueryKind = OptionQuery,260 QueryKind = OptionQuery,
261 >;261 >;
262262
modifiedprimitives/common/src/constants.rsdiffbeforeafterboth
28pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;28pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
2929
30// These time units are defined in number of blocks.30// These time units are defined in number of blocks.
31pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);31pub const MINUTES: u32 = 60_000 / (MILLISECS_PER_BLOCK as u32);
32pub const HOURS: BlockNumber = MINUTES * 60;32pub const HOURS: u32 = MINUTES * 60;
33pub const DAYS: BlockNumber = HOURS * 24;33pub const DAYS: u32 = HOURS * 24;
3434
35// These time units are defined in number of relay blocks.35// These time units are defined in number of relay blocks.
36pub const RELAY_MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_RELAY_BLOCK as BlockNumber);36pub const RELAY_MINUTES: u32 = 60_000 / (MILLISECS_PER_RELAY_BLOCK as u32);
37pub const RELAY_HOURS: BlockNumber = RELAY_MINUTES * 60;37pub const RELAY_HOURS: u32 = RELAY_MINUTES * 60;
38pub const RELAY_DAYS: BlockNumber = RELAY_HOURS * 24;38pub const RELAY_DAYS: u32 = RELAY_HOURS * 24;
3939
40pub const MICROUNIQUE: Balance = 1_000_000_000_000;40pub const MICROUNIQUE: Balance = 1_000_000_000_000;
41pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;41pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;
modifiedprimitives/common/src/types.rsdiffbeforeafterboth
37 Unknown(sp_std::vec::Vec<u8>),37 Unknown(sp_std::vec::Vec<u8>),
38 }38 }
3939
40 /// Opaque block header type.
41 pub type Header = generic::Header<BlockNumber, BlakeTwo256>;40 pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
4241
43 /// Opaque block type.
44 pub type Block = generic::Block<Header, UncheckedExtrinsic>;42 pub type Block = generic::Block<Header, UncheckedExtrinsic>;
4543
46 pub trait RuntimeInstance {44 pub trait RuntimeInstance {
71pub type Balance = u128;69pub type Balance = u128;
7270
73/// Index of a transaction in the chain.71/// Index of a transaction in the chain.
74pub type Index = u32;72pub type Nonce = u32;
7573
76/// A hash of some data used by the chain.74/// A hash of some data used by the chain.
77pub type Hash = sp_core::H256;75pub type Hash = sp_core::H256;
modifiedprimitives/data-structs/src/bondrewd_codec.rsdiffbeforeafterboth
5macro_rules! bondrewd_codec {5macro_rules! bondrewd_codec {
6 ($T:ty) => {6 ($T:ty) => {
7 impl Encode for $T {7 impl Encode for $T {
8 fn encode_to<O: codec::Output + ?Sized>(&self, dest: &mut O) {8 fn encode_to<O: parity_scale_codec::Output + ?Sized>(&self, dest: &mut O) {
9 dest.write(&self.into_bytes())9 dest.write(&self.into_bytes())
10 }10 }
11 }11 }
12 impl codec::Decode for $T {12 impl parity_scale_codec::Decode for $T {
13 fn decode<I: codec::Input + ?Sized>(from: &mut I) -> Result<Self, codec::Error> {13 fn decode<I: parity_scale_codec::Input + ?Sized>(
14 from: &mut I,
15 ) -> Result<Self, parity_scale_codec::Error> {
14 let mut bytes = [0; Self::BYTE_SIZE];16 let mut bytes = [0; Self::BYTE_SIZE];
15 from.read(&mut bytes)?;17 from.read(&mut bytes)?;
16 Ok(Self::from_bytes(bytes))18 Ok(Self::from_bytes(bytes))
modifiedprimitives/data-structs/src/bounded.rsdiffbeforeafterboth
26};26};
2727
28/// [`serde`] implementations for [`BoundedVec`].28/// [`serde`] implementations for [`BoundedVec`].
29#[cfg(feature = "serde1")]
30pub mod vec_serde {29pub mod vec_serde {
31 use core::convert::TryFrom;30 use core::convert::TryFrom;
31
32 use frame_support::{BoundedVec, traits::Get};32 use frame_support::{traits::Get, BoundedVec};
33 use serde::{33 use serde::{
34 ser::{self, Serialize},34 de::{self, Deserialize, Error},
35 de::{self, Deserialize, Error},35 ser::{self, Serialize},
36 };36 };
37 use sp_std::vec::Vec;37 use sp_std::vec::Vec;
3838
66 (v as &Vec<V>).fmt(f)66 (v as &Vec<V>).fmt(f)
67}67}
6868
69#[cfg(feature = "serde1")]
70#[allow(dead_code)]69#[allow(dead_code)]
71/// [`serde`] implementations for [`BoundedBTreeMap`].70/// [`serde`] implementations for [`BoundedBTreeMap`].
72pub mod map_serde {71pub mod map_serde {
73 use core::convert::TryFrom;72 use core::convert::TryFrom;
74 use sp_std::collections::btree_map::BTreeMap;73
75 use frame_support::{traits::Get, storage::bounded_btree_map::BoundedBTreeMap};74 use frame_support::{storage::bounded_btree_map::BoundedBTreeMap, traits::Get};
76 use serde::{75 use serde::{
77 ser::{self, Serialize},76 de::{self, Deserialize, Error},
78 de::{self, Deserialize, Error},77 ser::{self, Serialize},
79 };78 };
79 use sp_std::collections::btree_map::BTreeMap;
80 pub fn serialize<D, K, V, S>(80 pub fn serialize<D, K, V, S>(
81 value: &BoundedBTreeMap<K, V, S>,81 value: &BoundedBTreeMap<K, V, S>,
82 serializer: D,82 serializer: D,
117 (v as &BTreeMap<K, V>).fmt(f)117 (v as &BTreeMap<K, V>).fmt(f)
118}118}
119119
120#[cfg(feature = "serde1")]
121#[allow(dead_code)]120#[allow(dead_code)]
122/// [`serde`] implementations for [`BoundedBTreeSet`].121/// [`serde`] implementations for [`BoundedBTreeSet`].
123pub mod set_serde {122pub mod set_serde {
124 use core::convert::TryFrom;123 use core::convert::TryFrom;
125 use sp_std::collections::btree_set::BTreeSet;124
126 use frame_support::{traits::Get, storage::bounded_btree_set::BoundedBTreeSet};125 use frame_support::{storage::bounded_btree_set::BoundedBTreeSet, traits::Get};
127 use serde::{126 use serde::{
128 ser::{self, Serialize},127 de::{self, Deserialize, Error},
129 de::{self, Deserialize, Error},128 ser::{self, Serialize},
130 };129 };
130 use sp_std::collections::btree_set::BTreeSet;
131 pub fn serialize<D, K, S>(131 pub fn serialize<D, K, S>(
132 value: &BoundedBTreeSet<K, S>,132 value: &BoundedBTreeSet<K, S>,
133 serializer: D,133 serializer: D,
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
153 Default,153 Default,
154 TypeInfo,154 TypeInfo,
155 MaxEncodedLen,155 MaxEncodedLen,
156 Serialize,
157 Deserialize,
156)]158)]
157#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
158pub struct CollectionId(pub u32);159pub struct CollectionId(pub u32);
159impl EncodeLike<u32> for CollectionId {}160impl EncodeLike<u32> for CollectionId {}
160impl EncodeLike<CollectionId> for u32 {}161impl EncodeLike<CollectionId> for u32 {}
187 Default,188 Default,
188 TypeInfo,189 TypeInfo,
189 MaxEncodedLen,190 MaxEncodedLen,
191 Serialize,
192 Deserialize,
190)]193)]
191#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
192pub struct TokenId(pub u32);194pub struct TokenId(pub u32);
193impl EncodeLike<u32> for TokenId {}195impl EncodeLike<u32> for TokenId {}
194impl EncodeLike<TokenId> for u32 {}196impl EncodeLike<TokenId> for u32 {}
221223
222/// Token data.224/// Token data.
223#[struct_versioning::versioned(version = 2, upper)]225#[struct_versioning::versioned(version = 2, upper)]
224#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]226#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]
225#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
226pub struct TokenData<CrossAccountId> {227pub struct TokenData<CrossAccountId> {
227 /// Properties of token.228 /// Properties of token.
228 pub properties: Vec<Property>,229 pub properties: Vec<Property>,
252/// Each collection can contain only one type of tokens at a time.253/// Each collection can contain only one type of tokens at a time.
253/// This type helps to understand which tokens the collection contains.254/// This type helps to understand which tokens the collection contains.
254#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]255#[derive(
255#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]256 Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
257)]
256pub enum CollectionMode {258pub enum CollectionMode {
257 /// Non fungible tokens.259 /// Non fungible tokens.
280282
281/// Access mode for some token operations.283/// Access mode for some token operations.
282#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]284#[derive(
283#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]285 Encode,
286 Decode,
287 Eq,
288 Debug,
289 Clone,
290 Copy,
291 PartialEq,
292 TypeInfo,
293 MaxEncodedLen,
294 Serialize,
295 Deserialize,
296)]
284pub enum AccessMode {297pub enum AccessMode {
285 /// Access grant for owner and admins. Used as default.298 /// Access grant for owner and admins. Used as default.
295308
296// TODO: remove in future.309// TODO: remove in future.
297#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]310#[derive(
298#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]311 Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
312)]
299pub enum SchemaVersion {313pub enum SchemaVersion {
300 ImageURL,314 ImageURL,
307}321}
308322
309// TODO: unused type323// TODO: unused type
310#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]324#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]
311#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
312pub struct Ownership<AccountId> {325pub struct Ownership<AccountId> {
313 pub owner: AccountId,326 pub owner: AccountId,
314 pub fraction: u128,327 pub fraction: u128,
315}328}
316329
317/// The state of collection sponsorship.330/// The state of collection sponsorship.
318#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]331#[derive(
319#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]332 Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
333)]
320pub enum SponsorshipState<AccountId> {334pub enum SponsorshipState<AccountId> {
321 /// The fees are applied to the transaction sender.335 /// The fees are applied to the transaction sender.
444 pub meta_update_permission: MetaUpdatePermission,458 pub meta_update_permission: MetaUpdatePermission,
445}459}
446460
447#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo)]461#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]
448#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
449pub struct RpcCollectionFlags {462pub struct RpcCollectionFlags {
450 /// Is collection is foreign.463 /// Is collection is foreign.
451 pub foreign: bool,464 pub foreign: bool,
455468
456/// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).469/// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).
457#[struct_versioning::versioned(version = 2, upper)]470#[struct_versioning::versioned(version = 2, upper)]
458#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo)]471#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]
459#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
460pub struct RpcCollection<AccountId> {472pub struct RpcCollection<AccountId> {
461 /// Collection owner account.473 /// Collection owner account.
462 pub owner: AccountId,474 pub owner: AccountId,
538550
539pub struct RawEncoded(Vec<u8>);551pub struct RawEncoded(Vec<u8>);
540552
541impl codec::Decode for RawEncoded {553impl parity_scale_codec::Decode for RawEncoded {
542 fn decode<I: codec::Input>(input: &mut I) -> Result<Self, codec::Error> {554 fn decode<I: parity_scale_codec::Input>(
555 input: &mut I,
556 ) -> Result<Self, parity_scale_codec::Error> {
543 let mut out = Vec::new();557 let mut out = Vec::new();
544 while let Ok(v) = input.read_byte() {558 while let Ok(v) = input.read_byte() {
545 out.push(v);559 out.push(v);
613/// Update with `pallet_common::Pallet::clamp_limits`.627/// Update with `pallet_common::Pallet::clamp_limits`.
614// IMPORTANT: When adding/removing fields from this struct - don't forget to also628// IMPORTANT: When adding/removing fields from this struct - don't forget to also
615#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]629#[derive(
616#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]630 Encode,
631 Decode,
632 Debug,
633 Default,
634 Clone,
635 PartialEq,
636 TypeInfo,
637 MaxEncodedLen,
638 Serialize,
639 Deserialize,
640)]
617// When adding/removing fields from this struct - don't forget to also update with `pallet_common::Pallet::clamp_limits`.641// 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`.642// TODO: move `pallet_common::Pallet::clamp_limits` into `impl CollectionLimits`.
770///794///
771/// Update with `pallet_common::Pallet::clamp_permissions`.795/// Update with `pallet_common::Pallet::clamp_permissions`.
772#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]796#[derive(
773#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]797 Encode,
798 Decode,
799 Debug,
800 Default,
801 Clone,
802 PartialEq,
803 TypeInfo,
804 MaxEncodedLen,
805 Serialize,
806 Deserialize,
807)]
774// When adding/removing fields from this struct - don't forget to also update `pallet_common::Pallet::clamp_permissions`.808// 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`.809// TODO: move `pallet_common::Pallet::clamp_permissions` into `impl CollectionPermissions`.
822856
823/// Wraper for collections set allowing nest.857/// Wraper for collections set allowing nest.
824#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]858#[derive(
825#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]859 Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative, Serialize, Deserialize,
860)]
826#[derivative(Debug)]861#[derivative(Debug)]
827pub struct OwnerRestrictedSet(862pub struct OwnerRestrictedSet(
828 #[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]863 #[serde(with = "bounded::set_serde")]
829 #[derivative(Debug(format_with = "bounded::set_debug"))]864 #[derivative(Debug(format_with = "bounded::set_debug"))]
830 pub OwnerRestrictedSetInner,865 pub OwnerRestrictedSetInner,
831);866);
863898
864/// Part of collection permissions, if set, defines who is able to nest tokens into other tokens.899/// 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)]900#[derive(
866#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]901 Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative, Serialize, Deserialize,
902)]
867#[derivative(Debug)]903#[derivative(Debug)]
868pub struct NestingPermissions {904pub struct NestingPermissions {
882///918///
883/// Used for [`collection limits`](CollectionLimits).919/// Used for [`collection limits`](CollectionLimits).
884#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]920#[derive(
885#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]921 Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
922)]
886pub enum SponsoringRateLimit {923pub enum SponsoringRateLimit {
887 /// Sponsoring is disabled, and the collection sponsor will not pay for transactions924 /// Sponsoring is disabled, and the collection sponsor will not pay for transactions
892929
893/// Data used to describe an NFT at creation.930/// Data used to describe an NFT at creation.
894#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]931#[derive(
895#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]932 Encode,
933 Decode,
934 MaxEncodedLen,
935 Default,
936 PartialEq,
937 Clone,
938 Derivative,
939 TypeInfo,
940 Serialize,
941 Deserialize,
942)]
896#[derivative(Debug)]943#[derivative(Debug)]
897pub struct CreateNftData {944pub struct CreateNftData {
898 /// Key-value pairs used to describe the token as metadata945 /// Key-value pairs used to describe the token as metadata
899 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]946 #[serde(with = "bounded::vec_serde")]
900 #[derivative(Debug(format_with = "bounded::vec_debug"))]947 #[derivative(Debug(format_with = "bounded::vec_debug"))]
901 /// Properties that wil be assignet to created item.948 /// Properties that wil be assignet to created item.
902 pub properties: CollectionPropertiesVec,949 pub properties: CollectionPropertiesVec,
903}950}
904951
905/// Data used to describe a Fungible token at creation.952/// Data used to describe a Fungible token at creation.
906#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]953#[derive(
907#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]954 Encode,
955 Decode,
956 MaxEncodedLen,
957 Default,
958 Debug,
959 Clone,
960 PartialEq,
961 TypeInfo,
962 Serialize,
963 Deserialize,
964)]
908pub struct CreateFungibleData {965pub struct CreateFungibleData {
909 /// Number of fungible coins minted966 /// Number of fungible coins minted
910 pub value: u128,967 pub value: u128,
911}968}
912969
913/// Data used to describe a Refungible token at creation.970/// Data used to describe a Refungible token at creation.
914#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]971#[derive(
915#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]972 Encode,
973 Decode,
974 MaxEncodedLen,
975 Default,
976 PartialEq,
977 Clone,
978 Derivative,
979 TypeInfo,
980 Serialize,
981 Deserialize,
982)]
916#[derivative(Debug)]983#[derivative(Debug)]
917pub struct CreateReFungibleData {984pub struct CreateReFungibleData {
918 /// Number of pieces the RFT is split into985 /// Number of pieces the RFT is split into
919 pub pieces: u128,986 pub pieces: u128,
920987
921 /// Key-value pairs used to describe the token as metadata988 /// Key-value pairs used to describe the token as metadata
922 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]989 #[serde(with = "bounded::vec_serde")]
923 #[derivative(Debug(format_with = "bounded::vec_debug"))]990 #[derivative(Debug(format_with = "bounded::vec_debug"))]
924 pub properties: CollectionPropertiesVec,991 pub properties: CollectionPropertiesVec,
925}992}
926993
927// TODO: remove this.994// TODO: remove this.
928#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]995#[derive(
929#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]996 Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen, Serialize, Deserialize,
997)]
930pub enum MetaUpdatePermission {998pub enum MetaUpdatePermission {
931 ItemOwner,999 ItemOwner,
936/// Enum holding data used for creation of all three item types.1004/// Enum holding data used for creation of all three item types.
937/// Unified data for create item.1005/// Unified data for create item.
938#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]1006#[derive(
939#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1007 Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo, Serialize, Deserialize,
1008)]
940pub enum CreateItemData {1009pub enum CreateItemData {
941 /// Data for create NFT.1010 /// Data for create NFT.
10261095
1027/// Token's address, dictated by its collection and token IDs.1096/// Token's address, dictated by its collection and token IDs.
1028#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]1097#[derive(
1029#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1098 Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo, Serialize, Deserialize,
1099)]
1030// todo possibly rename to be used generally as an address pair1100// todo possibly rename to be used generally as an address pair
1031pub struct TokenChild {1101pub struct TokenChild {
10381108
1039/// Collection statistics.1109/// Collection statistics.
1040#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]1110#[derive(
1041#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1111 Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo, Serialize, Deserialize,
1112)]
1042pub struct CollectionStats {1113pub struct CollectionStats {
1043 /// Number of created items.1114 /// Number of created items.
10601131
1061 fn type_info() -> scale_info::Type {1132 fn type_info() -> scale_info::Type {
1062 use scale_info::{1133 use scale_info::{
1063 Type, Path,
1064 build::{FieldsBuilder, UnnamedFields},1134 build::{FieldsBuilder, UnnamedFields},
1065 form::MetaForm,1135 form::MetaForm,
1066 type_params,1136 type_params, Path, Type,
1067 };1137 };
1068 Type::builder()1138 Type::builder()
1069 .path(Path::new("up_data_structs", "PhantomType"))1139 .path(Path::new("up_data_structs", "PhantomType"))
10931163
1094/// Property permission.1164/// Property permission.
1095#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone, Default)]1165#[derive(
1096#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1166 Encode,
1167 Decode,
1168 TypeInfo,
1169 Debug,
1170 MaxEncodedLen,
1171 PartialEq,
1172 Clone,
1173 Default,
1174 Serialize,
1175 Deserialize,
1176)]
1097pub struct PropertyPermission {1177pub struct PropertyPermission {
1098 /// Permission to change the property and property permission.1178 /// Permission to change the property and property permission.
11201200
1121/// Property is simpl key-value record.1201/// Property is simpl key-value record.
1122#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]1202#[derive(
1123#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1203 Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen, Serialize, Deserialize,
1204)]
1124pub struct Property {1205pub struct Property {
1125 /// Property key.1206 /// Property key.
1126 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1207 #[serde(with = "bounded::vec_serde")]
1127 pub key: PropertyKey,1208 pub key: PropertyKey,
11281209
1129 /// Property value.1210 /// Property value.
1130 #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1211 #[serde(with = "bounded::vec_serde")]
1131 pub value: PropertyValue,1212 pub value: PropertyValue,
1132}1213}
11331214
11391220
1140/// Record for proprty key permission.1221/// Record for proprty key permission.
1141#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]1222#[derive(
1142#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1223 Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone, Serialize, Deserialize,
1224)]
1143pub struct PropertyKeyPermission {1225pub struct PropertyKeyPermission {
1144 /// Key.1226 /// Key.
1362 scoped_slice_size(PropertyScope::None, data)1444 scoped_slice_size(PropertyScope::None, data)
1363}1445}
1364fn scoped_slice_size(scope: PropertyScope, data: &[u8]) -> u32 {1446fn scoped_slice_size(scope: PropertyScope, data: &[u8]) -> u32 {
1365 use codec::Compact;1447 use parity_scale_codec::Compact;
1366 let prefix = scope.prefix();1448 let prefix = scope.prefix();
1367 <Compact<u32>>::encoded_size(&Compact(data.len() as u32 + prefix.len() as u32)) as u321449 <Compact<u32>>::encoded_size(&Compact(data.len() as u32 + prefix.len() as u32)) as u32
1368 + data.len() as u321450 + data.len() as u32
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
82 collection: CollectionId,82 collection: CollectionId,
83 token_id: TokenId,83 token_id: TokenId,
84 keys: Option<Vec<Vec<u8>>>84 keys: Option<Vec<Vec<u8>>>
85 ) -> Result<TokenDataVersion1<CrossAccountId>>;85 ) -> Result<up_data_structs::TokenDataVersion1<CrossAccountId>>;
8686
87 /// Total number of tokens in collection.87 /// Total number of tokens in collection.
88 fn total_supply(collection: CollectionId) -> Result<u32>;88 fn total_supply(collection: CollectionId) -> Result<u32>;
117 fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>>;117 fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>>;
118118
119 #[changed_in(3)]119 #[changed_in(3)]
120 fn collection_by_id(collection: CollectionId) -> Result<Option<RawEncoded>>;120 fn collection_by_id(collection: CollectionId) -> Result<Option<up_data_structs::RawEncoded>>;
121121
122 /// Get collection stats.122 /// Get collection stats.
123 fn collection_stats() -> Result<CollectionStats>;123 fn collection_stats() -> Result<CollectionStats>;
modifiedruntime/common/config/pallets/collator_selection.rsdiffbeforeafterboth
107107
108impl pallet_collator_selection::Config for Runtime {108impl pallet_collator_selection::Config for Runtime {
109 type RuntimeEvent = RuntimeEvent;109 type RuntimeEvent = RuntimeEvent;
110 type RuntimeHoldReason = RuntimeHoldReason;
110 type Currency = Balances;111 type Currency = Balances;
111 // We allow root only to execute privileged collator selection operations.112 // We allow root only to execute privileged collator selection operations.
112113
128 type ValidatorIdOf = pallet_collator_selection::IdentityCollator;129 type ValidatorIdOf = pallet_collator_selection::IdentityCollator;
129 type ValidatorRegistration = Session;130 type ValidatorRegistration = Session;
130 type WeightInfo = pallet_collator_selection::weights::SubstrateWeight<Runtime>;131 type WeightInfo = pallet_collator_selection::weights::SubstrateWeight<Runtime>;
131 type LicenceBondIdentifier = LicenceBondIdentifier;
132 type DesiredCollators = DesiredCollators;132 type DesiredCollators = DesiredCollators;
133 type LicenseBond = LicenseBond;133 type LicenseBond = LicenseBond;
134 type KickThreshold = KickThreshold;134 type KickThreshold = KickThreshold;
modifiedruntime/common/config/substrate.rsdiffbeforeafterboth
76 type BaseCallFilter = Everything;76 type BaseCallFilter = Everything;
77 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).77 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
78 type BlockHashCount = BlockHashCount;78 type BlockHashCount = BlockHashCount;
79 /// The maximum length of a block (in bytes).79 /// The block type.
80 type BlockLength = RuntimeBlockLength;80 type Block = Block;
81 /// The index type for blocks.81 /// The maximum length of a block (in bytes).
82 type BlockNumber = BlockNumber;82 type BlockLength = RuntimeBlockLength;
83 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.83 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.
84 type BlockWeights = RuntimeBlockWeights;84 type BlockWeights = RuntimeBlockWeights;
85 /// The aggregated dispatch type that is available for extrinsics.85 /// The aggregated dispatch type that is available for extrinsics.
92 type Hash = Hash;92 type Hash = Hash;
93 /// The hashing algorithm used.93 /// The hashing algorithm used.
94 type Hashing = BlakeTwo256;94 type Hashing = BlakeTwo256;
95 /// The header type.
96 type Header = generic::Header<BlockNumber, BlakeTwo256>;
97 /// The index type for storing how many extrinsics an account has signed.95 /// The index type for storing how many extrinsics an account has signed.
98 type Index = Index;96 type Nonce = Nonce;
99 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.97 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
100 type Lookup = AccountIdLookup<AccountId, ()>;98 type Lookup = AccountIdLookup<AccountId, ()>;
101 /// What to do if an account is fully reaped from the system.99 /// What to do if an account is fully reaped from the system.
171 type ExistentialDeposit = ExistentialDeposit;169 type ExistentialDeposit = ExistentialDeposit;
172 type AccountStore = System;170 type AccountStore = System;
173 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;171 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;
174 type HoldIdentifier = [u8; 16];172 type RuntimeHoldReason = RuntimeHoldReason;
175 type FreezeIdentifier = [u8; 16];173 type FreezeIdentifier = [u8; 16];
176 type MaxHolds = MaxHolds;174 type MaxHolds = MaxHolds;
177 type MaxFreezes = MaxFreezes;175 type MaxFreezes = MaxFreezes;
247 type AuthorityId = AuraId;245 type AuthorityId = AuraId;
248 type DisabledValidators = ();246 type DisabledValidators = ();
249 type MaxAuthorities = MaxAuthorities;247 type MaxAuthorities = MaxAuthorities;
248 type AllowMultipleBlocksPerSlot = ConstBool<true>;
250}249}
251250
252impl pallet_utility::Config for Runtime {251impl pallet_utility::Config for Runtime {
modifiedruntime/common/config/xcm/foreignassets.rsdiffbeforeafterboth
36 pub CheckingAccount: AccountId = PolkadotXcm::check_account();36 pub CheckingAccount: AccountId = PolkadotXcm::check_account();
37}37}
3838
39pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);39pub struct AsInnerId<ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);
40impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>40impl<ConvertAssetId: MaybeEquivalence<AssetId, AssetId>> MaybeEquivalence<MultiLocation, AssetId>
41 ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>41 for AsInnerId<ConvertAssetId>
42where
43 AssetId: Borrow<AssetId>,
44 AssetId: TryAsForeign<AssetId, ForeignAssetId>,
45 AssetIds: Borrow<AssetId>,
46{42{
47 fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {43 fn convert(id: &MultiLocation) -> Option<AssetId> {
48 let id = id.borrow();
49
50 log::trace!(44 log::trace!(
51 target: "xcm::AsInnerId::Convert",45 target: "xcm::AsInnerId::Convert",
58 let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));52 let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
5953
60 if *id == parent {54 if *id == parent {
61 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));55 return ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Parent));
62 }56 }
6357
64 if *id == here || *id == self_location {58 if *id == here || *id == self_location {
65 return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));59 return ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Here));
66 }60 }
6761
68 match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(*id) {62 match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(*id) {
69 Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {63 Some(AssetId::ForeignAssetId(foreign_asset_id)) => {
70 ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))64 ConvertAssetId::convert(&AssetId::ForeignAssetId(foreign_asset_id))
71 }65 }
72 _ => Err(()),66 _ => None,
73 }67 }
74 }68 }
7569
76 fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {70 fn convert_back(asset_id: &AssetId) -> Option<MultiLocation> {
77 log::trace!(71 log::trace!(
78 target: "xcm::AsInnerId::Reverse",72 target: "xcm::AsInnerId::Reverse",
79 "AsInnerId",73 "AsInnerId",
80 );74 );
81
82 let asset_id = what.borrow();
8375
84 let parent_id =76 let parent_id =
85 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();77 ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Parent)).unwrap();
86 let here_id =78 let here_id =
87 ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();79 ConvertAssetId::convert(&AssetId::NativeAssetId(NativeCurrency::Here)).unwrap();
8880
89 if asset_id.clone() == parent_id {81 if asset_id.clone() == parent_id {
90 return Ok(MultiLocation::parent());82 return Some(MultiLocation::parent());
91 }83 }
9284
93 if asset_id.clone() == here_id {85 if asset_id.clone() == here_id {
94 return Ok(MultiLocation::new(86 return Some(MultiLocation::new(
95 1,87 1,
96 X1(Parachain(ParachainInfo::get().into())),88 X1(Parachain(ParachainInfo::get().into())),
97 ));89 ));
98 }90 }
9991
92 let fid =
100 match <AssetId as TryAsForeign<AssetId, ForeignAssetId>>::try_as_foreign(asset_id.clone()) {93 <AssetId as TryAsForeign<AssetId, ForeignAssetId>>::try_as_foreign(asset_id.clone())?;
101 Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {94 XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid)
102 Some(location) => Ok(location),
103 None => Err(()),
104 },
105 None => Err(()),
106 }
107 }95 }
108}96}
10997
112 // Use this fungibles implementation:100 // Use this fungibles implementation:
113 ForeignAssets,101 ForeignAssets,
114 // Use this currency when it is a fungible asset matching the given location or name:102 // Use this currency when it is a fungible asset matching the given location or name:
115 ConvertedConcreteId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,103 ConvertedConcreteId<AssetId, Balance, AsInnerId<JustTry>, JustTry>,
116 // Convert an XCM MultiLocation into a local account id:104 // Convert an XCM MultiLocation into a local account id:
117 LocationToAccountId,105 LocationToAccountId,
118 // Our chain's account ID type (we can't get away without mentioning it explicitly):106 // Our chain's account ID type (we can't get away without mentioning it explicitly):
154 what: &MultiAsset,142 what: &MultiAsset,
155 who: &MultiLocation,143 who: &MultiLocation,
156 maybe_context: Option<&XcmContext>,144 maybe_context: Option<&XcmContext>,
157 ) -> Result<xcm_executor::Assets, XcmError> {145 ) -> Result<staging_xcm_executor::Assets, XcmError> {
158 FungiblesTransactor::withdraw_asset(what, who, maybe_context)146 FungiblesTransactor::withdraw_asset(what, who, maybe_context)
159 }147 }
160148
163 from: &MultiLocation,151 from: &MultiLocation,
164 to: &MultiLocation,152 to: &MultiLocation,
165 context: &XcmContext,153 context: &XcmContext,
166 ) -> Result<xcm_executor::Assets, XcmError> {154 ) -> Result<staging_xcm_executor::Assets, XcmError> {
167 FungiblesTransactor::internal_transfer_asset(what, from, to, context)155 FungiblesTransactor::internal_transfer_asset(what, from, to, context)
168 }156 }
169}157}
179>;167>;
180168
181pub struct CurrencyIdConvert;169pub struct CurrencyIdConvert;
182impl Convert<AssetIds, Option<MultiLocation>> for CurrencyIdConvert {170impl Convert<AssetId, Option<MultiLocation>> for CurrencyIdConvert {
183 fn convert(id: AssetIds) -> Option<MultiLocation> {171 fn convert(id: AssetId) -> Option<MultiLocation> {
184 match id {172 match id {
185 AssetIds::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(173 AssetId::NativeAssetId(NativeCurrency::Here) => Some(MultiLocation::new(
186 1,174 1,
187 X1(Parachain(ParachainInfo::get().into())),175 X1(Parachain(ParachainInfo::get().into())),
188 )),176 )),
189 AssetIds::NativeAssetId(NativeCurrency::Parent) => Some(MultiLocation::parent()),177 AssetId::NativeAssetId(NativeCurrency::Parent) => Some(MultiLocation::parent()),
190 AssetIds::ForeignAssetId(foreign_asset_id) => {178 AssetId::ForeignAssetId(foreign_asset_id) => {
191 XcmForeignAssetIdMapping::<Runtime>::get_multi_location(foreign_asset_id)179 XcmForeignAssetIdMapping::<Runtime>::get_multi_location(foreign_asset_id)
192 }180 }
193 }181 }
199 if location == MultiLocation::here()187 if location == MultiLocation::here()
200 || location == MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())))188 || location == MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())))
201 {189 {
202 return Some(AssetIds::NativeAssetId(NativeCurrency::Here));190 return Some(AssetId::NativeAssetId(NativeCurrency::Here));
203 }191 }
204192
205 if location == MultiLocation::parent() {193 if location == MultiLocation::parent() {
206 return Some(AssetIds::NativeAssetId(NativeCurrency::Parent));194 return Some(AssetId::NativeAssetId(NativeCurrency::Parent));
207 }195 }
208196
209 if let Some(currency_id) = XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location) {197 if let Some(currency_id) = XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location) {
modifiedruntime/common/config/xcm/mod.rsdiffbeforeafterboth
153 origin: &MultiLocation,153 origin: &MultiLocation,
154 message: &mut [Instruction<Call>],154 message: &mut [Instruction<Call>],
155 max_weight: Weight,155 max_weight: Weight,
156 weight_credit: &mut Weight,156 properties: &mut Properties,
157 ) -> Result<(), ProcessMessageError> {157 ) -> Result<(), ProcessMessageError> {
158 Deny::try_pass(origin, message)?;158 Deny::try_pass(origin, message)?;
159 Allow::should_execute(origin, message, max_weight, weight_credit)159 Allow::should_execute(origin, message, max_weight, properties)
160 }160 }
161}161}
162162
211}211}
212212
213pub struct XcmExecutorConfig<T>(PhantomData<T>);213pub struct XcmExecutorConfig<T>(PhantomData<T>);
214impl<T> xcm_executor::Config for XcmExecutorConfig<T>214impl<T> staging_xcm_executor::Config for XcmExecutorConfig<T>
215where215where
216 T: pallet_configuration::Config,216 T: pallet_configuration::Config,
217{217{
240 type UniversalAliases = Nothing;240 type UniversalAliases = Nothing;
241 type CallDispatcher = RuntimeCall;241 type CallDispatcher = RuntimeCall;
242 type SafeCallFilter = XcmCallFilter;242 type SafeCallFilter = XcmCallFilter;
243 type Aliasers = Nothing;
243}244}
244245
245#[cfg(feature = "runtime-benchmarks")]246#[cfg(feature = "runtime-benchmarks")]
modifiedruntime/common/config/xcm/nativeassets.rsdiffbeforeafterboth
109 fn buy_weight(&mut self, _weight: Weight, payment: Assets) -> Result<Assets, XcmError> {109 fn buy_weight(
110 &mut self,
111 _weight: Weight,
112 payment: Assets,
113 _xcm: &XcmContext,
114 ) -> Result<Assets, XcmError> {
110 Ok(payment)115 Ok(payment)
111 }116 }
modifiedruntime/common/construct_runtime.rsdiffbeforeafterboth
19 () => {19 () => {
20 frame_support::construct_runtime! {20 frame_support::construct_runtime! {
2121
22 pub enum Runtime where22 pub enum Runtime {
23 Block = Block,
24 NodeBlock = opaque::Block,
25 UncheckedExtrinsic = UncheckedExtrinsic
26 {
27 System: frame_system = 0,23 System: frame_system = 0,
28 StateTrieMigration: pallet_state_trie_migration = 1,24 StateTrieMigration: pallet_state_trie_migration = 1,
modifiedruntime/common/mod.rsdiffbeforeafterboth
6363
64/// The address format for describing accounts.64/// The address format for describing accounts.
65pub type Address = sp_runtime::MultiAddress<AccountId, ()>;65pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
66/// Block header type as expected by this runtime.
67pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
68/// Block type as expected by this runtime.
69pub type Block = generic::Block<Header, UncheckedExtrinsic>;
70/// A Block signed with a Justification66/// A Block signed with a Justification
71pub type SignedBlock = generic::SignedBlock<Block>;67pub type SignedBlock = generic::SignedBlock<Block>;
68/// Frontier wrapped extrinsic
69pub type UncheckedExtrinsic =
70 fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
71/// Header type.
72pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
73/// Block type.
74pub type Block = generic::Block<Header, UncheckedExtrinsic>;
72/// BlockId type as expected by this runtime.75/// BlockId type as expected by this runtime.
73pub type BlockId = generic::BlockId<Block>;76pub type BlockId = generic::BlockId<Block>;
7477
103 pallet_ethereum::FakeTransactionFinalizer<Runtime>,106 pallet_ethereum::FakeTransactionFinalizer<Runtime>,
104);107);
105
106/// Unchecked extrinsic type as expected by this runtime.
107pub type UncheckedExtrinsic =
108 fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
109
110/// Extrinsic type that has already been checked.
111pub type CheckedExtrinsic =
112 fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra, H160>;
113108
114/// Executive: handles dispatch to the various modules.109/// Executive: handles dispatch to the various modules.
115pub type Executive = frame_executive::Executive<110pub type Executive = frame_executive::Executive<
modifiedruntime/common/sponsoring.rsdiffbeforeafterboth
79 return None;79 return None;
80 }80 }
8181
82 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;82 let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
83 let limit = collection.limits.sponsored_data_rate_limit()?;83 let limit = collection.limits.sponsored_data_rate_limit()?;
8484
85 if let Some(last_tx_block) = TokenPropertyBasket::<T>::get(collection.id, item_id) {85 if let Some(last_tx_block) = TokenPropertyBasket::<T>::get(collection.id, item_id) {
123 }123 }
124124
125 // sponsor timeout125 // sponsor timeout
126 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;126 let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
127 let limit = collection127 let limit = collection
128 .limits128 .limits
129 .sponsor_transfer_timeout(match collection.mode {129 .sponsor_transfer_timeout(match collection.mode {
169 properties: &CreateItemData,169 properties: &CreateItemData,
170) -> Option<()> {170) -> Option<()> {
171 // sponsor timeout171 // sponsor timeout
172 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;172 let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
173 let limit = collection173 let limit = collection
174 .limits174 .limits
175 .sponsor_transfer_timeout(match properties {175 .sponsor_transfer_timeout(match properties {
195 item_id: &TokenId,195 item_id: &TokenId,
196) -> Option<()> {196) -> Option<()> {
197 // sponsor timeout197 // sponsor timeout
198 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;198 let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
199 let limit = collection.limits.sponsor_approve_timeout();199 let limit = collection.limits.sponsor_approve_timeout();
200200
201 let last_tx_block = match collection.mode {201 let last_tx_block = match collection.mode {
307pub trait SponsorshipPredict<T: Config> {307pub trait SponsorshipPredict<T: Config> {
308 fn predict(collection: CollectionId, account: T::CrossAccountId, token: TokenId) -> Option<u64>308 fn predict(collection: CollectionId, account: T::CrossAccountId, token: TokenId) -> Option<u64>
309 where309 where
310 u64: From<<T as frame_system::Config>::BlockNumber>;310 u64: From<BlockNumberFor<T>>;
311}311}
312312
313pub struct UniqueSponsorshipPredict<T>(PhantomData<T>);313pub struct UniqueSponsorshipPredict<T>(PhantomData<T>);
314314
315impl<T: Config> SponsorshipPredict<T> for UniqueSponsorshipPredict<T> {315impl<T: Config> SponsorshipPredict<T> for UniqueSponsorshipPredict<T> {
316 fn predict(collection_id: CollectionId, who: T::CrossAccountId, token: TokenId) -> Option<u64>316 fn predict(collection_id: CollectionId, who: T::CrossAccountId, token: TokenId) -> Option<u64>
317 where317 where
318 u64: From<<T as frame_system::Config>::BlockNumber>,318 u64: From<BlockNumberFor<T>>,
319 {319 {
320 let collection = <CollectionHandle<T>>::try_get(collection_id).ok()?;320 let collection = <CollectionHandle<T>>::try_get(collection_id).ok()?;
321 let _ = collection.sponsorship.sponsor()?;321 let _ = collection.sponsorship.sponsor()?;
322322
323 // sponsor timeout323 // sponsor timeout
324 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;324 let block_number = <frame_system::Pallet<T>>::block_number() as BlockNumberFor<T>;
325 let limit = collection325 let limit = collection
326 .limits326 .limits
327 .sponsor_transfer_timeout(match collection.mode {327 .sponsor_transfer_timeout(match collection.mode {
modifiedruntime/common/tests/mod.rsdiffbeforeafterboth
51fn new_test_ext(balances: Vec<(AccountId, Balance)>) -> sp_io::TestExternalities {51fn new_test_ext(balances: Vec<(AccountId, Balance)>) -> sp_io::TestExternalities {
52 let mut storage = make_basic_storage();52 let mut storage = make_basic_storage();
5353
54 pallet_balances::GenesisConfig::<Runtime> { balances }54 pallet_balances::BuildGenesisConfig::<Runtime> { balances }
55 .assimilate_storage(&mut storage)55 .build_storage(&mut storage)
56 .unwrap();56 .unwrap();
5757
58 let mut ext = sp_io::TestExternalities::new(storage);58 let mut ext = sp_io::TestExternalities::new(storage);
94 .map(|acc| get_account_id_from_seed::<sr25519::Public>(acc))94 .map(|acc| get_account_id_from_seed::<sr25519::Public>(acc))
95 .collect::<Vec<_>>();95 .collect::<Vec<_>>();
9696
97 let cfg = GenesisConfig {97 let cfg = BuildGenesisConfig {
98 collator_selection: CollatorSelectionConfig { invulnerables },98 collator_selection: CollatorSelectionConfig { invulnerables },
99 session: SessionConfig { keys },99 session: SessionConfig { keys },
100 parachain_info: ParachainInfoConfig {100 parachain_info: ParachainInfoConfig {
101 parachain_id: PARA_ID.into(),101 parachain_id: PARA_ID.into(),
102 ..Default::default()
102 },103 },
103 ..GenesisConfig::default()104 ..Default::default()
104 };105 };
105106
106 cfg.build_storage().unwrap()107 cfg.build_storage().unwrap()
110fn make_basic_storage() -> Storage {111fn make_basic_storage() -> Storage {
111 use crate::AuraConfig;112 use crate::AuraConfig;
112113
113 let cfg = GenesisConfig {114 let cfg = BuildGenesisConfig {
114 aura: AuraConfig {115 aura: AuraConfig {
115 authorities: vec![116 authorities: vec![
116 get_from_seed::<AuraId>("Alice"),117 get_from_seed::<AuraId>("Alice"),
119 },120 },
120 parachain_info: ParachainInfoConfig {121 parachain_info: ParachainInfoConfig {
121 parachain_id: PARA_ID.into(),122 parachain_id: PARA_ID.into(),
123 ..Default::default()
122 },124 },
123 ..GenesisConfig::default()125 ..Default::default()
124 };126 };
125127
126 cfg.build_storage().unwrap().into()128 cfg.build_storage().unwrap().into()
modifiedruntime/tests/src/lib.rsdiffbeforeafterboth
5757
58// Configure a mock runtime to test the pallet.58// Configure a mock runtime to test the pallet.
59frame_support::construct_runtime!(59frame_support::construct_runtime!(
60 pub enum Test where60 pub enum Test {
61 Block = Block,
62 NodeBlock = Block,
63 UncheckedExtrinsic = UncheckedExtrinsic,
64 {
65 System: frame_system,61 System: frame_system,
66 Timestamp: pallet_timestamp,62 Timestamp: pallet_timestamp,
67 Unique: pallet_unique::{Pallet, Call, Storage},63 Unique: pallet_unique,
68 Balances: pallet_balances::{Pallet, Call, Storage, Event<T>},64 Balances: pallet_balances,
69 Common: pallet_common::{Pallet, Storage, Event<T>},65 Common: pallet_common,
70 Fungible: pallet_fungible::{Pallet, Storage},66 Fungible: pallet_fungible,
71 Refungible: pallet_refungible::{Pallet, Storage},67 Refungible: pallet_refungible,
72 Nonfungible: pallet_nonfungible::{Pallet, Storage},68 Nonfungible: pallet_nonfungible,
73 Structure: pallet_structure::{Pallet, Storage, Event<T>},69 Structure: pallet_structure,
74 TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event<T>},70 TransactionPayment: pallet_transaction_payment,
75 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin},71 Ethereum: pallet_ethereum,
76 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>},72 EVM: pallet_evm,
77 }73 }
78);74);
7975
90 type DbWeight = ();86 type DbWeight = ();
91 type RuntimeOrigin = RuntimeOrigin;87 type RuntimeOrigin = RuntimeOrigin;
92 type RuntimeCall = RuntimeCall;88 type RuntimeCall = RuntimeCall;
93 type Index = u64;89 type Nonce = u64;
94 type BlockNumber = u64;
95 type Hash = H256;90 type Hash = H256;
96 type Hashing = BlakeTwo256;91 type Hashing = BlakeTwo256;
97 type AccountId = u64;92 type AccountId = u64;
98 type Lookup = IdentityLookup<Self::AccountId>;93 type Lookup = IdentityLookup<Self::AccountId>;
99 type Header = Header;
100 type BlockHashCount = BlockHashCount;94 type BlockHashCount = BlockHashCount;
101 type Version = ();95 type Version = ();
102 type PalletInfo = PalletInfo;96 type PalletInfo = PalletInfo;
127 type MaxFreezes = MaxLocks;121 type MaxFreezes = MaxLocks;
128 type FreezeIdentifier = [u8; 8];122 type FreezeIdentifier = [u8; 8];
129 type MaxHolds = MaxLocks;123 type MaxHolds = MaxLocks;
130 type HoldIdentifier = [u8; 8];
131}124}
132125
133parameter_types! {126parameter_types! {
242 type OnChargeTransaction = ();235 type OnChargeTransaction = ();
243 type FindAuthor = ();236 type FindAuthor = ();
244 type BlockHashMapping = SubstrateBlockHashMapping<Self>;237 type BlockHashMapping = SubstrateBlockHashMapping<Self>;
245 type TransactionValidityHack = ();
246 type Timestamp = Timestamp;238 type Timestamp = Timestamp;
247 type GasLimitPovSizeRatio = ConstU64<0>;239 type GasLimitPovSizeRatio = ConstU64<0>;
248}240}