Newer
Older
})
}
fn session_info(index: SessionIndex) -> Option<SessionInfo> {
parachains_runtime_api_impl::session_info::<Runtime>(index)
fn session_executor_params(session_index: SessionIndex) -> Option<ExecutorParams> {
parachains_runtime_api_impl::session_executor_params::<Runtime>(session_index)
fn dmq_contents(recipient: ParaId) -> Vec<InboundDownwardMessage<BlockNumber>> {
parachains_runtime_api_impl::dmq_contents::<Runtime>(recipient)
recipient: ParaId
) -> BTreeMap<ParaId, Vec<InboundHrmpMessage<BlockNumber>>> {
parachains_runtime_api_impl::inbound_hrmp_channels_contents::<Runtime>(recipient)
fn validation_code_by_hash(hash: ValidationCodeHash) -> Option<ValidationCode> {
parachains_runtime_api_impl::validation_code_by_hash::<Runtime>(hash)
fn on_chain_votes() -> Option<ScrapedOnChainVotes<Hash>> {
parachains_runtime_api_impl::on_chain_votes::<Runtime>()
}
fn submit_pvf_check_statement(
Dan Shields
committed
stmt: PvfCheckStatement,
signature: ValidatorSignature,
) {
parachains_runtime_api_impl::submit_pvf_check_statement::<Runtime>(stmt, signature)
}
fn pvfs_require_precheck() -> Vec<ValidationCodeHash> {
parachains_runtime_api_impl::pvfs_require_precheck::<Runtime>()
}
fn validation_code_hash(para_id: ParaId, assumption: OccupiedCoreAssumption)
-> Option<ValidationCodeHash>
{
parachains_runtime_api_impl::validation_code_hash::<Runtime>(para_id, assumption)
}
fn disputes() -> Vec<(SessionIndex, CandidateHash, DisputeState<BlockNumber>)> {
parachains_runtime_api_impl::get_session_disputes::<Runtime>()
) -> Vec<(SessionIndex, CandidateHash, slashing::PendingSlashes)> {
parachains_runtime_api_impl::unapplied_slashes::<Runtime>()
}
fn key_ownership_proof(
validator_id: ValidatorId,
) -> Option<slashing::OpaqueKeyOwnershipProof> {
use parity_scale_codec::Encode;
Historical::prove((PARACHAIN_KEY_TYPE_ID, validator_id))
.map(|p| p.encode())
.map(slashing::OpaqueKeyOwnershipProof::new)
}
fn submit_report_dispute_lost(
dispute_proof: slashing::DisputeProof,
key_ownership_proof: slashing::OpaqueKeyOwnershipProof,
parachains_runtime_api_impl::submit_unsigned_slashing_report::<Runtime>(
dispute_proof,
key_ownership_proof,
)
}
fn minimum_backing_votes() -> u32 {
parachains_runtime_api_impl::minimum_backing_votes::<Runtime>()
}
fn para_backing_state(para_id: ParaId) -> Option<primitives::async_backing::BackingState> {
parachains_runtime_api_impl::backing_state::<Runtime>(para_id)
}
fn async_backing_params() -> primitives::AsyncBackingParams {
parachains_runtime_api_impl::async_backing_params::<Runtime>()
fn approval_voting_params() -> ApprovalVotingParams {
parachains_staging_runtime_api_impl::approval_voting_params::<Runtime>()
}
fn disabled_validators() -> Vec<ValidatorIndex> {
parachains_staging_runtime_api_impl::disabled_validators::<Runtime>()
}
fn node_features() -> NodeFeatures {
parachains_staging_runtime_api_impl::node_features::<Runtime>()
}
impl beefy_primitives::BeefyApi<Block, BeefyId> for Runtime {
fn beefy_genesis() -> Option<BlockNumber> {
pallet_beefy::GenesisBlock::<Runtime>::get()
}
fn validator_set() -> Option<beefy_primitives::ValidatorSet<BeefyId>> {
Beefy::validator_set()
fn submit_report_equivocation_unsigned_extrinsic(
equivocation_proof: beefy_primitives::EquivocationProof<
BlockNumber,
BeefyId,
BeefySignature,
>,
key_owner_proof: beefy_primitives::OpaqueKeyOwnershipProof,
) -> Option<()> {
let key_owner_proof = key_owner_proof.decode()?;
Beefy::submit_unsigned_equivocation_report(
equivocation_proof,
key_owner_proof,
)
}
fn generate_key_ownership_proof(
_set_id: beefy_primitives::ValidatorSetId,
authority_id: BeefyId,
) -> Option<beefy_primitives::OpaqueKeyOwnershipProof> {
use parity_scale_codec::Encode;
Historical::prove((beefy_primitives::KEY_TYPE, authority_id))
.map(|p| p.encode())
.map(beefy_primitives::OpaqueKeyOwnershipProof::new)
}
impl mmr::MmrApi<Block, Hash, BlockNumber> for Runtime {
fn mmr_root() -> Result<mmr::Hash, mmr::Error> {
Ok(pallet_mmr::RootHash::<Runtime>::get())
}
fn mmr_leaf_count() -> Result<mmr::LeafIndex, mmr::Error> {
Ok(pallet_mmr::NumberOfLeaves::<Runtime>::get())
Robert Hambrock
committed
fn generate_proof(
block_numbers: Vec<BlockNumber>,
best_known_block_number: Option<BlockNumber>,
) -> Result<(Vec<mmr::EncodableOpaqueLeaf>, mmr::Proof<mmr::Hash>), mmr::Error> {
Mmr::generate_proof(block_numbers, best_known_block_number).map(
|(leaves, proof)| {
(
leaves
.into_iter()
.map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf))
.collect(),
proof,
)
},
)
fn verify_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::Proof<mmr::Hash>)
-> Result<(), mmr::Error>
{
let leaves = leaves.into_iter().map(|leaf|
leaf.into_opaque_leaf()
.try_decode()
.ok_or(mmr::Error::Verify)).collect::<Result<Vec<mmr::Leaf>, mmr::Error>>()?;
Mmr::verify_leaves(leaves, proof)
Robert Hambrock
committed
fn verify_proof_stateless(
root: mmr::Hash,
leaves: Vec<mmr::EncodableOpaqueLeaf>,
proof: mmr::Proof<mmr::Hash>
) -> Result<(), mmr::Error> {
let nodes = leaves.into_iter().map(|leaf|mmr::DataOrHash::Data(leaf.into_opaque_leaf())).collect();
pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(root, nodes, proof)
}
}
impl pallet_beefy_mmr::BeefyMmrApi<Block, Hash> for RuntimeApi {
fn authority_set_proof() -> beefy_primitives::mmr::BeefyAuthoritySet<Hash> {
BeefyMmrLeaf::authority_set_proof()
}
fn next_authority_set_proof() -> beefy_primitives::mmr::BeefyNextAuthoritySet<Hash> {
BeefyMmrLeaf::next_authority_set_proof()
Adrian Catangiu
committed
}
impl fg_primitives::GrandpaApi<Block> for Runtime {
fn grandpa_authorities() -> Vec<(GrandpaId, u64)> {
Grandpa::grandpa_authorities()
}
fn current_set_id() -> fg_primitives::SetId {
Grandpa::current_set_id()
}
fn submit_report_equivocation_unsigned_extrinsic(
equivocation_proof: fg_primitives::EquivocationProof<
<Block as BlockT>::Hash,
sp_runtime::traits::NumberFor<Block>,
>,
key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,
) -> Option<()> {
let key_owner_proof = key_owner_proof.decode()?;
Grandpa::submit_unsigned_equivocation_report(
equivocation_proof,
key_owner_proof,
)
}
fn generate_key_ownership_proof(
_set_id: fg_primitives::SetId,
authority_id: fg_primitives::AuthorityId,
) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {
Historical::prove((fg_primitives::KEY_TYPE, authority_id))
.map(|p| p.encode())
.map(fg_primitives::OpaqueKeyOwnershipProof::new)
}
}
impl babe_primitives::BabeApi<Block> for Runtime {
fn configuration() -> babe_primitives::BabeConfiguration {
let epoch_config = Babe::epoch_config().unwrap_or(BABE_GENESIS_EPOCH_CONFIG);
babe_primitives::BabeConfiguration {
slot_duration: Babe::slot_duration(),
epoch_length: EpochDuration::get(),
c: epoch_config.c,
authorities: Babe::authorities().to_vec(),
allowed_slots: epoch_config.allowed_slots,
fn current_epoch_start() -> babe_primitives::Slot {
fn current_epoch() -> babe_primitives::Epoch {
Babe::current_epoch()
}
fn next_epoch() -> babe_primitives::Epoch {
Babe::next_epoch()
}
fn generate_key_ownership_proof(
authority_id: babe_primitives::AuthorityId,
) -> Option<babe_primitives::OpaqueKeyOwnershipProof> {
Historical::prove((babe_primitives::KEY_TYPE, authority_id))
.map(|p| p.encode())
.map(babe_primitives::OpaqueKeyOwnershipProof::new)
}
fn submit_report_equivocation_unsigned_extrinsic(
equivocation_proof: babe_primitives::EquivocationProof<<Block as BlockT>::Header>,
key_owner_proof: babe_primitives::OpaqueKeyOwnershipProof,
) -> Option<()> {
let key_owner_proof = key_owner_proof.decode()?;
Babe::submit_unsigned_equivocation_report(
equivocation_proof,
key_owner_proof,
)
}
}
impl authority_discovery_primitives::AuthorityDiscoveryApi<Block> for Runtime {
fn authorities() -> Vec<AuthorityDiscoveryId> {
parachains_runtime_api_impl::relevant_authority_ids::<Runtime>()
}
}
impl sp_session::SessionKeys<Block> for Runtime {
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
SessionKeys::generate(seed)
}
fn decode_session_keys(
encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
SessionKeys::decode_into_raw_public_keys(&encoded)
}
}
impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
fn account_nonce(account: AccountId) -> Nonce {
System::account_nonce(account)
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {
fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {
TransactionPayment::query_fee_details(uxt, len)
}
fn query_weight_to_fee(weight: Weight) -> Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> Balance {
TransactionPayment::length_to_fee(length)
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
Muharem Ismailov
committed
for Runtime
{
fn query_call_info(call: RuntimeCall, len: u32) -> RuntimeDispatchInfo<Balance> {
Muharem Ismailov
committed
TransactionPayment::query_call_info(call, len)
}
fn query_call_fee_details(call: RuntimeCall, len: u32) -> FeeDetails<Balance> {
Muharem Ismailov
committed
TransactionPayment::query_call_fee_details(call, len)
}
fn query_weight_to_fee(weight: Weight) -> Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> Balance {
TransactionPayment::length_to_fee(length)
}
Muharem Ismailov
committed
}
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
impl xcm_fee_payment_runtime_api::XcmPaymentApi<Block> for Runtime {
fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
if !matches!(xcm_version, 3 | 4) {
return Err(XcmPaymentApiError::UnhandledXcmVersion);
}
Ok([VersionedAssetId::V4(xcm_config::TokenLocation::get().into())]
.into_iter()
.filter_map(|asset| asset.into_version(xcm_version).ok())
.collect())
}
fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
let local_asset = VersionedAssetId::V4(xcm_config::TokenLocation::get().into());
let asset = asset
.into_version(4)
.map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;
if asset != local_asset { return Err(XcmPaymentApiError::AssetNotFound); }
Ok(WeightToFee::weight_to_fee(&weight))
}
fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
XcmPallet::query_xcm_weight(message)
}
fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
XcmPallet::query_delivery_fees(destination, message)
}
}
impl pallet_nomination_pools_runtime_api::NominationPoolsApi<
Block,
AccountId,
Balance,
> for Runtime {
fn pending_rewards(member: AccountId) -> Balance {
NominationPools::api_pending_rewards(member).unwrap_or_default()
}
fn points_to_balance(pool_id: pallet_nomination_pools::PoolId, points: Balance) -> Balance {
NominationPools::api_points_to_balance(pool_id, points)
}
fn balance_to_points(pool_id: pallet_nomination_pools::PoolId, new_funds: Balance) -> Balance {
NominationPools::api_balance_to_points(pool_id, new_funds)
}
}
impl pallet_staking_runtime_api::StakingApi<Block, Balance, AccountId> for Runtime {
fn nominations_quota(balance: Balance) -> u32 {
Staking::api_nominations_quota(balance)
fn eras_stakers_page_count(era: sp_staking::EraIndex, account: AccountId) -> sp_staking::Page {
Staking::api_eras_stakers_page_count(era, account)
}
#[cfg(feature = "try-runtime")]
impl frame_try_runtime::TryRuntime<Block> for Runtime {
fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
log::info!("try-runtime::on_runtime_upgrade westend.");
let weight = Executive::try_runtime_upgrade(checks).unwrap();
(weight, BlockWeights::get().max_block)
}
fn execute_block(
block: Block,
state_root_check: bool,
signature_check: bool,
select: frame_try_runtime::TryStateSelect,
) -> Weight {
// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
// have a backtrace here.
Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(extra: bool) -> (
Vec<frame_benchmarking::BenchmarkList>,
Vec<frame_support::traits::StorageInfo>,
) {
use frame_benchmarking::{Benchmarking, BenchmarkList};
use frame_support::traits::StorageInfoTrait;
use pallet_session_benchmarking::Pallet as SessionBench;
use pallet_offences_benchmarking::Pallet as OffencesBench;
Georges
committed
use pallet_election_provider_support_benchmarking::Pallet as ElectionProviderBench;
use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
use frame_system_benchmarking::Pallet as SystemBench;
use pallet_nomination_pools_benchmarking::Pallet as NominationPoolsBench;
type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
let mut list = Vec::<BenchmarkList>::new();
let storage_info = AllPalletsWithSystem::storage_info();
return (list, storage_info)
}
Shawn Tabrizi
committed
config: frame_benchmarking::BenchmarkConfig,
Vec<frame_benchmarking::BenchmarkBatch>,
sp_runtime::RuntimeString,
> {
use frame_support::traits::WhitelistedStorageKeys;
use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError};
use sp_storage::TrackedStorageKey;
// Trying to add benchmarks directly to some pallets caused cyclic dependency issues.
// To get around that, we separated the benchmarks into its own crate.
Shaun Wang
committed
use pallet_session_benchmarking::Pallet as SessionBench;
use pallet_offences_benchmarking::Pallet as OffencesBench;
Georges
committed
use pallet_election_provider_support_benchmarking::Pallet as ElectionProviderBench;
use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
Shaun Wang
committed
use frame_system_benchmarking::Pallet as SystemBench;
use pallet_nomination_pools_benchmarking::Pallet as NominationPoolsBench;
impl pallet_session_benchmarking::Config for Runtime {}
impl pallet_offences_benchmarking::Config for Runtime {}
Georges
committed
impl pallet_election_provider_support_benchmarking::Config for Runtime {}
Branislav Kontur
committed
use xcm_config::{AssetHub, TokenLocation};
parameter_types! {
pub ExistentialDepositAsset: Option<Asset> = Some((
TokenLocation::get(),
ExistentialDeposit::get()
).into());
pub AssetHubParaId: ParaId = westend_runtime_constants::system_parachain::ASSET_HUB_ID.into();
pub const RandomParaId: ParaId = ParaId::new(43211234);
}
Adrian Catangiu
committed
impl pallet_xcm::benchmarking::Config for Runtime {
Branislav Kontur
committed
type DeliveryHelper = (
runtime_common::xcm_sender::ToParachainDeliveryHelper<
xcm_config::XcmConfig,
ExistentialDepositAsset,
xcm_config::PriceForChildParachainDelivery,
AssetHubParaId,
(),
>,
runtime_common::xcm_sender::ToParachainDeliveryHelper<
xcm_config::XcmConfig,
ExistentialDepositAsset,
xcm_config::PriceForChildParachainDelivery,
RandomParaId,
(),
>
);
Adrian Catangiu
committed
Some(crate::xcm_config::AssetHub::get())
}
fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
Adrian Catangiu
committed
// Relay/native token can be teleported to/from AH.
Some((
Branislav Kontur
committed
Asset { fun: Fungible(ExistentialDeposit::get()), id: AssetId(Here.into()) },
Adrian Catangiu
committed
crate::xcm_config::AssetHub::get(),
))
}
fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
Adrian Catangiu
committed
// Relay can reserve transfer native token to some random parachain.
Some((
Branislav Kontur
committed
fun: Fungible(ExistentialDeposit::get()),
Adrian Catangiu
committed
},
Branislav Kontur
committed
crate::Junction::Parachain(RandomParaId::get().into()).into(),
Adrian Catangiu
committed
))
}
fn set_up_complex_asset_transfer(
) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
// Relay supports only native token, either reserve transfer it to non-system parachains,
// or teleport it to system parachain. Use the teleport case for benchmarking as it's
// slightly heavier.
// Relay/native token can be teleported to/from AH.
let native_location = Here.into();
let dest = crate::xcm_config::AssetHub::get();
pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::<Runtime>(
native_location,
dest
)
}
fn get_asset() -> Asset {
Asset {
id: AssetId(Location::here()),
fun: Fungible(ExistentialDeposit::get()),
}
}
Adrian Catangiu
committed
}
impl frame_system_benchmarking::Config for Runtime {}
impl pallet_nomination_pools_benchmarking::Config for Runtime {}
impl runtime_parachains::disputes::slashing::benchmarking::Config for Runtime {}
use xcm::latest::{
AssetId, Fungibility::*, InteriorLocation, Junction, Junctions::*,
Asset, Assets, Location, NetworkId, Response,
impl pallet_xcm_benchmarks::Config for Runtime {
type XcmConfig = xcm_config::XcmConfig;
type AccountIdConverter = xcm_config::LocationConverter;
type DeliveryHelper = runtime_common::xcm_sender::ToParachainDeliveryHelper<
xcm_config::XcmConfig,
xcm_config::PriceForChildParachainDelivery,
Branislav Kontur
committed
AssetHubParaId,
fn valid_destination() -> Result<Location, BenchmarkError> {
fn worst_case_holding(_depositable_count: u32) -> Assets {
// Westend only knows about WND.
fun: Fungible(1_000_000 * UNITS),
}].into()
}
}
parameter_types! {
pub TrustedTeleporter: Option<(Location, Asset)> = Some((
Asset { fun: Fungible(1 * UNITS), id: AssetId(TokenLocation::get()) },
pub const TrustedReserve: Option<(Location, Asset)> = None;
}
impl pallet_xcm_benchmarks::fungible::Config for Runtime {
type TransactAsset = Balances;
type TrustedTeleporter = TrustedTeleporter;
type TrustedReserve = TrustedReserve;
fn get_asset() -> Asset {
Asset {
id: AssetId(TokenLocation::get()),
fun: Fungible(1 * UNITS),
}
}
}
impl pallet_xcm_benchmarks::generic::Config for Runtime {
type TransactAsset = Balances;
fn worst_case_response() -> (u64, Response) {
(0u64, Response::Version(Default::default()))
}
fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
// Westend doesn't support asset exchanges
Err(BenchmarkError::Skip)
}
fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
// The XCM executor of Westend doesn't have a configured `UniversalAliases`
Err(BenchmarkError::Skip)
}
fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
Ok((AssetHub::get(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
fn subscribe_origin() -> Result<Location, BenchmarkError> {
fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
let origin = AssetHub::get();
let assets: Assets = (AssetId(TokenLocation::get()), 1_000 * UNITS).into();
let ticket = Location { parents: 0, interior: Here };
Ok((origin, ticket, assets))
}
fn fee_asset() -> Result<Asset, BenchmarkError> {
Ok(Asset {
id: AssetId(TokenLocation::get()),
fun: Fungible(1_000_000 * UNITS),
})
}
fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
// Westend doesn't support asset locking
Err(BenchmarkError::Skip)
}
fn export_message_origin_and_destination(
) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
// Westend doesn't support exporting messages
Err(BenchmarkError::Skip)
}
fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
// The XCM executor of Westend doesn't have a configured `Aliasers`
Err(BenchmarkError::Skip)
}
type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::<Runtime>;
type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::<Runtime>;
let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
Shawn Tabrizi
committed
let params = (&config, &whitelist);
Ok(batches)
impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
fn create_default_config() -> Vec<u8> {
create_default_config::<RuntimeGenesisConfig>()
}
fn build_config(config: Vec<u8>) -> sp_genesis_builder::Result {
build_config::<RuntimeGenesisConfig>(config)
}
}
#[cfg(all(test, feature = "try-runtime"))]
mod remote_tests {
use super::*;
use frame_try_runtime::{runtime_decl_for_try_runtime::TryRuntime, UpgradeCheckSelect};
use remote_externalities::{
Builder, Mode, OfflineConfig, OnlineConfig, SnapshotConfig, Transport,
};
use std::env::var;
#[tokio::test]
async fn run_migrations() {
if var("RUN_MIGRATION_TESTS").is_err() {
sp_tracing::try_init_simple();
let transport: Transport =
var("WS").unwrap_or("wss://westend-rpc.polkadot.io:443".to_string()).into();
let maybe_state_snapshot: Option<SnapshotConfig> = var("SNAP").map(|s| s.into()).ok();
let mut ext = Builder::<Block>::default()
.mode(if let Some(state_snapshot) = maybe_state_snapshot {
Mode::OfflineOrElseOnline(
OfflineConfig { state_snapshot: state_snapshot.clone() },
OnlineConfig {
transport,
state_snapshot: Some(state_snapshot),
..Default::default()
},
)
} else {
Mode::Online(OnlineConfig { transport, ..Default::default() })
})
.build()
.await
.unwrap();
ext.execute_with(|| Runtime::on_runtime_upgrade(UpgradeCheckSelect::PreAndPost));
mod clean_state_migration {
use frame_support::{pallet_prelude::*, storage_alias, traits::OnRuntimeUpgrade};
use pallet_state_trie_migration::MigrationLimits;
#[storage_alias]
type AutoLimits = StorageValue<StateTrieMigration, Option<MigrationLimits>, ValueQuery>;
// Actual type of value is `MigrationTask<T>`, putting a dummy
// one to avoid the trait constraint on T.
// Since we only use `kill` it is fine.
#[storage_alias]
type MigrationProcess = StorageValue<StateTrieMigration, u32, ValueQuery>;
#[storage_alias]
type SignedMigrationMaxLimits = StorageValue<StateTrieMigration, MigrationLimits, OptionQuery>;
/// Initialize an automatic migration process.
pub struct CleanMigrate;
impl OnRuntimeUpgrade for CleanMigrate {
fn pre_upgrade() -> Result<Vec<u8>, sp_runtime::TryRuntimeError> {
Ok(Default::default())
}
fn on_runtime_upgrade() -> frame_support::weights::Weight {
MigrationProcess::kill();
AutoLimits::kill();
SignedMigrationMaxLimits::kill();
<Runtime as frame_system::Config>::DbWeight::get().writes(3)
}
#[cfg(feature = "try-runtime")]
fn post_upgrade(_state: Vec<u8>) -> Result<(), sp_runtime::TryRuntimeError> {
!AutoLimits::exists() && !SignedMigrationMaxLimits::exists(),
"State migration clean.",