Bump Substrate/Polkadot/Cumulus refs (aka Weights v1.5) (#1597)

* update Substrate + Polkadot + Cumulus refs

* Origin -> RuntimeOrigin

* weights v1.5

* update refs once again + `cargo test -p pallet-bridge-grandpa` works

* started work on `cargo test -p pallet-bridge-messages`

* cargo test -p pallet-bridge-relayers

* cargo test -p pallet-bridge-parachains

* cargo test -p millau-runtime

* cargo test -p bridge-runtime-common

* cargo test -p rialto-runtime

* cargo test -p rialto-parachain-runtime

* cargo test -p millau-bridge-node

* cargo test -p rialto-bridge-node

* cargo test -p rialto-parachain-collator

* cargo test -p messages-relay

* cargo test -p parachains-relay

* cargo test -p substrate-relay

* cargo test --all

* cargo check -p millau-runtime --locked --features runtime-benchmarks

* fix remaining test

* fmt

* try to allow clippy failure temporarily

* Revert "try to allow clippy failure temporarily"

This reverts commit d1b6593580f07e0dbeecb7ab0aa92cee98888ed3.

* use min_by

* Revert "use min_by"

This reverts commit 33042f49ed37e8dd0505370289e17f03bf1a56ee.

* Revert "Revert "use min_by""

This reverts commit 1d2204f0b14dc81e5650bb574dedb5fa78c7097d.

* trigger CI

* Revert "trigger CI"

This reverts commit 259d91b5606743bba9d043c69f07eac6c8700ef5.

* new day, new clippy warning

* more clippy issues
This commit is contained in:
Svyatoslav Nikolsky
2022-10-20 10:27:23 +03:00
committed by Bastian Köcher
parent 9e1847d12a
commit a3dc2d2748
66 changed files with 991 additions and 893 deletions
+32 -21
View File
@@ -18,7 +18,7 @@
use jsonrpsee::RpcModule; use jsonrpsee::RpcModule;
use millau_runtime::{self, opaque::Block, RuntimeApi}; use millau_runtime::{self, opaque::Block, RuntimeApi};
use sc_client_api::{BlockBackend, ExecutorProvider}; use sc_client_api::BlockBackend;
use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams}; use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams};
pub use sc_executor::NativeElseWasmExecutor; pub use sc_executor::NativeElseWasmExecutor;
use sc_finality_grandpa::SharedVoterState; use sc_finality_grandpa::SharedVoterState;
@@ -140,7 +140,7 @@ pub fn new_partial(
let slot_duration = sc_consensus_aura::slot_duration(&*client)?; let slot_duration = sc_consensus_aura::slot_duration(&*client)?;
let import_queue = let import_queue =
sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _, _>(ImportQueueParams { sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _>(ImportQueueParams {
block_import: beefy_block_import, block_import: beefy_block_import,
justification_import: Some(Box::new(grandpa_block_import.clone())), justification_import: Some(Box::new(grandpa_block_import.clone())),
client: client.clone(), client: client.clone(),
@@ -153,12 +153,9 @@ pub fn new_partial(
slot_duration, slot_duration,
); );
Ok((timestamp, slot)) Ok((slot, timestamp))
}, },
spawner: &task_manager.spawn_essential_handle(), spawner: &task_manager.spawn_essential_handle(),
can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(
client.executor().clone(),
),
registry: config.prometheus_registry(), registry: config.prometheus_registry(),
check_for_equivocation: Default::default(), check_for_equivocation: Default::default(),
telemetry: telemetry.as_ref().map(|x| x.handle()), telemetry: telemetry.as_ref().map(|x| x.handle()),
@@ -207,6 +204,8 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
}; };
} }
let genesis_hash = client.block_hash(0).ok().flatten().expect("Genesis block exists; qed");
// Note: GrandPa is pushed before the Polkadot-specific protocols. This doesn't change // Note: GrandPa is pushed before the Polkadot-specific protocols. This doesn't change
// anything in terms of behaviour, but makes the logs more consistent with the other // anything in terms of behaviour, but makes the logs more consistent with the other
// Substrate nodes. // Substrate nodes.
@@ -219,14 +218,21 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
.extra_sets .extra_sets
.push(sc_finality_grandpa::grandpa_peers_set_config(grandpa_protocol_name.clone())); .push(sc_finality_grandpa::grandpa_peers_set_config(grandpa_protocol_name.clone()));
let beefy_protocol_name = beefy_gadget::protocol_standard_name( let beefy_gossip_proto_name =
&client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"), beefy_gadget::gossip_protocol_name(genesis_hash, config.chain_spec.fork_id());
&config.chain_spec, // `beefy_on_demand_justifications_handler` is given to `beefy-gadget` task to be run,
); // while `beefy_req_resp_cfg` is added to `config.network.request_response_protocols`.
let (beefy_on_demand_justifications_handler, beefy_req_resp_cfg) =
beefy_gadget::communication::request_response::BeefyJustifsRequestHandler::new(
genesis_hash,
config.chain_spec.fork_id(),
client.clone(),
);
config config
.network .network
.extra_sets .extra_sets
.push(beefy_gadget::beefy_peers_set_config(beefy_protocol_name.clone())); .push(beefy_gadget::communication::beefy_peers_set_config(beefy_gossip_proto_name.clone()));
config.network.request_response_protocols.push(beefy_req_resp_cfg);
let warp_sync = Arc::new(sc_finality_grandpa::warp_proof::NetworkProvider::new( let warp_sync = Arc::new(sc_finality_grandpa::warp_proof::NetworkProvider::new(
backend.clone(), backend.clone(),
@@ -234,7 +240,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
Vec::default(), Vec::default(),
)); ));
let (network, system_rpc_tx, network_starter) = let (network, system_rpc_tx, tx_handler_controller, network_starter) =
sc_service::build_network(sc_service::BuildNetworkParams { sc_service::build_network(sc_service::BuildNetworkParams {
config: &config, config: &config,
client: client.clone(), client: client.clone(),
@@ -327,6 +333,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
backend: backend.clone(), backend: backend.clone(),
system_rpc_tx, system_rpc_tx,
config, config,
tx_handler_controller,
telemetry: telemetry.as_mut(), telemetry: telemetry.as_mut(),
})?; })?;
@@ -339,12 +346,9 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
telemetry.as_ref().map(|x| x.handle()), telemetry.as_ref().map(|x| x.handle()),
); );
let can_author_with =
sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());
let slot_duration = sc_consensus_aura::slot_duration(&*client)?; let slot_duration = sc_consensus_aura::slot_duration(&*client)?;
let aura = sc_consensus_aura::start_aura::<AuraPair, _, _, _, _, _, _, _, _, _, _, _>( let aura = sc_consensus_aura::start_aura::<AuraPair, _, _, _, _, _, _, _, _, _, _>(
StartAuraParams { StartAuraParams {
slot_duration, slot_duration,
client: client.clone(), client: client.clone(),
@@ -360,12 +364,11 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
slot_duration, slot_duration,
); );
Ok((timestamp, slot)) Ok((slot, timestamp))
}, },
force_authoring, force_authoring,
backoff_authoring_blocks, backoff_authoring_blocks,
keystore: keystore_container.sync_keystore(), keystore: keystore_container.sync_keystore(),
can_author_with,
sync_oracle: network.clone(), sync_oracle: network.clone(),
justification_sync_link: network.clone(), justification_sync_link: network.clone(),
block_proposal_slot_portion: SlotProportion::new(2f32 / 3f32), block_proposal_slot_portion: SlotProportion::new(2f32 / 3f32),
@@ -386,23 +389,31 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
let keystore = let keystore =
if role.is_authority() { Some(keystore_container.sync_keystore()) } else { None }; if role.is_authority() { Some(keystore_container.sync_keystore()) } else { None };
let justifications_protocol_name = beefy_on_demand_justifications_handler.protocol_name();
let payload_provider = beefy_primitives::mmr::MmrRootProvider::new(client.clone());
let beefy_params = beefy_gadget::BeefyParams { let beefy_params = beefy_gadget::BeefyParams {
client: client.clone(), client: client.clone(),
backend, backend,
payload_provider,
runtime: client, runtime: client,
key_store: keystore.clone(), key_store: keystore.clone(),
network: network.clone(), network_params: beefy_gadget::BeefyNetworkParams {
network: network.clone(),
gossip_protocol_name: beefy_gossip_proto_name,
justifications_protocol_name,
_phantom: core::marker::PhantomData::<Block>,
},
min_block_delta: 2, min_block_delta: 2,
prometheus_registry: prometheus_registry.clone(), prometheus_registry: prometheus_registry.clone(),
protocol_name: beefy_protocol_name,
links: beefy_voter_links, links: beefy_voter_links,
on_demand_justifications_handler: beefy_on_demand_justifications_handler,
}; };
// Start the BEEFY bridge gadget. // Start the BEEFY bridge gadget.
task_manager.spawn_essential_handle().spawn_blocking( task_manager.spawn_essential_handle().spawn_blocking(
"beefy-gadget", "beefy-gadget",
None, None,
beefy_gadget::start_beefy_gadget::<_, _, _, _, _>(beefy_params), beefy_gadget::start_beefy_gadget::<_, _, _, _, _, _>(beefy_params),
); );
let grandpa_config = sc_finality_grandpa::Config { let grandpa_config = sc_finality_grandpa::Config {
+44 -24
View File
@@ -69,11 +69,12 @@ pub use bridge_runtime_common;
// A few exports that help ease life for downstream crates. // A few exports that help ease life for downstream crates.
pub use frame_support::{ pub use frame_support::{
construct_runtime, parameter_types, construct_runtime,
dispatch::DispatchClass,
parameter_types,
traits::{Currency, ExistenceRequirement, Imbalance, KeyOwnerProofSystem}, traits::{Currency, ExistenceRequirement, Imbalance, KeyOwnerProofSystem},
weights::{ weights::{
constants::WEIGHT_PER_SECOND, ConstantMultiplier, DispatchClass, IdentityFee, constants::WEIGHT_PER_SECOND, ConstantMultiplier, IdentityFee, RuntimeDbWeight, Weight,
RuntimeDbWeight, Weight,
}, },
RuntimeDebug, StorageValue, RuntimeDebug, StorageValue,
}; };
@@ -177,7 +178,7 @@ impl frame_system::Config for Runtime {
/// The identifier used to distinguish between accounts. /// The identifier used to distinguish between accounts.
type AccountId = AccountId; type AccountId = AccountId;
/// The aggregated dispatch type that is available for extrinsics. /// The aggregated dispatch type that is available for extrinsics.
type Call = Call; type RuntimeCall = RuntimeCall;
/// The lookup mechanism to get account ID from whatever is passed in dispatchers. /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
type Lookup = IdentityLookup<AccountId>; type Lookup = IdentityLookup<AccountId>;
/// The index type for storing how many extrinsics an account has signed. /// The index type for storing how many extrinsics an account has signed.
@@ -191,9 +192,9 @@ impl frame_system::Config for Runtime {
/// The header type. /// The header type.
type Header = generic::Header<BlockNumber, Hashing>; type Header = generic::Header<BlockNumber, Hashing>;
/// The ubiquitous event type. /// The ubiquitous event type.
type Event = Event; type RuntimeEvent = RuntimeEvent;
/// The ubiquitous origin type. /// The ubiquitous origin type.
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first). /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
/// Version of the runtime. /// Version of the runtime.
@@ -241,8 +242,7 @@ impl pallet_beefy::Config for Runtime {
} }
impl pallet_grandpa::Config for Runtime { impl pallet_grandpa::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type Call = Call;
type KeyOwnerProofSystem = (); type KeyOwnerProofSystem = ();
type KeyOwnerProof = type KeyOwnerProof =
<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof; <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
@@ -331,7 +331,7 @@ impl pallet_balances::Config for Runtime {
/// The type for recording an account's balance. /// The type for recording an account's balance.
type Balance = Balance; type Balance = Balance;
/// The ubiquitous event type. /// The ubiquitous event type.
type Event = Event; type RuntimeEvent = RuntimeEvent;
type DustRemoval = (); type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit; type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System; type AccountStore = System;
@@ -351,6 +351,7 @@ parameter_types! {
pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25); pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25);
pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(3, 100_000); pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(3, 100_000);
pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 1_000_000u128); pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 1_000_000u128);
pub MaximumMultiplier: Multiplier = sp_runtime::traits::Bounded::max_value();
} }
impl pallet_transaction_payment::Config for Runtime { impl pallet_transaction_payment::Config for Runtime {
@@ -363,13 +364,14 @@ impl pallet_transaction_payment::Config for Runtime {
TargetBlockFullness, TargetBlockFullness,
AdjustmentVariable, AdjustmentVariable,
MinimumMultiplier, MinimumMultiplier,
MaximumMultiplier,
>; >;
type Event = Event; type RuntimeEvent = RuntimeEvent;
} }
impl pallet_sudo::Config for Runtime { impl pallet_sudo::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type Call = Call; type RuntimeCall = RuntimeCall;
} }
parameter_types! { parameter_types! {
@@ -379,7 +381,7 @@ parameter_types! {
} }
impl pallet_session::Config for Runtime { impl pallet_session::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type ValidatorId = <Self as frame_system::Config>::AccountId; type ValidatorId = <Self as frame_system::Config>::AccountId;
type ValidatorIdOf = (); type ValidatorIdOf = ();
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>; type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
@@ -400,7 +402,7 @@ parameter_types! {
} }
impl pallet_bridge_relayers::Config for Runtime { impl pallet_bridge_relayers::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type Reward = Balance; type Reward = Balance;
type PaymentProcedure = bp_relayers::MintReward<pallet_balances::Pallet<Runtime>, AccountId>; type PaymentProcedure = bp_relayers::MintReward<pallet_balances::Pallet<Runtime>, AccountId>;
type WeightInfo = (); type WeightInfo = ();
@@ -470,7 +472,7 @@ parameter_types! {
bp_rialto::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; bp_rialto::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;
// `IdentityFee` is used by Millau => we may use weight directly // `IdentityFee` is used by Millau => we may use weight directly
pub const GetDeliveryConfirmationTransactionFee: Balance = pub const GetDeliveryConfirmationTransactionFee: Balance =
bp_millau::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT as _; bp_millau::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT.ref_time() as _;
pub const RootAccountForPayments: Option<AccountId> = None; pub const RootAccountForPayments: Option<AccountId> = None;
pub const RialtoChainId: bp_runtime::ChainId = bp_runtime::RIALTO_CHAIN_ID; pub const RialtoChainId: bp_runtime::ChainId = bp_runtime::RIALTO_CHAIN_ID;
pub const RialtoParachainChainId: bp_runtime::ChainId = bp_runtime::RIALTO_PARACHAIN_CHAIN_ID; pub const RialtoParachainChainId: bp_runtime::ChainId = bp_runtime::RIALTO_PARACHAIN_CHAIN_ID;
@@ -480,7 +482,7 @@ parameter_types! {
pub type WithRialtoMessagesInstance = (); pub type WithRialtoMessagesInstance = ();
impl pallet_bridge_messages::Config<WithRialtoMessagesInstance> for Runtime { impl pallet_bridge_messages::Config<WithRialtoMessagesInstance> for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_bridge_messages::weights::BridgeWeight<Runtime>; type WeightInfo = pallet_bridge_messages::weights::BridgeWeight<Runtime>;
type Parameter = rialto_messages::MillauToRialtoMessagesParameter; type Parameter = rialto_messages::MillauToRialtoMessagesParameter;
type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce;
@@ -515,7 +517,7 @@ impl pallet_bridge_messages::Config<WithRialtoMessagesInstance> for Runtime {
pub type WithRialtoParachainMessagesInstance = pallet_bridge_messages::Instance1; pub type WithRialtoParachainMessagesInstance = pallet_bridge_messages::Instance1;
impl pallet_bridge_messages::Config<WithRialtoParachainMessagesInstance> for Runtime { impl pallet_bridge_messages::Config<WithRialtoParachainMessagesInstance> for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_bridge_messages::weights::BridgeWeight<Runtime>; type WeightInfo = pallet_bridge_messages::weights::BridgeWeight<Runtime>;
type Parameter = rialto_parachain_messages::MillauToRialtoParachainMessagesParameter; type Parameter = rialto_parachain_messages::MillauToRialtoParachainMessagesParameter;
type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce;
@@ -558,7 +560,7 @@ parameter_types! {
pub type WithRialtoParachainsInstance = (); pub type WithRialtoParachainsInstance = ();
impl pallet_bridge_parachains::Config<WithRialtoParachainsInstance> for Runtime { impl pallet_bridge_parachains::Config<WithRialtoParachainsInstance> for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_bridge_parachains::weights::BridgeWeight<Runtime>; type WeightInfo = pallet_bridge_parachains::weights::BridgeWeight<Runtime>;
type BridgesGrandpaPalletInstance = RialtoGrandpaInstance; type BridgesGrandpaPalletInstance = RialtoGrandpaInstance;
type ParasPalletName = RialtoParasPalletName; type ParasPalletName = RialtoParasPalletName;
@@ -571,7 +573,7 @@ impl pallet_bridge_parachains::Config<WithRialtoParachainsInstance> for Runtime
pub type WithWestendParachainsInstance = pallet_bridge_parachains::Instance1; pub type WithWestendParachainsInstance = pallet_bridge_parachains::Instance1;
impl pallet_bridge_parachains::Config<WithWestendParachainsInstance> for Runtime { impl pallet_bridge_parachains::Config<WithWestendParachainsInstance> for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_bridge_parachains::weights::BridgeWeight<Runtime>; type WeightInfo = pallet_bridge_parachains::weights::BridgeWeight<Runtime>;
type BridgesGrandpaPalletInstance = WestendGrandpaInstance; type BridgesGrandpaPalletInstance = WestendGrandpaInstance;
type ParasPalletName = WestendParasPalletName; type ParasPalletName = WestendParasPalletName;
@@ -626,7 +628,7 @@ construct_runtime!(
); );
generate_bridge_reject_obsolete_headers_and_messages! { generate_bridge_reject_obsolete_headers_and_messages! {
Call, AccountId, RuntimeCall, AccountId,
// Grandpa // Grandpa
BridgeRialtoGrandpa, BridgeWestendGrandpa, BridgeRialtoGrandpa, BridgeWestendGrandpa,
// Parachains // Parachains
@@ -658,11 +660,12 @@ pub type SignedExtra = (
BridgeRejectObsoleteHeadersAndMessages, BridgeRejectObsoleteHeadersAndMessages,
); );
/// The payload being signed in transactions. /// The payload being signed in transactions.
pub type SignedPayload = generic::SignedPayload<Call, SignedExtra>; pub type SignedPayload = generic::SignedPayload<RuntimeCall, SignedExtra>;
/// Unchecked extrinsic type as expected by this runtime. /// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>; pub type UncheckedExtrinsic =
generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
/// Extrinsic type that has already been checked. /// Extrinsic type that has already been checked.
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>; pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
/// Executive: handles dispatch to the various modules. /// Executive: handles dispatch to the various modules.
pub type Executive = frame_executive::Executive< pub type Executive = frame_executive::Executive<
Runtime, Runtime,
@@ -821,6 +824,23 @@ impl_runtime_apis! {
.map(|(leaves, proof)| (leaves.into_iter().map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf)).collect(), proof)) .map(|(leaves, proof)| (leaves.into_iter().map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf)).collect(), proof))
} }
fn generate_historical_batch_proof(
leaf_indices: Vec<mmr::LeafIndex>,
leaves_count: mmr::LeafIndex,
) -> Result<(Vec<mmr::EncodableOpaqueLeaf>, mmr::BatchProof<mmr::Hash>), mmr::Error> {
Mmr::generate_historical_batch_proof(leaf_indices, leaves_count).map(
|(leaves, proof)| {
(
leaves
.into_iter()
.map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf))
.collect(),
proof,
)
},
)
}
fn verify_batch_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::BatchProof<mmr::Hash>) fn verify_batch_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::BatchProof<mmr::Hash>)
-> Result<(), mmr::Error> -> Result<(), mmr::Error>
{ {
@@ -1151,6 +1171,6 @@ mod tests {
BRIDGES_PALLETS_MAX_CALL_SIZE BRIDGES_PALLETS_MAX_CALL_SIZE
); );
const MAX_CALL_SIZE: usize = 230; // value from polkadot-runtime tests const MAX_CALL_SIZE: usize = 230; // value from polkadot-runtime tests
assert!(core::mem::size_of::<Call>() <= MAX_CALL_SIZE); assert!(core::mem::size_of::<RuntimeCall>() <= MAX_CALL_SIZE);
} }
} }
@@ -16,7 +16,7 @@
//! Everything required to serve Millau <-> Rialto messages. //! Everything required to serve Millau <-> Rialto messages.
use crate::{Call, OriginCaller, Runtime}; use crate::{OriginCaller, Runtime, RuntimeCall, RuntimeOrigin};
use bp_messages::{ use bp_messages::{
source_chain::{SenderOrigin, TargetHeaderChain}, source_chain::{SenderOrigin, TargetHeaderChain},
@@ -28,11 +28,7 @@ use bridge_runtime_common::messages::{
self, BasicConfirmationTransactionEstimation, MessageBridge, MessageTransaction, self, BasicConfirmationTransactionEstimation, MessageBridge, MessageTransaction,
}; };
use codec::{Decode, Encode}; use codec::{Decode, Encode};
use frame_support::{ use frame_support::{dispatch::DispatchClass, parameter_types, weights::Weight, RuntimeDebug};
parameter_types,
weights::{DispatchClass, Weight},
RuntimeDebug,
};
use scale_info::TypeInfo; use scale_info::TypeInfo;
use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128};
use sp_std::convert::TryFrom; use sp_std::convert::TryFrom;
@@ -47,13 +43,18 @@ pub const INITIAL_RIALTO_FEE_MULTIPLIER: FixedU128 = FixedU128::from_inner(Fixed
/// Weight of 2 XCM instructions is for simple `Trap(42)` program, coming through bridge /// Weight of 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction). It is used just for simplest manual /// (it is prepended with `UniversalOrigin` instruction). It is used just for simplest manual
/// tests, confirming that we don't break encoding somewhere between. /// tests, confirming that we don't break encoding somewhere between.
pub const BASE_XCM_WEIGHT_TWICE: Weight = 2 * crate::xcm_config::BASE_XCM_WEIGHT; pub const BASE_XCM_WEIGHT_TWICE: u64 = 2 * crate::xcm_config::BASE_XCM_WEIGHT;
parameter_types! { parameter_types! {
/// Rialto to Millau conversion rate. Initially we treat both tokens as equal. /// Rialto to Millau conversion rate. Initially we treat both tokens as equal.
pub storage RialtoToMillauConversionRate: FixedU128 = INITIAL_RIALTO_TO_MILLAU_CONVERSION_RATE; pub storage RialtoToMillauConversionRate: FixedU128 = INITIAL_RIALTO_TO_MILLAU_CONVERSION_RATE;
/// Fee multiplier value at Rialto chain. /// Fee multiplier value at Rialto chain.
pub storage RialtoFeeMultiplier: FixedU128 = INITIAL_RIALTO_FEE_MULTIPLIER; pub storage RialtoFeeMultiplier: FixedU128 = INITIAL_RIALTO_FEE_MULTIPLIER;
/// Weight credit for our test messages.
///
/// 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction).
pub const WeightCredit: Weight = Weight::from_ref_time(BASE_XCM_WEIGHT_TWICE);
} }
/// Message payload for Millau -> Rialto messages. /// Message payload for Millau -> Rialto messages.
@@ -64,7 +65,7 @@ pub type ToRialtoMessageVerifier =
messages::source::FromThisChainMessageVerifier<WithRialtoMessageBridge>; messages::source::FromThisChainMessageVerifier<WithRialtoMessageBridge>;
/// Message payload for Rialto -> Millau messages. /// Message payload for Rialto -> Millau messages.
pub type FromRialtoMessagePayload = messages::target::FromBridgedChainMessagePayload<Call>; pub type FromRialtoMessagePayload = messages::target::FromBridgedChainMessagePayload<RuntimeCall>;
/// Messages proof for Rialto -> Millau messages. /// Messages proof for Rialto -> Millau messages.
pub type FromRialtoMessagesProof = messages::target::FromBridgedChainMessagesProof<bp_rialto::Hash>; pub type FromRialtoMessagesProof = messages::target::FromBridgedChainMessagesProof<bp_rialto::Hash>;
@@ -78,9 +79,7 @@ pub type FromRialtoMessageDispatch = messages::target::FromBridgedChainMessageDi
WithRialtoMessageBridge, WithRialtoMessageBridge,
xcm_executor::XcmExecutor<crate::xcm_config::XcmConfig>, xcm_executor::XcmExecutor<crate::xcm_config::XcmConfig>,
crate::xcm_config::XcmWeigher, crate::xcm_config::XcmWeigher,
// 2 XCM instructions is for simple `Trap(42)` program, coming through bridge WeightCredit,
// (it is prepended with `UniversalOrigin` instruction)
frame_support::traits::ConstU64<BASE_XCM_WEIGHT_TWICE>,
>; >;
/// Maximal outbound payload size of Millau -> Rialto messages. /// Maximal outbound payload size of Millau -> Rialto messages.
@@ -120,21 +119,20 @@ impl messages::ChainWithMessages for Millau {
type AccountId = bp_millau::AccountId; type AccountId = bp_millau::AccountId;
type Signer = bp_millau::AccountSigner; type Signer = bp_millau::AccountSigner;
type Signature = bp_millau::Signature; type Signature = bp_millau::Signature;
type Weight = Weight;
type Balance = bp_millau::Balance; type Balance = bp_millau::Balance;
} }
impl messages::ThisChainWithMessages for Millau { impl messages::ThisChainWithMessages for Millau {
type Origin = crate::Origin; type RuntimeOrigin = RuntimeOrigin;
type Call = crate::Call; type RuntimeCall = RuntimeCall;
type ConfirmationTransactionEstimation = BasicConfirmationTransactionEstimation< type ConfirmationTransactionEstimation = BasicConfirmationTransactionEstimation<
Self::AccountId, Self::AccountId,
{ bp_millau::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT }, { bp_millau::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT.ref_time() },
{ bp_rialto::EXTRA_STORAGE_PROOF_SIZE }, { bp_rialto::EXTRA_STORAGE_PROOF_SIZE },
{ bp_millau::TX_EXTRA_BYTES }, { bp_millau::TX_EXTRA_BYTES },
>; >;
fn is_message_accepted(send_origin: &Self::Origin, lane: &LaneId) -> bool { fn is_message_accepted(send_origin: &Self::RuntimeOrigin, lane: &LaneId) -> bool {
let here_location = let here_location =
xcm::v3::MultiLocation::from(crate::xcm_config::UniversalLocation::get()); xcm::v3::MultiLocation::from(crate::xcm_config::UniversalLocation::get());
match send_origin.caller { match send_origin.caller {
@@ -168,7 +166,7 @@ impl messages::ThisChainWithMessages for Millau {
bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic, bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
1, 1,
multiplier, multiplier,
|weight| weight as _, |weight| weight.ref_time() as _,
transaction, transaction,
) )
} }
@@ -183,7 +181,6 @@ impl messages::ChainWithMessages for Rialto {
type AccountId = bp_rialto::AccountId; type AccountId = bp_rialto::AccountId;
type Signer = bp_rialto::AccountSigner; type Signer = bp_rialto::AccountSigner;
type Signature = bp_rialto::Signature; type Signature = bp_rialto::Signature;
type Weight = Weight;
type Balance = bp_rialto::Balance; type Balance = bp_rialto::Balance;
} }
@@ -202,15 +199,15 @@ impl messages::BridgedChainWithMessages for Rialto {
message_dispatch_weight: Weight, message_dispatch_weight: Weight,
) -> MessageTransaction<Weight> { ) -> MessageTransaction<Weight> {
let message_payload_len = u32::try_from(message_payload.len()).unwrap_or(u32::MAX); let message_payload_len = u32::try_from(message_payload.len()).unwrap_or(u32::MAX);
let extra_bytes_in_payload = Weight::from(message_payload_len) let extra_bytes_in_payload = message_payload_len
.saturating_sub(pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH.into()); .saturating_sub(pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH);
MessageTransaction { MessageTransaction {
dispatch_weight: extra_bytes_in_payload dispatch_weight: bp_rialto::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT
.saturating_mul(bp_rialto::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT) .saturating_mul(extra_bytes_in_payload as u64)
.saturating_add(bp_rialto::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT) .saturating_add(bp_rialto::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT)
.saturating_sub(if include_pay_dispatch_fee_cost { .saturating_sub(if include_pay_dispatch_fee_cost {
0 Weight::from_ref_time(0)
} else { } else {
bp_rialto::PAY_INBOUND_DISPATCH_FEE_WEIGHT bp_rialto::PAY_INBOUND_DISPATCH_FEE_WEIGHT
}) })
@@ -230,7 +227,7 @@ impl messages::BridgedChainWithMessages for Rialto {
bp_rialto::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic, bp_rialto::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
1, 1,
multiplier, multiplier,
|weight| weight as _, |weight| weight.ref_time() as _,
transaction, transaction,
) )
} }
@@ -280,7 +277,7 @@ impl SourceHeaderChain<bp_rialto::Balance> for Rialto {
} }
} }
impl SenderOrigin<crate::AccountId> for crate::Origin { impl SenderOrigin<crate::AccountId> for RuntimeOrigin {
fn linked_account(&self) -> Option<crate::AccountId> { fn linked_account(&self) -> Option<crate::AccountId> {
// XCM deals wit fees in our deployments // XCM deals wit fees in our deployments
None None
@@ -16,7 +16,7 @@
//! Everything required to serve Millau <-> RialtoParachain messages. //! Everything required to serve Millau <-> RialtoParachain messages.
use crate::Runtime; use crate::{Runtime, RuntimeCall, RuntimeOrigin};
use bp_messages::{ use bp_messages::{
source_chain::TargetHeaderChain, source_chain::TargetHeaderChain,
@@ -29,11 +29,7 @@ use bridge_runtime_common::messages::{
self, BasicConfirmationTransactionEstimation, MessageBridge, MessageTransaction, self, BasicConfirmationTransactionEstimation, MessageBridge, MessageTransaction,
}; };
use codec::{Decode, Encode}; use codec::{Decode, Encode};
use frame_support::{ use frame_support::{dispatch::DispatchClass, parameter_types, weights::Weight, RuntimeDebug};
parameter_types,
weights::{DispatchClass, Weight},
RuntimeDebug,
};
use scale_info::TypeInfo; use scale_info::TypeInfo;
use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128};
use sp_std::convert::TryFrom; use sp_std::convert::TryFrom;
@@ -43,7 +39,7 @@ pub const DEFAULT_XCM_LANE_TO_RIALTO_PARACHAIN: LaneId = [0, 0, 0, 0];
/// Weight of 2 XCM instructions is for simple `Trap(42)` program, coming through bridge /// Weight of 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction). It is used just for simplest manual /// (it is prepended with `UniversalOrigin` instruction). It is used just for simplest manual
/// tests, confirming that we don't break encoding somewhere between. /// tests, confirming that we don't break encoding somewhere between.
pub const BASE_XCM_WEIGHT_TWICE: Weight = 2 * crate::xcm_config::BASE_XCM_WEIGHT; pub const BASE_XCM_WEIGHT_TWICE: u64 = 2 * crate::xcm_config::BASE_XCM_WEIGHT;
/// Initial value of `RialtoParachainToMillauConversionRate` parameter. /// Initial value of `RialtoParachainToMillauConversionRate` parameter.
pub const INITIAL_RIALTO_PARACHAIN_TO_MILLAU_CONVERSION_RATE: FixedU128 = pub const INITIAL_RIALTO_PARACHAIN_TO_MILLAU_CONVERSION_RATE: FixedU128 =
@@ -57,6 +53,11 @@ parameter_types! {
pub storage RialtoParachainToMillauConversionRate: FixedU128 = INITIAL_RIALTO_PARACHAIN_TO_MILLAU_CONVERSION_RATE; pub storage RialtoParachainToMillauConversionRate: FixedU128 = INITIAL_RIALTO_PARACHAIN_TO_MILLAU_CONVERSION_RATE;
/// Fee multiplier value at RialtoParachain chain. /// Fee multiplier value at RialtoParachain chain.
pub storage RialtoParachainFeeMultiplier: FixedU128 = INITIAL_RIALTO_PARACHAIN_FEE_MULTIPLIER; pub storage RialtoParachainFeeMultiplier: FixedU128 = INITIAL_RIALTO_PARACHAIN_FEE_MULTIPLIER;
/// Weight credit for our test messages.
///
/// 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction).
pub const WeightCredit: Weight = Weight::from_ref_time(BASE_XCM_WEIGHT_TWICE);
} }
/// Message payload for Millau -> RialtoParachain messages. /// Message payload for Millau -> RialtoParachain messages.
@@ -68,7 +69,7 @@ pub type ToRialtoParachainMessageVerifier =
/// Message payload for RialtoParachain -> Millau messages. /// Message payload for RialtoParachain -> Millau messages.
pub type FromRialtoParachainMessagePayload = pub type FromRialtoParachainMessagePayload =
messages::target::FromBridgedChainMessagePayload<crate::Call>; messages::target::FromBridgedChainMessagePayload<RuntimeCall>;
/// Messages proof for RialtoParachain -> Millau messages. /// Messages proof for RialtoParachain -> Millau messages.
type FromRialtoParachainMessagesProof = type FromRialtoParachainMessagesProof =
@@ -83,9 +84,7 @@ pub type FromRialtoParachainMessageDispatch = messages::target::FromBridgedChain
WithRialtoParachainMessageBridge, WithRialtoParachainMessageBridge,
xcm_executor::XcmExecutor<crate::xcm_config::XcmConfig>, xcm_executor::XcmExecutor<crate::xcm_config::XcmConfig>,
crate::xcm_config::XcmWeigher, crate::xcm_config::XcmWeigher,
// 2 XCM instructions is for simple `Trap(42)` program, coming through bridge WeightCredit,
// (it is prepended with `UniversalOrigin` instruction)
frame_support::traits::ConstU64<BASE_XCM_WEIGHT_TWICE>,
>; >;
/// Maximal outbound payload size of Millau -> RialtoParachain messages. /// Maximal outbound payload size of Millau -> RialtoParachain messages.
@@ -125,21 +124,20 @@ impl messages::ChainWithMessages for Millau {
type AccountId = bp_millau::AccountId; type AccountId = bp_millau::AccountId;
type Signer = bp_millau::AccountSigner; type Signer = bp_millau::AccountSigner;
type Signature = bp_millau::Signature; type Signature = bp_millau::Signature;
type Weight = Weight;
type Balance = bp_millau::Balance; type Balance = bp_millau::Balance;
} }
impl messages::ThisChainWithMessages for Millau { impl messages::ThisChainWithMessages for Millau {
type Call = crate::Call; type RuntimeCall = RuntimeCall;
type Origin = crate::Origin; type RuntimeOrigin = RuntimeOrigin;
type ConfirmationTransactionEstimation = BasicConfirmationTransactionEstimation< type ConfirmationTransactionEstimation = BasicConfirmationTransactionEstimation<
Self::AccountId, Self::AccountId,
{ bp_millau::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT }, { bp_millau::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT.ref_time() },
{ bp_rialto_parachain::EXTRA_STORAGE_PROOF_SIZE }, { bp_rialto_parachain::EXTRA_STORAGE_PROOF_SIZE },
{ bp_millau::TX_EXTRA_BYTES }, { bp_millau::TX_EXTRA_BYTES },
>; >;
fn is_message_accepted(_send_origin: &Self::Origin, lane: &LaneId) -> bool { fn is_message_accepted(_send_origin: &Self::RuntimeOrigin, lane: &LaneId) -> bool {
*lane == DEFAULT_XCM_LANE_TO_RIALTO_PARACHAIN || *lane == [0, 0, 0, 1] *lane == DEFAULT_XCM_LANE_TO_RIALTO_PARACHAIN || *lane == [0, 0, 0, 1]
} }
@@ -157,7 +155,7 @@ impl messages::ThisChainWithMessages for Millau {
bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic, bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
1, 1,
multiplier, multiplier,
|weight| weight as _, |weight| weight.ref_time() as _,
transaction, transaction,
) )
} }
@@ -172,7 +170,6 @@ impl messages::ChainWithMessages for RialtoParachain {
type AccountId = bp_rialto_parachain::AccountId; type AccountId = bp_rialto_parachain::AccountId;
type Signer = bp_rialto_parachain::AccountSigner; type Signer = bp_rialto_parachain::AccountSigner;
type Signature = bp_rialto_parachain::Signature; type Signature = bp_rialto_parachain::Signature;
type Weight = Weight;
type Balance = bp_rialto_parachain::Balance; type Balance = bp_rialto_parachain::Balance;
} }
@@ -191,15 +188,15 @@ impl messages::BridgedChainWithMessages for RialtoParachain {
message_dispatch_weight: Weight, message_dispatch_weight: Weight,
) -> MessageTransaction<Weight> { ) -> MessageTransaction<Weight> {
let message_payload_len = u32::try_from(message_payload.len()).unwrap_or(u32::MAX); let message_payload_len = u32::try_from(message_payload.len()).unwrap_or(u32::MAX);
let extra_bytes_in_payload = Weight::from(message_payload_len) let extra_bytes_in_payload = message_payload_len
.saturating_sub(pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH.into()); .saturating_sub(pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH);
MessageTransaction { MessageTransaction {
dispatch_weight: extra_bytes_in_payload dispatch_weight: bp_rialto_parachain::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT
.saturating_mul(bp_rialto_parachain::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT) .saturating_mul(extra_bytes_in_payload as _)
.saturating_add(bp_rialto_parachain::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT) .saturating_add(bp_rialto_parachain::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT)
.saturating_sub(if include_pay_dispatch_fee_cost { .saturating_sub(if include_pay_dispatch_fee_cost {
0 Weight::from_ref_time(0)
} else { } else {
bp_rialto_parachain::PAY_INBOUND_DISPATCH_FEE_WEIGHT bp_rialto_parachain::PAY_INBOUND_DISPATCH_FEE_WEIGHT
}) })
@@ -223,7 +220,7 @@ impl messages::BridgedChainWithMessages for RialtoParachain {
.base_extrinsic, .base_extrinsic,
1, 1,
multiplier, multiplier,
|weight| weight as _, |weight| weight.ref_time() as _,
transaction, transaction,
) )
} }
+24 -21
View File
@@ -21,7 +21,7 @@ use super::{
rialto_parachain_messages::{ rialto_parachain_messages::{
WithRialtoParachainMessageBridge, DEFAULT_XCM_LANE_TO_RIALTO_PARACHAIN, WithRialtoParachainMessageBridge, DEFAULT_XCM_LANE_TO_RIALTO_PARACHAIN,
}, },
AccountId, AllPalletsWithSystem, Balances, Call, Event, Origin, Runtime, AccountId, AllPalletsWithSystem, Balances, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin,
WithRialtoMessagesInstance, WithRialtoParachainMessagesInstance, XcmPallet, WithRialtoMessagesInstance, WithRialtoParachainMessagesInstance, XcmPallet,
}; };
use bp_messages::LaneId; use bp_messages::LaneId;
@@ -34,12 +34,11 @@ use bridge_runtime_common::{
use frame_support::{ use frame_support::{
parameter_types, parameter_types,
traits::{Everything, Nothing}, traits::{Everything, Nothing},
weights::Weight,
}; };
use xcm::latest::prelude::*; use xcm::latest::prelude::*;
use xcm_builder::{ use xcm_builder::{
AccountId32Aliases, AllowKnownQueryResponses, AllowTopLevelPaidExecutionFrom, AccountId32Aliases, AllowKnownQueryResponses, AllowTopLevelPaidExecutionFrom,
CurrencyAdapter as XcmCurrencyAdapter, IsConcrete, SignedAccountId32AsNative, CurrencyAdapter as XcmCurrencyAdapter, IsConcrete, MintLocation, SignedAccountId32AsNative,
SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, UsingComponents, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,
}; };
@@ -60,7 +59,7 @@ parameter_types! {
/// Since Kusama is a top-level relay-chain with its own consensus, it's just our network ID. /// Since Kusama is a top-level relay-chain with its own consensus, it's just our network ID.
pub UniversalLocation: InteriorMultiLocation = ThisNetwork::get().into(); pub UniversalLocation: InteriorMultiLocation = ThisNetwork::get().into();
/// The check account, which holds any native assets that have been teleported out and not back in (yet). /// The check account, which holds any native assets that have been teleported out and not back in (yet).
pub CheckAccount: AccountId = XcmPallet::check_account(); pub CheckAccount: (AccountId, MintLocation) = (XcmPallet::check_account(), MintLocation::Local);
} }
/// The canonical means of converting a `MultiLocation` into an `AccountId`, used when we want to /// The canonical means of converting a `MultiLocation` into an `AccountId`, used when we want to
@@ -90,17 +89,17 @@ pub type LocalAssetTransactor = XcmCurrencyAdapter<
/// The means that we convert the XCM message origin location into a local dispatch origin. /// The means that we convert the XCM message origin location into a local dispatch origin.
type LocalOriginConverter = ( type LocalOriginConverter = (
// A `Signed` origin of the sovereign account that the original location controls. // A `Signed` origin of the sovereign account that the original location controls.
SovereignSignedViaLocation<SovereignAccountOf, Origin>, SovereignSignedViaLocation<SovereignAccountOf, RuntimeOrigin>,
// The AccountId32 location type can be expressed natively as a `Signed` origin. // The AccountId32 location type can be expressed natively as a `Signed` origin.
SignedAccountId32AsNative<ThisNetwork, Origin>, SignedAccountId32AsNative<ThisNetwork, RuntimeOrigin>,
); );
/// The amount of weight an XCM operation takes. This is a safe overestimate. /// The amount of weight an XCM operation takes. This is a safe overestimate.
pub const BASE_XCM_WEIGHT: Weight = 1_000_000_000; pub const BASE_XCM_WEIGHT: u64 = 1_000_000_000;
parameter_types! { parameter_types! {
/// The amount of weight an XCM operation takes. This is a safe overestimate. /// The amount of weight an XCM operation takes. This is a safe overestimate.
pub const BaseXcmWeight: Weight = BASE_XCM_WEIGHT; pub const BaseXcmWeight: u64 = BASE_XCM_WEIGHT;
/// Maximum number of instructions in a single XCM fragment. A sanity check against weight /// Maximum number of instructions in a single XCM fragment. A sanity check against weight
/// calculations getting too crazy. /// calculations getting too crazy.
pub const MaxInstructions: u32 = 100; pub const MaxInstructions: u32 = 100;
@@ -130,11 +129,11 @@ pub type Barrier = (
); );
/// XCM weigher type. /// XCM weigher type.
pub type XcmWeigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, Call, MaxInstructions>; pub type XcmWeigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
pub struct XcmConfig; pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig { impl xcm_executor::Config for XcmConfig {
type Call = Call; type RuntimeCall = RuntimeCall;
type XcmSender = XcmRouter; type XcmSender = XcmRouter;
type AssetTransactor = LocalAssetTransactor; type AssetTransactor = LocalAssetTransactor;
type OriginConverter = LocalOriginConverter; type OriginConverter = LocalOriginConverter;
@@ -156,26 +155,26 @@ impl xcm_executor::Config for XcmConfig {
type FeeManager = (); type FeeManager = ();
type MessageExporter = (); type MessageExporter = ();
type UniversalAliases = Nothing; type UniversalAliases = Nothing;
type CallDispatcher = Call; type CallDispatcher = RuntimeCall;
} }
/// Type to convert an `Origin` type value into a `MultiLocation` value which represents an interior /// Type to convert an `Origin` type value into a `MultiLocation` value which represents an interior
/// location of this chain. /// location of this chain.
pub type LocalOriginToLocation = ( pub type LocalOriginToLocation = (
// Usual Signed origin to be used in XCM as a corresponding AccountId32 // Usual Signed origin to be used in XCM as a corresponding AccountId32
SignedToAccountId32<Origin, AccountId, ThisNetwork>, SignedToAccountId32<RuntimeOrigin, AccountId, ThisNetwork>,
); );
impl pallet_xcm::Config for Runtime { impl pallet_xcm::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
// We don't allow any messages to be sent via the transaction yet. This is basically safe to // We don't allow any messages to be sent via the transaction yet. This is basically safe to
// enable, (safe the possibility of someone spamming the parachain if they're willing to pay // enable, (safe the possibility of someone spamming the parachain if they're willing to pay
// the DOT to send from the Relay-chain). But it's useless until we bring in XCM v3 which will // the DOT to send from the Relay-chain). But it's useless until we bring in XCM v3 which will
// make `DescendOrigin` a bit more useful. // make `DescendOrigin` a bit more useful.
type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<Origin, LocalOriginToLocation>; type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmRouter = XcmRouter; type XcmRouter = XcmRouter;
// Anyone can execute XCM messages locally. // Anyone can execute XCM messages locally.
type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<Origin, LocalOriginToLocation>; type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmExecuteFilter = Everything; type XcmExecuteFilter = Everything;
type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>; type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
// Anyone is able to use teleportation regardless of who they are and what they want to // Anyone is able to use teleportation regardless of who they are and what they want to
@@ -186,8 +185,8 @@ impl pallet_xcm::Config for Runtime {
type XcmReserveTransferFilter = Everything; type XcmReserveTransferFilter = Everything;
type Weigher = XcmWeigher; type Weigher = XcmWeigher;
type UniversalLocation = UniversalLocation; type UniversalLocation = UniversalLocation;
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
type Call = Call; type RuntimeCall = RuntimeCall;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type Currency = Balances; type Currency = Balances;
@@ -253,6 +252,7 @@ impl XcmBridge for ToRialtoParachainBridge {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::rialto_messages::WeightCredit;
use bp_messages::{ use bp_messages::{
target_chain::{DispatchMessage, DispatchMessageData, MessageDispatch}, target_chain::{DispatchMessage, DispatchMessageData, MessageDispatch},
MessageKey, MessageKey,
@@ -295,13 +295,13 @@ mod tests {
WithRialtoMessageBridge, WithRialtoMessageBridge,
XcmExecutor, XcmExecutor,
XcmWeigher, XcmWeigher,
frame_support::traits::ConstU64<BASE_XCM_WEIGHT>, WeightCredit,
>; >;
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
let location: MultiLocation = let location: MultiLocation =
(Parent, X1(GlobalConsensus(RialtoNetwork::get()))).into(); (Parent, X1(GlobalConsensus(RialtoNetwork::get()))).into();
let xcm: Xcm<Call> = vec![Instruction::Trap(42)].into(); let xcm: Xcm<RuntimeCall> = vec![Instruction::Trap(42)].into();
let mut incoming_message = DispatchMessage { let mut incoming_message = DispatchMessage {
key: MessageKey { lane_id: [0, 0, 0, 0], nonce: 1 }, key: MessageKey { lane_id: [0, 0, 0, 0], nonce: 1 },
@@ -309,7 +309,10 @@ mod tests {
}; };
let dispatch_weight = MessageDispatcher::dispatch_weight(&mut incoming_message); let dispatch_weight = MessageDispatcher::dispatch_weight(&mut incoming_message);
assert_eq!(dispatch_weight, 1_000_000_000); assert_eq!(
dispatch_weight,
frame_support::weights::Weight::from_ref_time(1_000_000_000)
);
let dispatch_result = let dispatch_result =
MessageDispatcher::dispatch(&AccountId::from([0u8; 32]), incoming_message); MessageDispatcher::dispatch(&AccountId::from([0u8; 32]), incoming_message);
@@ -317,7 +320,7 @@ mod tests {
dispatch_result, dispatch_result,
MessageDispatchResult { MessageDispatchResult {
dispatch_result: true, dispatch_result: true,
unspent_weight: 0, unspent_weight: frame_support::weights::Weight::from_ref_time(0),
dispatch_fee_paid_during_dispatch: false, dispatch_fee_paid_during_dispatch: false,
} }
); );
@@ -354,7 +354,7 @@ impl CliConfiguration<Self> for RelayChainCli {
fn base_path(&self) -> Result<Option<BasePath>> { fn base_path(&self) -> Result<Option<BasePath>> {
Ok(self Ok(self
.shared_params() .shared_params()
.base_path() .base_path()?
.or_else(|| self.base_path.clone().map(Into::into))) .or_else(|| self.base_path.clone().map(Into::into)))
} }
@@ -40,7 +40,6 @@ use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;
use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface}; use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface};
// Substrate Imports // Substrate Imports
use sc_client_api::ExecutorProvider;
use sc_executor::{NativeElseWasmExecutor, NativeExecutionDispatch}; use sc_executor::{NativeElseWasmExecutor, NativeExecutionDispatch};
use sc_network::{NetworkBlock, NetworkService}; use sc_network::{NetworkBlock, NetworkService};
use sc_service::{Configuration, PartialComponents, TFullBackend, TFullClient, TaskManager}; use sc_service::{Configuration, PartialComponents, TFullBackend, TFullClient, TaskManager};
@@ -289,7 +288,7 @@ where
let prometheus_registry = parachain_config.prometheus_registry().cloned(); let prometheus_registry = parachain_config.prometheus_registry().cloned();
let transaction_pool = params.transaction_pool.clone(); let transaction_pool = params.transaction_pool.clone();
let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue); let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);
let (network, system_rpc_tx, start_network) = let (network, system_rpc_tx, tx_handler_controller, start_network) =
sc_service::build_network(sc_service::BuildNetworkParams { sc_service::build_network(sc_service::BuildNetworkParams {
config: &parachain_config, config: &parachain_config,
client: client.clone(), client: client.clone(),
@@ -318,6 +317,7 @@ where
backend: backend.clone(), backend: backend.clone(),
network: network.clone(), network: network.clone(),
system_rpc_tx, system_rpc_tx,
tx_handler_controller,
telemetry: telemetry.as_mut(), telemetry: telemetry.as_mut(),
})?; })?;
@@ -401,10 +401,9 @@ pub fn parachain_build_import_queue(
_, _,
_, _,
_, _,
_,
>(cumulus_client_consensus_aura::ImportQueueParams { >(cumulus_client_consensus_aura::ImportQueueParams {
block_import: client.clone(), block_import: client.clone(),
client: client.clone(), client,
create_inherent_data_providers: move |_, _| async move { create_inherent_data_providers: move |_, _| async move {
let time = sp_timestamp::InherentDataProvider::from_system_time(); let time = sp_timestamp::InherentDataProvider::from_system_time();
@@ -414,10 +413,9 @@ pub fn parachain_build_import_queue(
slot_duration, slot_duration,
); );
Ok((time, slot)) Ok((slot, time))
}, },
registry: config.prometheus_registry(), registry: config.prometheus_registry(),
can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),
spawner: &task_manager.spawn_essential_handle(), spawner: &task_manager.spawn_essential_handle(),
telemetry, telemetry,
}) })
@@ -496,7 +494,7 @@ pub async fn start_node(
"Failed to create parachain inherent", "Failed to create parachain inherent",
) )
})?; })?;
Ok((time, slot, parachain_inherent)) Ok((slot, time, parachain_inherent))
} }
}, },
block_import: client.clone(), block_import: client.clone(),
+49 -42
View File
@@ -52,11 +52,13 @@ use sp_version::RuntimeVersion;
// A few exports that help ease life for downstream crates. // A few exports that help ease life for downstream crates.
use bp_runtime::{HeaderId, HeaderIdProvider}; use bp_runtime::{HeaderId, HeaderIdProvider};
pub use frame_support::{ pub use frame_support::{
construct_runtime, match_types, parameter_types, construct_runtime,
dispatch::DispatchClass,
match_types, parameter_types,
traits::{Everything, IsInVec, Nothing, Randomness}, traits::{Everything, IsInVec, Nothing, Randomness},
weights::{ weights::{
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND}, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
DispatchClass, IdentityFee, Weight, IdentityFee, Weight,
}, },
StorageValue, StorageValue,
}; };
@@ -114,9 +116,10 @@ pub type SignedExtra = (
pallet_transaction_payment::ChargeTransactionPayment<Runtime>, pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
); );
/// Unchecked extrinsic type as expected by this runtime. /// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>; pub type UncheckedExtrinsic =
generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
/// Extrinsic type that has already been checked. /// Extrinsic type that has already been checked.
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>; pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
/// Executive: handles dispatch to the various modules. /// Executive: handles dispatch to the various modules.
pub type Executive = frame_executive::Executive< pub type Executive = frame_executive::Executive<
Runtime, Runtime,
@@ -188,7 +191,7 @@ impl frame_system::Config for Runtime {
/// The identifier used to distinguish between accounts. /// The identifier used to distinguish between accounts.
type AccountId = AccountId; type AccountId = AccountId;
/// The aggregated dispatch type that is available for extrinsics. /// The aggregated dispatch type that is available for extrinsics.
type Call = Call; type RuntimeCall = RuntimeCall;
/// The lookup mechanism to get account ID from whatever is passed in dispatchers. /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
type Lookup = AccountIdLookup<AccountId, ()>; type Lookup = AccountIdLookup<AccountId, ()>;
/// The index type for storing how many extrinsics an account has signed. /// The index type for storing how many extrinsics an account has signed.
@@ -202,9 +205,9 @@ impl frame_system::Config for Runtime {
/// The header type. /// The header type.
type Header = generic::Header<BlockNumber, Hashing>; type Header = generic::Header<BlockNumber, Hashing>;
/// The ubiquitous event type. /// The ubiquitous event type.
type Event = Event; type RuntimeEvent = RuntimeEvent;
/// The ubiquitous origin type. /// The ubiquitous origin type.
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first). /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
/// Runtime version. /// Runtime version.
@@ -259,7 +262,7 @@ impl pallet_balances::Config for Runtime {
/// The type for recording an account's balance. /// The type for recording an account's balance.
type Balance = Balance; type Balance = Balance;
/// The ubiquitous event type. /// The ubiquitous event type.
type Event = Event; type RuntimeEvent = RuntimeEvent;
type DustRemoval = (); type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit; type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System; type AccountStore = System;
@@ -275,21 +278,21 @@ impl pallet_transaction_payment::Config for Runtime {
type WeightToFee = IdentityFee<Balance>; type WeightToFee = IdentityFee<Balance>;
type LengthToFee = IdentityFee<Balance>; type LengthToFee = IdentityFee<Balance>;
type FeeMultiplierUpdate = (); type FeeMultiplierUpdate = ();
type Event = Event; type RuntimeEvent = RuntimeEvent;
} }
impl pallet_sudo::Config for Runtime { impl pallet_sudo::Config for Runtime {
type Call = Call; type RuntimeCall = RuntimeCall;
type Event = Event; type RuntimeEvent = RuntimeEvent;
} }
parameter_types! { parameter_types! {
pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4; pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
} }
impl cumulus_pallet_parachain_system::Config for Runtime { impl cumulus_pallet_parachain_system::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type OnSystemEvent = (); type OnSystemEvent = ();
type SelfParaId = parachain_info::Pallet<Runtime>; type SelfParaId = parachain_info::Pallet<Runtime>;
type OutboundXcmpMessageSource = XcmpQueue; type OutboundXcmpMessageSource = XcmpQueue;
@@ -309,7 +312,7 @@ impl pallet_randomness_collective_flip::Config for Runtime {}
parameter_types! { parameter_types! {
pub const RelayLocation: MultiLocation = MultiLocation::parent(); pub const RelayLocation: MultiLocation = MultiLocation::parent();
pub const RelayNetwork: NetworkId = CustomNetworkId::Rialto.as_network_id(); pub const RelayNetwork: NetworkId = CustomNetworkId::Rialto.as_network_id();
pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into(); pub RelayOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation = X1(Parachain(ParachainInfo::parachain_id().into())); pub UniversalLocation: InteriorMultiLocation = X1(Parachain(ParachainInfo::parachain_id().into()));
/// The Millau network ID. /// The Millau network ID.
pub const MillauNetwork: NetworkId = CustomNetworkId::Millau.as_network_id(); pub const MillauNetwork: NetworkId = CustomNetworkId::Millau.as_network_id();
@@ -350,31 +353,31 @@ pub type XcmOriginToTransactDispatchOrigin = (
// Sovereign account converter; this attempts to derive an `AccountId` from the origin location // Sovereign account converter; this attempts to derive an `AccountId` from the origin location
// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
// foreign chains who want to have a local sovereign account on this chain which they control. // foreign chains who want to have a local sovereign account on this chain which they control.
SovereignSignedViaLocation<LocationToAccountId, Origin>, SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when
// recognised. // recognised.
RelayChainAsNative<RelayOrigin, Origin>, RelayChainAsNative<RelayOrigin, RuntimeOrigin>,
// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
// recognised. // recognised.
SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>, SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a
// transaction from the Root origin. // transaction from the Root origin.
ParentAsSuperuser<Origin>, ParentAsSuperuser<RuntimeOrigin>,
// Native signed account converter; this just converts an `AccountId32` origin into a normal // Native signed account converter; this just converts an `AccountId32` origin into a normal
// `Origin::Signed` origin of the same 32-byte value. // `Origin::Signed` origin of the same 32-byte value.
SignedAccountId32AsNative<RelayNetwork, Origin>, SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
// Xcm origins can be represented natively under the Xcm pallet's Xcm origin. // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
XcmPassthrough<Origin>, XcmPassthrough<RuntimeOrigin>,
); );
// TODO: until https://github.com/paritytech/parity-bridges-common/issues/1417 is fixed (in either way), // TODO: until https://github.com/paritytech/parity-bridges-common/issues/1417 is fixed (in either way),
// the following constant must match the similar constant in the Millau runtime. // the following constant must match the similar constant in the Millau runtime.
/// One XCM operation is `1_000_000_000` weight - almost certainly a conservative estimate. /// One XCM operation is `1_000_000_000` weight - almost certainly a conservative estimate.
pub const BASE_XCM_WEIGHT: Weight = 1_000_000_000; pub const BASE_XCM_WEIGHT: u64 = 1_000_000_000;
parameter_types! { parameter_types! {
pub UnitWeightCost: Weight = BASE_XCM_WEIGHT; pub UnitWeightCost: u64 = BASE_XCM_WEIGHT;
// One UNIT buys 1 second of weight. // One UNIT buys 1 second of weight.
pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), UNIT); pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), UNIT);
pub const MaxInstructions: u32 = 100; pub const MaxInstructions: u32 = 100;
@@ -397,11 +400,11 @@ pub type Barrier = (
); );
/// XCM weigher type. /// XCM weigher type.
pub type XcmWeigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>; pub type XcmWeigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
pub struct XcmConfig; pub struct XcmConfig;
impl Config for XcmConfig { impl Config for XcmConfig {
type Call = Call; type RuntimeCall = RuntimeCall;
type XcmSender = XcmRouter; type XcmSender = XcmRouter;
type AssetTransactor = LocalAssetTransactor; type AssetTransactor = LocalAssetTransactor;
type OriginConverter = XcmOriginToTransactDispatchOrigin; type OriginConverter = XcmOriginToTransactDispatchOrigin;
@@ -422,11 +425,11 @@ impl Config for XcmConfig {
type FeeManager = (); type FeeManager = ();
type MessageExporter = (); type MessageExporter = ();
type UniversalAliases = Nothing; type UniversalAliases = Nothing;
type CallDispatcher = Call; type CallDispatcher = RuntimeCall;
} }
/// No local origins on this chain are allowed to dispatch XCM sends/executions. /// No local origins on this chain are allowed to dispatch XCM sends/executions.
pub type LocalOriginToLocation = SignedToAccountId32<Origin, AccountId, RelayNetwork>; pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
/// The means for routing XCM messages which are not for local execution into the right message /// The means for routing XCM messages which are not for local execution into the right message
/// queues. /// queues.
@@ -462,17 +465,17 @@ impl XcmBridge for ToMillauBridge {
} }
impl pallet_xcm::Config for Runtime { impl pallet_xcm::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>; type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmRouter = XcmRouter; type XcmRouter = XcmRouter;
type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>; type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmExecuteFilter = Everything; type XcmExecuteFilter = Everything;
type XcmExecutor = XcmExecutor<XcmConfig>; type XcmExecutor = XcmExecutor<XcmConfig>;
type XcmTeleportFilter = Everything; type XcmTeleportFilter = Everything;
type XcmReserveTransferFilter = Everything; type XcmReserveTransferFilter = Everything;
type Weigher = XcmWeigher; type Weigher = XcmWeigher;
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
type Call = Call; type RuntimeCall = RuntimeCall;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type Currency = Balances; type Currency = Balances;
@@ -484,12 +487,12 @@ impl pallet_xcm::Config for Runtime {
} }
impl cumulus_pallet_xcm::Config for Runtime { impl cumulus_pallet_xcm::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type XcmExecutor = XcmExecutor<XcmConfig>; type XcmExecutor = XcmExecutor<XcmConfig>;
} }
impl cumulus_pallet_xcmp_queue::Config for Runtime { impl cumulus_pallet_xcmp_queue::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type XcmExecutor = XcmExecutor<XcmConfig>; type XcmExecutor = XcmExecutor<XcmConfig>;
type ChannelInfo = ParachainSystem; type ChannelInfo = ParachainSystem;
type VersionWrapper = (); type VersionWrapper = ();
@@ -501,7 +504,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime {
} }
impl cumulus_pallet_dmp_queue::Config for Runtime { impl cumulus_pallet_dmp_queue::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type XcmExecutor = XcmExecutor<XcmConfig>; type XcmExecutor = XcmExecutor<XcmConfig>;
type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>; type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;
} }
@@ -513,7 +516,7 @@ impl pallet_aura::Config for Runtime {
} }
impl pallet_bridge_relayers::Config for Runtime { impl pallet_bridge_relayers::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type Reward = Balance; type Reward = Balance;
type PaymentProcedure = bp_relayers::MintReward<pallet_balances::Pallet<Runtime>, AccountId>; type PaymentProcedure = bp_relayers::MintReward<pallet_balances::Pallet<Runtime>, AccountId>;
type WeightInfo = (); type WeightInfo = ();
@@ -556,7 +559,7 @@ parameter_types! {
bp_millau::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; bp_millau::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;
// `IdentityFee` is used by Rialto => we may use weight directly // `IdentityFee` is used by Rialto => we may use weight directly
pub const GetDeliveryConfirmationTransactionFee: Balance = pub const GetDeliveryConfirmationTransactionFee: Balance =
bp_rialto_parachain::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT as _; bp_rialto_parachain::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT.ref_time() as _;
pub const RootAccountForPayments: Option<AccountId> = None; pub const RootAccountForPayments: Option<AccountId> = None;
pub const BridgedChainId: bp_runtime::ChainId = bp_runtime::MILLAU_CHAIN_ID; pub const BridgedChainId: bp_runtime::ChainId = bp_runtime::MILLAU_CHAIN_ID;
} }
@@ -565,7 +568,7 @@ parameter_types! {
pub type WithMillauMessagesInstance = (); pub type WithMillauMessagesInstance = ();
impl pallet_bridge_messages::Config<WithMillauMessagesInstance> for Runtime { impl pallet_bridge_messages::Config<WithMillauMessagesInstance> for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_bridge_messages::weights::BridgeWeight<Runtime>; type WeightInfo = pallet_bridge_messages::weights::BridgeWeight<Runtime>;
type Parameter = millau_messages::RialtoParachainToMillauMessagesParameter; type Parameter = millau_messages::RialtoParachainToMillauMessagesParameter;
type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce;
@@ -856,6 +859,7 @@ cumulus_pallet_parachain_system::register_validate_block!(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::millau_messages::WeightCredit;
use bp_messages::{ use bp_messages::{
target_chain::{DispatchMessage, DispatchMessageData, MessageDispatch}, target_chain::{DispatchMessage, DispatchMessageData, MessageDispatch},
MessageKey, MessageKey,
@@ -892,13 +896,13 @@ mod tests {
WithMillauMessageBridge, WithMillauMessageBridge,
XcmExecutor, XcmExecutor,
XcmWeigher, XcmWeigher,
frame_support::traits::ConstU64<BASE_XCM_WEIGHT>, WeightCredit,
>; >;
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
let location: MultiLocation = let location: MultiLocation =
(Parent, X1(GlobalConsensus(MillauNetwork::get()))).into(); (Parent, X1(GlobalConsensus(MillauNetwork::get()))).into();
let xcm: Xcm<Call> = vec![Instruction::Trap(42)].into(); let xcm: Xcm<RuntimeCall> = vec![Instruction::Trap(42)].into();
let mut incoming_message = DispatchMessage { let mut incoming_message = DispatchMessage {
key: MessageKey { lane_id: [0, 0, 0, 0], nonce: 1 }, key: MessageKey { lane_id: [0, 0, 0, 0], nonce: 1 },
@@ -906,7 +910,10 @@ mod tests {
}; };
let dispatch_weight = MessageDispatcher::dispatch_weight(&mut incoming_message); let dispatch_weight = MessageDispatcher::dispatch_weight(&mut incoming_message);
assert_eq!(dispatch_weight, 1_000_000_000); assert_eq!(
dispatch_weight,
frame_support::weights::Weight::from_ref_time(1_000_000_000)
);
let dispatch_result = let dispatch_result =
MessageDispatcher::dispatch(&AccountId::from([0u8; 32]), incoming_message); MessageDispatcher::dispatch(&AccountId::from([0u8; 32]), incoming_message);
@@ -914,7 +921,7 @@ mod tests {
dispatch_result, dispatch_result,
MessageDispatchResult { MessageDispatchResult {
dispatch_result: true, dispatch_result: true,
unspent_weight: 0, unspent_weight: frame_support::weights::Weight::from_ref_time(0),
dispatch_fee_paid_during_dispatch: false, dispatch_fee_paid_during_dispatch: false,
} }
); );
@@ -19,7 +19,7 @@
// TODO: this is almost exact copy of `millau_messages.rs` from Rialto runtime. // TODO: this is almost exact copy of `millau_messages.rs` from Rialto runtime.
// Should be extracted to a separate crate and reused here. // Should be extracted to a separate crate and reused here.
use crate::{OriginCaller, Runtime}; use crate::{OriginCaller, Runtime, RuntimeCall, RuntimeOrigin};
use bp_messages::{ use bp_messages::{
source_chain::{SenderOrigin, TargetHeaderChain}, source_chain::{SenderOrigin, TargetHeaderChain},
@@ -31,11 +31,7 @@ use bridge_runtime_common::messages::{
self, BasicConfirmationTransactionEstimation, MessageBridge, MessageTransaction, self, BasicConfirmationTransactionEstimation, MessageBridge, MessageTransaction,
}; };
use codec::{Decode, Encode}; use codec::{Decode, Encode};
use frame_support::{ use frame_support::{dispatch::DispatchClass, parameter_types, weights::Weight, RuntimeDebug};
parameter_types,
weights::{DispatchClass, Weight},
RuntimeDebug,
};
use scale_info::TypeInfo; use scale_info::TypeInfo;
use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128};
use sp_std::convert::TryFrom; use sp_std::convert::TryFrom;
@@ -50,13 +46,18 @@ pub const INITIAL_MILLAU_FEE_MULTIPLIER: FixedU128 = FixedU128::from_inner(Fixed
/// Weight of 2 XCM instructions is for simple `Trap(42)` program, coming through bridge /// Weight of 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction). It is used just for simplest manual /// (it is prepended with `UniversalOrigin` instruction). It is used just for simplest manual
/// tests, confirming that we don't break encoding somewhere between. /// tests, confirming that we don't break encoding somewhere between.
pub const BASE_XCM_WEIGHT_TWICE: Weight = 2 * crate::BASE_XCM_WEIGHT; pub const BASE_XCM_WEIGHT_TWICE: u64 = 2 * crate::BASE_XCM_WEIGHT;
parameter_types! { parameter_types! {
/// Millau to RialtoParachain conversion rate. Initially we treat both tokens as equal. /// Millau to RialtoParachain conversion rate. Initially we treat both tokens as equal.
pub storage MillauToRialtoParachainConversionRate: FixedU128 = INITIAL_MILLAU_TO_RIALTO_PARACHAIN_CONVERSION_RATE; pub storage MillauToRialtoParachainConversionRate: FixedU128 = INITIAL_MILLAU_TO_RIALTO_PARACHAIN_CONVERSION_RATE;
/// Fee multiplier value at Millau chain. /// Fee multiplier value at Millau chain.
pub storage MillauFeeMultiplier: FixedU128 = INITIAL_MILLAU_FEE_MULTIPLIER; pub storage MillauFeeMultiplier: FixedU128 = INITIAL_MILLAU_FEE_MULTIPLIER;
/// Weight credit for our test messages.
///
/// 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction).
pub const WeightCredit: Weight = Weight::from_ref_time(BASE_XCM_WEIGHT_TWICE);
} }
/// Message payload for RialtoParachain -> Millau messages. /// Message payload for RialtoParachain -> Millau messages.
@@ -67,16 +68,14 @@ pub type ToMillauMessageVerifier =
messages::source::FromThisChainMessageVerifier<WithMillauMessageBridge>; messages::source::FromThisChainMessageVerifier<WithMillauMessageBridge>;
/// Message payload for Millau -> RialtoParachain messages. /// Message payload for Millau -> RialtoParachain messages.
pub type FromMillauMessagePayload = messages::target::FromBridgedChainMessagePayload<crate::Call>; pub type FromMillauMessagePayload = messages::target::FromBridgedChainMessagePayload<RuntimeCall>;
/// Call-dispatch based message dispatch for Millau -> RialtoParachain messages. /// Call-dispatch based message dispatch for Millau -> RialtoParachain messages.
pub type FromMillauMessageDispatch = messages::target::FromBridgedChainMessageDispatch< pub type FromMillauMessageDispatch = messages::target::FromBridgedChainMessageDispatch<
WithMillauMessageBridge, WithMillauMessageBridge,
xcm_executor::XcmExecutor<crate::XcmConfig>, xcm_executor::XcmExecutor<crate::XcmConfig>,
crate::XcmWeigher, crate::XcmWeigher,
// 2 XCM instructions is for simple `Trap(42)` program, coming through bridge WeightCredit,
// (it is prepended with `UniversalOrigin` instruction)
frame_support::traits::ConstU64<BASE_XCM_WEIGHT_TWICE>,
>; >;
/// Messages proof for Millau -> RialtoParachain messages. /// Messages proof for Millau -> RialtoParachain messages.
@@ -124,21 +123,20 @@ impl messages::ChainWithMessages for RialtoParachain {
type AccountId = bp_rialto_parachain::AccountId; type AccountId = bp_rialto_parachain::AccountId;
type Signer = bp_rialto_parachain::AccountSigner; type Signer = bp_rialto_parachain::AccountSigner;
type Signature = bp_rialto_parachain::Signature; type Signature = bp_rialto_parachain::Signature;
type Weight = Weight;
type Balance = bp_rialto_parachain::Balance; type Balance = bp_rialto_parachain::Balance;
} }
impl messages::ThisChainWithMessages for RialtoParachain { impl messages::ThisChainWithMessages for RialtoParachain {
type Call = crate::Call; type RuntimeCall = RuntimeCall;
type Origin = crate::Origin; type RuntimeOrigin = RuntimeOrigin;
type ConfirmationTransactionEstimation = BasicConfirmationTransactionEstimation< type ConfirmationTransactionEstimation = BasicConfirmationTransactionEstimation<
Self::AccountId, Self::AccountId,
{ bp_rialto_parachain::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT }, { bp_rialto_parachain::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT.ref_time() },
{ bp_millau::EXTRA_STORAGE_PROOF_SIZE }, { bp_millau::EXTRA_STORAGE_PROOF_SIZE },
{ bp_rialto_parachain::TX_EXTRA_BYTES }, { bp_rialto_parachain::TX_EXTRA_BYTES },
>; >;
fn is_message_accepted(send_origin: &Self::Origin, lane: &LaneId) -> bool { fn is_message_accepted(send_origin: &Self::RuntimeOrigin, lane: &LaneId) -> bool {
let here_location = xcm::v3::MultiLocation::from(crate::UniversalLocation::get()); let here_location = xcm::v3::MultiLocation::from(crate::UniversalLocation::get());
match send_origin.caller { match send_origin.caller {
OriginCaller::PolkadotXcm(pallet_xcm::Origin::Xcm(ref location)) OriginCaller::PolkadotXcm(pallet_xcm::Origin::Xcm(ref location))
@@ -175,7 +173,7 @@ impl messages::ThisChainWithMessages for RialtoParachain {
.base_extrinsic, .base_extrinsic,
1, 1,
multiplier, multiplier,
|weight| weight as _, |weight| weight.ref_time() as _,
transaction, transaction,
) )
} }
@@ -190,7 +188,6 @@ impl messages::ChainWithMessages for Millau {
type AccountId = bp_millau::AccountId; type AccountId = bp_millau::AccountId;
type Signer = bp_millau::AccountSigner; type Signer = bp_millau::AccountSigner;
type Signature = bp_millau::Signature; type Signature = bp_millau::Signature;
type Weight = Weight;
type Balance = bp_millau::Balance; type Balance = bp_millau::Balance;
} }
@@ -209,15 +206,15 @@ impl messages::BridgedChainWithMessages for Millau {
message_dispatch_weight: Weight, message_dispatch_weight: Weight,
) -> MessageTransaction<Weight> { ) -> MessageTransaction<Weight> {
let message_payload_len = u32::try_from(message_payload.len()).unwrap_or(u32::MAX); let message_payload_len = u32::try_from(message_payload.len()).unwrap_or(u32::MAX);
let extra_bytes_in_payload = Weight::from(message_payload_len) let extra_bytes_in_payload = message_payload_len
.saturating_sub(pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH.into()); .saturating_sub(pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH);
MessageTransaction { MessageTransaction {
dispatch_weight: extra_bytes_in_payload dispatch_weight: bp_millau::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT
.saturating_mul(bp_millau::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT) .saturating_mul(extra_bytes_in_payload as u64)
.saturating_add(bp_millau::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT) .saturating_add(bp_millau::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT)
.saturating_sub(if include_pay_dispatch_fee_cost { .saturating_sub(if include_pay_dispatch_fee_cost {
0 Weight::from_ref_time(0)
} else { } else {
bp_millau::PAY_INBOUND_DISPATCH_FEE_WEIGHT bp_millau::PAY_INBOUND_DISPATCH_FEE_WEIGHT
}) })
@@ -237,7 +234,7 @@ impl messages::BridgedChainWithMessages for Millau {
bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic, bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
1, 1,
multiplier, multiplier,
|weight| weight as _, |weight| weight.ref_time() as _,
transaction, transaction,
) )
} }
@@ -287,7 +284,7 @@ impl SourceHeaderChain<bp_millau::Balance> for Millau {
} }
} }
impl SenderOrigin<crate::AccountId> for crate::Origin { impl SenderOrigin<crate::AccountId> for RuntimeOrigin {
fn linked_account(&self) -> Option<crate::AccountId> { fn linked_account(&self) -> Option<crate::AccountId> {
match self.caller { match self.caller {
crate::OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) => crate::OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) =>
+1
View File
@@ -21,6 +21,7 @@ rialto-runtime = { path = "../runtime" }
beefy-primitives = { git = "https://github.com/paritytech/substrate", branch = "master" } beefy-primitives = { git = "https://github.com/paritytech/substrate", branch = "master" }
frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "master" } frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "master" }
frame-benchmarking-cli = { git = "https://github.com/paritytech/substrate", branch = "master" } frame-benchmarking-cli = { git = "https://github.com/paritytech/substrate", branch = "master" }
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" }
node-inspect = { git = "https://github.com/paritytech/substrate", branch = "master" } node-inspect = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-cli = { git = "https://github.com/paritytech/substrate", branch = "master", features = ["wasmtime"] } sc-cli = { git = "https://github.com/paritytech/substrate", branch = "master", features = ["wasmtime"] }
sc-executor = { git = "https://github.com/paritytech/substrate", branch = "master" } sc-executor = { git = "https://github.com/paritytech/substrate", branch = "master" }
+2 -1
View File
@@ -15,6 +15,7 @@
// along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>. // along with Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
use beefy_primitives::crypto::AuthorityId as BeefyId; use beefy_primitives::crypto::AuthorityId as BeefyId;
use frame_support::weights::Weight;
use polkadot_primitives::v2::{AssignmentId, ValidatorId}; use polkadot_primitives::v2::{AssignmentId, ValidatorId};
use rialto_runtime::{ use rialto_runtime::{
AccountId, BabeConfig, BalancesConfig, BeefyConfig, BridgeMillauMessagesConfig, AccountId, BabeConfig, BalancesConfig, BeefyConfig, BridgeMillauMessagesConfig,
@@ -252,7 +253,7 @@ fn testnet_genesis(
max_upward_queue_count: 8, max_upward_queue_count: 8,
max_upward_queue_size: 1024 * 1024, max_upward_queue_size: 1024 * 1024,
max_downward_message_size: 1024 * 1024, max_downward_message_size: 1024 * 1024,
ump_service_total_weight: 100_000_000_000, ump_service_total_weight: Weight::from_ref_time(100_000_000_000),
max_upward_message_size: 50 * 1024, max_upward_message_size: 50 * 1024,
max_upward_message_num_per_candidate: 5, max_upward_message_num_per_candidate: 5,
hrmp_sender_deposit: 0, hrmp_sender_deposit: 0,
+47 -27
View File
@@ -63,9 +63,11 @@ use sp_version::RuntimeVersion;
// A few exports that help ease life for downstream crates. // A few exports that help ease life for downstream crates.
pub use frame_support::{ pub use frame_support::{
construct_runtime, parameter_types, construct_runtime,
dispatch::DispatchClass,
parameter_types,
traits::{Currency, ExistenceRequirement, Imbalance, KeyOwnerProofSystem}, traits::{Currency, ExistenceRequirement, Imbalance, KeyOwnerProofSystem},
weights::{constants::WEIGHT_PER_SECOND, DispatchClass, IdentityFee, RuntimeDbWeight, Weight}, weights::{constants::WEIGHT_PER_SECOND, IdentityFee, RuntimeDbWeight, Weight},
StorageValue, StorageValue,
}; };
@@ -169,7 +171,7 @@ impl frame_system::Config for Runtime {
/// The identifier used to distinguish between accounts. /// The identifier used to distinguish between accounts.
type AccountId = AccountId; type AccountId = AccountId;
/// The aggregated dispatch type that is available for extrinsics. /// The aggregated dispatch type that is available for extrinsics.
type Call = Call; type RuntimeCall = RuntimeCall;
/// The lookup mechanism to get account ID from whatever is passed in dispatchers. /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
type Lookup = AccountIdLookup<AccountId, ()>; type Lookup = AccountIdLookup<AccountId, ()>;
/// The index type for storing how many extrinsics an account has signed. /// The index type for storing how many extrinsics an account has signed.
@@ -183,9 +185,9 @@ impl frame_system::Config for Runtime {
/// The header type. /// The header type.
type Header = generic::Header<BlockNumber, Hashing>; type Header = generic::Header<BlockNumber, Hashing>;
/// The ubiquitous event type. /// The ubiquitous event type.
type Event = Event; type RuntimeEvent = RuntimeEvent;
/// The ubiquitous origin type. /// The ubiquitous origin type.
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first). /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
/// Version of the runtime. /// Version of the runtime.
@@ -258,8 +260,7 @@ impl pallet_beefy::Config for Runtime {
} }
impl pallet_grandpa::Config for Runtime { impl pallet_grandpa::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type Call = Call;
type MaxAuthorities = MaxAuthorities; type MaxAuthorities = MaxAuthorities;
type KeyOwnerProofSystem = (); type KeyOwnerProofSystem = ();
type KeyOwnerProof = type KeyOwnerProof =
@@ -340,7 +341,7 @@ impl pallet_balances::Config for Runtime {
/// The type for recording an account's balance. /// The type for recording an account's balance.
type Balance = Balance; type Balance = Balance;
/// The ubiquitous event type. /// The ubiquitous event type.
type Event = Event; type RuntimeEvent = RuntimeEvent;
type DustRemoval = (); type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit; type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System; type AccountStore = System;
@@ -360,6 +361,7 @@ parameter_types! {
pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25); pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25);
pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(3, 100_000); pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(3, 100_000);
pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 1_000_000u128); pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 1_000_000u128);
pub MaximumMultiplier: Multiplier = sp_runtime::traits::Bounded::max_value();
} }
impl pallet_transaction_payment::Config for Runtime { impl pallet_transaction_payment::Config for Runtime {
@@ -372,17 +374,18 @@ impl pallet_transaction_payment::Config for Runtime {
TargetBlockFullness, TargetBlockFullness,
AdjustmentVariable, AdjustmentVariable,
MinimumMultiplier, MinimumMultiplier,
MaximumMultiplier,
>; >;
type Event = Event; type RuntimeEvent = RuntimeEvent;
} }
impl pallet_sudo::Config for Runtime { impl pallet_sudo::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type Call = Call; type RuntimeCall = RuntimeCall;
} }
impl pallet_session::Config for Runtime { impl pallet_session::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type ValidatorId = <Self as frame_system::Config>::AccountId; type ValidatorId = <Self as frame_system::Config>::AccountId;
type ValidatorIdOf = (); type ValidatorIdOf = ();
type ShouldEndSession = Babe; type ShouldEndSession = Babe;
@@ -399,7 +402,7 @@ impl pallet_authority_discovery::Config for Runtime {
} }
impl pallet_bridge_relayers::Config for Runtime { impl pallet_bridge_relayers::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type Reward = Balance; type Reward = Balance;
type PaymentProcedure = bp_relayers::MintReward<pallet_balances::Pallet<Runtime>, AccountId>; type PaymentProcedure = bp_relayers::MintReward<pallet_balances::Pallet<Runtime>, AccountId>;
type WeightInfo = (); type WeightInfo = ();
@@ -444,7 +447,7 @@ parameter_types! {
bp_millau::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; bp_millau::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;
// `IdentityFee` is used by Rialto => we may use weight directly // `IdentityFee` is used by Rialto => we may use weight directly
pub const GetDeliveryConfirmationTransactionFee: Balance = pub const GetDeliveryConfirmationTransactionFee: Balance =
bp_rialto::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT as _; bp_rialto::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT.ref_time() as _;
pub const RootAccountForPayments: Option<AccountId> = None; pub const RootAccountForPayments: Option<AccountId> = None;
pub const BridgedChainId: bp_runtime::ChainId = bp_runtime::MILLAU_CHAIN_ID; pub const BridgedChainId: bp_runtime::ChainId = bp_runtime::MILLAU_CHAIN_ID;
} }
@@ -453,7 +456,7 @@ parameter_types! {
pub type WithMillauMessagesInstance = (); pub type WithMillauMessagesInstance = ();
impl pallet_bridge_messages::Config<WithMillauMessagesInstance> for Runtime { impl pallet_bridge_messages::Config<WithMillauMessagesInstance> for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_bridge_messages::weights::BridgeWeight<Runtime>; type WeightInfo = pallet_bridge_messages::weights::BridgeWeight<Runtime>;
type Parameter = millau_messages::RialtoToMillauMessagesParameter; type Parameter = millau_messages::RialtoToMillauMessagesParameter;
type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce;
@@ -529,6 +532,9 @@ construct_runtime!(
Ump: polkadot_runtime_parachains::ump::{Pallet, Call, Storage, Event}, Ump: polkadot_runtime_parachains::ump::{Pallet, Call, Storage, Event},
Hrmp: polkadot_runtime_parachains::hrmp::{Pallet, Call, Storage, Event<T>, Config}, Hrmp: polkadot_runtime_parachains::hrmp::{Pallet, Call, Storage, Event<T>, Config},
SessionInfo: polkadot_runtime_parachains::session_info::{Pallet, Storage}, SessionInfo: polkadot_runtime_parachains::session_info::{Pallet, Storage},
ParaSessionInfo: polkadot_runtime_parachains::session_info::{Pallet, Storage},
ParasDisputes: polkadot_runtime_parachains::disputes::{Pallet, Call, Storage, Event<T>},
ParasSlashing: polkadot_runtime_parachains::disputes::slashing::{Pallet, Call, Storage, ValidateUnsigned},
// Parachain Onboarding Pallets // Parachain Onboarding Pallets
Registrar: polkadot_runtime_common::paras_registrar::{Pallet, Call, Storage, Event<T>}, Registrar: polkadot_runtime_common::paras_registrar::{Pallet, Call, Storage, Event<T>},
@@ -562,11 +568,12 @@ pub type SignedExtra = (
pallet_transaction_payment::ChargeTransactionPayment<Runtime>, pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
); );
/// The payload being signed in transactions. /// The payload being signed in transactions.
pub type SignedPayload = generic::SignedPayload<Call, SignedExtra>; pub type SignedPayload = generic::SignedPayload<RuntimeCall, SignedExtra>;
/// Unchecked extrinsic type as expected by this runtime. /// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>; pub type UncheckedExtrinsic =
generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
/// Extrinsic type that has already been checked. /// Extrinsic type that has already been checked.
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>; pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
/// Executive: handles dispatch to the various modules. /// Executive: handles dispatch to the various modules.
pub type Executive = frame_executive::Executive< pub type Executive = frame_executive::Executive<
Runtime, Runtime,
@@ -679,6 +686,23 @@ impl_runtime_apis! {
.map(|(leaves, proof)| (leaves.into_iter().map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf)).collect(), proof)) .map(|(leaves, proof)| (leaves.into_iter().map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf)).collect(), proof))
} }
fn generate_historical_batch_proof(
leaf_indices: Vec<mmr::LeafIndex>,
leaves_count: mmr::LeafIndex,
) -> Result<(Vec<mmr::EncodableOpaqueLeaf>, mmr::BatchProof<MmrHash>), mmr::Error> {
Mmr::generate_historical_batch_proof(leaf_indices, leaves_count).map(
|(leaves, proof)| {
(
leaves
.into_iter()
.map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf))
.collect(),
proof,
)
},
)
}
fn verify_batch_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::BatchProof<MmrHash>) fn verify_batch_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::BatchProof<MmrHash>)
-> Result<(), mmr::Error> -> Result<(), mmr::Error>
{ {
@@ -725,17 +749,17 @@ impl_runtime_apis! {
} }
impl sp_consensus_babe::BabeApi<Block> for Runtime { impl sp_consensus_babe::BabeApi<Block> for Runtime {
fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { fn configuration() -> sp_consensus_babe::BabeConfiguration {
// The choice of `c` parameter (where `1 - c` represents the // The choice of `c` parameter (where `1 - c` represents the
// probability of a slot being empty), is done in accordance to the // probability of a slot being empty), is done in accordance to the
// slot duration and expected target block time, for safely // slot duration and expected target block time, for safely
// resisting network delays of maximum two seconds. // resisting network delays of maximum two seconds.
// <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results> // <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>
sp_consensus_babe::BabeGenesisConfiguration { sp_consensus_babe::BabeConfiguration {
slot_duration: Babe::slot_duration(), slot_duration: Babe::slot_duration(),
epoch_length: EpochDuration::get(), epoch_length: EpochDuration::get(),
c: BABE_GENESIS_EPOCH_CONFIG.c, c: BABE_GENESIS_EPOCH_CONFIG.c,
genesis_authorities: Babe::authorities().to_vec(), authorities: Babe::authorities().to_vec(),
randomness: Babe::randomness(), randomness: Babe::randomness(),
allowed_slots: BABE_GENESIS_EPOCH_CONFIG.allowed_slots, allowed_slots: BABE_GENESIS_EPOCH_CONFIG.allowed_slots,
} }
@@ -824,7 +848,7 @@ impl_runtime_apis! {
fn candidate_events() -> Vec<polkadot_primitives::v2::CandidateEvent<Hash>> { fn candidate_events() -> Vec<polkadot_primitives::v2::CandidateEvent<Hash>> {
polkadot_runtime_parachains::runtime_api_impl::v2::candidate_events::<Runtime, _>(|ev| { polkadot_runtime_parachains::runtime_api_impl::v2::candidate_events::<Runtime, _>(|ev| {
match ev { match ev {
Event::Inclusion(ev) => { RuntimeEvent::Inclusion(ev) => {
Some(ev) Some(ev)
} }
_ => None, _ => None,
@@ -867,10 +891,6 @@ impl_runtime_apis! {
{ {
polkadot_runtime_parachains::runtime_api_impl::v2::validation_code_hash::<Runtime>(para_id, assumption) polkadot_runtime_parachains::runtime_api_impl::v2::validation_code_hash::<Runtime>(para_id, assumption)
} }
fn staging_get_disputes() -> Vec<(polkadot_primitives::v2::SessionIndex, polkadot_primitives::v2::CandidateHash, polkadot_primitives::v2::DisputeState<BlockNumber>)> {
unimplemented!()
}
} }
impl sp_authority_discovery::AuthorityDiscoveryApi<Block> for Runtime { impl sp_authority_discovery::AuthorityDiscoveryApi<Block> for Runtime {
@@ -995,6 +1015,6 @@ mod tests {
// result of large `SessionKeys` struct. // result of large `SessionKeys` struct.
// Total size of Rialto runtime Call is 232. // Total size of Rialto runtime Call is 232.
const MAX_CALL_SIZE: usize = 232; const MAX_CALL_SIZE: usize = 232;
assert!(core::mem::size_of::<Call>() <= MAX_CALL_SIZE); assert!(core::mem::size_of::<RuntimeCall>() <= MAX_CALL_SIZE);
} }
} }
@@ -16,7 +16,7 @@
//! Everything required to serve Millau <-> Rialto messages. //! Everything required to serve Millau <-> Rialto messages.
use crate::{Call, OriginCaller, Runtime}; use crate::{OriginCaller, Runtime, RuntimeCall, RuntimeOrigin};
use bp_messages::{ use bp_messages::{
source_chain::{SenderOrigin, TargetHeaderChain}, source_chain::{SenderOrigin, TargetHeaderChain},
@@ -28,11 +28,7 @@ use bridge_runtime_common::messages::{
self, BasicConfirmationTransactionEstimation, MessageBridge, MessageTransaction, self, BasicConfirmationTransactionEstimation, MessageBridge, MessageTransaction,
}; };
use codec::{Decode, Encode}; use codec::{Decode, Encode};
use frame_support::{ use frame_support::{dispatch::DispatchClass, parameter_types, weights::Weight, RuntimeDebug};
parameter_types,
weights::{DispatchClass, Weight},
RuntimeDebug,
};
use scale_info::TypeInfo; use scale_info::TypeInfo;
use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128}; use sp_runtime::{traits::Saturating, FixedPointNumber, FixedU128};
use sp_std::convert::TryFrom; use sp_std::convert::TryFrom;
@@ -45,13 +41,18 @@ pub const INITIAL_MILLAU_FEE_MULTIPLIER: FixedU128 = FixedU128::from_inner(Fixed
/// Weight of 2 XCM instructions is for simple `Trap(42)` program, coming through bridge /// Weight of 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction). It is used just for simplest manual /// (it is prepended with `UniversalOrigin` instruction). It is used just for simplest manual
/// tests, confirming that we don't break encoding somewhere between. /// tests, confirming that we don't break encoding somewhere between.
pub const BASE_XCM_WEIGHT_TWICE: Weight = 2 * crate::xcm_config::BASE_XCM_WEIGHT; pub const BASE_XCM_WEIGHT_TWICE: u64 = 2 * crate::xcm_config::BASE_XCM_WEIGHT;
parameter_types! { parameter_types! {
/// Millau to Rialto conversion rate. Initially we treat both tokens as equal. /// Millau to Rialto conversion rate. Initially we treat both tokens as equal.
pub storage MillauToRialtoConversionRate: FixedU128 = INITIAL_MILLAU_TO_RIALTO_CONVERSION_RATE; pub storage MillauToRialtoConversionRate: FixedU128 = INITIAL_MILLAU_TO_RIALTO_CONVERSION_RATE;
/// Fee multiplier value at Millau chain. /// Fee multiplier value at Millau chain.
pub storage MillauFeeMultiplier: FixedU128 = INITIAL_MILLAU_FEE_MULTIPLIER; pub storage MillauFeeMultiplier: FixedU128 = INITIAL_MILLAU_FEE_MULTIPLIER;
/// Weight credit for our test messages.
///
/// 2 XCM instructions is for simple `Trap(42)` program, coming through bridge
/// (it is prepended with `UniversalOrigin` instruction).
pub const WeightCredit: Weight = Weight::from_ref_time(BASE_XCM_WEIGHT_TWICE);
} }
/// Message payload for Rialto -> Millau messages. /// Message payload for Rialto -> Millau messages.
@@ -62,15 +63,14 @@ pub type ToMillauMessageVerifier =
messages::source::FromThisChainMessageVerifier<WithMillauMessageBridge>; messages::source::FromThisChainMessageVerifier<WithMillauMessageBridge>;
/// Message payload for Millau -> Rialto messages. /// Message payload for Millau -> Rialto messages.
pub type FromMillauMessagePayload = messages::target::FromBridgedChainMessagePayload<Call>; pub type FromMillauMessagePayload = messages::target::FromBridgedChainMessagePayload<RuntimeCall>;
/// Call-dispatch based message dispatch for Millau -> Rialto messages. /// Call-dispatch based message dispatch for Millau -> Rialto messages.
pub type FromMillauMessageDispatch = messages::target::FromBridgedChainMessageDispatch< pub type FromMillauMessageDispatch = messages::target::FromBridgedChainMessageDispatch<
WithMillauMessageBridge, WithMillauMessageBridge,
xcm_executor::XcmExecutor<crate::xcm_config::XcmConfig>, xcm_executor::XcmExecutor<crate::xcm_config::XcmConfig>,
crate::xcm_config::XcmWeigher, crate::xcm_config::XcmWeigher,
// WeightCredit,
frame_support::traits::ConstU64<BASE_XCM_WEIGHT_TWICE>,
>; >;
/// Messages proof for Millau -> Rialto messages. /// Messages proof for Millau -> Rialto messages.
@@ -117,21 +117,20 @@ impl messages::ChainWithMessages for Rialto {
type AccountId = bp_rialto::AccountId; type AccountId = bp_rialto::AccountId;
type Signer = bp_rialto::AccountSigner; type Signer = bp_rialto::AccountSigner;
type Signature = bp_rialto::Signature; type Signature = bp_rialto::Signature;
type Weight = Weight;
type Balance = bp_rialto::Balance; type Balance = bp_rialto::Balance;
} }
impl messages::ThisChainWithMessages for Rialto { impl messages::ThisChainWithMessages for Rialto {
type Origin = crate::Origin; type RuntimeOrigin = RuntimeOrigin;
type Call = crate::Call; type RuntimeCall = RuntimeCall;
type ConfirmationTransactionEstimation = BasicConfirmationTransactionEstimation< type ConfirmationTransactionEstimation = BasicConfirmationTransactionEstimation<
Self::AccountId, Self::AccountId,
{ bp_rialto::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT }, { bp_rialto::MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT.ref_time() },
{ bp_millau::EXTRA_STORAGE_PROOF_SIZE }, { bp_millau::EXTRA_STORAGE_PROOF_SIZE },
{ bp_rialto::TX_EXTRA_BYTES }, { bp_rialto::TX_EXTRA_BYTES },
>; >;
fn is_message_accepted(send_origin: &Self::Origin, lane: &LaneId) -> bool { fn is_message_accepted(send_origin: &Self::RuntimeOrigin, lane: &LaneId) -> bool {
let here_location = let here_location =
xcm::v3::MultiLocation::from(crate::xcm_config::UniversalLocation::get()); xcm::v3::MultiLocation::from(crate::xcm_config::UniversalLocation::get());
match send_origin.caller { match send_origin.caller {
@@ -165,7 +164,7 @@ impl messages::ThisChainWithMessages for Rialto {
bp_rialto::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic, bp_rialto::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
1, 1,
multiplier, multiplier,
|weight| weight as _, |weight| weight.ref_time() as _,
transaction, transaction,
) )
} }
@@ -180,7 +179,6 @@ impl messages::ChainWithMessages for Millau {
type AccountId = bp_millau::AccountId; type AccountId = bp_millau::AccountId;
type Signer = bp_millau::AccountSigner; type Signer = bp_millau::AccountSigner;
type Signature = bp_millau::Signature; type Signature = bp_millau::Signature;
type Weight = Weight;
type Balance = bp_millau::Balance; type Balance = bp_millau::Balance;
} }
@@ -199,15 +197,15 @@ impl messages::BridgedChainWithMessages for Millau {
message_dispatch_weight: Weight, message_dispatch_weight: Weight,
) -> MessageTransaction<Weight> { ) -> MessageTransaction<Weight> {
let message_payload_len = u32::try_from(message_payload.len()).unwrap_or(u32::MAX); let message_payload_len = u32::try_from(message_payload.len()).unwrap_or(u32::MAX);
let extra_bytes_in_payload = Weight::from(message_payload_len) let extra_bytes_in_payload = message_payload_len
.saturating_sub(pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH.into()); .saturating_sub(pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH);
MessageTransaction { MessageTransaction {
dispatch_weight: extra_bytes_in_payload dispatch_weight: bp_millau::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT
.saturating_mul(bp_millau::ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT) .saturating_mul(extra_bytes_in_payload as u64)
.saturating_add(bp_millau::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT) .saturating_add(bp_millau::DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT)
.saturating_sub(if include_pay_dispatch_fee_cost { .saturating_sub(if include_pay_dispatch_fee_cost {
0 Weight::from_ref_time(0)
} else { } else {
bp_millau::PAY_INBOUND_DISPATCH_FEE_WEIGHT bp_millau::PAY_INBOUND_DISPATCH_FEE_WEIGHT
}) })
@@ -227,7 +225,7 @@ impl messages::BridgedChainWithMessages for Millau {
bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic, bp_millau::BlockWeights::get().get(DispatchClass::Normal).base_extrinsic,
1, 1,
multiplier, multiplier,
|weight| weight as _, |weight| weight.ref_time() as _,
transaction, transaction,
) )
} }
@@ -277,7 +275,7 @@ impl SourceHeaderChain<bp_millau::Balance> for Millau {
} }
} }
impl SenderOrigin<crate::AccountId> for crate::Origin { impl SenderOrigin<crate::AccountId> for RuntimeOrigin {
fn linked_account(&self) -> Option<crate::AccountId> { fn linked_account(&self) -> Option<crate::AccountId> {
// XCM deals wit fees in our deployments // XCM deals wit fees in our deployments
None None
+46 -24
View File
@@ -17,29 +17,31 @@
//! Parachains support in Rialto runtime. //! Parachains support in Rialto runtime.
use crate::{ use crate::{
AccountId, Babe, Balance, Balances, BlockNumber, Call, Event, Origin, Registrar, Runtime, AccountId, Babe, Balance, Balances, BlockNumber, Registrar, Runtime, RuntimeCall, RuntimeEvent,
ShiftSessionManager, Slots, UncheckedExtrinsic, RuntimeOrigin, ShiftSessionManager, Slots, UncheckedExtrinsic,
}; };
use frame_support::{parameter_types, weights::Weight}; use frame_support::{parameter_types, traits::KeyOwnerProofSystem, weights::Weight};
use frame_system::EnsureRoot; use frame_system::EnsureRoot;
use polkadot_primitives::v2::ValidatorIndex; use polkadot_primitives::v2::{ValidatorId, ValidatorIndex};
use polkadot_runtime_common::{paras_registrar, paras_sudo_wrapper, slots}; use polkadot_runtime_common::{paras_registrar, paras_sudo_wrapper, slots};
use polkadot_runtime_parachains::{ use polkadot_runtime_parachains::{
configuration as parachains_configuration, dmp as parachains_dmp, hrmp as parachains_hrmp, configuration as parachains_configuration, disputes as parachains_disputes,
disputes::slashing as parachains_slashing, dmp as parachains_dmp, hrmp as parachains_hrmp,
inclusion as parachains_inclusion, initializer as parachains_initializer, inclusion as parachains_inclusion, initializer as parachains_initializer,
origin as parachains_origin, paras as parachains_paras, origin as parachains_origin, paras as parachains_paras,
paras_inherent as parachains_paras_inherent, scheduler as parachains_scheduler, paras_inherent as parachains_paras_inherent, scheduler as parachains_scheduler,
session_info as parachains_session_info, shared as parachains_shared, ump as parachains_ump, session_info as parachains_session_info, shared as parachains_shared, ump as parachains_ump,
}; };
use sp_core::crypto::KeyTypeId;
use sp_runtime::transaction_validity::TransactionPriority; use sp_runtime::transaction_validity::TransactionPriority;
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
where where
Call: From<C>, RuntimeCall: From<C>,
{ {
type Extrinsic = UncheckedExtrinsic; type Extrinsic = UncheckedExtrinsic;
type OverarchingCall = Call; type OverarchingCall = RuntimeCall;
} }
/// Special `RewardValidators` that does nothing ;) /// Special `RewardValidators` that does nothing ;)
@@ -58,14 +60,14 @@ impl parachains_configuration::Config for Runtime {
impl parachains_dmp::Config for Runtime {} impl parachains_dmp::Config for Runtime {}
impl parachains_hrmp::Config for Runtime { impl parachains_hrmp::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
type Currency = Balances; type Currency = Balances;
type WeightInfo = parachains_hrmp::TestWeightInfo; type WeightInfo = parachains_hrmp::TestWeightInfo;
} }
impl parachains_inclusion::Config for Runtime { impl parachains_inclusion::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type RewardValidators = RewardValidators; type RewardValidators = RewardValidators;
type DisputesHandler = (); type DisputesHandler = ();
} }
@@ -76,6 +78,26 @@ impl parachains_initializer::Config for Runtime {
type WeightInfo = (); type WeightInfo = ();
} }
impl parachains_disputes::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RewardValidators = ();
type SlashingHandler = ();
type WeightInfo = parachains_disputes::TestWeightInfo;
}
impl parachains_slashing::Config for Runtime {
type KeyOwnerProofSystem = ();
type KeyOwnerProof =
<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, ValidatorId)>>::Proof;
type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
ValidatorId,
)>>::IdentificationTuple;
type HandleReports = ();
type WeightInfo = parachains_slashing::TestWeightInfo;
type BenchmarkingConfig = parachains_slashing::BenchConfig<200>;
}
impl parachains_origin::Config for Runtime {} impl parachains_origin::Config for Runtime {}
parameter_types! { parameter_types! {
@@ -83,7 +105,7 @@ parameter_types! {
} }
impl parachains_paras::Config for Runtime { impl parachains_paras::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type WeightInfo = parachains_paras::TestWeightInfo; type WeightInfo = parachains_paras::TestWeightInfo;
type UnsignedPriority = ParasUnsignedPriority; type UnsignedPriority = ParasUnsignedPriority;
type NextSessionRotation = Babe; type NextSessionRotation = Babe;
@@ -106,7 +128,7 @@ parameter_types! {
} }
impl parachains_ump::Config for Runtime { impl parachains_ump::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type UmpSink = (); type UmpSink = ();
type FirstMessageFactorPercent = FirstMessageFactorPercent; type FirstMessageFactorPercent = FirstMessageFactorPercent;
type ExecuteOverweightOrigin = EnsureRoot<AccountId>; type ExecuteOverweightOrigin = EnsureRoot<AccountId>;
@@ -121,8 +143,8 @@ parameter_types! {
} }
impl paras_registrar::Config for Runtime { impl paras_registrar::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
type Currency = Balances; type Currency = Balances;
type OnSwap = Slots; type OnSwap = Slots;
type ParaDeposit = ParaDeposit; type ParaDeposit = ParaDeposit;
@@ -135,7 +157,7 @@ parameter_types! {
} }
impl slots::Config for Runtime { impl slots::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type Currency = Balances; type Currency = Balances;
type Registrar = Registrar; type Registrar = Registrar;
type LeasePeriod = LeasePeriod; type LeasePeriod = LeasePeriod;
@@ -150,33 +172,33 @@ pub struct ZeroWeights;
impl polkadot_runtime_common::paras_registrar::WeightInfo for ZeroWeights { impl polkadot_runtime_common::paras_registrar::WeightInfo for ZeroWeights {
fn reserve() -> Weight { fn reserve() -> Weight {
0 Weight::from_ref_time(0)
} }
fn register() -> Weight { fn register() -> Weight {
0 Weight::from_ref_time(0)
} }
fn force_register() -> Weight { fn force_register() -> Weight {
0 Weight::from_ref_time(0)
} }
fn deregister() -> Weight { fn deregister() -> Weight {
0 Weight::from_ref_time(0)
} }
fn swap() -> Weight { fn swap() -> Weight {
0 Weight::from_ref_time(0)
} }
} }
impl polkadot_runtime_common::slots::WeightInfo for ZeroWeights { impl polkadot_runtime_common::slots::WeightInfo for ZeroWeights {
fn force_lease() -> Weight { fn force_lease() -> Weight {
0 Weight::from_ref_time(0)
} }
fn manage_lease_period_start(_c: u32, _t: u32) -> Weight { fn manage_lease_period_start(_c: u32, _t: u32) -> Weight {
0 Weight::from_ref_time(0)
} }
fn clear_all_leases() -> Weight { fn clear_all_leases() -> Weight {
0 Weight::from_ref_time(0)
} }
fn trigger_onboard() -> Weight { fn trigger_onboard() -> Weight {
0 Weight::from_ref_time(0)
} }
} }
+25 -22
View File
@@ -17,8 +17,8 @@
//! XCM configurations for the Rialto runtime. //! XCM configurations for the Rialto runtime.
use super::{ use super::{
millau_messages::WithMillauMessageBridge, AccountId, AllPalletsWithSystem, Balances, Call, millau_messages::WithMillauMessageBridge, AccountId, AllPalletsWithSystem, Balances, Runtime,
Event, Origin, Runtime, WithMillauMessagesInstance, XcmPallet, RuntimeCall, RuntimeEvent, RuntimeOrigin, WithMillauMessagesInstance, XcmPallet,
}; };
use bp_rialto::WeightToFee; use bp_rialto::WeightToFee;
use bridge_runtime_common::{ use bridge_runtime_common::{
@@ -28,12 +28,11 @@ use bridge_runtime_common::{
use frame_support::{ use frame_support::{
parameter_types, parameter_types,
traits::{Everything, Nothing}, traits::{Everything, Nothing},
weights::Weight,
}; };
use xcm::latest::prelude::*; use xcm::latest::prelude::*;
use xcm_builder::{ use xcm_builder::{
AccountId32Aliases, AllowKnownQueryResponses, AllowTopLevelPaidExecutionFrom, AccountId32Aliases, AllowKnownQueryResponses, AllowTopLevelPaidExecutionFrom,
CurrencyAdapter as XcmCurrencyAdapter, IsConcrete, SignedAccountId32AsNative, CurrencyAdapter as XcmCurrencyAdapter, IsConcrete, MintLocation, SignedAccountId32AsNative,
SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, UsingComponents, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,
}; };
@@ -52,7 +51,7 @@ parameter_types! {
/// Since Polkadot is a top-level relay-chain with its own consensus, it's just our network ID. /// Since Polkadot is a top-level relay-chain with its own consensus, it's just our network ID.
pub UniversalLocation: InteriorMultiLocation = ThisNetwork::get().into(); pub UniversalLocation: InteriorMultiLocation = ThisNetwork::get().into();
/// The check account, which holds any native assets that have been teleported out and not back in (yet). /// The check account, which holds any native assets that have been teleported out and not back in (yet).
pub CheckAccount: AccountId = XcmPallet::check_account(); pub CheckAccount: (AccountId, MintLocation) = (XcmPallet::check_account(), MintLocation::Local);
} }
/// The canonical means of converting a `MultiLocation` into an `AccountId`, used when we want to /// The canonical means of converting a `MultiLocation` into an `AccountId`, used when we want to
@@ -82,17 +81,17 @@ pub type LocalAssetTransactor = XcmCurrencyAdapter<
/// The means that we convert the XCM message origin location into a local dispatch origin. /// The means that we convert the XCM message origin location into a local dispatch origin.
type LocalOriginConverter = ( type LocalOriginConverter = (
// A `Signed` origin of the sovereign account that the original location controls. // A `Signed` origin of the sovereign account that the original location controls.
SovereignSignedViaLocation<SovereignAccountOf, Origin>, SovereignSignedViaLocation<SovereignAccountOf, RuntimeOrigin>,
// The AccountId32 location type can be expressed natively as a `Signed` origin. // The AccountId32 location type can be expressed natively as a `Signed` origin.
SignedAccountId32AsNative<ThisNetwork, Origin>, SignedAccountId32AsNative<ThisNetwork, RuntimeOrigin>,
); );
/// The amount of weight an XCM operation takes. This is a safe overestimate. /// The amount of weight an XCM operation takes. This is a safe overestimate.
pub const BASE_XCM_WEIGHT: Weight = 1_000_000_000; pub const BASE_XCM_WEIGHT: u64 = 1_000_000_000;
parameter_types! { parameter_types! {
/// The amount of weight an XCM operation takes. This is a safe overestimate. /// The amount of weight an XCM operation takes. This is a safe overestimate.
pub const BaseXcmWeight: Weight = BASE_XCM_WEIGHT; pub const BaseXcmWeight: u64 = BASE_XCM_WEIGHT;
/// Maximum number of instructions in a single XCM fragment. A sanity check against weight /// Maximum number of instructions in a single XCM fragment. A sanity check against weight
/// calculations getting too crazy. /// calculations getting too crazy.
pub const MaxInstructions: u32 = 100; pub const MaxInstructions: u32 = 100;
@@ -120,11 +119,11 @@ pub type Barrier = (
); );
/// Incoming XCM weigher type. /// Incoming XCM weigher type.
pub type XcmWeigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, Call, MaxInstructions>; pub type XcmWeigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
pub struct XcmConfig; pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig { impl xcm_executor::Config for XcmConfig {
type Call = Call; type RuntimeCall = RuntimeCall;
type XcmSender = XcmRouter; type XcmSender = XcmRouter;
type AssetTransactor = LocalAssetTransactor; type AssetTransactor = LocalAssetTransactor;
type OriginConverter = LocalOriginConverter; type OriginConverter = LocalOriginConverter;
@@ -146,26 +145,26 @@ impl xcm_executor::Config for XcmConfig {
type FeeManager = (); type FeeManager = ();
type MessageExporter = (); type MessageExporter = ();
type UniversalAliases = Nothing; type UniversalAliases = Nothing;
type CallDispatcher = Call; type CallDispatcher = RuntimeCall;
} }
/// Type to convert an `Origin` type value into a `MultiLocation` value which represents an interior /// Type to convert an `Origin` type value into a `MultiLocation` value which represents an interior
/// location of this chain. /// location of this chain.
pub type LocalOriginToLocation = ( pub type LocalOriginToLocation = (
// Usual Signed origin to be used in XCM as a corresponding AccountId32 // Usual Signed origin to be used in XCM as a corresponding AccountId32
SignedToAccountId32<Origin, AccountId, ThisNetwork>, SignedToAccountId32<RuntimeOrigin, AccountId, ThisNetwork>,
); );
impl pallet_xcm::Config for Runtime { impl pallet_xcm::Config for Runtime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
// We don't allow any messages to be sent via the transaction yet. This is basically safe to // We don't allow any messages to be sent via the transaction yet. This is basically safe to
// enable, (safe the possibility of someone spamming the parachain if they're willing to pay // enable, (safe the possibility of someone spamming the parachain if they're willing to pay
// the DOT to send from the Relay-chain). But it's useless until we bring in XCM v3 which will // the DOT to send from the Relay-chain). But it's useless until we bring in XCM v3 which will
// make `DescendOrigin` a bit more useful. // make `DescendOrigin` a bit more useful.
type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<Origin, LocalOriginToLocation>; type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmRouter = XcmRouter; type XcmRouter = XcmRouter;
// Anyone can execute XCM messages locally. // Anyone can execute XCM messages locally.
type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<Origin, LocalOriginToLocation>; type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmExecuteFilter = Everything; type XcmExecuteFilter = Everything;
type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>; type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
// Anyone is able to use teleportation regardless of who they are and what they want to // Anyone is able to use teleportation regardless of who they are and what they want to
@@ -176,8 +175,8 @@ impl pallet_xcm::Config for Runtime {
type XcmReserveTransferFilter = Everything; type XcmReserveTransferFilter = Everything;
type Weigher = XcmWeigher; type Weigher = XcmWeigher;
type UniversalLocation = UniversalLocation; type UniversalLocation = UniversalLocation;
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
type Call = Call; type RuntimeCall = RuntimeCall;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type Currency = Balances; type Currency = Balances;
@@ -216,6 +215,7 @@ impl XcmBridge for ToMillauBridge {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::millau_messages::WeightCredit;
use bp_messages::{ use bp_messages::{
target_chain::{DispatchMessage, DispatchMessageData, MessageDispatch}, target_chain::{DispatchMessage, DispatchMessageData, MessageDispatch},
MessageKey, MessageKey,
@@ -252,13 +252,13 @@ mod tests {
WithMillauMessageBridge, WithMillauMessageBridge,
XcmExecutor, XcmExecutor,
XcmWeigher, XcmWeigher,
frame_support::traits::ConstU64<BASE_XCM_WEIGHT>, WeightCredit,
>; >;
new_test_ext().execute_with(|| { new_test_ext().execute_with(|| {
let location: MultiLocation = let location: MultiLocation =
(Parent, X1(GlobalConsensus(MillauNetwork::get()))).into(); (Parent, X1(GlobalConsensus(MillauNetwork::get()))).into();
let xcm: Xcm<Call> = vec![Instruction::Trap(42)].into(); let xcm: Xcm<RuntimeCall> = vec![Instruction::Trap(42)].into();
let mut incoming_message = DispatchMessage { let mut incoming_message = DispatchMessage {
key: MessageKey { lane_id: [0, 0, 0, 0], nonce: 1 }, key: MessageKey { lane_id: [0, 0, 0, 0], nonce: 1 },
@@ -266,7 +266,10 @@ mod tests {
}; };
let dispatch_weight = MessageDispatcher::dispatch_weight(&mut incoming_message); let dispatch_weight = MessageDispatcher::dispatch_weight(&mut incoming_message);
assert_eq!(dispatch_weight, 1_000_000_000); assert_eq!(
dispatch_weight,
frame_support::weights::Weight::from_ref_time(1_000_000_000)
);
let dispatch_result = let dispatch_result =
MessageDispatcher::dispatch(&AccountId::from([0u8; 32]), incoming_message); MessageDispatcher::dispatch(&AccountId::from([0u8; 32]), incoming_message);
@@ -274,7 +277,7 @@ mod tests {
dispatch_result, dispatch_result,
MessageDispatchResult { MessageDispatchResult {
dispatch_result: true, dispatch_result: true,
unspent_weight: 0, unspent_weight: frame_support::weights::Weight::from_ref_time(0),
dispatch_fee_paid_during_dispatch: false, dispatch_fee_paid_during_dispatch: false,
} }
); );
+2 -4
View File
@@ -60,7 +60,7 @@ macro_rules! assert_bridge_types(
// `frame_support::weights::Weight` is used here directly, because all chains we know are using this // `frame_support::weights::Weight` is used here directly, because all chains we know are using this
// primitive (may be changed in the future) // primitive (may be changed in the future)
use $crate::messages::{ use $crate::messages::{
AccountIdOf, BalanceOf, BridgedChain, HashOf, SignatureOf, SignerOf, ThisChain, WeightOf, AccountIdOf, BalanceOf, BridgedChain, HashOf, SignatureOf, SignerOf, ThisChain,
}; };
use static_assertions::assert_type_eq_all; use static_assertions::assert_type_eq_all;
@@ -68,14 +68,12 @@ macro_rules! assert_bridge_types(
assert_type_eq_all!(AccountIdOf<ThisChain<$bridge>>, bp_runtime::AccountIdOf<$this>); assert_type_eq_all!(AccountIdOf<ThisChain<$bridge>>, bp_runtime::AccountIdOf<$this>);
assert_type_eq_all!(SignerOf<ThisChain<$bridge>>, bp_runtime::AccountPublicOf<$this>); assert_type_eq_all!(SignerOf<ThisChain<$bridge>>, bp_runtime::AccountPublicOf<$this>);
assert_type_eq_all!(SignatureOf<ThisChain<$bridge>>, bp_runtime::SignatureOf<$this>); assert_type_eq_all!(SignatureOf<ThisChain<$bridge>>, bp_runtime::SignatureOf<$this>);
assert_type_eq_all!(WeightOf<ThisChain<$bridge>>, frame_support::weights::Weight);
assert_type_eq_all!(BalanceOf<ThisChain<$bridge>>, bp_runtime::BalanceOf<$this>); assert_type_eq_all!(BalanceOf<ThisChain<$bridge>>, bp_runtime::BalanceOf<$this>);
assert_type_eq_all!(HashOf<BridgedChain<$bridge>>, bp_runtime::HashOf<$bridged>); assert_type_eq_all!(HashOf<BridgedChain<$bridge>>, bp_runtime::HashOf<$bridged>);
assert_type_eq_all!(AccountIdOf<BridgedChain<$bridge>>, bp_runtime::AccountIdOf<$bridged>); assert_type_eq_all!(AccountIdOf<BridgedChain<$bridge>>, bp_runtime::AccountIdOf<$bridged>);
assert_type_eq_all!(SignerOf<BridgedChain<$bridge>>, bp_runtime::AccountPublicOf<$bridged>); assert_type_eq_all!(SignerOf<BridgedChain<$bridge>>, bp_runtime::AccountPublicOf<$bridged>);
assert_type_eq_all!(SignatureOf<BridgedChain<$bridge>>, bp_runtime::SignatureOf<$bridged>); assert_type_eq_all!(SignatureOf<BridgedChain<$bridge>>, bp_runtime::SignatureOf<$bridged>);
assert_type_eq_all!(WeightOf<BridgedChain<$bridge>>, frame_support::weights::Weight);
assert_type_eq_all!(BalanceOf<BridgedChain<$bridge>>, bp_runtime::BalanceOf<$bridged>); assert_type_eq_all!(BalanceOf<BridgedChain<$bridge>>, bp_runtime::BalanceOf<$bridged>);
} }
} }
@@ -114,7 +112,7 @@ macro_rules! assert_bridge_messages_pallet_types(
use $crate::messages::{ use $crate::messages::{
source::FromThisChainMessagePayload, source::FromThisChainMessagePayload,
target::FromBridgedChainMessagePayload, target::FromBridgedChainMessagePayload,
AccountIdOf, BalanceOf, BridgedChain, CallOf, ThisChain, WeightOf, AccountIdOf, BalanceOf, BridgedChain, CallOf, ThisChain,
}; };
use pallet_bridge_messages::Config as MessagesConfig; use pallet_bridge_messages::Config as MessagesConfig;
use static_assertions::assert_type_eq_all; use static_assertions::assert_type_eq_all;
+2 -2
View File
@@ -156,14 +156,14 @@ mod tests {
} }
impl sp_runtime::traits::Dispatchable for MockCall { impl sp_runtime::traits::Dispatchable for MockCall {
type Origin = (); type RuntimeOrigin = ();
type Config = (); type Config = ();
type Info = (); type Info = ();
type PostInfo = (); type PostInfo = ();
fn dispatch( fn dispatch(
self, self,
_origin: Self::Origin, _origin: Self::RuntimeOrigin,
) -> sp_runtime::DispatchResultWithInfo<Self::PostInfo> { ) -> sp_runtime::DispatchResultWithInfo<Self::PostInfo> {
unimplemented!() unimplemented!()
} }
+59 -62
View File
@@ -75,11 +75,6 @@ pub trait ChainWithMessages {
type Signer: Encode + Decode; type Signer: Encode + Decode;
/// Signature type used on the chain. /// Signature type used on the chain.
type Signature: Encode + Decode; type Signature: Encode + Decode;
/// Type of weight that is used on the chain. This would almost always be a regular
/// `frame_support::weight::Weight`. But since the meaning of weight on different chains
/// may be different, the `WeightOf<>` construct is used to avoid confusion between
/// different weights.
type Weight: From<frame_support::weights::Weight> + PartialOrd;
/// Type of balances that is used on the chain. /// Type of balances that is used on the chain.
type Balance: Encode type Balance: Encode
+ Decode + Decode
@@ -110,14 +105,14 @@ pub trait ConfirmationTransactionEstimation<Weight> {
/// Default implementation for `ConfirmationTransactionEstimation`. /// Default implementation for `ConfirmationTransactionEstimation`.
pub struct BasicConfirmationTransactionEstimation< pub struct BasicConfirmationTransactionEstimation<
AccountId: MaxEncodedLen, AccountId: MaxEncodedLen,
const MAX_CONFIRMATION_TX_WEIGHT: Weight, const MAX_CONFIRMATION_TX_WEIGHT: u64,
const EXTRA_STORAGE_PROOF_SIZE: u32, const EXTRA_STORAGE_PROOF_SIZE: u32,
const TX_EXTRA_BYTES: u32, const TX_EXTRA_BYTES: u32,
>(PhantomData<AccountId>); >(PhantomData<AccountId>);
impl< impl<
AccountId: MaxEncodedLen, AccountId: MaxEncodedLen,
const MAX_CONFIRMATION_TX_WEIGHT: Weight, const MAX_CONFIRMATION_TX_WEIGHT: u64,
const EXTRA_STORAGE_PROOF_SIZE: u32, const EXTRA_STORAGE_PROOF_SIZE: u32,
const TX_EXTRA_BYTES: u32, const TX_EXTRA_BYTES: u32,
> ConfirmationTransactionEstimation<Weight> > ConfirmationTransactionEstimation<Weight>
@@ -131,7 +126,7 @@ impl<
fn estimate_delivery_confirmation_transaction() -> MessageTransaction<Weight> { fn estimate_delivery_confirmation_transaction() -> MessageTransaction<Weight> {
let inbound_data_size = InboundLaneData::<AccountId>::encoded_size_hint_u32(1, 1); let inbound_data_size = InboundLaneData::<AccountId>::encoded_size_hint_u32(1, 1);
MessageTransaction { MessageTransaction {
dispatch_weight: MAX_CONFIRMATION_TX_WEIGHT, dispatch_weight: Weight::from_ref_time(MAX_CONFIRMATION_TX_WEIGHT),
size: inbound_data_size size: inbound_data_size
.saturating_add(EXTRA_STORAGE_PROOF_SIZE) .saturating_add(EXTRA_STORAGE_PROOF_SIZE)
.saturating_add(TX_EXTRA_BYTES), .saturating_add(TX_EXTRA_BYTES),
@@ -142,15 +137,15 @@ impl<
/// This chain that has `pallet-bridge-messages` and `dispatch` modules. /// This chain that has `pallet-bridge-messages` and `dispatch` modules.
pub trait ThisChainWithMessages: ChainWithMessages { pub trait ThisChainWithMessages: ChainWithMessages {
/// Call origin on the chain. /// Call origin on the chain.
type Origin; type RuntimeOrigin;
/// Call type on the chain. /// Call type on the chain.
type Call: Encode + Decode; type RuntimeCall: Encode + Decode;
/// Helper for estimating the size and weight of a single message delivery confirmation /// Helper for estimating the size and weight of a single message delivery confirmation
/// transaction at this chain. /// transaction at this chain.
type ConfirmationTransactionEstimation: ConfirmationTransactionEstimation<WeightOf<Self>>; type ConfirmationTransactionEstimation: ConfirmationTransactionEstimation<Weight>;
/// Do we accept message sent by given origin to given lane? /// Do we accept message sent by given origin to given lane?
fn is_message_accepted(origin: &Self::Origin, lane: &LaneId) -> bool; fn is_message_accepted(origin: &Self::RuntimeOrigin, lane: &LaneId) -> bool;
/// Maximal number of pending (not yet delivered) messages at This chain. /// Maximal number of pending (not yet delivered) messages at This chain.
/// ///
@@ -158,12 +153,12 @@ pub trait ThisChainWithMessages: ChainWithMessages {
fn maximal_pending_messages_at_outbound_lane() -> MessageNonce; fn maximal_pending_messages_at_outbound_lane() -> MessageNonce;
/// Estimate size and weight of single message delivery confirmation transaction at This chain. /// Estimate size and weight of single message delivery confirmation transaction at This chain.
fn estimate_delivery_confirmation_transaction() -> MessageTransaction<WeightOf<Self>> { fn estimate_delivery_confirmation_transaction() -> MessageTransaction<Weight> {
Self::ConfirmationTransactionEstimation::estimate_delivery_confirmation_transaction() Self::ConfirmationTransactionEstimation::estimate_delivery_confirmation_transaction()
} }
/// Returns minimal transaction fee that must be paid for given transaction at This chain. /// Returns minimal transaction fee that must be paid for given transaction at This chain.
fn transaction_payment(transaction: MessageTransaction<WeightOf<Self>>) -> BalanceOf<Self>; fn transaction_payment(transaction: MessageTransaction<Weight>) -> BalanceOf<Self>;
} }
/// Bridged chain that has `pallet-bridge-messages` and `dispatch` modules. /// Bridged chain that has `pallet-bridge-messages` and `dispatch` modules.
@@ -179,12 +174,12 @@ pub trait BridgedChainWithMessages: ChainWithMessages {
fn estimate_delivery_transaction( fn estimate_delivery_transaction(
message_payload: &[u8], message_payload: &[u8],
include_pay_dispatch_fee_cost: bool, include_pay_dispatch_fee_cost: bool,
message_dispatch_weight: WeightOf<Self>, message_dispatch_weight: Weight,
) -> MessageTransaction<WeightOf<Self>>; ) -> MessageTransaction<Weight>;
/// Returns minimal transaction fee that must be paid for given transaction at the Bridged /// Returns minimal transaction fee that must be paid for given transaction at the Bridged
/// chain. /// chain.
fn transaction_payment(transaction: MessageTransaction<WeightOf<Self>>) -> BalanceOf<Self>; fn transaction_payment(transaction: MessageTransaction<Weight>) -> BalanceOf<Self>;
} }
/// This chain in context of message bridge. /// This chain in context of message bridge.
@@ -199,14 +194,12 @@ pub type AccountIdOf<C> = <C as ChainWithMessages>::AccountId;
pub type SignerOf<C> = <C as ChainWithMessages>::Signer; pub type SignerOf<C> = <C as ChainWithMessages>::Signer;
/// Signature type used on the chain. /// Signature type used on the chain.
pub type SignatureOf<C> = <C as ChainWithMessages>::Signature; pub type SignatureOf<C> = <C as ChainWithMessages>::Signature;
/// Type of weight that used on the chain.
pub type WeightOf<C> = <C as ChainWithMessages>::Weight;
/// Type of balances that is used on the chain. /// Type of balances that is used on the chain.
pub type BalanceOf<C> = <C as ChainWithMessages>::Balance; pub type BalanceOf<C> = <C as ChainWithMessages>::Balance;
/// Type of origin that is used on the chain. /// Type of origin that is used on the chain.
pub type OriginOf<C> = <C as ThisChainWithMessages>::Origin; pub type OriginOf<C> = <C as ThisChainWithMessages>::RuntimeOrigin;
/// Type of call that is used on this chain. /// Type of call that is used on this chain.
pub type CallOf<C> = <C as ThisChainWithMessages>::Call; pub type CallOf<C> = <C as ThisChainWithMessages>::RuntimeCall;
/// Raw storage proof type (just raw trie nodes). /// Raw storage proof type (just raw trie nodes).
pub type RawStorageProof = Vec<Vec<u8>>; pub type RawStorageProof = Vec<Vec<u8>>;
@@ -411,8 +404,11 @@ pub mod source {
// //
// if we're going to pay dispatch fee at the target chain, then we don't include weight // if we're going to pay dispatch fee at the target chain, then we don't include weight
// of the message dispatch in the delivery transaction cost // of the message dispatch in the delivery transaction cost
let delivery_transaction = let delivery_transaction = BridgedChain::<B>::estimate_delivery_transaction(
BridgedChain::<B>::estimate_delivery_transaction(&payload.encode(), true, 0.into()); &payload.encode(),
true,
Weight::from_ref_time(0),
);
let delivery_transaction_fee = BridgedChain::<B>::transaction_payment(delivery_transaction); let delivery_transaction_fee = BridgedChain::<B>::transaction_payment(delivery_transaction);
// the fee (in This tokens) of all transactions that are made on This chain // the fee (in This tokens) of all transactions that are made on This chain
@@ -720,7 +716,7 @@ pub mod target {
// I have no idea why this method takes `&mut` reference and there's nothing // I have no idea why this method takes `&mut` reference and there's nothing
// about that in documentation. Hope it'll only mutate iff error is returned. // about that in documentation. Hope it'll only mutate iff error is returned.
let weight = XcmWeigher::weight(&mut payload.xcm.1); let weight = XcmWeigher::weight(&mut payload.xcm.1);
let weight = weight.unwrap_or_else(|e| { let weight = Weight::from_ref_time(weight.unwrap_or_else(|e| {
log::debug!( log::debug!(
target: "runtime::bridge-dispatch", target: "runtime::bridge-dispatch",
"Failed to compute dispatch weight of incoming XCM message {:?}/{}: {:?}", "Failed to compute dispatch weight of incoming XCM message {:?}/{}: {:?}",
@@ -732,12 +728,12 @@ pub mod target {
// we shall return 0 and then the XCM executor will fail to execute XCM // we shall return 0 and then the XCM executor will fail to execute XCM
// if we'll return something else (e.g. maximal value), the lane may stuck // if we'll return something else (e.g. maximal value), the lane may stuck
0 0
}); }));
payload.weight = Some(weight); payload.weight = Some(weight);
weight weight
}, },
_ => 0, _ => Weight::from_ref_time(0),
} }
} }
@@ -766,8 +762,8 @@ pub mod target {
location, location,
xcm, xcm,
hash, hash,
weight_limit.unwrap_or(0), weight_limit.unwrap_or(Weight::from_ref_time(0)).ref_time(),
weight_credit, weight_credit.ref_time(),
); );
Ok(xcm_outcome) Ok(xcm_outcome)
}; };
@@ -776,7 +772,7 @@ pub mod target {
log::trace!(target: "runtime::bridge-dispatch", "Incoming message {:?} dispatched with result: {:?}", message_id, xcm_outcome); log::trace!(target: "runtime::bridge-dispatch", "Incoming message {:?} dispatched with result: {:?}", message_id, xcm_outcome);
MessageDispatchResult { MessageDispatchResult {
dispatch_result: true, dispatch_result: true,
unspent_weight: 0, unspent_weight: Weight::from_ref_time(0),
dispatch_fee_paid_during_dispatch: false, dispatch_fee_paid_during_dispatch: false,
} }
} }
@@ -1093,6 +1089,7 @@ pub mod xcm_copy {
fn validate( fn validate(
network: NetworkId, network: NetworkId,
_channel: u32, _channel: u32,
_universal_source: &mut Option<InteriorMultiLocation>,
destination: &mut Option<InteriorMultiLocation>, destination: &mut Option<InteriorMultiLocation>,
message: &mut Option<Xcm<()>>, message: &mut Option<Xcm<()>>,
) -> Result<((Vec<u8>, XcmHash), MultiAssets), SendError> { ) -> Result<((Vec<u8>, XcmHash), MultiAssets), SendError> {
@@ -1127,10 +1124,10 @@ mod tests {
use frame_support::weights::Weight; use frame_support::weights::Weight;
use std::ops::RangeInclusive; use std::ops::RangeInclusive;
const DELIVERY_TRANSACTION_WEIGHT: Weight = 100; const DELIVERY_TRANSACTION_WEIGHT: Weight = Weight::from_ref_time(100);
const DELIVERY_CONFIRMATION_TRANSACTION_WEIGHT: Weight = 100; const DELIVERY_CONFIRMATION_TRANSACTION_WEIGHT: u64 = 100;
const THIS_CHAIN_WEIGHT_TO_BALANCE_RATE: Weight = 2; const THIS_CHAIN_WEIGHT_TO_BALANCE_RATE: u32 = 2;
const BRIDGED_CHAIN_WEIGHT_TO_BALANCE_RATE: Weight = 4; const BRIDGED_CHAIN_WEIGHT_TO_BALANCE_RATE: u32 = 4;
const BRIDGED_CHAIN_TO_THIS_CHAIN_BALANCE_RATE: u32 = 6; const BRIDGED_CHAIN_TO_THIS_CHAIN_BALANCE_RATE: u32 = 6;
const BRIDGED_CHAIN_MIN_EXTRINSIC_WEIGHT: usize = 5; const BRIDGED_CHAIN_MIN_EXTRINSIC_WEIGHT: usize = 5;
const BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT: usize = 2048; const BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT: usize = 2048;
@@ -1301,13 +1298,12 @@ mod tests {
type AccountId = ThisChainAccountId; type AccountId = ThisChainAccountId;
type Signer = ThisChainSigner; type Signer = ThisChainSigner;
type Signature = ThisChainSignature; type Signature = ThisChainSignature;
type Weight = frame_support::weights::Weight;
type Balance = ThisChainBalance; type Balance = ThisChainBalance;
} }
impl ThisChainWithMessages for ThisChain { impl ThisChainWithMessages for ThisChain {
type Origin = ThisChainOrigin; type RuntimeOrigin = ThisChainOrigin;
type Call = ThisChainCall; type RuntimeCall = ThisChainCall;
type ConfirmationTransactionEstimation = BasicConfirmationTransactionEstimation< type ConfirmationTransactionEstimation = BasicConfirmationTransactionEstimation<
<ThisChain as ChainWithMessages>::AccountId, <ThisChain as ChainWithMessages>::AccountId,
{ DELIVERY_CONFIRMATION_TRANSACTION_WEIGHT }, { DELIVERY_CONFIRMATION_TRANSACTION_WEIGHT },
@@ -1315,7 +1311,7 @@ mod tests {
0, 0,
>; >;
fn is_message_accepted(_send_origin: &Self::Origin, lane: &LaneId) -> bool { fn is_message_accepted(_send_origin: &Self::RuntimeOrigin, lane: &LaneId) -> bool {
lane == TEST_LANE_ID lane == TEST_LANE_ID
} }
@@ -1323,9 +1319,12 @@ mod tests {
MAXIMAL_PENDING_MESSAGES_AT_TEST_LANE MAXIMAL_PENDING_MESSAGES_AT_TEST_LANE
} }
fn transaction_payment(transaction: MessageTransaction<WeightOf<Self>>) -> BalanceOf<Self> { fn transaction_payment(transaction: MessageTransaction<Weight>) -> BalanceOf<Self> {
ThisChainBalance( ThisChainBalance(
transaction.dispatch_weight as u32 * THIS_CHAIN_WEIGHT_TO_BALANCE_RATE as u32, transaction
.dispatch_weight
.saturating_mul(THIS_CHAIN_WEIGHT_TO_BALANCE_RATE as u64)
.ref_time() as _,
) )
} }
} }
@@ -1342,14 +1341,12 @@ mod tests {
fn estimate_delivery_transaction( fn estimate_delivery_transaction(
_message_payload: &[u8], _message_payload: &[u8],
_include_pay_dispatch_fee_cost: bool, _include_pay_dispatch_fee_cost: bool,
_message_dispatch_weight: WeightOf<Self>, _message_dispatch_weight: Weight,
) -> MessageTransaction<WeightOf<Self>> { ) -> MessageTransaction<Weight> {
unreachable!() unreachable!()
} }
fn transaction_payment( fn transaction_payment(_transaction: MessageTransaction<Weight>) -> BalanceOf<Self> {
_transaction: MessageTransaction<WeightOf<Self>>,
) -> BalanceOf<Self> {
unreachable!() unreachable!()
} }
} }
@@ -1361,13 +1358,12 @@ mod tests {
type AccountId = BridgedChainAccountId; type AccountId = BridgedChainAccountId;
type Signer = BridgedChainSigner; type Signer = BridgedChainSigner;
type Signature = BridgedChainSignature; type Signature = BridgedChainSignature;
type Weight = frame_support::weights::Weight;
type Balance = BridgedChainBalance; type Balance = BridgedChainBalance;
} }
impl ThisChainWithMessages for BridgedChain { impl ThisChainWithMessages for BridgedChain {
type Origin = BridgedChainOrigin; type RuntimeOrigin = BridgedChainOrigin;
type Call = BridgedChainCall; type RuntimeCall = BridgedChainCall;
type ConfirmationTransactionEstimation = BasicConfirmationTransactionEstimation< type ConfirmationTransactionEstimation = BasicConfirmationTransactionEstimation<
<BridgedChain as ChainWithMessages>::AccountId, <BridgedChain as ChainWithMessages>::AccountId,
0, 0,
@@ -1375,7 +1371,7 @@ mod tests {
0, 0,
>; >;
fn is_message_accepted(_send_origin: &Self::Origin, _lane: &LaneId) -> bool { fn is_message_accepted(_send_origin: &Self::RuntimeOrigin, _lane: &LaneId) -> bool {
unreachable!() unreachable!()
} }
@@ -1383,9 +1379,7 @@ mod tests {
unreachable!() unreachable!()
} }
fn transaction_payment( fn transaction_payment(_transaction: MessageTransaction<Weight>) -> BalanceOf<Self> {
_transaction: MessageTransaction<WeightOf<Self>>,
) -> BalanceOf<Self> {
unreachable!() unreachable!()
} }
} }
@@ -1403,17 +1397,20 @@ mod tests {
fn estimate_delivery_transaction( fn estimate_delivery_transaction(
_message_payload: &[u8], _message_payload: &[u8],
_include_pay_dispatch_fee_cost: bool, _include_pay_dispatch_fee_cost: bool,
message_dispatch_weight: WeightOf<Self>, message_dispatch_weight: Weight,
) -> MessageTransaction<WeightOf<Self>> { ) -> MessageTransaction<Weight> {
MessageTransaction { MessageTransaction {
dispatch_weight: DELIVERY_TRANSACTION_WEIGHT + message_dispatch_weight, dispatch_weight: DELIVERY_TRANSACTION_WEIGHT + message_dispatch_weight,
size: 0, size: 0,
} }
} }
fn transaction_payment(transaction: MessageTransaction<WeightOf<Self>>) -> BalanceOf<Self> { fn transaction_payment(transaction: MessageTransaction<Weight>) -> BalanceOf<Self> {
BridgedChainBalance( BridgedChainBalance(
transaction.dispatch_weight as u32 * BRIDGED_CHAIN_WEIGHT_TO_BALANCE_RATE as u32, transaction
.dispatch_weight
.saturating_mul(BRIDGED_CHAIN_WEIGHT_TO_BALANCE_RATE as u64)
.ref_time() as _,
) )
} }
} }
@@ -1786,11 +1783,11 @@ mod tests {
assert_eq!( assert_eq!(
transaction_payment( transaction_payment(
100, Weight::from_ref_time(100),
10, 10,
FixedU128::zero(), FixedU128::zero(),
|weight| weight, |weight| weight.ref_time(),
MessageTransaction { size: 50, dispatch_weight: 777 }, MessageTransaction { size: 50, dispatch_weight: Weight::from_ref_time(777) },
), ),
100 + 50 * 10, 100 + 50 * 10,
); );
@@ -1801,12 +1798,12 @@ mod tests {
use sp_runtime::traits::One; use sp_runtime::traits::One;
assert_eq!( assert_eq!(
transaction_payment( transaction_payment::<u64>(
100, Weight::from_ref_time(100),
10, 10,
FixedU128::one(), FixedU128::one(),
|weight| weight, |weight| weight.ref_time(),
MessageTransaction { size: 50, dispatch_weight: 777 }, MessageTransaction { size: 50, dispatch_weight: Weight::from_ref_time(777) },
), ),
100 + 50 * 10 + 777, 100 + 50 * 10 + 777,
); );
@@ -39,7 +39,7 @@ where
nonce, nonce,
// dispatch message weight is always zero at the source chain, since we're paying for // dispatch message weight is always zero at the source chain, since we're paying for
// dispatch at the target chain // dispatch at the target chain
dispatch_weight: 0, dispatch_weight: frame_support::weights::Weight::from_ref_time(0),
size: message_data.payload.len() as _, size: message_data.payload.len() as _,
delivery_and_dispatch_fee: message_data.fee, delivery_and_dispatch_fee: message_data.fee,
// we're delivering XCM messages here, so fee is always paid at the target chain // we're delivering XCM messages here, so fee is always paid at the target chain
@@ -29,7 +29,7 @@ use crate::messages::{
use bp_messages::{storage_keys, MessageData, MessageKey, MessagePayload}; use bp_messages::{storage_keys, MessageData, MessageKey, MessagePayload};
use bp_runtime::{record_all_trie_keys, StorageProofSize}; use bp_runtime::{record_all_trie_keys, StorageProofSize};
use codec::Encode; use codec::Encode;
use frame_support::weights::{GetDispatchInfo, Weight}; use frame_support::{dispatch::GetDispatchInfo, weights::Weight};
use pallet_bridge_messages::benchmarking::{ use pallet_bridge_messages::benchmarking::{
MessageDeliveryProofParams, MessageParams, MessageProofParams, MessageDeliveryProofParams, MessageParams, MessageProofParams,
}; };
@@ -94,7 +94,7 @@ where
nonces_start: *params.message_nonces.start(), nonces_start: *params.message_nonces.start(),
nonces_end: *params.message_nonces.end(), nonces_end: *params.message_nonces.end(),
}, },
0, Weight::from_ref_time(0),
) )
} }
@@ -40,7 +40,7 @@ impl<
MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof<BridgedHeaderHash>, MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof<BridgedHeaderHash>,
>, >,
Call: IsSubType<CallableCallFor<Pallet<T, I>, T>>, Call: IsSubType<CallableCallFor<Pallet<T, I>, T>>,
T: frame_system::Config<Call = Call> T: frame_system::Config<RuntimeCall = Call>
+ Config<I, SourceHeaderChain = SourceHeaderChain, TargetHeaderChain = TargetHeaderChain>, + Config<I, SourceHeaderChain = SourceHeaderChain, TargetHeaderChain = TargetHeaderChain>,
I: 'static, I: 'static,
> BridgeRuntimeFilterCall<Call> for Pallet<T, I> > BridgeRuntimeFilterCall<Call> for Pallet<T, I>
@@ -106,7 +106,7 @@ mod tests {
}, },
BridgeRuntimeFilterCall, BridgeRuntimeFilterCall,
}, },
Call, Runtime, WithRialtoMessagesInstance, Runtime, RuntimeCall, WithRialtoMessagesInstance,
}; };
fn deliver_message_10() { fn deliver_message_10() {
@@ -121,11 +121,11 @@ mod tests {
nonces_end: bp_messages::MessageNonce, nonces_end: bp_messages::MessageNonce,
) -> bool { ) -> bool {
pallet_bridge_messages::Pallet::<Runtime, WithRialtoMessagesInstance>::validate( pallet_bridge_messages::Pallet::<Runtime, WithRialtoMessagesInstance>::validate(
&Call::BridgeRialtoMessages( &RuntimeCall::BridgeRialtoMessages(
pallet_bridge_messages::Call::<Runtime, ()>::receive_messages_proof { pallet_bridge_messages::Call::<Runtime, ()>::receive_messages_proof {
relayer_id_at_bridged_chain: [0u8; 32].into(), relayer_id_at_bridged_chain: [0u8; 32].into(),
messages_count: (nonces_end - nonces_start + 1) as u32, messages_count: (nonces_end - nonces_start + 1) as u32,
dispatch_weight: 0, dispatch_weight: frame_support::weights::Weight::from_ref_time(0),
proof: FromBridgedChainMessagesProof { proof: FromBridgedChainMessagesProof {
bridged_header_hash: Default::default(), bridged_header_hash: Default::default(),
storage_proof: vec![], storage_proof: vec![],
@@ -182,7 +182,7 @@ mod tests {
fn validate_message_confirmation(last_delivered_nonce: bp_messages::MessageNonce) -> bool { fn validate_message_confirmation(last_delivered_nonce: bp_messages::MessageNonce) -> bool {
pallet_bridge_messages::Pallet::<Runtime, WithRialtoMessagesInstance>::validate( pallet_bridge_messages::Pallet::<Runtime, WithRialtoMessagesInstance>::validate(
&Call::BridgeRialtoMessages(pallet_bridge_messages::Call::< &RuntimeCall::BridgeRialtoMessages(pallet_bridge_messages::Call::<
Runtime, Runtime,
WithRialtoMessagesInstance, WithRialtoMessagesInstance,
>::receive_messages_delivery_proof { >::receive_messages_delivery_proof {
+10 -9
View File
@@ -27,11 +27,11 @@ use sp_runtime::{
/// if there are multiple relays running and submitting the same information. /// if there are multiple relays running and submitting the same information.
impl< impl<
Call: IsSubType<CallableCallFor<Pallet<T, I>, T>>, Call: IsSubType<CallableCallFor<Pallet<T, I>, T>>,
T: frame_system::Config<Call = Call> + Config<I>, T: frame_system::Config<RuntimeCall = Call> + Config<I>,
I: 'static, I: 'static,
> FilterCall<Call> for Pallet<T, I> > FilterCall<Call> for Pallet<T, I>
{ {
fn validate(call: &<T as frame_system::Config>::Call) -> TransactionValidity { fn validate(call: &<T as frame_system::Config>::RuntimeCall) -> TransactionValidity {
let bundled_block_number = match call.is_sub_type() { let bundled_block_number = match call.is_sub_type() {
Some(crate::Call::<T, I>::submit_finality_proof { ref finality_target, .. }) => Some(crate::Call::<T, I>::submit_finality_proof { ref finality_target, .. }) =>
*finality_target.number(), *finality_target.number(),
@@ -63,18 +63,19 @@ impl<
mod tests { mod tests {
use super::FilterCall; use super::FilterCall;
use crate::{ use crate::{
mock::{run_test, test_header, Call, TestNumber, TestRuntime}, mock::{run_test, test_header, RuntimeCall, TestNumber, TestRuntime},
BestFinalized, BestFinalized,
}; };
use bp_test_utils::make_default_justification; use bp_test_utils::make_default_justification;
fn validate_block_submit(num: TestNumber) -> bool { fn validate_block_submit(num: TestNumber) -> bool {
crate::Pallet::<TestRuntime>::validate(&Call::Grandpa( crate::Pallet::<TestRuntime>::validate(&RuntimeCall::Grandpa(crate::Call::<
crate::Call::<TestRuntime, ()>::submit_finality_proof { TestRuntime,
finality_target: Box::new(test_header(num)), (),
justification: make_default_justification(&test_header(num)), >::submit_finality_proof {
}, finality_target: Box::new(test_header(num)),
)) justification: make_default_justification(&test_header(num)),
}))
.is_ok() .is_ok()
} }
+28 -28
View File
@@ -135,7 +135,7 @@ pub mod pallet {
fn on_initialize(_n: T::BlockNumber) -> frame_support::weights::Weight { fn on_initialize(_n: T::BlockNumber) -> frame_support::weights::Weight {
<RequestCount<T, I>>::mutate(|count| *count = count.saturating_sub(1)); <RequestCount<T, I>>::mutate(|count| *count = count.saturating_sub(1));
(0_u64) Weight::from_ref_time(0)
.saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes(1))
} }
@@ -666,7 +666,7 @@ pub fn initialize_for_benchmarks<T: Config<I>, I: 'static>(header: BridgedHeader
mod tests { mod tests {
use super::*; use super::*;
use crate::mock::{ use crate::mock::{
run_test, test_header, Origin, TestHeader, TestNumber, TestRuntime, run_test, test_header, RuntimeOrigin, TestHeader, TestNumber, TestRuntime,
MAX_BRIDGED_AUTHORITIES, MAX_HEADER_SIZE, MAX_BRIDGED_AUTHORITIES, MAX_HEADER_SIZE,
}; };
use bp_runtime::BasicOperatingMode; use bp_runtime::BasicOperatingMode;
@@ -676,17 +676,17 @@ mod tests {
}; };
use codec::Encode; use codec::Encode;
use frame_support::{ use frame_support::{
assert_err, assert_noop, assert_ok, storage::generator::StorageValue, assert_err, assert_noop, assert_ok, dispatch::PostDispatchInfo,
weights::PostDispatchInfo, storage::generator::StorageValue,
}; };
use sp_runtime::{Digest, DigestItem, DispatchError}; use sp_runtime::{Digest, DigestItem, DispatchError};
fn initialize_substrate_bridge() { fn initialize_substrate_bridge() {
assert_ok!(init_with_origin(Origin::root())); assert_ok!(init_with_origin(RuntimeOrigin::root()));
} }
fn init_with_origin( fn init_with_origin(
origin: Origin, origin: RuntimeOrigin,
) -> Result< ) -> Result<
InitializationData<TestHeader>, InitializationData<TestHeader>,
sp_runtime::DispatchErrorWithPostInfo<PostDispatchInfo>, sp_runtime::DispatchErrorWithPostInfo<PostDispatchInfo>,
@@ -708,7 +708,7 @@ mod tests {
let justification = make_default_justification(&header); let justification = make_default_justification(&header);
Pallet::<TestRuntime>::submit_finality_proof( Pallet::<TestRuntime>::submit_finality_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
Box::new(header), Box::new(header),
justification, justification,
) )
@@ -763,13 +763,13 @@ mod tests {
#[test] #[test]
fn init_root_or_owner_origin_can_initialize_pallet() { fn init_root_or_owner_origin_can_initialize_pallet() {
run_test(|| { run_test(|| {
assert_noop!(init_with_origin(Origin::signed(1)), DispatchError::BadOrigin); assert_noop!(init_with_origin(RuntimeOrigin::signed(1)), DispatchError::BadOrigin);
assert_ok!(init_with_origin(Origin::root())); assert_ok!(init_with_origin(RuntimeOrigin::root()));
// Reset storage so we can initialize the pallet again // Reset storage so we can initialize the pallet again
BestFinalized::<TestRuntime>::kill(); BestFinalized::<TestRuntime>::kill();
PalletOwner::<TestRuntime>::put(2); PalletOwner::<TestRuntime>::put(2);
assert_ok!(init_with_origin(Origin::signed(2))); assert_ok!(init_with_origin(RuntimeOrigin::signed(2)));
}) })
} }
@@ -779,7 +779,7 @@ mod tests {
assert_eq!(BestFinalized::<TestRuntime>::get(), None,); assert_eq!(BestFinalized::<TestRuntime>::get(), None,);
assert_eq!(Pallet::<TestRuntime>::best_finalized(), None); assert_eq!(Pallet::<TestRuntime>::best_finalized(), None);
let init_data = init_with_origin(Origin::root()).unwrap(); let init_data = init_with_origin(RuntimeOrigin::root()).unwrap();
assert!(<ImportedHeaders<TestRuntime>>::contains_key(init_data.header.hash())); assert!(<ImportedHeaders<TestRuntime>>::contains_key(init_data.header.hash()));
assert_eq!(BestFinalized::<TestRuntime>::get().unwrap().1, init_data.header.hash()); assert_eq!(BestFinalized::<TestRuntime>::get().unwrap().1, init_data.header.hash());
@@ -796,7 +796,7 @@ mod tests {
run_test(|| { run_test(|| {
initialize_substrate_bridge(); initialize_substrate_bridge();
assert_noop!( assert_noop!(
init_with_origin(Origin::root()), init_with_origin(RuntimeOrigin::root()),
<Error<TestRuntime>>::AlreadyInitialized <Error<TestRuntime>>::AlreadyInitialized
); );
}) })
@@ -816,7 +816,7 @@ mod tests {
}; };
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::initialize(Origin::root(), init_data), Pallet::<TestRuntime>::initialize(RuntimeOrigin::root(), init_data),
Error::<TestRuntime>::TooManyAuthoritiesInSet, Error::<TestRuntime>::TooManyAuthoritiesInSet,
); );
}); });
@@ -835,7 +835,7 @@ mod tests {
}; };
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::initialize(Origin::root(), init_data), Pallet::<TestRuntime>::initialize(RuntimeOrigin::root(), init_data),
Error::<TestRuntime>::TooLargeHeader, Error::<TestRuntime>::TooLargeHeader,
); );
}); });
@@ -847,7 +847,7 @@ mod tests {
initialize_substrate_bridge(); initialize_substrate_bridge();
assert_ok!(Pallet::<TestRuntime>::set_operating_mode( assert_ok!(Pallet::<TestRuntime>::set_operating_mode(
Origin::root(), RuntimeOrigin::root(),
BasicOperatingMode::Halted BasicOperatingMode::Halted
)); ));
assert_noop!( assert_noop!(
@@ -856,7 +856,7 @@ mod tests {
); );
assert_ok!(Pallet::<TestRuntime>::set_operating_mode( assert_ok!(Pallet::<TestRuntime>::set_operating_mode(
Origin::root(), RuntimeOrigin::root(),
BasicOperatingMode::Normal BasicOperatingMode::Normal
)); ));
assert_ok!(submit_finality_proof(1)); assert_ok!(submit_finality_proof(1));
@@ -878,7 +878,7 @@ mod tests {
submit_finality_proof(1), submit_finality_proof(1),
PostDispatchInfo { PostDispatchInfo {
actual_weight: None, actual_weight: None,
pays_fee: frame_support::weights::Pays::Yes, pays_fee: frame_support::dispatch::Pays::Yes,
}, },
); );
@@ -901,7 +901,7 @@ mod tests {
assert_err!( assert_err!(
Pallet::<TestRuntime>::submit_finality_proof( Pallet::<TestRuntime>::submit_finality_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
Box::new(header), Box::new(header),
justification, justification,
), ),
@@ -921,7 +921,7 @@ mod tests {
assert_err!( assert_err!(
Pallet::<TestRuntime>::submit_finality_proof( Pallet::<TestRuntime>::submit_finality_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
Box::new(header), Box::new(header),
justification, justification,
), ),
@@ -943,14 +943,14 @@ mod tests {
operating_mode: BasicOperatingMode::Normal, operating_mode: BasicOperatingMode::Normal,
}; };
assert_ok!(Pallet::<TestRuntime>::initialize(Origin::root(), init_data)); assert_ok!(Pallet::<TestRuntime>::initialize(RuntimeOrigin::root(), init_data));
let header = test_header(1); let header = test_header(1);
let justification = make_default_justification(&header); let justification = make_default_justification(&header);
assert_err!( assert_err!(
Pallet::<TestRuntime>::submit_finality_proof( Pallet::<TestRuntime>::submit_finality_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
Box::new(header), Box::new(header),
justification, justification,
), ),
@@ -989,13 +989,13 @@ mod tests {
// Let's import our test header // Let's import our test header
assert_ok!( assert_ok!(
Pallet::<TestRuntime>::submit_finality_proof( Pallet::<TestRuntime>::submit_finality_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
Box::new(header.clone()), Box::new(header.clone()),
justification justification
), ),
PostDispatchInfo { PostDispatchInfo {
actual_weight: None, actual_weight: None,
pays_fee: frame_support::weights::Pays::No, pays_fee: frame_support::dispatch::Pays::No,
}, },
); );
@@ -1028,7 +1028,7 @@ mod tests {
// Should not be allowed to import this header // Should not be allowed to import this header
assert_err!( assert_err!(
Pallet::<TestRuntime>::submit_finality_proof( Pallet::<TestRuntime>::submit_finality_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
Box::new(header), Box::new(header),
justification justification
), ),
@@ -1053,7 +1053,7 @@ mod tests {
// Should not be allowed to import this header // Should not be allowed to import this header
assert_err!( assert_err!(
Pallet::<TestRuntime>::submit_finality_proof( Pallet::<TestRuntime>::submit_finality_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
Box::new(header), Box::new(header),
justification justification
), ),
@@ -1078,7 +1078,7 @@ mod tests {
// Should not be allowed to import this header // Should not be allowed to import this header
assert_err!( assert_err!(
Pallet::<TestRuntime>::submit_finality_proof( Pallet::<TestRuntime>::submit_finality_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
Box::new(header), Box::new(header),
justification justification
), ),
@@ -1103,7 +1103,7 @@ mod tests {
// Should not be allowed to import this header // Should not be allowed to import this header
assert_err!( assert_err!(
Pallet::<TestRuntime>::submit_finality_proof( Pallet::<TestRuntime>::submit_finality_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
Box::new(header), Box::new(header),
justification justification
), ),
@@ -1168,7 +1168,7 @@ mod tests {
invalid_justification.round = 42; invalid_justification.round = 42;
Pallet::<TestRuntime>::submit_finality_proof( Pallet::<TestRuntime>::submit_finality_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
Box::new(header), Box::new(header),
invalid_justification, invalid_justification,
) )
+4 -4
View File
@@ -51,22 +51,22 @@ construct_runtime! {
parameter_types! { parameter_types! {
pub const BlockHashCount: u64 = 250; pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockWeight: Weight = Weight::from_ref_time(1024);
pub const MaximumBlockLength: u32 = 2 * 1024; pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one(); pub const AvailableBlockRatio: Perbill = Perbill::one();
} }
impl frame_system::Config for TestRuntime { impl frame_system::Config for TestRuntime {
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
type Index = u64; type Index = u64;
type Call = Call; type RuntimeCall = RuntimeCall;
type BlockNumber = u64; type BlockNumber = u64;
type Hash = H256; type Hash = H256;
type Hashing = BlakeTwo256; type Hashing = BlakeTwo256;
type AccountId = AccountId; type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header; type Header = Header;
type Event = (); type RuntimeEvent = ();
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
type Version = (); type Version = ();
type PalletInfo = PalletInfo; type PalletInfo = PalletInfo;
+1 -1
View File
@@ -43,7 +43,7 @@ impl<T: Config<I>, I: 'static> StoredAuthoritySet<T, I> {
/// ///
/// Returns error if number of authorities in the provided list is too large. /// Returns error if number of authorities in the provided list is too large.
pub fn try_new(authorities: AuthorityList, set_id: SetId) -> Result<Self, ()> { pub fn try_new(authorities: AuthorityList, set_id: SetId) -> Result<Self, ()> {
Ok(Self { authorities: TryFrom::try_from(authorities)?, set_id }) Ok(Self { authorities: TryFrom::try_from(authorities).map_err(drop)?, set_id })
} }
} }
+10 -10
View File
@@ -59,21 +59,21 @@ pub trait WeightInfo {
pub struct BridgeWeight<T>(PhantomData<T>); pub struct BridgeWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> { impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
fn submit_finality_proof(p: u32, v: u32) -> Weight { fn submit_finality_proof(p: u32, v: u32) -> Weight {
(105_417_000 as Weight) Weight::from_ref_time(105_417_000 as u64)
.saturating_add((40_923_000 as Weight).saturating_mul(p as Weight)) .saturating_add(Weight::from_ref_time(40_923_000 as u64).saturating_mul(p as u64))
.saturating_add((1_691_000 as Weight).saturating_mul(v as Weight)) .saturating_add(Weight::from_ref_time(1_691_000 as u64).saturating_mul(v as u64))
.saturating_add(T::DbWeight::get().reads(7 as Weight)) .saturating_add(T::DbWeight::get().reads(7 as u64))
.saturating_add(T::DbWeight::get().writes(6 as Weight)) .saturating_add(T::DbWeight::get().writes(6 as u64))
} }
} }
// For backwards compatibility and tests // For backwards compatibility and tests
impl WeightInfo for () { impl WeightInfo for () {
fn submit_finality_proof(p: u32, v: u32) -> Weight { fn submit_finality_proof(p: u32, v: u32) -> Weight {
(105_417_000 as Weight) Weight::from_ref_time(105_417_000 as u64)
.saturating_add((40_923_000 as Weight).saturating_mul(p as Weight)) .saturating_add(Weight::from_ref_time(40_923_000 as u64).saturating_mul(p as u64))
.saturating_add((1_691_000 as Weight).saturating_mul(v as Weight)) .saturating_add(Weight::from_ref_time(1_691_000 as u64).saturating_mul(v as u64))
.saturating_add(RocksDbWeight::get().reads(7 as Weight)) .saturating_add(RocksDbWeight::get().reads(7 as u64))
.saturating_add(RocksDbWeight::get().writes(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(6 as u64))
} }
} }
+1 -1
View File
@@ -554,7 +554,7 @@ mod tests {
run_test(|| { run_test(|| {
let mut lane = inbound_lane::<TestRuntime, _>(TEST_LANE_ID); let mut lane = inbound_lane::<TestRuntime, _>(TEST_LANE_ID);
let mut payload = REGULAR_PAYLOAD; let mut payload = REGULAR_PAYLOAD;
payload.dispatch_result.unspent_weight = 1; *payload.dispatch_result.unspent_weight.ref_time_mut() = 1;
assert_eq!( assert_eq!(
lane.receive_message::<TestMessageDispatch, _>( lane.receive_message::<TestMessageDispatch, _>(
&TEST_RELAYER_A, &TEST_RELAYER_A,
+137 -105
View File
@@ -65,11 +65,7 @@ use bp_messages::{
}; };
use bp_runtime::{BasicOperatingMode, ChainId, OwnedBridgeModule, Size}; use bp_runtime::{BasicOperatingMode, ChainId, OwnedBridgeModule, Size};
use codec::{Decode, Encode, MaxEncodedLen}; use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{ use frame_support::{dispatch::PostDispatchInfo, ensure, fail, traits::Get};
ensure, fail,
traits::Get,
weights::{Pays, PostDispatchInfo},
};
use num_traits::{SaturatingAdd, Zero}; use num_traits::{SaturatingAdd, Zero};
use sp_std::{ use sp_std::{
cell::RefCell, cmp::PartialOrd, collections::vec_deque::VecDeque, marker::PhantomData, cell::RefCell, cmp::PartialOrd, collections::vec_deque::VecDeque, marker::PhantomData,
@@ -104,7 +100,8 @@ pub mod pallet {
// General types // General types
/// The overarching event type. /// The overarching event type.
type Event: From<Event<Self, I>> + IsType<<Self as frame_system::Config>::Event>; type RuntimeEvent: From<Event<Self, I>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Benchmarks results from runtime we're plugged into. /// Benchmarks results from runtime we're plugged into.
type WeightInfo: WeightInfoExt; type WeightInfo: WeightInfoExt;
@@ -174,13 +171,13 @@ pub mod pallet {
type TargetHeaderChain: TargetHeaderChain<Self::OutboundPayload, Self::AccountId>; type TargetHeaderChain: TargetHeaderChain<Self::OutboundPayload, Self::AccountId>;
/// Message payload verifier. /// Message payload verifier.
type LaneMessageVerifier: LaneMessageVerifier< type LaneMessageVerifier: LaneMessageVerifier<
Self::Origin, Self::RuntimeOrigin,
Self::OutboundPayload, Self::OutboundPayload,
Self::OutboundMessageFee, Self::OutboundMessageFee,
>; >;
/// Message delivery payment. /// Message delivery payment.
type MessageDeliveryAndDispatchPayment: MessageDeliveryAndDispatchPayment< type MessageDeliveryAndDispatchPayment: MessageDeliveryAndDispatchPayment<
Self::Origin, Self::RuntimeOrigin,
Self::AccountId, Self::AccountId,
Self::OutboundMessageFee, Self::OutboundMessageFee,
>; >;
@@ -333,9 +330,10 @@ pub mod pallet {
}); });
// compute actual dispatch weight that depends on the stored message size // compute actual dispatch weight that depends on the stored message size
let actual_weight = sp_std::cmp::min( let actual_weight = sp_std::cmp::min_by(
T::WeightInfo::maximal_increase_message_fee(), T::WeightInfo::maximal_increase_message_fee(),
T::WeightInfo::increase_message_fee(message_size as _), T::WeightInfo::increase_message_fee(message_size as _),
|w1, w2| w1.ref_time().cmp(&w2.ref_time()),
); );
Ok(PostDispatchInfo { actual_weight: Some(actual_weight), pays_fee: Pays::Yes }) Ok(PostDispatchInfo { actual_weight: Some(actual_weight), pays_fee: Pays::Yes })
@@ -418,7 +416,7 @@ pub mod pallet {
// on this lane. We can't dispatch lane messages out-of-order, so if declared // on this lane. We can't dispatch lane messages out-of-order, so if declared
// weight is not enough, let's move to next lane // weight is not enough, let's move to next lane
let dispatch_weight = T::MessageDispatch::dispatch_weight(&mut message); let dispatch_weight = T::MessageDispatch::dispatch_weight(&mut message);
if dispatch_weight > dispatch_weight_left { if dispatch_weight.ref_time() > dispatch_weight_left.ref_time() {
log::trace!( log::trace!(
target: LOG_TARGET, target: LOG_TARGET,
"Cannot dispatch any more messages on lane {:?}. Weight: declared={}, left={}", "Cannot dispatch any more messages on lane {:?}. Weight: declared={}, left={}",
@@ -456,7 +454,10 @@ pub mod pallet {
ReceivalResult::TooManyUnconfirmedMessages => (dispatch_weight, true), ReceivalResult::TooManyUnconfirmedMessages => (dispatch_weight, true),
}; };
let unspent_weight = sp_std::cmp::min(unspent_weight, dispatch_weight); let unspent_weight =
sp_std::cmp::min_by(unspent_weight, dispatch_weight, |w1, w2| {
w1.ref_time().cmp(&w2.ref_time())
});
dispatch_weight_left -= dispatch_weight - unspent_weight; dispatch_weight_left -= dispatch_weight - unspent_weight;
actual_weight = actual_weight.saturating_sub(unspent_weight).saturating_sub( actual_weight = actual_weight.saturating_sub(unspent_weight).saturating_sub(
// delivery call weight formula assumes that the fee is paid at // delivery call weight formula assumes that the fee is paid at
@@ -465,7 +466,7 @@ pub mod pallet {
if refund_pay_dispatch_fee { if refund_pay_dispatch_fee {
T::WeightInfo::pay_inbound_dispatch_fee_overhead() T::WeightInfo::pay_inbound_dispatch_fee_overhead()
} else { } else {
0 Weight::from_ref_time(0)
}, },
); );
} }
@@ -580,11 +581,11 @@ pub mod pallet {
if let Some(confirmed_messages) = confirmed_messages { if let Some(confirmed_messages) = confirmed_messages {
// handle messages delivery confirmation // handle messages delivery confirmation
let preliminary_callback_overhead = let preliminary_callback_overhead =
relayers_state.total_messages.saturating_mul(single_message_callback_overhead); single_message_callback_overhead.saturating_mul(relayers_state.total_messages);
let actual_callback_weight = let actual_callback_weight =
T::OnDeliveryConfirmed::on_messages_delivered(&lane_id, &confirmed_messages); T::OnDeliveryConfirmed::on_messages_delivered(&lane_id, &confirmed_messages);
match preliminary_callback_overhead.checked_sub(actual_callback_weight) { match preliminary_callback_overhead.checked_sub(&actual_callback_weight) {
Some(difference) if difference == 0 => (), Some(difference) if difference.ref_time() == 0 => (),
Some(difference) => { Some(difference) => {
log::trace!( log::trace!(
target: LOG_TARGET, target: LOG_TARGET,
@@ -775,8 +776,11 @@ pub mod pallet {
} }
impl<T, I> impl<T, I>
bp_messages::source_chain::MessagesBridge<T::Origin, T::OutboundMessageFee, T::OutboundPayload> bp_messages::source_chain::MessagesBridge<
for Pallet<T, I> T::RuntimeOrigin,
T::OutboundMessageFee,
T::OutboundPayload,
> for Pallet<T, I>
where where
T: Config<I>, T: Config<I>,
I: 'static, I: 'static,
@@ -784,7 +788,7 @@ where
type Error = sp_runtime::DispatchErrorWithPostInfo<PostDispatchInfo>; type Error = sp_runtime::DispatchErrorWithPostInfo<PostDispatchInfo>;
fn send_message( fn send_message(
sender: T::Origin, sender: T::RuntimeOrigin,
lane: LaneId, lane: LaneId,
message: T::OutboundPayload, message: T::OutboundPayload,
delivery_and_dispatch_fee: T::OutboundMessageFee, delivery_and_dispatch_fee: T::OutboundMessageFee,
@@ -795,7 +799,7 @@ where
/// Function that actually sends message. /// Function that actually sends message.
fn send_message<T: Config<I>, I: 'static>( fn send_message<T: Config<I>, I: 'static>(
submitter: T::Origin, submitter: T::RuntimeOrigin,
lane_id: LaneId, lane_id: LaneId,
payload: T::OutboundPayload, payload: T::OutboundPayload,
delivery_and_dispatch_fee: T::OutboundMessageFee, delivery_and_dispatch_fee: T::OutboundMessageFee,
@@ -875,8 +879,8 @@ fn send_message<T: Config<I>, I: 'static>(
let single_message_callback_overhead = let single_message_callback_overhead =
T::WeightInfo::single_message_callback_overhead(T::DbWeight::get()); T::WeightInfo::single_message_callback_overhead(T::DbWeight::get());
let actual_callback_weight = T::OnMessageAccepted::on_messages_accepted(&lane_id, &nonce); let actual_callback_weight = T::OnMessageAccepted::on_messages_accepted(&lane_id, &nonce);
match single_message_callback_overhead.checked_sub(actual_callback_weight) { match single_message_callback_overhead.checked_sub(&actual_callback_weight) {
Some(difference) if difference == 0 => (), Some(difference) if difference.ref_time() == 0 => (),
Some(difference) => { Some(difference) => {
log::trace!( log::trace!(
target: LOG_TARGET, target: LOG_TARGET,
@@ -1104,8 +1108,8 @@ fn verify_and_decode_messages_proof<Chain: SourceHeaderChain<Fee>, Fee, Dispatch
mod tests { mod tests {
use super::*; use super::*;
use crate::mock::{ use crate::mock::{
message, message_payload, run_test, unrewarded_relayer, Balance, Event as TestEvent, message, message_payload, run_test, unrewarded_relayer, Balance, RuntimeEvent as TestEvent,
Origin, TestMessageDeliveryAndDispatchPayment, TestMessagesDeliveryProof, RuntimeOrigin, TestMessageDeliveryAndDispatchPayment, TestMessagesDeliveryProof,
TestMessagesParameter, TestMessagesProof, TestOnDeliveryConfirmed1, TestMessagesParameter, TestMessagesProof, TestOnDeliveryConfirmed1,
TestOnDeliveryConfirmed2, TestOnMessageAccepted, TestRuntime, TokenConversionRate, TestOnDeliveryConfirmed2, TestOnMessageAccepted, TestRuntime, TokenConversionRate,
MAX_OUTBOUND_PAYLOAD_SIZE, PAYLOAD_REJECTED_BY_TARGET_CHAIN, REGULAR_PAYLOAD, TEST_LANE_ID, MAX_OUTBOUND_PAYLOAD_SIZE, PAYLOAD_REJECTED_BY_TARGET_CHAIN, REGULAR_PAYLOAD, TEST_LANE_ID,
@@ -1149,10 +1153,10 @@ mod tests {
let message_nonce = let message_nonce =
outbound_lane::<TestRuntime, ()>(TEST_LANE_ID).data().latest_generated_nonce + 1; outbound_lane::<TestRuntime, ()>(TEST_LANE_ID).data().latest_generated_nonce + 1;
let weight = Pallet::<TestRuntime>::send_message( let weight = Pallet::<TestRuntime>::send_message(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
REGULAR_PAYLOAD, REGULAR_PAYLOAD,
REGULAR_PAYLOAD.declared_weight, REGULAR_PAYLOAD.declared_weight.ref_time(),
) )
.expect("send_message has failed") .expect("send_message has failed")
.actual_weight .actual_weight
@@ -1174,7 +1178,7 @@ mod tests {
// check that fee has been withdrawn from submitter // check that fee has been withdrawn from submitter
assert!(TestMessageDeliveryAndDispatchPayment::is_fee_paid( assert!(TestMessageDeliveryAndDispatchPayment::is_fee_paid(
1, 1,
REGULAR_PAYLOAD.declared_weight REGULAR_PAYLOAD.declared_weight.ref_time()
)); ));
weight weight
@@ -1185,7 +1189,7 @@ mod tests {
System::<TestRuntime>::reset_events(); System::<TestRuntime>::reset_events();
assert_ok!(Pallet::<TestRuntime>::receive_messages_delivery_proof( assert_ok!(Pallet::<TestRuntime>::receive_messages_delivery_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TestMessagesDeliveryProof(Ok(( TestMessagesDeliveryProof(Ok((
TEST_LANE_ID, TEST_LANE_ID,
InboundLaneData { InboundLaneData {
@@ -1226,7 +1230,7 @@ mod tests {
let parameter = TestMessagesParameter::TokenConversionRate(10.into()); let parameter = TestMessagesParameter::TokenConversionRate(10.into());
assert_ok!(Pallet::<TestRuntime>::update_pallet_parameter( assert_ok!(Pallet::<TestRuntime>::update_pallet_parameter(
Origin::root(), RuntimeOrigin::root(),
parameter.clone(), parameter.clone(),
)); ));
@@ -1250,7 +1254,7 @@ mod tests {
let parameter = TestMessagesParameter::TokenConversionRate(10.into()); let parameter = TestMessagesParameter::TokenConversionRate(10.into());
assert_ok!(Pallet::<TestRuntime>::update_pallet_parameter( assert_ok!(Pallet::<TestRuntime>::update_pallet_parameter(
Origin::signed(2), RuntimeOrigin::signed(2),
parameter.clone(), parameter.clone(),
)); ));
@@ -1271,7 +1275,7 @@ mod tests {
run_test(|| { run_test(|| {
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::update_pallet_parameter( Pallet::<TestRuntime>::update_pallet_parameter(
Origin::signed(2), RuntimeOrigin::signed(2),
TestMessagesParameter::TokenConversionRate(10.into()), TestMessagesParameter::TokenConversionRate(10.into()),
), ),
DispatchError::BadOrigin, DispatchError::BadOrigin,
@@ -1281,7 +1285,7 @@ mod tests {
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::update_pallet_parameter( Pallet::<TestRuntime>::update_pallet_parameter(
Origin::signed(1), RuntimeOrigin::signed(1),
TestMessagesParameter::TokenConversionRate(10.into()), TestMessagesParameter::TokenConversionRate(10.into()),
), ),
DispatchError::BadOrigin, DispatchError::BadOrigin,
@@ -1327,22 +1331,27 @@ mod tests {
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::send_message( Pallet::<TestRuntime>::send_message(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
REGULAR_PAYLOAD, REGULAR_PAYLOAD,
REGULAR_PAYLOAD.declared_weight, REGULAR_PAYLOAD.declared_weight.ref_time(),
), ),
Error::<TestRuntime, ()>::NotOperatingNormally, Error::<TestRuntime, ()>::NotOperatingNormally,
); );
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::increase_message_fee(Origin::signed(1), TEST_LANE_ID, 1, 1,), Pallet::<TestRuntime>::increase_message_fee(
RuntimeOrigin::signed(1),
TEST_LANE_ID,
1,
1,
),
Error::<TestRuntime, ()>::BridgeModule(bp_runtime::OwnedBridgeModuleError::Halted), Error::<TestRuntime, ()>::BridgeModule(bp_runtime::OwnedBridgeModuleError::Halted),
); );
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::receive_messages_proof( Pallet::<TestRuntime>::receive_messages_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_RELAYER_A, TEST_RELAYER_A,
Ok(vec![message(2, REGULAR_PAYLOAD)]).into(), Ok(vec![message(2, REGULAR_PAYLOAD)]).into(),
1, 1,
@@ -1353,7 +1362,7 @@ mod tests {
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::receive_messages_delivery_proof( Pallet::<TestRuntime>::receive_messages_delivery_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TestMessagesDeliveryProof(Ok(( TestMessagesDeliveryProof(Ok((
TEST_LANE_ID, TEST_LANE_ID,
InboundLaneData { InboundLaneData {
@@ -1387,23 +1396,23 @@ mod tests {
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::send_message( Pallet::<TestRuntime>::send_message(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
REGULAR_PAYLOAD, REGULAR_PAYLOAD,
REGULAR_PAYLOAD.declared_weight, REGULAR_PAYLOAD.declared_weight.ref_time(),
), ),
Error::<TestRuntime, ()>::NotOperatingNormally, Error::<TestRuntime, ()>::NotOperatingNormally,
); );
assert_ok!(Pallet::<TestRuntime>::increase_message_fee( assert_ok!(Pallet::<TestRuntime>::increase_message_fee(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
1, 1,
1, 1,
)); ));
assert_ok!(Pallet::<TestRuntime>::receive_messages_proof( assert_ok!(Pallet::<TestRuntime>::receive_messages_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_RELAYER_A, TEST_RELAYER_A,
Ok(vec![message(1, REGULAR_PAYLOAD)]).into(), Ok(vec![message(1, REGULAR_PAYLOAD)]).into(),
1, 1,
@@ -1411,7 +1420,7 @@ mod tests {
),); ),);
assert_ok!(Pallet::<TestRuntime>::receive_messages_delivery_proof( assert_ok!(Pallet::<TestRuntime>::receive_messages_delivery_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TestMessagesDeliveryProof(Ok(( TestMessagesDeliveryProof(Ok((
TEST_LANE_ID, TEST_LANE_ID,
InboundLaneData { InboundLaneData {
@@ -1449,7 +1458,7 @@ mod tests {
.extend_from_slice(&[0u8; MAX_OUTBOUND_PAYLOAD_SIZE as usize]); .extend_from_slice(&[0u8; MAX_OUTBOUND_PAYLOAD_SIZE as usize]);
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::send_message( Pallet::<TestRuntime>::send_message(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
message_payload.clone(), message_payload.clone(),
Balance::MAX, Balance::MAX,
@@ -1463,7 +1472,7 @@ mod tests {
} }
assert_eq!(message_payload.size(), MAX_OUTBOUND_PAYLOAD_SIZE); assert_eq!(message_payload.size(), MAX_OUTBOUND_PAYLOAD_SIZE);
assert_ok!(Pallet::<TestRuntime>::send_message( assert_ok!(Pallet::<TestRuntime>::send_message(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
message_payload, message_payload,
Balance::MAX, Balance::MAX,
@@ -1477,10 +1486,10 @@ mod tests {
// messages with this payload are rejected by target chain verifier // messages with this payload are rejected by target chain verifier
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::send_message( Pallet::<TestRuntime>::send_message(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
PAYLOAD_REJECTED_BY_TARGET_CHAIN, PAYLOAD_REJECTED_BY_TARGET_CHAIN,
PAYLOAD_REJECTED_BY_TARGET_CHAIN.declared_weight PAYLOAD_REJECTED_BY_TARGET_CHAIN.declared_weight.ref_time(),
), ),
Error::<TestRuntime, ()>::MessageRejectedByChainVerifier, Error::<TestRuntime, ()>::MessageRejectedByChainVerifier,
); );
@@ -1493,7 +1502,7 @@ mod tests {
// messages with zero fee are rejected by lane verifier // messages with zero fee are rejected by lane verifier
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::send_message( Pallet::<TestRuntime>::send_message(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
REGULAR_PAYLOAD, REGULAR_PAYLOAD,
0 0
@@ -1509,10 +1518,10 @@ mod tests {
TestMessageDeliveryAndDispatchPayment::reject_payments(); TestMessageDeliveryAndDispatchPayment::reject_payments();
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::send_message( Pallet::<TestRuntime>::send_message(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
REGULAR_PAYLOAD, REGULAR_PAYLOAD,
REGULAR_PAYLOAD.declared_weight REGULAR_PAYLOAD.declared_weight.ref_time(),
), ),
Error::<TestRuntime, ()>::FailedToWithdrawMessageFee, Error::<TestRuntime, ()>::FailedToWithdrawMessageFee,
); );
@@ -1523,7 +1532,7 @@ mod tests {
fn receive_messages_proof_works() { fn receive_messages_proof_works() {
run_test(|| { run_test(|| {
assert_ok!(Pallet::<TestRuntime>::receive_messages_proof( assert_ok!(Pallet::<TestRuntime>::receive_messages_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_RELAYER_A, TEST_RELAYER_A,
Ok(vec![message(1, REGULAR_PAYLOAD)]).into(), Ok(vec![message(1, REGULAR_PAYLOAD)]).into(),
1, 1,
@@ -1567,7 +1576,7 @@ mod tests {
Some(OutboundLaneData { latest_received_nonce: 9, ..Default::default() }); Some(OutboundLaneData { latest_received_nonce: 9, ..Default::default() });
assert_ok!(Pallet::<TestRuntime>::receive_messages_proof( assert_ok!(Pallet::<TestRuntime>::receive_messages_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_RELAYER_A, TEST_RELAYER_A,
message_proof, message_proof,
1, 1,
@@ -1601,12 +1610,14 @@ mod tests {
#[test] #[test]
fn receive_messages_proof_does_not_accept_message_if_dispatch_weight_is_not_enough() { fn receive_messages_proof_does_not_accept_message_if_dispatch_weight_is_not_enough() {
run_test(|| { run_test(|| {
let mut declared_weight = REGULAR_PAYLOAD.declared_weight;
*declared_weight.ref_time_mut() -= 1;
assert_ok!(Pallet::<TestRuntime>::receive_messages_proof( assert_ok!(Pallet::<TestRuntime>::receive_messages_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_RELAYER_A, TEST_RELAYER_A,
Ok(vec![message(1, REGULAR_PAYLOAD)]).into(), Ok(vec![message(1, REGULAR_PAYLOAD)]).into(),
1, 1,
REGULAR_PAYLOAD.declared_weight - 1, declared_weight,
)); ));
assert_eq!(InboundLanes::<TestRuntime>::get(TEST_LANE_ID).last_delivered_nonce(), 0); assert_eq!(InboundLanes::<TestRuntime>::get(TEST_LANE_ID).last_delivered_nonce(), 0);
}); });
@@ -1617,11 +1628,11 @@ mod tests {
run_test(|| { run_test(|| {
assert_noop!( assert_noop!(
Pallet::<TestRuntime, ()>::receive_messages_proof( Pallet::<TestRuntime, ()>::receive_messages_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_RELAYER_A, TEST_RELAYER_A,
Err(()).into(), Err(()).into(),
1, 1,
0, Weight::from_ref_time(0),
), ),
Error::<TestRuntime, ()>::InvalidMessagesProof, Error::<TestRuntime, ()>::InvalidMessagesProof,
); );
@@ -1633,11 +1644,11 @@ mod tests {
run_test(|| { run_test(|| {
assert_noop!( assert_noop!(
Pallet::<TestRuntime, ()>::receive_messages_proof( Pallet::<TestRuntime, ()>::receive_messages_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_RELAYER_A, TEST_RELAYER_A,
Ok(vec![message(1, REGULAR_PAYLOAD)]).into(), Ok(vec![message(1, REGULAR_PAYLOAD)]).into(),
u32::MAX, u32::MAX,
0, Weight::from_ref_time(0),
), ),
Error::<TestRuntime, ()>::TooManyMessagesInTheProof, Error::<TestRuntime, ()>::TooManyMessagesInTheProof,
); );
@@ -1661,13 +1672,13 @@ mod tests {
fn receive_messages_delivery_proof_rewards_relayers() { fn receive_messages_delivery_proof_rewards_relayers() {
run_test(|| { run_test(|| {
assert_ok!(Pallet::<TestRuntime>::send_message( assert_ok!(Pallet::<TestRuntime>::send_message(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
REGULAR_PAYLOAD, REGULAR_PAYLOAD,
1000, 1000,
)); ));
assert_ok!(Pallet::<TestRuntime>::send_message( assert_ok!(Pallet::<TestRuntime>::send_message(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
REGULAR_PAYLOAD, REGULAR_PAYLOAD,
2000, 2000,
@@ -1675,7 +1686,7 @@ mod tests {
// this reports delivery of message 1 => reward is paid to TEST_RELAYER_A // this reports delivery of message 1 => reward is paid to TEST_RELAYER_A
assert_ok!(Pallet::<TestRuntime>::receive_messages_delivery_proof( assert_ok!(Pallet::<TestRuntime>::receive_messages_delivery_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TestMessagesDeliveryProof(Ok(( TestMessagesDeliveryProof(Ok((
TEST_LANE_ID, TEST_LANE_ID,
InboundLaneData { InboundLaneData {
@@ -1698,7 +1709,7 @@ mod tests {
// this reports delivery of both message 1 and message 2 => reward is paid only to // this reports delivery of both message 1 and message 2 => reward is paid only to
// TEST_RELAYER_B // TEST_RELAYER_B
assert_ok!(Pallet::<TestRuntime>::receive_messages_delivery_proof( assert_ok!(Pallet::<TestRuntime>::receive_messages_delivery_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TestMessagesDeliveryProof(Ok(( TestMessagesDeliveryProof(Ok((
TEST_LANE_ID, TEST_LANE_ID,
InboundLaneData { InboundLaneData {
@@ -1728,7 +1739,7 @@ mod tests {
run_test(|| { run_test(|| {
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::receive_messages_delivery_proof( Pallet::<TestRuntime>::receive_messages_delivery_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TestMessagesDeliveryProof(Err(())), TestMessagesDeliveryProof(Err(())),
Default::default(), Default::default(),
), ),
@@ -1743,7 +1754,7 @@ mod tests {
// when number of relayers entries is invalid // when number of relayers entries is invalid
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::receive_messages_delivery_proof( Pallet::<TestRuntime>::receive_messages_delivery_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TestMessagesDeliveryProof(Ok(( TestMessagesDeliveryProof(Ok((
TEST_LANE_ID, TEST_LANE_ID,
InboundLaneData { InboundLaneData {
@@ -1769,7 +1780,7 @@ mod tests {
// when number of messages is invalid // when number of messages is invalid
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::receive_messages_delivery_proof( Pallet::<TestRuntime>::receive_messages_delivery_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TestMessagesDeliveryProof(Ok(( TestMessagesDeliveryProof(Ok((
TEST_LANE_ID, TEST_LANE_ID,
InboundLaneData { InboundLaneData {
@@ -1795,7 +1806,7 @@ mod tests {
// when last delivered nonce is invalid // when last delivered nonce is invalid
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::receive_messages_delivery_proof( Pallet::<TestRuntime>::receive_messages_delivery_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TestMessagesDeliveryProof(Ok(( TestMessagesDeliveryProof(Ok((
TEST_LANE_ID, TEST_LANE_ID,
InboundLaneData { InboundLaneData {
@@ -1827,11 +1838,12 @@ mod tests {
invalid_message.data.payload = Vec::new(); invalid_message.data.payload = Vec::new();
assert_ok!(Pallet::<TestRuntime, ()>::receive_messages_proof( assert_ok!(Pallet::<TestRuntime, ()>::receive_messages_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_RELAYER_A, TEST_RELAYER_A,
Ok(vec![invalid_message]).into(), Ok(vec![invalid_message]).into(),
1, 1,
0, // weight may be zero in this case (all messages are improperly encoded) Weight::from_ref_time(0), /* weight may be zero in this case (all messages are
* improperly encoded) */
),); ),);
assert_eq!(InboundLanes::<TestRuntime>::get(TEST_LANE_ID).last_delivered_nonce(), 1,); assert_eq!(InboundLanes::<TestRuntime>::get(TEST_LANE_ID).last_delivered_nonce(), 1,);
@@ -1845,7 +1857,7 @@ mod tests {
invalid_message.data.payload = Vec::new(); invalid_message.data.payload = Vec::new();
assert_ok!(Pallet::<TestRuntime, ()>::receive_messages_proof( assert_ok!(Pallet::<TestRuntime, ()>::receive_messages_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_RELAYER_A, TEST_RELAYER_A,
Ok( Ok(
vec![message(1, REGULAR_PAYLOAD), invalid_message, message(3, REGULAR_PAYLOAD),] vec![message(1, REGULAR_PAYLOAD), invalid_message, message(3, REGULAR_PAYLOAD),]
@@ -1862,12 +1874,12 @@ mod tests {
#[test] #[test]
fn actual_dispatch_weight_does_not_overlow() { fn actual_dispatch_weight_does_not_overlow() {
run_test(|| { run_test(|| {
let message1 = message(1, message_payload(0, Weight::MAX / 2)); let message1 = message(1, message_payload(0, u64::MAX / 2));
let message2 = message(2, message_payload(0, Weight::MAX / 2)); let message2 = message(2, message_payload(0, u64::MAX / 2));
let message3 = message(3, message_payload(0, Weight::MAX / 2)); let message3 = message(3, message_payload(0, u64::MAX / 2));
assert_ok!(Pallet::<TestRuntime, ()>::receive_messages_proof( assert_ok!(Pallet::<TestRuntime, ()>::receive_messages_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_RELAYER_A, TEST_RELAYER_A,
// this may cause overflow if source chain storage is invalid // this may cause overflow if source chain storage is invalid
Ok(vec![message1, message2, message3]).into(), Ok(vec![message1, message2, message3]).into(),
@@ -1886,7 +1898,7 @@ mod tests {
assert_noop!( assert_noop!(
Pallet::<TestRuntime, ()>::increase_message_fee( Pallet::<TestRuntime, ()>::increase_message_fee(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
1, 1,
100, 100,
@@ -1901,7 +1913,7 @@ mod tests {
run_test(|| { run_test(|| {
assert_noop!( assert_noop!(
Pallet::<TestRuntime, ()>::increase_message_fee( Pallet::<TestRuntime, ()>::increase_message_fee(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
1, 1,
100, 100,
@@ -1920,7 +1932,7 @@ mod tests {
assert_noop!( assert_noop!(
Pallet::<TestRuntime, ()>::increase_message_fee( Pallet::<TestRuntime, ()>::increase_message_fee(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
1, 1,
100, 100,
@@ -1936,7 +1948,7 @@ mod tests {
send_regular_message(); send_regular_message();
assert_ok!(Pallet::<TestRuntime, ()>::increase_message_fee( assert_ok!(Pallet::<TestRuntime, ()>::increase_message_fee(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
1, 1,
100, 100,
@@ -1950,11 +1962,11 @@ mod tests {
run_test(|| { run_test(|| {
fn submit_with_unspent_weight( fn submit_with_unspent_weight(
nonce: MessageNonce, nonce: MessageNonce,
unspent_weight: Weight, unspent_weight: u64,
is_prepaid: bool, is_prepaid: bool,
) -> (Weight, Weight) { ) -> (Weight, Weight) {
let mut payload = REGULAR_PAYLOAD; let mut payload = REGULAR_PAYLOAD;
payload.dispatch_result.unspent_weight = unspent_weight; *payload.dispatch_result.unspent_weight.ref_time_mut() = unspent_weight;
payload.dispatch_result.dispatch_fee_paid_during_dispatch = !is_prepaid; payload.dispatch_result.dispatch_fee_paid_during_dispatch = !is_prepaid;
let proof = Ok(vec![message(nonce, payload)]).into(); let proof = Ok(vec![message(nonce, payload)]).into();
let messages_count = 1; let messages_count = 1;
@@ -1965,7 +1977,7 @@ mod tests {
REGULAR_PAYLOAD.declared_weight, REGULAR_PAYLOAD.declared_weight,
); );
let post_dispatch_weight = Pallet::<TestRuntime>::receive_messages_proof( let post_dispatch_weight = Pallet::<TestRuntime>::receive_messages_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_RELAYER_A, TEST_RELAYER_A,
proof, proof,
messages_count, messages_count,
@@ -1980,16 +1992,26 @@ mod tests {
// when dispatch is returning `unspent_weight < declared_weight` // when dispatch is returning `unspent_weight < declared_weight`
let (pre, post) = submit_with_unspent_weight(1, 1, false); let (pre, post) = submit_with_unspent_weight(1, 1, false);
assert_eq!(post, pre - 1); assert_eq!(post.ref_time(), pre.ref_time() - 1);
// when dispatch is returning `unspent_weight = declared_weight` // when dispatch is returning `unspent_weight = declared_weight`
let (pre, post) = submit_with_unspent_weight(2, REGULAR_PAYLOAD.declared_weight, false); let (pre, post) =
assert_eq!(post, pre - REGULAR_PAYLOAD.declared_weight); submit_with_unspent_weight(2, REGULAR_PAYLOAD.declared_weight.ref_time(), false);
assert_eq!(
post.ref_time(),
pre.ref_time() - REGULAR_PAYLOAD.declared_weight.ref_time()
);
// when dispatch is returning `unspent_weight > declared_weight` // when dispatch is returning `unspent_weight > declared_weight`
let (pre, post) = let (pre, post) = submit_with_unspent_weight(
submit_with_unspent_weight(3, REGULAR_PAYLOAD.declared_weight + 1, false); 3,
assert_eq!(post, pre - REGULAR_PAYLOAD.declared_weight); REGULAR_PAYLOAD.declared_weight.ref_time() + 1,
false,
);
assert_eq!(
post.ref_time(),
pre.ref_time() - REGULAR_PAYLOAD.declared_weight.ref_time()
);
// when there's no unspent weight // when there's no unspent weight
let (pre, post) = submit_with_unspent_weight(4, 0, false); let (pre, post) = submit_with_unspent_weight(4, 0, false);
@@ -1998,8 +2020,10 @@ mod tests {
// when dispatch is returning `unspent_weight < declared_weight` AND message is prepaid // when dispatch is returning `unspent_weight < declared_weight` AND message is prepaid
let (pre, post) = submit_with_unspent_weight(5, 1, true); let (pre, post) = submit_with_unspent_weight(5, 1, true);
assert_eq!( assert_eq!(
post, post.ref_time(),
pre - 1 - <TestRuntime as Config>::WeightInfo::pay_inbound_dispatch_fee_overhead() pre.ref_time() -
1 - <TestRuntime as Config>::WeightInfo::pay_inbound_dispatch_fee_overhead()
.ref_time()
); );
}); });
} }
@@ -2043,7 +2067,7 @@ mod tests {
// first tx with messages 1+2 // first tx with messages 1+2
assert_ok!(Pallet::<TestRuntime>::receive_messages_delivery_proof( assert_ok!(Pallet::<TestRuntime>::receive_messages_delivery_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TestMessagesDeliveryProof(messages_1_and_2_proof), TestMessagesDeliveryProof(messages_1_and_2_proof),
UnrewardedRelayersState { UnrewardedRelayersState {
unrewarded_relayer_entries: 1, unrewarded_relayer_entries: 1,
@@ -2054,7 +2078,7 @@ mod tests {
)); ));
// second tx with message 3 // second tx with message 3
assert_ok!(Pallet::<TestRuntime>::receive_messages_delivery_proof( assert_ok!(Pallet::<TestRuntime>::receive_messages_delivery_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TestMessagesDeliveryProof(messages_3_proof), TestMessagesDeliveryProof(messages_3_proof),
UnrewardedRelayersState { UnrewardedRelayersState {
unrewarded_relayer_entries: 1, unrewarded_relayer_entries: 1,
@@ -2097,7 +2121,7 @@ mod tests {
crate::mock::DbWeight::get(), crate::mock::DbWeight::get(),
); );
let post_dispatch_weight = Pallet::<TestRuntime>::receive_messages_delivery_proof( let post_dispatch_weight = Pallet::<TestRuntime>::receive_messages_delivery_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
proof, proof,
relayers_state, relayers_state,
) )
@@ -2157,7 +2181,7 @@ mod tests {
// numer of actually confirmed messages is `1`. // numer of actually confirmed messages is `1`.
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::receive_messages_delivery_proof( Pallet::<TestRuntime>::receive_messages_delivery_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TestMessagesDeliveryProof(Ok(( TestMessagesDeliveryProof(Ok((
TEST_LANE_ID, TEST_LANE_ID,
InboundLaneData { last_confirmed_nonce: 1, relayers: Default::default() }, InboundLaneData { last_confirmed_nonce: 1, relayers: Default::default() },
@@ -2178,32 +2202,40 @@ mod tests {
large_payload.extra = vec![2; MAX_OUTBOUND_PAYLOAD_SIZE as usize / 5]; large_payload.extra = vec![2; MAX_OUTBOUND_PAYLOAD_SIZE as usize / 5];
assert_ok!(Pallet::<TestRuntime>::send_message( assert_ok!(Pallet::<TestRuntime>::send_message(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
small_payload, small_payload,
100, 100,
)); ));
assert_ok!(Pallet::<TestRuntime>::send_message( assert_ok!(Pallet::<TestRuntime>::send_message(
Origin::signed(1), RuntimeOrigin::signed(1),
TEST_LANE_ID, TEST_LANE_ID,
large_payload, large_payload,
100, 100,
)); ));
let small_weight = let small_weight = Pallet::<TestRuntime>::increase_message_fee(
Pallet::<TestRuntime>::increase_message_fee(Origin::signed(1), TEST_LANE_ID, 1, 1) RuntimeOrigin::signed(1),
.expect("increase_message_fee has failed") TEST_LANE_ID,
.actual_weight 1,
.expect("increase_message_fee always returns Some"); 1,
)
.expect("increase_message_fee has failed")
.actual_weight
.expect("increase_message_fee always returns Some");
let large_weight = let large_weight = Pallet::<TestRuntime>::increase_message_fee(
Pallet::<TestRuntime>::increase_message_fee(Origin::signed(1), TEST_LANE_ID, 2, 1) RuntimeOrigin::signed(1),
.expect("increase_message_fee has failed") TEST_LANE_ID,
.actual_weight 2,
.expect("increase_message_fee always returns Some"); 1,
)
.expect("increase_message_fee has failed")
.actual_weight
.expect("increase_message_fee always returns Some");
assert!( assert!(
large_weight > small_weight, large_weight.ref_time() > small_weight.ref_time(),
"Actual post-dispatch weigth for larger message {} must be larger than {} for small message", "Actual post-dispatch weigth for larger message {} must be larger than {} for small message",
large_weight, large_weight,
small_weight, small_weight,
@@ -2225,7 +2257,7 @@ mod tests {
// confirm delivery of all sent messages // confirm delivery of all sent messages
assert_ok!(Pallet::<TestRuntime>::receive_messages_delivery_proof( assert_ok!(Pallet::<TestRuntime>::receive_messages_delivery_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
TestMessagesDeliveryProof(Ok(( TestMessagesDeliveryProof(Ok((
TEST_LANE_ID, TEST_LANE_ID,
InboundLaneData { InboundLaneData {
@@ -2332,7 +2364,7 @@ mod tests {
REGULAR_PAYLOAD.encode(), REGULAR_PAYLOAD.encode(),
OutboundMessageDetails { OutboundMessageDetails {
nonce: 0, nonce: 0,
dispatch_weight: 0, dispatch_weight: Weight::from_ref_time(0),
size: 0, size: 0,
delivery_and_dispatch_fee: 0, delivery_and_dispatch_fee: 0,
dispatch_fee_payment: dispatch_fee_payment:
+24 -18
View File
@@ -87,23 +87,23 @@ frame_support::construct_runtime! {
parameter_types! { parameter_types! {
pub const BlockHashCount: u64 = 250; pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockWeight: Weight = Weight::from_ref_time(1024);
pub const MaximumBlockLength: u32 = 2 * 1024; pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one(); pub const AvailableBlockRatio: Perbill = Perbill::one();
pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 1, write: 2 }; pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 1, write: 2 };
} }
impl frame_system::Config for TestRuntime { impl frame_system::Config for TestRuntime {
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
type Index = u64; type Index = u64;
type Call = Call; type RuntimeCall = RuntimeCall;
type BlockNumber = u64; type BlockNumber = u64;
type Hash = H256; type Hash = H256;
type Hashing = BlakeTwo256; type Hashing = BlakeTwo256;
type AccountId = AccountId; type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = SubstrateHeader; type Header = SubstrateHeader;
type Event = Event; type RuntimeEvent = RuntimeEvent;
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
type Version = (); type Version = ();
type PalletInfo = PalletInfo; type PalletInfo = PalletInfo;
@@ -128,7 +128,7 @@ impl pallet_balances::Config for TestRuntime {
type MaxLocks = (); type MaxLocks = ();
type Balance = Balance; type Balance = Balance;
type DustRemoval = (); type DustRemoval = ();
type Event = Event; type RuntimeEvent = RuntimeEvent;
type ExistentialDeposit = ExistentialDeposit; type ExistentialDeposit = ExistentialDeposit;
type AccountStore = frame_system::Pallet<TestRuntime>; type AccountStore = frame_system::Pallet<TestRuntime>;
type WeightInfo = (); type WeightInfo = ();
@@ -159,7 +159,7 @@ impl MessagesParameter for TestMessagesParameter {
} }
impl Config for TestRuntime { impl Config for TestRuntime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type WeightInfo = (); type WeightInfo = ();
type Parameter = TestMessagesParameter; type Parameter = TestMessagesParameter;
type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce;
@@ -185,7 +185,7 @@ impl Config for TestRuntime {
type BridgedChainId = TestBridgedChainId; type BridgedChainId = TestBridgedChainId;
} }
impl SenderOrigin<AccountId> for Origin { impl SenderOrigin<AccountId> for RuntimeOrigin {
fn linked_account(&self) -> Option<AccountId> { fn linked_account(&self) -> Option<AccountId> {
match self.caller { match self.caller {
OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) => OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) =>
@@ -298,11 +298,11 @@ impl TargetHeaderChain<TestPayload, TestRelayer> for TestTargetHeaderChain {
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct TestLaneMessageVerifier; pub struct TestLaneMessageVerifier;
impl LaneMessageVerifier<Origin, TestPayload, TestMessageFee> for TestLaneMessageVerifier { impl LaneMessageVerifier<RuntimeOrigin, TestPayload, TestMessageFee> for TestLaneMessageVerifier {
type Error = &'static str; type Error = &'static str;
fn verify_message( fn verify_message(
_submitter: &Origin, _submitter: &RuntimeOrigin,
delivery_and_dispatch_fee: &TestMessageFee, delivery_and_dispatch_fee: &TestMessageFee,
_lane: &LaneId, _lane: &LaneId,
_lane_outbound_data: &OutboundLaneData, _lane_outbound_data: &OutboundLaneData,
@@ -328,7 +328,8 @@ impl TestMessageDeliveryAndDispatchPayment {
/// Returns true if given fee has been paid by given submitter. /// Returns true if given fee has been paid by given submitter.
pub fn is_fee_paid(submitter: AccountId, fee: TestMessageFee) -> bool { pub fn is_fee_paid(submitter: AccountId, fee: TestMessageFee) -> bool {
let raw_origin: Result<frame_system::RawOrigin<_>, _> = Origin::signed(submitter).into(); let raw_origin: Result<frame_system::RawOrigin<_>, _> =
RuntimeOrigin::signed(submitter).into();
frame_support::storage::unhashed::get(b":message-fee:") == Some((raw_origin.unwrap(), fee)) frame_support::storage::unhashed::get(b":message-fee:") == Some((raw_origin.unwrap(), fee))
} }
@@ -340,13 +341,13 @@ impl TestMessageDeliveryAndDispatchPayment {
} }
} }
impl MessageDeliveryAndDispatchPayment<Origin, AccountId, TestMessageFee> impl MessageDeliveryAndDispatchPayment<RuntimeOrigin, AccountId, TestMessageFee>
for TestMessageDeliveryAndDispatchPayment for TestMessageDeliveryAndDispatchPayment
{ {
type Error = &'static str; type Error = &'static str;
fn pay_delivery_and_dispatch_fee( fn pay_delivery_and_dispatch_fee(
submitter: &Origin, submitter: &RuntimeOrigin,
fee: &TestMessageFee, fee: &TestMessageFee,
) -> Result<(), Self::Error> { ) -> Result<(), Self::Error> {
if frame_support::storage::unhashed::get(b":reject-message-fee:") == Some(true) { if frame_support::storage::unhashed::get(b":reject-message-fee:") == Some(true) {
@@ -451,7 +452,7 @@ impl OnDeliveryConfirmed for TestOnDeliveryConfirmed2 {
fn on_messages_delivered(lane: &LaneId, messages: &DeliveredMessages) -> Weight { fn on_messages_delivered(lane: &LaneId, messages: &DeliveredMessages) -> Weight {
let key = (b"TestOnDeliveryConfirmed2", lane, messages).encode(); let key = (b"TestOnDeliveryConfirmed2", lane, messages).encode();
frame_support::storage::unhashed::put(&key, &true); frame_support::storage::unhashed::put(&key, &true);
0 Weight::from_ref_time(0)
} }
} }
@@ -482,7 +483,7 @@ impl MessageDispatch<AccountId, TestMessageFee> for TestMessageDispatch {
fn dispatch_weight(message: &mut DispatchMessage<TestPayload, TestMessageFee>) -> Weight { fn dispatch_weight(message: &mut DispatchMessage<TestPayload, TestMessageFee>) -> Weight {
match message.data.payload.as_ref() { match message.data.payload.as_ref() {
Ok(payload) => payload.declared_weight, Ok(payload) => payload.declared_weight,
Err(_) => 0, Err(_) => Weight::from_ref_time(0),
} }
} }
@@ -503,8 +504,13 @@ pub fn message(nonce: MessageNonce, payload: TestPayload) -> Message<TestMessage
} }
/// Constructs message payload using given arguments and zero unspent weight. /// Constructs message payload using given arguments and zero unspent weight.
pub const fn message_payload(id: u64, declared_weight: Weight) -> TestPayload { pub const fn message_payload(id: u64, declared_weight: u64) -> TestPayload {
TestPayload { id, declared_weight, dispatch_result: dispatch_result(0), extra: Vec::new() } TestPayload {
id,
declared_weight: Weight::from_ref_time(declared_weight),
dispatch_result: dispatch_result(0),
extra: Vec::new(),
}
} }
/// Return message data with valid fee for given payload. /// Return message data with valid fee for given payload.
@@ -513,10 +519,10 @@ pub fn message_data(payload: TestPayload) -> MessageData<TestMessageFee> {
} }
/// Returns message dispatch result with given unspent weight. /// Returns message dispatch result with given unspent weight.
pub const fn dispatch_result(unspent_weight: Weight) -> MessageDispatchResult { pub const fn dispatch_result(unspent_weight: u64) -> MessageDispatchResult {
MessageDispatchResult { MessageDispatchResult {
dispatch_result: true, dispatch_result: true,
unspent_weight, unspent_weight: Weight::from_ref_time(unspent_weight),
dispatch_fee_paid_during_dispatch: true, dispatch_fee_paid_during_dispatch: true,
} }
} }
+87 -87
View File
@@ -17,7 +17,7 @@
//! Autogenerated weights for `pallet_bridge_messages` //! Autogenerated weights for `pallet_bridge_messages`
//! //!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2022-10-04, STEPS: 50, REPEAT: 20 //! DATE: 2022-10-17, STEPS: 50, REPEAT: 20
//! LOW RANGE: [], HIGH RANGE: [] //! LOW RANGE: [], HIGH RANGE: []
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled
//! CHAIN: Some("dev"), DB CACHE: 1024 //! CHAIN: Some("dev"), DB CACHE: 1024
@@ -72,149 +72,149 @@ pub trait WeightInfo {
pub struct BridgeWeight<T>(PhantomData<T>); pub struct BridgeWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> { impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
fn send_minimal_message_worst_case() -> Weight { fn send_minimal_message_worst_case() -> Weight {
(62_300_000 as Weight) Weight::from_ref_time(61_807_000 as u64)
.saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().reads(5 as u64))
.saturating_add(T::DbWeight::get().writes(10 as Weight)) .saturating_add(T::DbWeight::get().writes(10 as u64))
} }
fn send_1_kb_message_worst_case() -> Weight { fn send_1_kb_message_worst_case() -> Weight {
(63_176_000 as Weight) Weight::from_ref_time(65_074_000 as u64)
.saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().reads(5 as u64))
.saturating_add(T::DbWeight::get().writes(10 as Weight)) .saturating_add(T::DbWeight::get().writes(10 as u64))
} }
fn send_16_kb_message_worst_case() -> Weight { fn send_16_kb_message_worst_case() -> Weight {
(73_472_000 as Weight) Weight::from_ref_time(73_584_000 as u64)
.saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().reads(5 as u64))
.saturating_add(T::DbWeight::get().writes(10 as Weight)) .saturating_add(T::DbWeight::get().writes(10 as u64))
} }
fn maximal_increase_message_fee() -> Weight { fn maximal_increase_message_fee() -> Weight {
(2_539_209_000 as Weight) Weight::from_ref_time(2_522_629_000 as u64)
.saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().reads(3 as u64))
.saturating_add(T::DbWeight::get().writes(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as u64))
} }
fn increase_message_fee(i: u32) -> Weight { fn increase_message_fee(i: u32) -> Weight {
(0 as Weight) Weight::from_ref_time(27_072_000 as u64)
.saturating_add((1_000 as Weight).saturating_mul(i as Weight)) .saturating_add(Weight::from_ref_time(892 as u64).saturating_mul(i as u64))
.saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().reads(3 as u64))
.saturating_add(T::DbWeight::get().writes(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as u64))
} }
fn receive_single_message_proof() -> Weight { fn receive_single_message_proof() -> Weight {
(49_205_000 as Weight) Weight::from_ref_time(49_628_000 as u64)
.saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().reads(4 as u64))
.saturating_add(T::DbWeight::get().writes(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as u64))
} }
fn receive_two_messages_proof() -> Weight { fn receive_two_messages_proof() -> Weight {
(62_182_000 as Weight) Weight::from_ref_time(61_514_000 as u64)
.saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().reads(4 as u64))
.saturating_add(T::DbWeight::get().writes(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as u64))
} }
fn receive_single_message_proof_with_outbound_lane_state() -> Weight { fn receive_single_message_proof_with_outbound_lane_state() -> Weight {
(55_928_000 as Weight) Weight::from_ref_time(65_960_000 as u64)
.saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().reads(4 as u64))
.saturating_add(T::DbWeight::get().writes(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as u64))
} }
fn receive_single_message_proof_1_kb() -> Weight { fn receive_single_message_proof_1_kb() -> Weight {
(47_298_000 as Weight) Weight::from_ref_time(48_009_000 as u64)
.saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().reads(3 as u64))
.saturating_add(T::DbWeight::get().writes(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as u64))
} }
fn receive_single_message_proof_16_kb() -> Weight { fn receive_single_message_proof_16_kb() -> Weight {
(105_016_000 as Weight) Weight::from_ref_time(100_439_000 as u64)
.saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().reads(3 as u64))
.saturating_add(T::DbWeight::get().writes(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as u64))
} }
fn receive_single_prepaid_message_proof() -> Weight { fn receive_single_prepaid_message_proof() -> Weight {
(49_067_000 as Weight) Weight::from_ref_time(50_463_000 as u64)
.saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().reads(4 as u64))
.saturating_add(T::DbWeight::get().writes(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as u64))
} }
fn receive_delivery_proof_for_single_message() -> Weight { fn receive_delivery_proof_for_single_message() -> Weight {
(58_520_000 as Weight) Weight::from_ref_time(57_383_000 as u64)
.saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().reads(5 as u64))
.saturating_add(T::DbWeight::get().writes(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as u64))
} }
fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight {
(61_563_000 as Weight) Weight::from_ref_time(62_003_000 as u64)
.saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().reads(6 as u64))
.saturating_add(T::DbWeight::get().writes(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as u64))
} }
fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight {
(63_197_000 as Weight) Weight::from_ref_time(64_401_000 as u64)
.saturating_add(T::DbWeight::get().reads(7 as Weight)) .saturating_add(T::DbWeight::get().reads(7 as u64))
.saturating_add(T::DbWeight::get().writes(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as u64))
} }
} }
// For backwards compatibility and tests // For backwards compatibility and tests
impl WeightInfo for () { impl WeightInfo for () {
fn send_minimal_message_worst_case() -> Weight { fn send_minimal_message_worst_case() -> Weight {
(62_300_000 as Weight) Weight::from_ref_time(61_807_000 as u64)
.saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as u64))
.saturating_add(RocksDbWeight::get().writes(10 as Weight)) .saturating_add(RocksDbWeight::get().writes(10 as u64))
} }
fn send_1_kb_message_worst_case() -> Weight { fn send_1_kb_message_worst_case() -> Weight {
(63_176_000 as Weight) Weight::from_ref_time(65_074_000 as u64)
.saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as u64))
.saturating_add(RocksDbWeight::get().writes(10 as Weight)) .saturating_add(RocksDbWeight::get().writes(10 as u64))
} }
fn send_16_kb_message_worst_case() -> Weight { fn send_16_kb_message_worst_case() -> Weight {
(73_472_000 as Weight) Weight::from_ref_time(73_584_000 as u64)
.saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as u64))
.saturating_add(RocksDbWeight::get().writes(10 as Weight)) .saturating_add(RocksDbWeight::get().writes(10 as u64))
} }
fn maximal_increase_message_fee() -> Weight { fn maximal_increase_message_fee() -> Weight {
(2_539_209_000 as Weight) Weight::from_ref_time(2_522_629_000 as u64)
.saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as u64))
} }
fn increase_message_fee(i: u32) -> Weight { fn increase_message_fee(i: u32) -> Weight {
(0 as Weight) Weight::from_ref_time(27_072_000 as u64)
.saturating_add((1_000 as Weight).saturating_mul(i as Weight)) .saturating_add(Weight::from_ref_time(892 as u64).saturating_mul(i as u64))
.saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as u64))
} }
fn receive_single_message_proof() -> Weight { fn receive_single_message_proof() -> Weight {
(49_205_000 as Weight) Weight::from_ref_time(49_628_000 as u64)
.saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as u64))
.saturating_add(RocksDbWeight::get().writes(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as u64))
} }
fn receive_two_messages_proof() -> Weight { fn receive_two_messages_proof() -> Weight {
(62_182_000 as Weight) Weight::from_ref_time(61_514_000 as u64)
.saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as u64))
.saturating_add(RocksDbWeight::get().writes(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as u64))
} }
fn receive_single_message_proof_with_outbound_lane_state() -> Weight { fn receive_single_message_proof_with_outbound_lane_state() -> Weight {
(55_928_000 as Weight) Weight::from_ref_time(65_960_000 as u64)
.saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as u64))
.saturating_add(RocksDbWeight::get().writes(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as u64))
} }
fn receive_single_message_proof_1_kb() -> Weight { fn receive_single_message_proof_1_kb() -> Weight {
(47_298_000 as Weight) Weight::from_ref_time(48_009_000 as u64)
.saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as u64))
} }
fn receive_single_message_proof_16_kb() -> Weight { fn receive_single_message_proof_16_kb() -> Weight {
(105_016_000 as Weight) Weight::from_ref_time(100_439_000 as u64)
.saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as u64))
} }
fn receive_single_prepaid_message_proof() -> Weight { fn receive_single_prepaid_message_proof() -> Weight {
(49_067_000 as Weight) Weight::from_ref_time(50_463_000 as u64)
.saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as u64))
.saturating_add(RocksDbWeight::get().writes(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as u64))
} }
fn receive_delivery_proof_for_single_message() -> Weight { fn receive_delivery_proof_for_single_message() -> Weight {
(58_520_000 as Weight) Weight::from_ref_time(57_383_000 as u64)
.saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as u64))
.saturating_add(RocksDbWeight::get().writes(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as u64))
} }
fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight {
(61_563_000 as Weight) Weight::from_ref_time(62_003_000 as u64)
.saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().reads(6 as u64))
.saturating_add(RocksDbWeight::get().writes(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as u64))
} }
fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight {
(63_197_000 as Weight) Weight::from_ref_time(64_401_000 as u64)
.saturating_add(RocksDbWeight::get().reads(7 as Weight)) .saturating_add(RocksDbWeight::get().reads(7 as u64))
.saturating_add(RocksDbWeight::get().writes(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as u64))
} }
} }
+24 -23
View File
@@ -43,14 +43,14 @@ pub fn ensure_weights_are_correct<W: WeightInfoExt>(
db_weight: RuntimeDbWeight, db_weight: RuntimeDbWeight,
) { ) {
// verify `send_message` weight components // verify `send_message` weight components
assert_ne!(W::send_message_overhead(), 0); assert_ne!(W::send_message_overhead(), Weight::from_ref_time(0));
assert_ne!(W::send_message_size_overhead(0), 0); assert_ne!(W::send_message_size_overhead(0), Weight::from_ref_time(0));
// verify `receive_messages_proof` weight components // verify `receive_messages_proof` weight components
assert_ne!(W::receive_messages_proof_overhead(), 0); assert_ne!(W::receive_messages_proof_overhead(), Weight::from_ref_time(0));
assert_ne!(W::receive_messages_proof_messages_overhead(1), 0); assert_ne!(W::receive_messages_proof_messages_overhead(1), Weight::from_ref_time(0));
assert_ne!(W::receive_messages_proof_outbound_lane_state_overhead(), 0); assert_ne!(W::receive_messages_proof_outbound_lane_state_overhead(), Weight::from_ref_time(0));
assert_ne!(W::storage_proof_size_overhead(1), 0); assert_ne!(W::storage_proof_size_overhead(1), Weight::from_ref_time(0));
// verify that the hardcoded value covers `receive_messages_proof` weight // verify that the hardcoded value covers `receive_messages_proof` weight
let actual_single_regular_message_delivery_tx_weight = W::receive_messages_proof_weight( let actual_single_regular_message_delivery_tx_weight = W::receive_messages_proof_weight(
@@ -58,11 +58,11 @@ pub fn ensure_weights_are_correct<W: WeightInfoExt>(
(EXPECTED_DEFAULT_MESSAGE_LENGTH + W::expected_extra_storage_proof_size()) as usize, (EXPECTED_DEFAULT_MESSAGE_LENGTH + W::expected_extra_storage_proof_size()) as usize,
), ),
1, 1,
0, Weight::from_ref_time(0),
); );
assert!( assert!(
actual_single_regular_message_delivery_tx_weight <= actual_single_regular_message_delivery_tx_weight.ref_time() <=
expected_default_message_delivery_tx_weight, expected_default_message_delivery_tx_weight.ref_time(),
"Default message delivery transaction weight {} is larger than expected weight {}", "Default message delivery transaction weight {} is larger than expected weight {}",
actual_single_regular_message_delivery_tx_weight, actual_single_regular_message_delivery_tx_weight,
expected_default_message_delivery_tx_weight, expected_default_message_delivery_tx_weight,
@@ -71,15 +71,16 @@ pub fn ensure_weights_are_correct<W: WeightInfoExt>(
// verify that hardcoded value covers additional byte length of `receive_messages_proof` weight // verify that hardcoded value covers additional byte length of `receive_messages_proof` weight
let actual_additional_byte_delivery_weight = W::storage_proof_size_overhead(1); let actual_additional_byte_delivery_weight = W::storage_proof_size_overhead(1);
assert!( assert!(
actual_additional_byte_delivery_weight <= expected_additional_byte_delivery_weight, actual_additional_byte_delivery_weight.ref_time() <=
expected_additional_byte_delivery_weight.ref_time(),
"Single additional byte delivery weight {} is larger than expected weight {}", "Single additional byte delivery weight {} is larger than expected weight {}",
actual_additional_byte_delivery_weight, actual_additional_byte_delivery_weight,
expected_additional_byte_delivery_weight, expected_additional_byte_delivery_weight,
); );
// verify `receive_messages_delivery_proof` weight components // verify `receive_messages_delivery_proof` weight components
assert_ne!(W::receive_messages_delivery_proof_overhead(), 0); assert_ne!(W::receive_messages_delivery_proof_overhead(), Weight::from_ref_time(0));
assert_ne!(W::storage_proof_size_overhead(1), 0); assert_ne!(W::storage_proof_size_overhead(1), Weight::from_ref_time(0));
// `receive_messages_delivery_proof_messages_overhead` and // `receive_messages_delivery_proof_messages_overhead` and
// `receive_messages_delivery_proof_relayers_overhead` may return zero if rewards are not paid // `receive_messages_delivery_proof_relayers_overhead` may return zero if rewards are not paid
@@ -96,8 +97,8 @@ pub fn ensure_weights_are_correct<W: WeightInfoExt>(
db_weight, db_weight,
); );
assert!( assert!(
actual_messages_delivery_confirmation_tx_weight <= actual_messages_delivery_confirmation_tx_weight.ref_time() <=
expected_messages_delivery_confirmation_tx_weight, expected_messages_delivery_confirmation_tx_weight.ref_time(),
"Messages delivery confirmation transaction weight {} is larger than expected weight {}", "Messages delivery confirmation transaction weight {} is larger than expected weight {}",
actual_messages_delivery_confirmation_tx_weight, actual_messages_delivery_confirmation_tx_weight,
expected_messages_delivery_confirmation_tx_weight, expected_messages_delivery_confirmation_tx_weight,
@@ -106,7 +107,7 @@ pub fn ensure_weights_are_correct<W: WeightInfoExt>(
// verify pay-dispatch-fee overhead for inbound messages // verify pay-dispatch-fee overhead for inbound messages
let actual_pay_inbound_dispatch_fee_weight = W::pay_inbound_dispatch_fee_overhead(); let actual_pay_inbound_dispatch_fee_weight = W::pay_inbound_dispatch_fee_overhead();
assert!( assert!(
actual_pay_inbound_dispatch_fee_weight <= expected_pay_inbound_dispatch_fee_weight, actual_pay_inbound_dispatch_fee_weight.ref_time() <= expected_pay_inbound_dispatch_fee_weight.ref_time(),
"Weight {} of pay-dispatch-fee overhead for inbound messages is larger than expected weight {}", "Weight {} of pay-dispatch-fee overhead for inbound messages is larger than expected weight {}",
actual_pay_inbound_dispatch_fee_weight, actual_pay_inbound_dispatch_fee_weight,
expected_pay_inbound_dispatch_fee_weight, expected_pay_inbound_dispatch_fee_weight,
@@ -140,7 +141,7 @@ pub fn ensure_able_to_receive_message<W: WeightInfoExt>(
max_incoming_message_dispatch_weight, max_incoming_message_dispatch_weight,
); );
assert!( assert!(
max_delivery_transaction_dispatch_weight <= max_extrinsic_weight, max_delivery_transaction_dispatch_weight.ref_time() <= max_extrinsic_weight.ref_time(),
"Weight of maximal message delivery transaction + {} is larger than maximal possible transaction weight {}", "Weight of maximal message delivery transaction + {} is larger than maximal possible transaction weight {}",
max_delivery_transaction_dispatch_weight, max_delivery_transaction_dispatch_weight,
max_extrinsic_weight, max_extrinsic_weight,
@@ -179,7 +180,7 @@ pub fn ensure_able_to_receive_confirmation<W: WeightInfoExt>(
db_weight, db_weight,
); );
assert!( assert!(
max_confirmation_transaction_dispatch_weight <= max_extrinsic_weight, max_confirmation_transaction_dispatch_weight.ref_time() <= max_extrinsic_weight.ref_time(),
"Weight of maximal confirmation transaction {} is larger than maximal possible transaction weight {}", "Weight of maximal confirmation transaction {} is larger than maximal possible transaction weight {}",
max_confirmation_transaction_dispatch_weight, max_confirmation_transaction_dispatch_weight,
max_extrinsic_weight, max_extrinsic_weight,
@@ -264,13 +265,13 @@ pub trait WeightInfoExt: WeightInfo {
// message // message
let callback_overhead = relayers_state let callback_overhead = relayers_state
.total_messages .total_messages
.saturating_mul(Self::single_message_callback_overhead(db_weight)); .saturating_mul(Self::single_message_callback_overhead(db_weight).ref_time());
transaction_overhead transaction_overhead
.saturating_add(messages_overhead) .saturating_add(messages_overhead)
.saturating_add(relayers_overhead) .saturating_add(relayers_overhead)
.saturating_add(proof_size_overhead) .saturating_add(proof_size_overhead)
.saturating_add(callback_overhead) .saturating_add(Weight::from_ref_time(callback_overhead))
} }
// Functions that are used by extrinsics weights formulas. // Functions that are used by extrinsics weights formulas.
@@ -305,7 +306,7 @@ pub trait WeightInfoExt: WeightInfo {
let weight_of_single_message_and_single_tx_overhead = Self::receive_single_message_proof(); let weight_of_single_message_and_single_tx_overhead = Self::receive_single_message_proof();
weight_of_two_messages_and_single_tx_overhead weight_of_two_messages_and_single_tx_overhead
.saturating_sub(weight_of_single_message_and_single_tx_overhead) .saturating_sub(weight_of_single_message_and_single_tx_overhead)
.saturating_mul(messages as Weight) .saturating_mul(messages as _)
} }
/// Returns weight that needs to be accounted when message delivery transaction /// Returns weight that needs to be accounted when message delivery transaction
@@ -336,7 +337,7 @@ pub trait WeightInfoExt: WeightInfo {
let weight_of_single_message = Self::receive_delivery_proof_for_single_message(); let weight_of_single_message = Self::receive_delivery_proof_for_single_message();
weight_of_two_messages weight_of_two_messages
.saturating_sub(weight_of_single_message) .saturating_sub(weight_of_single_message)
.saturating_mul(messages as Weight) .saturating_mul(messages as _)
} }
/// Returns weight that needs to be accounted when receiving confirmations for given a number of /// Returns weight that needs to be accounted when receiving confirmations for given a number of
@@ -348,7 +349,7 @@ pub trait WeightInfoExt: WeightInfo {
Self::receive_delivery_proof_for_two_messages_by_single_relayer(); Self::receive_delivery_proof_for_two_messages_by_single_relayer();
weight_of_two_messages_by_two_relayers weight_of_two_messages_by_two_relayers
.saturating_sub(weight_of_two_messages_by_single_relayer) .saturating_sub(weight_of_two_messages_by_single_relayer)
.saturating_mul(relayers as Weight) .saturating_mul(relayers as _)
} }
/// Returns weight that needs to be accounted when storage proof of given size is received /// Returns weight that needs to be accounted when storage proof of given size is received
@@ -360,7 +361,7 @@ pub trait WeightInfoExt: WeightInfo {
/// relayer must pay when it relays proof of given size (even if cost based on other parameters /// relayer must pay when it relays proof of given size (even if cost based on other parameters
/// is less than that cost). /// is less than that cost).
fn storage_proof_size_overhead(proof_size: u32) -> Weight { fn storage_proof_size_overhead(proof_size: u32) -> Weight {
let proof_size_in_bytes = proof_size as Weight; let proof_size_in_bytes = proof_size;
let byte_weight = (Self::receive_single_message_proof_16_kb() - let byte_weight = (Self::receive_single_message_proof_16_kb() -
Self::receive_single_message_proof_1_kb()) / Self::receive_single_message_proof_1_kb()) /
(15 * 1024); (15 * 1024);
+10 -9
View File
@@ -31,7 +31,7 @@ use sp_runtime::transaction_validity::{InvalidTransaction, TransactionValidity,
/// pallet will be used in our environment. /// pallet will be used in our environment.
impl< impl<
Call: IsSubType<CallableCallFor<Pallet<T, I>, T>>, Call: IsSubType<CallableCallFor<Pallet<T, I>, T>>,
T: frame_system::Config<Call = Call> + Config<I>, T: frame_system::Config<RuntimeCall = Call> + Config<I>,
I: 'static, I: 'static,
> FilterCall<Call> for Pallet<T, I> > FilterCall<Call> for Pallet<T, I>
where where
@@ -77,7 +77,7 @@ where
mod tests { mod tests {
use crate::{ use crate::{
extension::FilterCall, extension::FilterCall,
mock::{run_test, Call, TestRuntime}, mock::{run_test, RuntimeCall, TestRuntime},
ParaInfo, ParasInfo, RelayBlockNumber, ParaInfo, ParasInfo, RelayBlockNumber,
}; };
use bp_parachains::BestParaHeadHash; use bp_parachains::BestParaHeadHash;
@@ -87,13 +87,14 @@ mod tests {
num: RelayBlockNumber, num: RelayBlockNumber,
parachains: Vec<(ParaId, ParaHash)>, parachains: Vec<(ParaId, ParaHash)>,
) -> bool { ) -> bool {
crate::Pallet::<TestRuntime>::validate(&Call::Parachains( crate::Pallet::<TestRuntime>::validate(&RuntimeCall::Parachains(crate::Call::<
crate::Call::<TestRuntime, ()>::submit_parachain_heads { TestRuntime,
at_relay_block: (num, Default::default()), (),
parachains, >::submit_parachain_heads {
parachain_heads_proof: ParaHeadsProof(Vec::new()), at_relay_block: (num, Default::default()),
}, parachains,
)) parachain_heads_proof: ParaHeadsProof(Vec::new()),
}))
.is_ok() .is_ok()
} }
+17 -16
View File
@@ -29,7 +29,7 @@ pub use weights_ext::WeightInfoExt;
use bp_parachains::{parachain_head_storage_key_at_source, ParaInfo}; use bp_parachains::{parachain_head_storage_key_at_source, ParaInfo};
use bp_polkadot_core::parachains::{ParaHash, ParaHasher, ParaHead, ParaHeadsProof, ParaId}; use bp_polkadot_core::parachains::{ParaHash, ParaHasher, ParaHead, ParaHeadsProof, ParaId};
use bp_runtime::StorageProofError; use bp_runtime::StorageProofError;
use frame_support::{traits::Contains, weights::PostDispatchInfo}; use frame_support::{dispatch::PostDispatchInfo, traits::Contains};
use sp_runtime::traits::Header as HeaderT; use sp_runtime::traits::Header as HeaderT;
use sp_std::vec::Vec; use sp_std::vec::Vec;
@@ -132,7 +132,8 @@ pub mod pallet {
pallet_bridge_grandpa::Config<Self::BridgesGrandpaPalletInstance> pallet_bridge_grandpa::Config<Self::BridgesGrandpaPalletInstance>
{ {
/// The overarching event type. /// The overarching event type.
type Event: From<Event<Self, I>> + IsType<<Self as frame_system::Config>::Event>; type RuntimeEvent: From<Event<Self, I>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Benchmarks results from runtime we're plugged into. /// Benchmarks results from runtime we're plugged into.
type WeightInfo: WeightInfoExt; type WeightInfo: WeightInfoExt;
@@ -620,7 +621,7 @@ pub mod pallet {
mod tests { mod tests {
use super::*; use super::*;
use crate::mock::{ use crate::mock::{
run_test, test_relay_header, Event as TestEvent, Origin, TestRuntime, run_test, test_relay_header, RuntimeEvent as TestEvent, RuntimeOrigin, TestRuntime,
MAXIMAL_PARACHAIN_HEAD_SIZE, PARAS_PALLET_NAME, UNTRACKED_PARACHAIN_ID, MAXIMAL_PARACHAIN_HEAD_SIZE, PARAS_PALLET_NAME, UNTRACKED_PARACHAIN_ID,
}; };
use codec::Encode; use codec::Encode;
@@ -650,7 +651,7 @@ mod tests {
fn initialize(state_root: RelayBlockHash) { fn initialize(state_root: RelayBlockHash) {
pallet_bridge_grandpa::Pallet::<TestRuntime, BridgesGrandpaPalletInstance>::initialize( pallet_bridge_grandpa::Pallet::<TestRuntime, BridgesGrandpaPalletInstance>::initialize(
Origin::root(), RuntimeOrigin::root(),
bp_header_chain::InitializationData { bp_header_chain::InitializationData {
header: Box::new(test_relay_header(0, state_root)), header: Box::new(test_relay_header(0, state_root)),
authority_list: authority_list(), authority_list: authority_list(),
@@ -670,7 +671,7 @@ mod tests {
let justification = make_default_justification(&header); let justification = make_default_justification(&header);
assert_ok!( assert_ok!(
pallet_bridge_grandpa::Pallet::<TestRuntime, BridgesGrandpaPalletInstance>::submit_finality_proof( pallet_bridge_grandpa::Pallet::<TestRuntime, BridgesGrandpaPalletInstance>::submit_finality_proof(
Origin::signed(1), RuntimeOrigin::signed(1),
Box::new(header), Box::new(header),
justification, justification,
) )
@@ -736,7 +737,7 @@ mod tests {
proof: ParaHeadsProof, proof: ParaHeadsProof,
) -> DispatchResultWithPostInfo { ) -> DispatchResultWithPostInfo {
Pallet::<TestRuntime>::submit_parachain_heads( Pallet::<TestRuntime>::submit_parachain_heads(
Origin::signed(1), RuntimeOrigin::signed(1),
(relay_chain_block, test_relay_header(relay_chain_block, relay_state_root).hash()), (relay_chain_block, test_relay_header(relay_chain_block, relay_state_root).hash()),
parachains, parachains,
proof, proof,
@@ -747,7 +748,7 @@ mod tests {
let db_weight = <TestRuntime as frame_system::Config>::DbWeight::get(); let db_weight = <TestRuntime as frame_system::Config>::DbWeight::get();
WeightInfoOf::<TestRuntime, ()>::submit_parachain_heads_weight(db_weight, proof, 1) WeightInfoOf::<TestRuntime, ()>::submit_parachain_heads_weight(db_weight, proof, 1)
.saturating_sub(if prune_expected { .saturating_sub(if prune_expected {
0 Weight::from_ref_time(0)
} else { } else {
WeightInfoOf::<TestRuntime, ()>::parachain_head_pruning_weight(db_weight) WeightInfoOf::<TestRuntime, ()>::parachain_head_pruning_weight(db_weight)
}) })
@@ -765,7 +766,7 @@ mod tests {
PalletOperatingMode::<TestRuntime>::put(BasicOperatingMode::Halted); PalletOperatingMode::<TestRuntime>::put(BasicOperatingMode::Halted);
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::submit_parachain_heads( Pallet::<TestRuntime>::submit_parachain_heads(
Origin::signed(1), RuntimeOrigin::signed(1),
(0, test_relay_header(0, state_root).hash()), (0, test_relay_header(0, state_root).hash()),
parachains.clone(), parachains.clone(),
proof.clone(), proof.clone(),
@@ -776,7 +777,7 @@ mod tests {
// `submit_parachain_heads()` should succeed now that the pallet is resumed. // `submit_parachain_heads()` should succeed now that the pallet is resumed.
PalletOperatingMode::<TestRuntime>::put(BasicOperatingMode::Normal); PalletOperatingMode::<TestRuntime>::put(BasicOperatingMode::Normal);
assert_ok!(Pallet::<TestRuntime>::submit_parachain_heads( assert_ok!(Pallet::<TestRuntime>::submit_parachain_heads(
Origin::signed(1), RuntimeOrigin::signed(1),
(0, test_relay_header(0, state_root).hash()), (0, test_relay_header(0, state_root).hash()),
parachains, parachains,
proof, proof,
@@ -795,7 +796,7 @@ mod tests {
let expected_weight = let expected_weight =
WeightInfo::submit_parachain_heads_weight(DbWeight::get(), &proof, 2); WeightInfo::submit_parachain_heads_weight(DbWeight::get(), &proof, 2);
let result = Pallet::<TestRuntime>::submit_parachain_heads( let result = Pallet::<TestRuntime>::submit_parachain_heads(
Origin::signed(1), RuntimeOrigin::signed(1),
(0, test_relay_header(0, state_root).hash()), (0, test_relay_header(0, state_root).hash()),
parachains, parachains,
proof, proof,
@@ -969,7 +970,7 @@ mod tests {
)); ));
initialize(state_root); initialize(state_root);
let result = Pallet::<TestRuntime>::submit_parachain_heads( let result = Pallet::<TestRuntime>::submit_parachain_heads(
Origin::signed(1), RuntimeOrigin::signed(1),
(0, test_relay_header(0, state_root).hash()), (0, test_relay_header(0, state_root).hash()),
parachains, parachains,
proof, proof,
@@ -1159,7 +1160,7 @@ mod tests {
// parachain // parachain
initialize(state_root); initialize(state_root);
let result = Pallet::<TestRuntime>::submit_parachain_heads( let result = Pallet::<TestRuntime>::submit_parachain_heads(
Origin::signed(1), RuntimeOrigin::signed(1),
(0, test_relay_header(0, state_root).hash()), (0, test_relay_header(0, state_root).hash()),
parachains, parachains,
proof, proof,
@@ -1303,7 +1304,7 @@ mod tests {
// => we'll leave previous value // => we'll leave previous value
proceed(20, state_root_10_at_20); proceed(20, state_root_10_at_20);
assert_ok!(Pallet::<TestRuntime>::submit_parachain_heads( assert_ok!(Pallet::<TestRuntime>::submit_parachain_heads(
Origin::signed(1), RuntimeOrigin::signed(1),
(20, test_relay_header(20, state_root_10_at_20).hash()), (20, test_relay_header(20, state_root_10_at_20).hash()),
parachains_10_at_20, parachains_10_at_20,
proof_10_at_20, proof_10_at_20,
@@ -1319,7 +1320,7 @@ mod tests {
// => we'll update value // => we'll update value
proceed(30, state_root_10_at_30); proceed(30, state_root_10_at_30);
assert_ok!(Pallet::<TestRuntime>::submit_parachain_heads( assert_ok!(Pallet::<TestRuntime>::submit_parachain_heads(
Origin::signed(1), RuntimeOrigin::signed(1),
(30, test_relay_header(30, state_root_10_at_30).hash()), (30, test_relay_header(30, state_root_10_at_30).hash()),
parachains_10_at_30, parachains_10_at_30,
proof_10_at_30, proof_10_at_30,
@@ -1360,7 +1361,7 @@ mod tests {
run_test(|| { run_test(|| {
initialize(state_root); initialize(state_root);
assert_ok!(Pallet::<TestRuntime>::submit_parachain_heads( assert_ok!(Pallet::<TestRuntime>::submit_parachain_heads(
Origin::signed(1), RuntimeOrigin::signed(1),
(0, test_relay_header(0, state_root).hash()), (0, test_relay_header(0, state_root).hash()),
parachains, parachains,
proof, proof,
@@ -1385,7 +1386,7 @@ mod tests {
run_test(|| { run_test(|| {
initialize(state_root); initialize(state_root);
assert_ok!(Pallet::<TestRuntime>::submit_parachain_heads( assert_ok!(Pallet::<TestRuntime>::submit_parachain_heads(
Origin::signed(1), RuntimeOrigin::signed(1),
(0, test_relay_header(0, state_root).hash()), (0, test_relay_header(0, state_root).hash()),
parachains, parachains,
proof, proof,
+5 -5
View File
@@ -53,22 +53,22 @@ construct_runtime! {
parameter_types! { parameter_types! {
pub const BlockHashCount: TestNumber = 250; pub const BlockHashCount: TestNumber = 250;
pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockWeight: Weight = Weight::from_ref_time(1024);
pub const MaximumBlockLength: u32 = 2 * 1024; pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one(); pub const AvailableBlockRatio: Perbill = Perbill::one();
} }
impl frame_system::Config for TestRuntime { impl frame_system::Config for TestRuntime {
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
type Index = u64; type Index = u64;
type Call = Call; type RuntimeCall = RuntimeCall;
type BlockNumber = TestNumber; type BlockNumber = TestNumber;
type Hash = H256; type Hash = H256;
type Hashing = BlakeTwo256; type Hashing = BlakeTwo256;
type AccountId = AccountId; type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header; type Header = Header;
type Event = Event; type RuntimeEvent = RuntimeEvent;
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
type Version = (); type Version = ();
type PalletInfo = PalletInfo; type PalletInfo = PalletInfo;
@@ -117,7 +117,7 @@ parameter_types! {
} }
impl pallet_bridge_parachains::Config for TestRuntime { impl pallet_bridge_parachains::Config for TestRuntime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type WeightInfo = (); type WeightInfo = ();
type BridgesGrandpaPalletInstance = pallet_bridge_grandpa::Instance1; type BridgesGrandpaPalletInstance = pallet_bridge_grandpa::Instance1;
type ParasPalletName = ParasPalletName; type ParasPalletName = ParasPalletName;
+22 -22
View File
@@ -61,41 +61,41 @@ pub trait WeightInfo {
pub struct BridgeWeight<T>(PhantomData<T>); pub struct BridgeWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> { impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
fn submit_parachain_heads_with_n_parachains(p: u32) -> Weight { fn submit_parachain_heads_with_n_parachains(p: u32) -> Weight {
(0 as Weight) Weight::from_ref_time(0 as u64)
.saturating_add((24_869_000 as Weight).saturating_mul(p as Weight)) .saturating_add(Weight::from_ref_time(24_869_000 as u64).saturating_mul(p as u64))
.saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().reads(2 as u64))
.saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(p as Weight))) .saturating_add(T::DbWeight::get().reads((2 as u64).saturating_mul(p as u64)))
.saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(p as Weight))) .saturating_add(T::DbWeight::get().writes((3 as u64).saturating_mul(p as u64)))
} }
fn submit_parachain_heads_with_1kb_proof() -> Weight { fn submit_parachain_heads_with_1kb_proof() -> Weight {
(56_262_000 as Weight) Weight::from_ref_time(56_262_000 as u64)
.saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().reads(4 as u64))
.saturating_add(T::DbWeight::get().writes(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as u64))
} }
fn submit_parachain_heads_with_16kb_proof() -> Weight { fn submit_parachain_heads_with_16kb_proof() -> Weight {
(105_189_000 as Weight) Weight::from_ref_time(105_189_000 as u64)
.saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().reads(4 as u64))
.saturating_add(T::DbWeight::get().writes(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as u64))
} }
} }
// For backwards compatibility and tests // For backwards compatibility and tests
impl WeightInfo for () { impl WeightInfo for () {
fn submit_parachain_heads_with_n_parachains(p: u32) -> Weight { fn submit_parachain_heads_with_n_parachains(p: u32) -> Weight {
(0 as Weight) Weight::from_ref_time(0 as u64)
.saturating_add((24_869_000 as Weight).saturating_mul(p as Weight)) .saturating_add(Weight::from_ref_time(24_869_000 as u64).saturating_mul(p as u64))
.saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as u64))
.saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(p as Weight))) .saturating_add(RocksDbWeight::get().reads((2 as u64).saturating_mul(p as u64)))
.saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(p as Weight))) .saturating_add(RocksDbWeight::get().writes((3 as u64).saturating_mul(p as u64)))
} }
fn submit_parachain_heads_with_1kb_proof() -> Weight { fn submit_parachain_heads_with_1kb_proof() -> Weight {
(56_262_000 as Weight) Weight::from_ref_time(56_262_000 as u64)
.saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as u64))
.saturating_add(RocksDbWeight::get().writes(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as u64))
} }
fn submit_parachain_heads_with_16kb_proof() -> Weight { fn submit_parachain_heads_with_16kb_proof() -> Weight {
(105_189_000 as Weight) Weight::from_ref_time(105_189_000 as u64)
.saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as u64))
.saturating_add(RocksDbWeight::get().writes(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as u64))
} }
} }
@@ -62,8 +62,8 @@ pub trait WeightInfoExt: WeightInfo {
); );
// potential pruning weight (refunded if hasn't happened) // potential pruning weight (refunded if hasn't happened)
let pruning_weight = (parachains_count as Weight) let pruning_weight =
.saturating_mul(Self::parachain_head_pruning_weight(db_weight)); Self::parachain_head_pruning_weight(db_weight).saturating_mul(parachains_count as u64);
base_weight.saturating_add(proof_size_overhead).saturating_add(pruning_weight) base_weight.saturating_add(proof_size_overhead).saturating_add(pruning_weight)
} }
@@ -87,11 +87,10 @@ pub trait WeightInfoExt: WeightInfo {
/// Returns weight that needs to be accounted when storage proof of given size is received. /// Returns weight that needs to be accounted when storage proof of given size is received.
fn storage_proof_size_overhead(extra_proof_bytes: u32) -> Weight { fn storage_proof_size_overhead(extra_proof_bytes: u32) -> Weight {
let extra_proof_bytes_in_bytes = extra_proof_bytes as Weight;
let extra_byte_weight = (Self::submit_parachain_heads_with_16kb_proof() - let extra_byte_weight = (Self::submit_parachain_heads_with_16kb_proof() -
Self::submit_parachain_heads_with_1kb_proof()) / Self::submit_parachain_heads_with_1kb_proof()) /
(15 * 1024); (15 * 1024);
extra_proof_bytes_in_bytes.saturating_mul(extra_byte_weight) extra_byte_weight.saturating_mul(extra_proof_bytes as u64)
} }
} }
+8 -6
View File
@@ -46,7 +46,7 @@ pub mod pallet {
#[pallet::config] #[pallet::config]
pub trait Config: frame_system::Config { pub trait Config: frame_system::Config {
/// The overarching event type. /// The overarching event type.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>; type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Type of relayer reward. /// Type of relayer reward.
type Reward: AtLeast32BitUnsigned + Copy + Parameter + MaxEncodedLen; type Reward: AtLeast32BitUnsigned + Copy + Parameter + MaxEncodedLen;
/// Pay rewards adapter. /// Pay rewards adapter.
@@ -113,7 +113,7 @@ pub mod pallet {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use mock::{Event as TestEvent, *}; use mock::{RuntimeEvent as TestEvent, *};
use crate::Event::RewardPaid; use crate::Event::RewardPaid;
use frame_support::{assert_noop, assert_ok, traits::fungible::Inspect}; use frame_support::{assert_noop, assert_ok, traits::fungible::Inspect};
@@ -129,7 +129,7 @@ mod tests {
fn root_cant_claim_anything() { fn root_cant_claim_anything() {
run_test(|| { run_test(|| {
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::claim_rewards(Origin::root()), Pallet::<TestRuntime>::claim_rewards(RuntimeOrigin::root()),
DispatchError::BadOrigin, DispatchError::BadOrigin,
); );
}); });
@@ -139,7 +139,7 @@ mod tests {
fn relayer_cant_claim_if_no_reward_exists() { fn relayer_cant_claim_if_no_reward_exists() {
run_test(|| { run_test(|| {
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::claim_rewards(Origin::signed(REGULAR_RELAYER)), Pallet::<TestRuntime>::claim_rewards(RuntimeOrigin::signed(REGULAR_RELAYER)),
Error::<TestRuntime>::NoRewardForRelayer, Error::<TestRuntime>::NoRewardForRelayer,
); );
}); });
@@ -150,7 +150,7 @@ mod tests {
run_test(|| { run_test(|| {
RelayerRewards::<TestRuntime>::insert(FAILING_RELAYER, 100); RelayerRewards::<TestRuntime>::insert(FAILING_RELAYER, 100);
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::claim_rewards(Origin::signed(FAILING_RELAYER)), Pallet::<TestRuntime>::claim_rewards(RuntimeOrigin::signed(FAILING_RELAYER)),
Error::<TestRuntime>::FailedToPayReward, Error::<TestRuntime>::FailedToPayReward,
); );
}); });
@@ -162,7 +162,9 @@ mod tests {
get_ready_for_events(); get_ready_for_events();
RelayerRewards::<TestRuntime>::insert(REGULAR_RELAYER, 100); RelayerRewards::<TestRuntime>::insert(REGULAR_RELAYER, 100);
assert_ok!(Pallet::<TestRuntime>::claim_rewards(Origin::signed(REGULAR_RELAYER))); assert_ok!(Pallet::<TestRuntime>::claim_rewards(RuntimeOrigin::signed(
REGULAR_RELAYER
)));
assert_eq!(RelayerRewards::<TestRuntime>::get(REGULAR_RELAYER), None); assert_eq!(RelayerRewards::<TestRuntime>::get(REGULAR_RELAYER), None);
//Check if the `RewardPaid` event was emitted. //Check if the `RewardPaid` event was emitted.
+6 -6
View File
@@ -51,16 +51,16 @@ parameter_types! {
} }
impl frame_system::Config for TestRuntime { impl frame_system::Config for TestRuntime {
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
type Index = u64; type Index = u64;
type Call = Call; type RuntimeCall = RuntimeCall;
type BlockNumber = u64; type BlockNumber = u64;
type Hash = H256; type Hash = H256;
type Hashing = BlakeTwo256; type Hashing = BlakeTwo256;
type AccountId = AccountId; type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = SubstrateHeader; type Header = SubstrateHeader;
type Event = Event; type RuntimeEvent = RuntimeEvent;
type BlockHashCount = frame_support::traits::ConstU64<250>; type BlockHashCount = frame_support::traits::ConstU64<250>;
type Version = (); type Version = ();
type PalletInfo = PalletInfo; type PalletInfo = PalletInfo;
@@ -81,7 +81,7 @@ impl pallet_balances::Config for TestRuntime {
type MaxLocks = (); type MaxLocks = ();
type Balance = Balance; type Balance = Balance;
type DustRemoval = (); type DustRemoval = ();
type Event = Event; type RuntimeEvent = RuntimeEvent;
type ExistentialDeposit = frame_support::traits::ConstU64<1>; type ExistentialDeposit = frame_support::traits::ConstU64<1>;
type AccountStore = frame_system::Pallet<TestRuntime>; type AccountStore = frame_system::Pallet<TestRuntime>;
type WeightInfo = (); type WeightInfo = ();
@@ -95,7 +95,7 @@ parameter_types! {
// we're not testing messages pallet here, so values in this config might be crazy // we're not testing messages pallet here, so values in this config might be crazy
impl pallet_bridge_messages::Config for TestRuntime { impl pallet_bridge_messages::Config for TestRuntime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type WeightInfo = (); type WeightInfo = ();
type Parameter = (); type Parameter = ();
type MaxMessagesToPruneAtOnce = frame_support::traits::ConstU64<0>; type MaxMessagesToPruneAtOnce = frame_support::traits::ConstU64<0>;
@@ -122,7 +122,7 @@ impl pallet_bridge_messages::Config for TestRuntime {
} }
impl pallet_bridge_relayers::Config for TestRuntime { impl pallet_bridge_relayers::Config for TestRuntime {
type Event = Event; type RuntimeEvent = RuntimeEvent;
type Reward = Balance; type Reward = Balance;
type PaymentProcedure = TestPaymentProcedure; type PaymentProcedure = TestPaymentProcedure;
type WeightInfo = (); type WeightInfo = ();
@@ -31,7 +31,7 @@ pub struct MessageDeliveryAndDispatchPaymentAdapter<T, MessagesInstance, GetConf
); );
impl<T, MessagesInstance, GetConfirmationFee> impl<T, MessagesInstance, GetConfirmationFee>
MessageDeliveryAndDispatchPayment<T::Origin, T::AccountId, T::Reward> MessageDeliveryAndDispatchPayment<T::RuntimeOrigin, T::AccountId, T::Reward>
for MessageDeliveryAndDispatchPaymentAdapter<T, MessagesInstance, GetConfirmationFee> for MessageDeliveryAndDispatchPaymentAdapter<T, MessagesInstance, GetConfirmationFee>
where where
T: Config + pallet_bridge_messages::Config<MessagesInstance, OutboundMessageFee = T::Reward>, T: Config + pallet_bridge_messages::Config<MessagesInstance, OutboundMessageFee = T::Reward>,
@@ -41,7 +41,7 @@ where
type Error = &'static str; type Error = &'static str;
fn pay_delivery_and_dispatch_fee( fn pay_delivery_and_dispatch_fee(
_submitter: &T::Origin, _submitter: &T::RuntimeOrigin,
_fee: &T::Reward, _fee: &T::Reward,
) -> Result<(), Self::Error> { ) -> Result<(), Self::Error> {
// nothing shall happen here, because XCM deals with fee payment (planned to be burnt? // nothing shall happen here, because XCM deals with fee payment (planned to be burnt?
+6 -6
View File
@@ -59,17 +59,17 @@ pub trait WeightInfo {
pub struct BridgeWeight<T>(PhantomData<T>); pub struct BridgeWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> { impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
fn claim_rewards() -> Weight { fn claim_rewards() -> Weight {
(55_856_000 as Weight) Weight::from_ref_time(55_856_000 as u64)
.saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().reads(2 as u64))
.saturating_add(T::DbWeight::get().writes(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as u64))
} }
} }
// For backwards compatibility and tests // For backwards compatibility and tests
impl WeightInfo for () { impl WeightInfo for () {
fn claim_rewards() -> Weight { fn claim_rewards() -> Weight {
(55_856_000 as Weight) Weight::from_ref_time(55_856_000 as u64)
.saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as u64))
.saturating_add(RocksDbWeight::get().writes(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as u64))
} }
} }
@@ -153,22 +153,22 @@ mod tests {
parameter_types! { parameter_types! {
pub const BlockHashCount: u64 = 250; pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockWeight: Weight = Weight::from_ref_time(1024);
pub const MaximumBlockLength: u32 = 2 * 1024; pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one(); pub const AvailableBlockRatio: Perbill = Perbill::one();
} }
impl frame_system::Config for TestRuntime { impl frame_system::Config for TestRuntime {
type Origin = Origin; type RuntimeOrigin = RuntimeOrigin;
type Index = u64; type Index = u64;
type Call = Call; type RuntimeCall = RuntimeCall;
type BlockNumber = u64; type BlockNumber = u64;
type Hash = H256; type Hash = H256;
type Hashing = BlakeTwo256; type Hashing = BlakeTwo256;
type AccountId = AccountId; type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header; type Header = Header;
type Event = (); type RuntimeEvent = ();
type BlockHashCount = BlockHashCount; type BlockHashCount = BlockHashCount;
type Version = (); type Version = ();
type PalletInfo = PalletInfo; type PalletInfo = PalletInfo;
@@ -191,7 +191,7 @@ mod tests {
} }
impl pallet_session::Config for TestRuntime { impl pallet_session::Config for TestRuntime {
type Event = (); type RuntimeEvent = ();
type ValidatorId = <Self as frame_system::Config>::AccountId; type ValidatorId = <Self as frame_system::Config>::AccountId;
type ValidatorIdOf = ConvertInto; type ValidatorIdOf = ConvertInto;
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>; type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
+1 -1
View File
@@ -16,7 +16,7 @@ fixed-hash = { version = "0.7.0", default-features = false }
hash256-std-hasher = { version = "0.15.2", default-features = false } hash256-std-hasher = { version = "0.15.2", default-features = false }
impl-codec = { version = "0.6", default-features = false } impl-codec = { version = "0.6", default-features = false }
impl-serde = { version = "0.3.1", optional = true } impl-serde = { version = "0.3.1", optional = true }
parity-util-mem = { version = "0.11", default-features = false, features = ["primitive-types"] } parity-util-mem = { version = "0.12", default-features = false, features = ["primitive-types"] }
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
serde = { version = "1.0", optional = true, features = ["derive"] } serde = { version = "1.0", optional = true, features = ["derive"] }
+11 -25
View File
@@ -25,7 +25,8 @@ use bp_messages::{
}; };
use bp_runtime::{decl_bridge_runtime_apis, Chain}; use bp_runtime::{decl_bridge_runtime_apis, Chain};
use frame_support::{ use frame_support::{
weights::{constants::WEIGHT_PER_SECOND, DispatchClass, IdentityFee, Weight}, dispatch::DispatchClass,
weights::{constants::WEIGHT_PER_SECOND, IdentityFee, Weight},
Parameter, RuntimeDebug, Parameter, RuntimeDebug,
}; };
use frame_system::limits; use frame_system::limits;
@@ -56,11 +57,8 @@ pub const TX_EXTRA_BYTES: u32 = 103;
/// Maximum weight of single Millau block. /// Maximum weight of single Millau block.
/// ///
/// This represents 0.5 seconds of compute assuming a target block time of six seconds. /// This represents 0.5 seconds of compute assuming a target block time of six seconds.
pub const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2; // TODO: https://github.com/paritytech/parity-bridges-common/issues/1543 - remove `set_proof_size`
pub const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND.set_proof_size(1_000).saturating_div(2);
/// Represents the average portion of a block's weight that will be used by an
/// `on_initialize()` runtime call.
pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);
/// Represents the portion of a block that will be used by Normal extrinsics. /// Represents the portion of a block that will be used by Normal extrinsics.
pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
@@ -77,21 +75,22 @@ pub const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 128;
/// for the case when single message of `pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH` /// for the case when single message of `pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH`
/// bytes is delivered. The message must have dispatch weight set to zero. The result then must be /// bytes is delivered. The message must have dispatch weight set to zero. The result then must be
/// rounded up to account possible future runtime upgrades. /// rounded up to account possible future runtime upgrades.
pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = 1_500_000_000; pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = Weight::from_ref_time(1_500_000_000);
/// Increase of delivery transaction weight on Millau chain with every additional message byte. /// Increase of delivery transaction weight on Millau chain with every additional message byte.
/// ///
/// This value is a result of /// This value is a result of
/// `pallet_bridge_messages::WeightInfoExt::storage_proof_size_overhead(1)` call. The result then /// `pallet_bridge_messages::WeightInfoExt::storage_proof_size_overhead(1)` call. The result then
/// must be rounded up to account possible future runtime upgrades. /// must be rounded up to account possible future runtime upgrades.
pub const ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT: Weight = 25_000; pub const ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT: Weight = Weight::from_ref_time(25_000);
/// Maximal weight of single message delivery confirmation transaction on Millau chain. /// Maximal weight of single message delivery confirmation transaction on Millau chain.
/// ///
/// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_delivery_proof` /// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_delivery_proof`
/// weight formula computation for the case when single message is confirmed. The result then must /// weight formula computation for the case when single message is confirmed. The result then must
/// be rounded up to account possible future runtime upgrades. /// be rounded up to account possible future runtime upgrades.
pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight = 2_000_000_000; pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight =
Weight::from_ref_time(2_000_000_000);
/// Weight of pay-dispatch-fee operation for inbound messages at Millau chain. /// Weight of pay-dispatch-fee operation for inbound messages at Millau chain.
/// ///
@@ -100,7 +99,7 @@ pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight = 2_000_000
/// chain. Don't put too much reserve there, because it is used to **decrease** /// chain. Don't put too much reserve there, because it is used to **decrease**
/// `DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT` cost. So putting large reserve would make delivery /// `DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT` cost. So putting large reserve would make delivery
/// transactions cheaper. /// transactions cheaper.
pub const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = 700_000_000; pub const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = Weight::from_ref_time(700_000_000);
/// The target length of a session (how often authorities change) on Millau measured in of number of /// The target length of a session (how often authorities change) on Millau measured in of number of
/// blocks. /// blocks.
@@ -227,21 +226,8 @@ impl sp_runtime::traits::Hash for BlakeTwoAndKeccak256 {
frame_support::parameter_types! { frame_support::parameter_types! {
pub BlockLength: limits::BlockLength = pub BlockLength: limits::BlockLength =
limits::BlockLength::max_with_normal_ratio(2 * 1024 * 1024, NORMAL_DISPATCH_RATIO); limits::BlockLength::max_with_normal_ratio(2 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
pub BlockWeights: limits::BlockWeights = limits::BlockWeights::builder() pub BlockWeights: limits::BlockWeights =
// Allowance for Normal class limits::BlockWeights::with_sensible_defaults(MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO);
.for_class(DispatchClass::Normal, |weights| {
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
// Allowance for Operational class
.for_class(DispatchClass::Operational, |weights| {
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
// Extra reserved space for Operational class
weights.reserved = Some(MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
// By default Mandatory class is not limited at all.
// This parameter is used to derive maximal size of a single extrinsic.
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
.build_or_panic();
} }
/// Name of the With-Millau GRANDPA pallet instance that is deployed at bridged chains. /// Name of the With-Millau GRANDPA pallet instance that is deployed at bridged chains.
@@ -23,7 +23,8 @@ use bp_messages::{
}; };
use bp_runtime::{decl_bridge_runtime_apis, Chain}; use bp_runtime::{decl_bridge_runtime_apis, Chain};
use frame_support::{ use frame_support::{
weights::{constants::WEIGHT_PER_SECOND, DispatchClass, IdentityFee, Weight}, dispatch::DispatchClass,
weights::{constants::WEIGHT_PER_SECOND, IdentityFee, Weight},
Parameter, RuntimeDebug, Parameter, RuntimeDebug,
}; };
use frame_system::limits; use frame_system::limits;
@@ -53,11 +54,8 @@ pub const TX_EXTRA_BYTES: u32 = 104;
/// Maximal weight of single RialtoParachain block. /// Maximal weight of single RialtoParachain block.
/// ///
/// This represents two seconds of compute assuming a target block time of six seconds. /// This represents two seconds of compute assuming a target block time of six seconds.
pub const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND; // TODO: https://github.com/paritytech/parity-bridges-common/issues/1543 - remove `set_proof_size`
pub const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND.set_proof_size(1_000).saturating_mul(2);
/// Represents the average portion of a block's weight that will be used by an
/// `on_initialize()` runtime call.
pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);
/// Represents the portion of a block that will be used by Normal extrinsics. /// Represents the portion of a block that will be used by Normal extrinsics.
pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
@@ -74,7 +72,7 @@ pub const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 1024;
/// for the case when single message of `pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH` /// for the case when single message of `pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH`
/// bytes is delivered. The message must have dispatch weight set to zero. The result then must be /// bytes is delivered. The message must have dispatch weight set to zero. The result then must be
/// rounded up to account possible future runtime upgrades. /// rounded up to account possible future runtime upgrades.
pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = 1_500_000_000; pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = Weight::from_ref_time(1_500_000_000);
/// Increase of delivery transaction weight on RialtoParachain chain with every additional message /// Increase of delivery transaction weight on RialtoParachain chain with every additional message
/// byte. /// byte.
@@ -82,14 +80,15 @@ pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = 1_500_000_000;
/// This value is a result of /// This value is a result of
/// `pallet_bridge_messages::WeightInfoExt::storage_proof_size_overhead(1)` call. The result then /// `pallet_bridge_messages::WeightInfoExt::storage_proof_size_overhead(1)` call. The result then
/// must be rounded up to account possible future runtime upgrades. /// must be rounded up to account possible future runtime upgrades.
pub const ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT: Weight = 25_000; pub const ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT: Weight = Weight::from_ref_time(25_000);
/// Maximal weight of single message delivery confirmation transaction on RialtoParachain chain. /// Maximal weight of single message delivery confirmation transaction on RialtoParachain chain.
/// ///
/// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_delivery_proof` /// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_delivery_proof`
/// weight formula computation for the case when single message is confirmed. The result then must /// weight formula computation for the case when single message is confirmed. The result then must
/// be rounded up to account possible future runtime upgrades. /// be rounded up to account possible future runtime upgrades.
pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight = 2_000_000_000; pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight =
Weight::from_ref_time(2_000_000_000);
/// Weight of pay-dispatch-fee operation for inbound messages at Rialto chain. /// Weight of pay-dispatch-fee operation for inbound messages at Rialto chain.
/// ///
@@ -98,7 +97,7 @@ pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight = 2_000_000
/// chain. Don't put too much reserve there, because it is used to **decrease** /// chain. Don't put too much reserve there, because it is used to **decrease**
/// `DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT` cost. So putting large reserve would make delivery /// `DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT` cost. So putting large reserve would make delivery
/// transactions cheaper. /// transactions cheaper.
pub const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = 600_000_000; pub const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = Weight::from_ref_time(600_000_000);
/// Block number type used in Rialto. /// Block number type used in Rialto.
pub type BlockNumber = u32; pub type BlockNumber = u32;
@@ -164,21 +163,8 @@ impl Chain for RialtoParachain {
frame_support::parameter_types! { frame_support::parameter_types! {
pub BlockLength: limits::BlockLength = pub BlockLength: limits::BlockLength =
limits::BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); limits::BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
pub BlockWeights: limits::BlockWeights = limits::BlockWeights::builder() pub BlockWeights: limits::BlockWeights =
// Allowance for Normal class limits::BlockWeights::with_sensible_defaults(MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO);
.for_class(DispatchClass::Normal, |weights| {
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
// Allowance for Operational class
.for_class(DispatchClass::Operational, |weights| {
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
// Extra reserved space for Operational class
weights.reserved = Some(MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
// By default Mandatory class is not limited at all.
// This parameter is used to derive maximal size of a single extrinsic.
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
.build_or_panic();
} }
/// Name of the With-Rialto-Parachain messages pallet instance that is deployed at bridged chains. /// Name of the With-Rialto-Parachain messages pallet instance that is deployed at bridged chains.
+11 -25
View File
@@ -23,7 +23,8 @@ use bp_messages::{
}; };
use bp_runtime::{decl_bridge_runtime_apis, Chain}; use bp_runtime::{decl_bridge_runtime_apis, Chain};
use frame_support::{ use frame_support::{
weights::{constants::WEIGHT_PER_SECOND, DispatchClass, IdentityFee, Weight}, dispatch::DispatchClass,
weights::{constants::WEIGHT_PER_SECOND, IdentityFee, Weight},
Parameter, RuntimeDebug, Parameter, RuntimeDebug,
}; };
use frame_system::limits; use frame_system::limits;
@@ -47,11 +48,8 @@ pub const TX_EXTRA_BYTES: u32 = 104;
/// Maximal weight of single Rialto block. /// Maximal weight of single Rialto block.
/// ///
/// This represents two seconds of compute assuming a target block time of six seconds. /// This represents two seconds of compute assuming a target block time of six seconds.
pub const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND; // TODO: https://github.com/paritytech/parity-bridges-common/issues/1543 - remove `set_proof_size`
pub const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND.set_proof_size(1_000).saturating_mul(2);
/// Represents the average portion of a block's weight that will be used by an
/// `on_initialize()` runtime call.
pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);
/// Represents the portion of a block that will be used by Normal extrinsics. /// Represents the portion of a block that will be used by Normal extrinsics.
pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
@@ -68,21 +66,22 @@ pub const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 1024;
/// for the case when single message of `pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH` /// for the case when single message of `pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH`
/// bytes is delivered. The message must have dispatch weight set to zero. The result then must be /// bytes is delivered. The message must have dispatch weight set to zero. The result then must be
/// rounded up to account possible future runtime upgrades. /// rounded up to account possible future runtime upgrades.
pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = 1_500_000_000; pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = Weight::from_ref_time(1_500_000_000);
/// Increase of delivery transaction weight on Rialto chain with every additional message byte. /// Increase of delivery transaction weight on Rialto chain with every additional message byte.
/// ///
/// This value is a result of /// This value is a result of
/// `pallet_bridge_messages::WeightInfoExt::storage_proof_size_overhead(1)` call. The result then /// `pallet_bridge_messages::WeightInfoExt::storage_proof_size_overhead(1)` call. The result then
/// must be rounded up to account possible future runtime upgrades. /// must be rounded up to account possible future runtime upgrades.
pub const ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT: Weight = 25_000; pub const ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT: Weight = Weight::from_ref_time(25_000);
/// Maximal weight of single message delivery confirmation transaction on Rialto chain. /// Maximal weight of single message delivery confirmation transaction on Rialto chain.
/// ///
/// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_delivery_proof` /// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_delivery_proof`
/// weight formula computation for the case when single message is confirmed. The result then must /// weight formula computation for the case when single message is confirmed. The result then must
/// be rounded up to account possible future runtime upgrades. /// be rounded up to account possible future runtime upgrades.
pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight = 2_000_000_000; pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight =
Weight::from_ref_time(2_000_000_000);
/// Weight of pay-dispatch-fee operation for inbound messages at Rialto chain. /// Weight of pay-dispatch-fee operation for inbound messages at Rialto chain.
/// ///
@@ -91,7 +90,7 @@ pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight = 2_000_000
/// chain. Don't put too much reserve there, because it is used to **decrease** /// chain. Don't put too much reserve there, because it is used to **decrease**
/// `DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT` cost. So putting large reserve would make delivery /// `DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT` cost. So putting large reserve would make delivery
/// transactions cheaper. /// transactions cheaper.
pub const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = 700_000_000; pub const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = Weight::from_ref_time(700_000_000);
/// The target length of a session (how often authorities change) on Rialto measured in of number of /// The target length of a session (how often authorities change) on Rialto measured in of number of
/// blocks. /// blocks.
@@ -193,21 +192,8 @@ impl Chain for Rialto {
frame_support::parameter_types! { frame_support::parameter_types! {
pub BlockLength: limits::BlockLength = pub BlockLength: limits::BlockLength =
limits::BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); limits::BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
pub BlockWeights: limits::BlockWeights = limits::BlockWeights::builder() pub BlockWeights: limits::BlockWeights =
// Allowance for Normal class limits::BlockWeights::with_sensible_defaults(MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO);
.for_class(DispatchClass::Normal, |weights| {
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
// Allowance for Operational class
.for_class(DispatchClass::Operational, |weights| {
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
// Extra reserved space for Operational class
weights.reserved = Some(MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
// By default Mandatory class is not limited at all.
// This parameter is used to derive maximal size of a single extrinsic.
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
.build_or_panic();
} }
/// Name of the With-Rialto GRANDPA pallet instance that is deployed at bridged chains. /// Name of the With-Rialto GRANDPA pallet instance that is deployed at bridged chains.
+5 -2
View File
@@ -33,12 +33,15 @@ pub type Westend = PolkadotLike;
pub enum Call {} pub enum Call {}
impl sp_runtime::traits::Dispatchable for Call { impl sp_runtime::traits::Dispatchable for Call {
type Origin = (); type RuntimeOrigin = ();
type Config = (); type Config = ();
type Info = (); type Info = ();
type PostInfo = (); type PostInfo = ();
fn dispatch(self, _origin: Self::Origin) -> sp_runtime::DispatchResultWithInfo<Self::PostInfo> { fn dispatch(
self,
_origin: Self::RuntimeOrigin,
) -> sp_runtime::DispatchResultWithInfo<Self::PostInfo> {
unimplemented!("The Call is not expected to be dispatched.") unimplemented!("The Call is not expected to be dispatched.")
} }
} }
@@ -212,7 +212,7 @@ impl<SenderOrigin, Balance, Payload> MessagesBridge<SenderOrigin, Balance, Paylo
_message: Payload, _message: Payload,
_delivery_and_dispatch_fee: Balance, _delivery_and_dispatch_fee: Balance,
) -> Result<SendMessageArtifacts, Self::Error> { ) -> Result<SendMessageArtifacts, Self::Error> {
Ok(SendMessageArtifacts { nonce: 0, weight: 0 }) Ok(SendMessageArtifacts { nonce: 0, weight: Weight::from_ref_time(0) })
} }
} }
@@ -233,10 +233,11 @@ pub trait OnDeliveryConfirmed {
fn on_messages_delivered(_lane: &LaneId, _messages: &DeliveredMessages) -> Weight; fn on_messages_delivered(_lane: &LaneId, _messages: &DeliveredMessages) -> Weight;
} }
#[allow(clippy::let_and_return)]
#[impl_trait_for_tuples::impl_for_tuples(30)] #[impl_trait_for_tuples::impl_for_tuples(30)]
impl OnDeliveryConfirmed for Tuple { impl OnDeliveryConfirmed for Tuple {
fn on_messages_delivered(lane: &LaneId, messages: &DeliveredMessages) -> Weight { fn on_messages_delivered(lane: &LaneId, messages: &DeliveredMessages) -> Weight {
let mut total_weight: Weight = 0; let mut total_weight = Weight::from_ref_time(0);
for_tuples!( for_tuples!(
#( #(
total_weight = total_weight.saturating_add(Tuple::on_messages_delivered(lane, messages)); total_weight = total_weight.saturating_add(Tuple::on_messages_delivered(lane, messages));
@@ -254,7 +255,7 @@ pub trait OnMessageAccepted {
impl OnMessageAccepted for () { impl OnMessageAccepted for () {
fn on_messages_accepted(_lane: &LaneId, _message: &MessageNonce) -> Weight { fn on_messages_accepted(_lane: &LaneId, _message: &MessageNonce) -> Weight {
0 Weight::from_ref_time(0)
} }
} }
@@ -167,7 +167,7 @@ impl<AccountId, Fee> MessageDispatch<AccountId, Fee> for ForbidInboundMessages {
) -> MessageDispatchResult { ) -> MessageDispatchResult {
MessageDispatchResult { MessageDispatchResult {
dispatch_result: false, dispatch_result: false,
unspent_weight: 0, unspent_weight: Weight::from_ref_time(0),
dispatch_fee_paid_during_dispatch: false, dispatch_fee_paid_during_dispatch: false,
} }
} }
+1 -1
View File
@@ -8,7 +8,7 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies] [dependencies]
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive"] }
parity-util-mem = { version = "0.11.0", optional = true } parity-util-mem = { version = "0.12.0", optional = true }
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
serde = { version = "1.0", optional = true, features = ["derive"] } serde = { version = "1.0", optional = true, features = ["derive"] }
+9 -7
View File
@@ -20,11 +20,11 @@ use bp_messages::MessageNonce;
use bp_runtime::{Chain, EncodedOrDecodedCall}; use bp_runtime::{Chain, EncodedOrDecodedCall};
use codec::Compact; use codec::Compact;
use frame_support::{ use frame_support::{
dispatch::Dispatchable, dispatch::{DispatchClass, Dispatchable},
parameter_types, parameter_types,
weights::{ weights::{
constants::{BlockExecutionWeight, WEIGHT_PER_SECOND}, constants::{BlockExecutionWeight, WEIGHT_PER_SECOND},
DispatchClass, Weight, Weight,
}, },
Blake2_128Concat, RuntimeDebug, StorageHasher, Twox128, Blake2_128Concat, RuntimeDebug, StorageHasher, Twox128,
}; };
@@ -73,7 +73,8 @@ const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
/// All Polkadot-like chains allow 2 seconds of compute with a 6-second average block time. /// All Polkadot-like chains allow 2 seconds of compute with a 6-second average block time.
/// ///
/// This is a copy-paste from the Polkadot repo's `polkadot-runtime-common` crate. /// This is a copy-paste from the Polkadot repo's `polkadot-runtime-common` crate.
pub const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND; // TODO: https://github.com/paritytech/parity-bridges-common/issues/1543 - remove `set_proof_size`
pub const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND.set_proof_size(1_000).saturating_mul(2);
/// All Polkadot-like chains assume that an on-initialize consumes 1 percent of the weight on /// All Polkadot-like chains assume that an on-initialize consumes 1 percent of the weight on
/// average, hence a single extrinsic will not be allowed to consume more than /// average, hence a single extrinsic will not be allowed to consume more than
@@ -134,7 +135,8 @@ pub const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 8192;
/// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_delivery_proof` /// This value is a result of `pallet_bridge_messages::Pallet::receive_messages_delivery_proof`
/// weight formula computation for the case when single message is confirmed. The result then must /// weight formula computation for the case when single message is confirmed. The result then must
/// be rounded up to account possible future runtime upgrades. /// be rounded up to account possible future runtime upgrades.
pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight = 2_000_000_000; pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight =
Weight::from_ref_time(2_000_000_000);
/// Increase of delivery transaction weight on Polkadot-like chain with every additional message /// Increase of delivery transaction weight on Polkadot-like chain with every additional message
/// byte. /// byte.
@@ -142,7 +144,7 @@ pub const MAX_SINGLE_MESSAGE_DELIVERY_CONFIRMATION_TX_WEIGHT: Weight = 2_000_000
/// This value is a result of /// This value is a result of
/// `pallet_bridge_messages::WeightInfoExt::storage_proof_size_overhead(1)` call. The result then /// `pallet_bridge_messages::WeightInfoExt::storage_proof_size_overhead(1)` call. The result then
/// must be rounded up to account possible future runtime upgrades. /// must be rounded up to account possible future runtime upgrades.
pub const ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT: Weight = 25_000; pub const ADDITIONAL_MESSAGE_BYTE_DELIVERY_WEIGHT: Weight = Weight::from_ref_time(25_000);
/// Maximal number of bytes, included in the signed Polkadot-like transaction apart from the encoded /// Maximal number of bytes, included in the signed Polkadot-like transaction apart from the encoded
/// call itself. /// call itself.
@@ -156,7 +158,7 @@ pub const TX_EXTRA_BYTES: u32 = 256;
/// for the case when single message of `pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH` /// for the case when single message of `pallet_bridge_messages::EXPECTED_DEFAULT_MESSAGE_LENGTH`
/// bytes is delivered. The message must have dispatch weight set to zero. The result then must be /// bytes is delivered. The message must have dispatch weight set to zero. The result then must be
/// rounded up to account possible future runtime upgrades. /// rounded up to account possible future runtime upgrades.
pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = 1_500_000_000; pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = Weight::from_ref_time(1_500_000_000);
/// Weight of pay-dispatch-fee operation for inbound messages at Polkadot-like chain. /// Weight of pay-dispatch-fee operation for inbound messages at Polkadot-like chain.
/// ///
@@ -165,7 +167,7 @@ pub const DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT: Weight = 1_500_000_000;
/// chain. Don't put too much reserve there, because it is used to **decrease** /// chain. Don't put too much reserve there, because it is used to **decrease**
/// `DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT` cost. So putting large reserve would make delivery /// `DEFAULT_MESSAGE_DELIVERY_TX_WEIGHT` cost. So putting large reserve would make delivery
/// transactions cheaper. /// transactions cheaper.
pub const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = 600_000_000; pub const PAY_INBOUND_DISPATCH_FEE_WEIGHT: Weight = Weight::from_ref_time(600_000_000);
/// Re-export `time_units` to make usage easier. /// Re-export `time_units` to make usage easier.
pub use time_units::*; pub use time_units::*;
+3 -3
View File
@@ -403,7 +403,7 @@ pub trait OwnedBridgeModule<T: frame_system::Config> {
} }
/// Ensure that the origin is either root, or `PalletOwner`. /// Ensure that the origin is either root, or `PalletOwner`.
fn ensure_owner_or_root(origin: T::Origin) -> Result<(), BadOrigin> { fn ensure_owner_or_root(origin: T::RuntimeOrigin) -> Result<(), BadOrigin> {
match origin.into() { match origin.into() {
Ok(RawOrigin::Root) => Ok(()), Ok(RawOrigin::Root) => Ok(()),
Ok(RawOrigin::Signed(ref signer)) Ok(RawOrigin::Signed(ref signer))
@@ -422,7 +422,7 @@ pub trait OwnedBridgeModule<T: frame_system::Config> {
} }
/// Change the owner of the module. /// Change the owner of the module.
fn set_owner(origin: T::Origin, maybe_owner: Option<T::AccountId>) -> DispatchResult { fn set_owner(origin: T::RuntimeOrigin, maybe_owner: Option<T::AccountId>) -> DispatchResult {
Self::ensure_owner_or_root(origin)?; Self::ensure_owner_or_root(origin)?;
match maybe_owner { match maybe_owner {
Some(owner) => { Some(owner) => {
@@ -440,7 +440,7 @@ pub trait OwnedBridgeModule<T: frame_system::Config> {
/// Halt or resume all/some module operations. /// Halt or resume all/some module operations.
fn set_operating_mode( fn set_operating_mode(
origin: T::Origin, origin: T::RuntimeOrigin,
operating_mode: Self::OperatingMode, operating_mode: Self::OperatingMode,
) -> DispatchResult { ) -> DispatchResult {
Self::ensure_owner_or_root(origin)?; Self::ensure_owner_or_root(origin)?;
+9 -9
View File
@@ -228,16 +228,16 @@ macro_rules! generate_owned_bridge_module_tests {
PalletOwner::<TestRuntime>::put(1); PalletOwner::<TestRuntime>::put(1);
// The root should be able to change the owner. // The root should be able to change the owner.
assert_ok!(Pallet::<TestRuntime>::set_owner(Origin::root(), Some(2))); assert_ok!(Pallet::<TestRuntime>::set_owner(RuntimeOrigin::root(), Some(2)));
assert_eq!(PalletOwner::<TestRuntime>::get(), Some(2)); assert_eq!(PalletOwner::<TestRuntime>::get(), Some(2));
// The owner should be able to change the owner. // The owner should be able to change the owner.
assert_ok!(Pallet::<TestRuntime>::set_owner(Origin::signed(2), Some(3))); assert_ok!(Pallet::<TestRuntime>::set_owner(RuntimeOrigin::signed(2), Some(3)));
assert_eq!(PalletOwner::<TestRuntime>::get(), Some(3)); assert_eq!(PalletOwner::<TestRuntime>::get(), Some(3));
// Other users shouldn't be able to change the owner. // Other users shouldn't be able to change the owner.
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::set_owner(Origin::signed(1), Some(4)), Pallet::<TestRuntime>::set_owner(RuntimeOrigin::signed(1), Some(4)),
DispatchError::BadOrigin DispatchError::BadOrigin
); );
assert_eq!(PalletOwner::<TestRuntime>::get(), Some(3)); assert_eq!(PalletOwner::<TestRuntime>::get(), Some(3));
@@ -252,26 +252,26 @@ macro_rules! generate_owned_bridge_module_tests {
// The root should be able to halt the pallet. // The root should be able to halt the pallet.
assert_ok!(Pallet::<TestRuntime>::set_operating_mode( assert_ok!(Pallet::<TestRuntime>::set_operating_mode(
Origin::root(), RuntimeOrigin::root(),
$halted_operating_mode $halted_operating_mode
)); ));
assert_eq!(PalletOperatingMode::<TestRuntime>::get(), $halted_operating_mode); assert_eq!(PalletOperatingMode::<TestRuntime>::get(), $halted_operating_mode);
// The root should be able to resume the pallet. // The root should be able to resume the pallet.
assert_ok!(Pallet::<TestRuntime>::set_operating_mode( assert_ok!(Pallet::<TestRuntime>::set_operating_mode(
Origin::root(), RuntimeOrigin::root(),
$normal_operating_mode $normal_operating_mode
)); ));
assert_eq!(PalletOperatingMode::<TestRuntime>::get(), $normal_operating_mode); assert_eq!(PalletOperatingMode::<TestRuntime>::get(), $normal_operating_mode);
// The owner should be able to halt the pallet. // The owner should be able to halt the pallet.
assert_ok!(Pallet::<TestRuntime>::set_operating_mode( assert_ok!(Pallet::<TestRuntime>::set_operating_mode(
Origin::signed(1), RuntimeOrigin::signed(1),
$halted_operating_mode $halted_operating_mode
)); ));
assert_eq!(PalletOperatingMode::<TestRuntime>::get(), $halted_operating_mode); assert_eq!(PalletOperatingMode::<TestRuntime>::get(), $halted_operating_mode);
// The owner should be able to resume the pallet. // The owner should be able to resume the pallet.
assert_ok!(Pallet::<TestRuntime>::set_operating_mode( assert_ok!(Pallet::<TestRuntime>::set_operating_mode(
Origin::signed(1), RuntimeOrigin::signed(1),
$normal_operating_mode $normal_operating_mode
)); ));
assert_eq!(PalletOperatingMode::<TestRuntime>::get(), $normal_operating_mode); assert_eq!(PalletOperatingMode::<TestRuntime>::get(), $normal_operating_mode);
@@ -279,7 +279,7 @@ macro_rules! generate_owned_bridge_module_tests {
// Other users shouldn't be able to halt the pallet. // Other users shouldn't be able to halt the pallet.
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::set_operating_mode( Pallet::<TestRuntime>::set_operating_mode(
Origin::signed(2), RuntimeOrigin::signed(2),
$halted_operating_mode $halted_operating_mode
), ),
DispatchError::BadOrigin DispatchError::BadOrigin
@@ -289,7 +289,7 @@ macro_rules! generate_owned_bridge_module_tests {
PalletOperatingMode::<TestRuntime>::put($halted_operating_mode); PalletOperatingMode::<TestRuntime>::put($halted_operating_mode);
assert_noop!( assert_noop!(
Pallet::<TestRuntime>::set_operating_mode( Pallet::<TestRuntime>::set_operating_mode(
Origin::signed(2), RuntimeOrigin::signed(2),
$normal_operating_mode $normal_operating_mode
), ),
DispatchError::BadOrigin DispatchError::BadOrigin
@@ -50,7 +50,7 @@ impl CliEncodeMessage for Millau {
), ),
}; };
Ok(millau_runtime::Call::XcmPallet(millau_runtime::XcmCall::send { Ok(millau_runtime::RuntimeCall::XcmPallet(millau_runtime::XcmCall::send {
dest: Box::new(dest.into()), dest: Box::new(dest.into()),
message: Box::new(message), message: Box::new(message),
}) })
@@ -64,7 +64,7 @@ impl CliEncodeMessage for Millau {
bridge_instance_index: u8, bridge_instance_index: u8,
) -> anyhow::Result<EncodedOrDecodedCall<Self::Call>> { ) -> anyhow::Result<EncodedOrDecodedCall<Self::Call>> {
Ok(match bridge_instance_index { Ok(match bridge_instance_index {
bridge::MILLAU_TO_RIALTO_INDEX => millau_runtime::Call::BridgeRialtoMessages( bridge::MILLAU_TO_RIALTO_INDEX => millau_runtime::RuntimeCall::BridgeRialtoMessages(
millau_runtime::MessagesCall::send_message { millau_runtime::MessagesCall::send_message {
lane_id: lane, lane_id: lane,
payload, payload,
@@ -73,7 +73,7 @@ impl CliEncodeMessage for Millau {
) )
.into(), .into(),
bridge::MILLAU_TO_RIALTO_PARACHAIN_INDEX => bridge::MILLAU_TO_RIALTO_PARACHAIN_INDEX =>
millau_runtime::Call::BridgeRialtoParachainMessages( millau_runtime::RuntimeCall::BridgeRialtoParachainMessages(
millau_runtime::MessagesCall::send_message { millau_runtime::MessagesCall::send_message {
lane_id: lane, lane_id: lane,
payload, payload,
@@ -69,8 +69,9 @@ mod tests {
} }
#[test] #[test]
fn rialto_tx_extra_bytes_constant_is_correct() { fn rialto_tx_extra_bytes_constant_is_correct() {
let rialto_call = let rialto_call = rialto_runtime::RuntimeCall::System(rialto_runtime::SystemCall::remark {
rialto_runtime::Call::System(rialto_runtime::SystemCall::remark { remark: vec![] }); remark: vec![],
});
let rialto_tx = Rialto::sign_transaction( let rialto_tx = Rialto::sign_transaction(
SignParam { SignParam {
spec_version: 1, spec_version: 1,
@@ -92,8 +93,9 @@ mod tests {
#[test] #[test]
fn millau_tx_extra_bytes_constant_is_correct() { fn millau_tx_extra_bytes_constant_is_correct() {
let millau_call = let millau_call = millau_runtime::RuntimeCall::System(millau_runtime::SystemCall::remark {
millau_runtime::Call::System(millau_runtime::SystemCall::remark { remark: vec![] }); remark: vec![],
});
let millau_tx = Millau::sign_transaction( let millau_tx = Millau::sign_transaction(
SignParam { SignParam {
spec_version: 0, spec_version: 0,
@@ -42,7 +42,7 @@ impl CliEncodeMessage for Rialto {
), ),
}; };
Ok(rialto_runtime::Call::XcmPallet(rialto_runtime::XcmCall::send { Ok(rialto_runtime::RuntimeCall::XcmPallet(rialto_runtime::XcmCall::send {
dest: Box::new(dest.into()), dest: Box::new(dest.into()),
message: Box::new(message), message: Box::new(message),
}) })
@@ -56,7 +56,7 @@ impl CliEncodeMessage for Rialto {
bridge_instance_index: u8, bridge_instance_index: u8,
) -> anyhow::Result<EncodedOrDecodedCall<Self::Call>> { ) -> anyhow::Result<EncodedOrDecodedCall<Self::Call>> {
Ok(match bridge_instance_index { Ok(match bridge_instance_index {
bridge::RIALTO_TO_MILLAU_INDEX => rialto_runtime::Call::BridgeMillauMessages( bridge::RIALTO_TO_MILLAU_INDEX => rialto_runtime::RuntimeCall::BridgeMillauMessages(
rialto_runtime::MessagesCall::send_message { rialto_runtime::MessagesCall::send_message {
lane_id: lane, lane_id: lane,
payload, payload,
@@ -42,10 +42,12 @@ impl CliEncodeMessage for RialtoParachain {
), ),
}; };
Ok(rialto_parachain_runtime::Call::PolkadotXcm(rialto_parachain_runtime::XcmCall::send { Ok(rialto_parachain_runtime::RuntimeCall::PolkadotXcm(
dest: Box::new(dest.into()), rialto_parachain_runtime::XcmCall::send {
message: Box::new(message), dest: Box::new(dest.into()),
}) message: Box::new(message),
},
)
.into()) .into())
} }
@@ -57,7 +59,7 @@ impl CliEncodeMessage for RialtoParachain {
) -> anyhow::Result<EncodedOrDecodedCall<Self::Call>> { ) -> anyhow::Result<EncodedOrDecodedCall<Self::Call>> {
Ok(match bridge_instance_index { Ok(match bridge_instance_index {
bridge::RIALTO_PARACHAIN_TO_MILLAU_INDEX => bridge::RIALTO_PARACHAIN_TO_MILLAU_INDEX =>
rialto_parachain_runtime::Call::BridgeMillauMessages( rialto_parachain_runtime::RuntimeCall::BridgeMillauMessages(
rialto_parachain_runtime::MessagesCall::send_message { rialto_parachain_runtime::MessagesCall::send_message {
lane_id: lane, lane_id: lane,
payload, payload,
+2 -2
View File
@@ -85,7 +85,7 @@ impl Chain for Millau {
const STORAGE_PROOF_OVERHEAD: u32 = bp_millau::EXTRA_STORAGE_PROOF_SIZE; const STORAGE_PROOF_OVERHEAD: u32 = bp_millau::EXTRA_STORAGE_PROOF_SIZE;
type SignedBlock = millau_runtime::SignedBlock; type SignedBlock = millau_runtime::SignedBlock;
type Call = millau_runtime::Call; type Call = millau_runtime::RuntimeCall;
} }
impl ChainWithBalances for Millau { impl ChainWithBalances for Millau {
@@ -186,7 +186,7 @@ mod tests {
#[test] #[test]
fn parse_transaction_works() { fn parse_transaction_works() {
let unsigned = UnsignedTransaction { let unsigned = UnsignedTransaction {
call: millau_runtime::Call::System(millau_runtime::SystemCall::remark { call: millau_runtime::RuntimeCall::System(millau_runtime::SystemCall::remark {
remark: b"Hello world!".to_vec(), remark: b"Hello world!".to_vec(),
}) })
.into(), .into(),
@@ -65,7 +65,7 @@ impl Chain for RialtoParachain {
const STORAGE_PROOF_OVERHEAD: u32 = bp_rialto_parachain::EXTRA_STORAGE_PROOF_SIZE; const STORAGE_PROOF_OVERHEAD: u32 = bp_rialto_parachain::EXTRA_STORAGE_PROOF_SIZE;
type SignedBlock = rialto_parachain_runtime::SignedBlock; type SignedBlock = rialto_parachain_runtime::SignedBlock;
type Call = rialto_parachain_runtime::Call; type Call = rialto_parachain_runtime::RuntimeCall;
} }
impl ChainWithBalances for RialtoParachain { impl ChainWithBalances for RialtoParachain {
+2 -2
View File
@@ -65,7 +65,7 @@ impl Chain for Rialto {
const STORAGE_PROOF_OVERHEAD: u32 = bp_rialto::EXTRA_STORAGE_PROOF_SIZE; const STORAGE_PROOF_OVERHEAD: u32 = bp_rialto::EXTRA_STORAGE_PROOF_SIZE;
type SignedBlock = rialto_runtime::SignedBlock; type SignedBlock = rialto_runtime::SignedBlock;
type Call = rialto_runtime::Call; type Call = rialto_runtime::RuntimeCall;
} }
impl RelayChain for Rialto { impl RelayChain for Rialto {
@@ -189,7 +189,7 @@ mod tests {
#[test] #[test]
fn parse_transaction_works() { fn parse_transaction_works() {
let unsigned = UnsignedTransaction { let unsigned = UnsignedTransaction {
call: rialto_runtime::Call::System(rialto_runtime::SystemCall::remark { call: rialto_runtime::RuntimeCall::System(rialto_runtime::SystemCall::remark {
remark: b"Hello world!".to_vec(), remark: b"Hello world!".to_vec(),
}) })
.into(), .into(),
@@ -168,7 +168,7 @@ async fn watch_transaction_status<
loop { loop {
match subscription.next().await { match subscription.next().await {
Some(TransactionStatusOf::<C>::Finalized(block_hash)) => { Some(TransactionStatusOf::<C>::Finalized((block_hash, _))) => {
// the only "successful" outcome of this method is when the block with transaction // the only "successful" outcome of this method is when the block with transaction
// has been finalized // has been finalized
log::trace!( log::trace!(
@@ -32,7 +32,7 @@ use bridge_runtime_common::messages::{
source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof,
}; };
use codec::Encode; use codec::Encode;
use frame_support::weights::{GetDispatchInfo, Weight}; use frame_support::{dispatch::GetDispatchInfo, weights::Weight};
use messages_relay::{message_lane::MessageLane, relay_strategy::RelayStrategy}; use messages_relay::{message_lane::MessageLane, relay_strategy::RelayStrategy};
use pallet_bridge_messages::{Call as BridgeMessagesCall, Config as BridgeMessagesConfig}; use pallet_bridge_messages::{Call as BridgeMessagesCall, Config as BridgeMessagesConfig};
use relay_substrate_client::{ use relay_substrate_client::{
@@ -461,17 +461,23 @@ pub fn select_delivery_transaction_limits<W: pallet_bridge_messages::WeightInfoE
let delivery_tx_base_weight = W::receive_messages_proof_overhead() + let delivery_tx_base_weight = W::receive_messages_proof_overhead() +
W::receive_messages_proof_outbound_lane_state_overhead(); W::receive_messages_proof_outbound_lane_state_overhead();
let delivery_tx_weight_rest = weight_for_delivery_tx - delivery_tx_base_weight; let delivery_tx_weight_rest = weight_for_delivery_tx - delivery_tx_base_weight;
let max_number_of_messages = std::cmp::min(
delivery_tx_weight_rest / W::receive_messages_proof_messages_overhead(1), let max_number_of_messages = if delivery_tx_weight_rest.ref_time() /
max_unconfirmed_messages_at_inbound_lane, W::receive_messages_proof_messages_overhead(1).ref_time() <
); max_unconfirmed_messages_at_inbound_lane
{
delivery_tx_weight_rest.ref_time() /
W::receive_messages_proof_messages_overhead(1).ref_time()
} else {
max_unconfirmed_messages_at_inbound_lane
};
assert!( assert!(
max_number_of_messages > 0, max_number_of_messages > 0,
"Relay should fit at least one message in every delivery transaction", "Relay should fit at least one message in every delivery transaction",
); );
assert!( assert!(
weight_for_messages_dispatch >= max_extrinsic_weight / 2, weight_for_messages_dispatch.ref_time() >= max_extrinsic_weight.ref_time() / 2,
"Relay shall be able to deliver messages with dispatch weight = max_extrinsic_weight / 2", "Relay shall be able to deliver messages with dispatch weight = max_extrinsic_weight / 2",
); );
@@ -500,7 +506,9 @@ mod tests {
// i.e. weight reserved for messages dispatch allows dispatch of non-trivial messages. // i.e. weight reserved for messages dispatch allows dispatch of non-trivial messages.
// //
// Any significant change in this values should attract additional attention. // Any significant change in this values should attract additional attention.
(1024, 216_609_134_667), //
// TODO: https://github.com/paritytech/parity-bridges-common/issues/1543 - remove `set_proof_size`
(1024, Weight::from_ref_time(216_609_134_667).set_proof_size(217)),
); );
} }
} }
@@ -653,7 +653,7 @@ mod tests {
.into_iter() .into_iter()
.map(|nonce| bp_messages::OutboundMessageDetails { .map(|nonce| bp_messages::OutboundMessageDetails {
nonce, nonce,
dispatch_weight: 0, dispatch_weight: Weight::from_ref_time(0),
size: 0, size: 0,
delivery_and_dispatch_fee: 0, delivery_and_dispatch_fee: 0,
dispatch_fee_payment: DispatchFeePayment::AtSourceChain, dispatch_fee_payment: DispatchFeePayment::AtSourceChain,
@@ -730,7 +730,7 @@ mod tests {
for (idx, _) in payload_sizes.iter().enumerate() { for (idx, _) in payload_sizes.iter().enumerate() {
out_msgs_details.push(OutboundMessageDetails::<BalanceOf<Rialto>> { out_msgs_details.push(OutboundMessageDetails::<BalanceOf<Rialto>> {
nonce: idx as MessageNonce, nonce: idx as MessageNonce,
dispatch_weight: 0, dispatch_weight: Weight::from_ref_time(0),
size: 0, size: 0,
delivery_and_dispatch_fee: 0, delivery_and_dispatch_fee: 0,
dispatch_fee_payment: DispatchFeePayment::AtTargetChain, dispatch_fee_payment: DispatchFeePayment::AtTargetChain,
@@ -347,7 +347,7 @@ where
// chain. This requires more knowledge of the Target chain, but seems there's no better way // chain. This requires more knowledge of the Target chain, but seems there's no better way
// to solve this now. // to solve this now.
let expected_refund_in_target_tokens = if total_prepaid_nonces != 0 { let expected_refund_in_target_tokens = if total_prepaid_nonces != 0 {
const WEIGHT_DIFFERENCE: Weight = 100; const WEIGHT_DIFFERENCE: Weight = Weight::from_ref_time(100);
let (spec_version, transaction_version) = let (spec_version, transaction_version) =
self.target_client.simple_runtime_version().await?; self.target_client.simple_runtime_version().await?;
@@ -533,7 +533,7 @@ mod tests {
#[test] #[test]
fn prepare_dummy_messages_proof_works() { fn prepare_dummy_messages_proof_works() {
const DISPATCH_WEIGHT: Weight = 1_000_000; const DISPATCH_WEIGHT: Weight = Weight::from_ref_time(1_000_000);
const SIZE: u32 = 1_000; const SIZE: u32 = 1_000;
let dummy_proof = prepare_dummy_messages_proof::<Rococo>(1..=10, DISPATCH_WEIGHT, SIZE); let dummy_proof = prepare_dummy_messages_proof::<Rococo>(1..=10, DISPATCH_WEIGHT, SIZE);
assert_eq!(dummy_proof.0, DISPATCH_WEIGHT); assert_eq!(dummy_proof.0, DISPATCH_WEIGHT);
@@ -563,21 +563,24 @@ mod tests {
#[test] #[test]
fn compute_fee_multiplier_returns_sane_results() { fn compute_fee_multiplier_returns_sane_results() {
let multiplier: FixedU128 = bp_rialto::WeightToFee::weight_to_fee(&1).into(); let multiplier: FixedU128 =
bp_rialto::WeightToFee::weight_to_fee(&Weight::from_ref_time(1)).into();
let smaller_weight = 1_000_000; let smaller_weight = 1_000_000;
let smaller_adjusted_weight_fee = let smaller_adjusted_weight_fee = multiplier.saturating_mul_int(
multiplier.saturating_mul_int(WeightToFeeOf::<Rialto>::weight_to_fee(&smaller_weight)); WeightToFeeOf::<Rialto>::weight_to_fee(&Weight::from_ref_time(smaller_weight)),
);
let larger_weight = smaller_weight + 200_000; let larger_weight = smaller_weight + 200_000;
let larger_adjusted_weight_fee = let larger_adjusted_weight_fee = multiplier.saturating_mul_int(
multiplier.saturating_mul_int(WeightToFeeOf::<Rialto>::weight_to_fee(&larger_weight)); WeightToFeeOf::<Rialto>::weight_to_fee(&Weight::from_ref_time(larger_weight)),
);
assert_eq!( assert_eq!(
compute_fee_multiplier::<Rialto>( compute_fee_multiplier::<Rialto>(
smaller_adjusted_weight_fee, smaller_adjusted_weight_fee,
smaller_weight, Weight::from_ref_time(smaller_weight),
larger_adjusted_weight_fee, larger_adjusted_weight_fee,
larger_weight, Weight::from_ref_time(larger_weight),
), ),
multiplier, multiplier,
); );
@@ -589,7 +592,9 @@ mod tests {
compute_prepaid_messages_refund::<Rialto>( compute_prepaid_messages_refund::<Rialto>(
10, 10,
FixedU128::saturating_from_rational(110, 100), FixedU128::saturating_from_rational(110, 100),
) > (10 * Rialto::PAY_INBOUND_DISPATCH_FEE_WEIGHT_AT_CHAIN).into() ) > Rialto::PAY_INBOUND_DISPATCH_FEE_WEIGHT_AT_CHAIN
.saturating_mul(10u64)
.ref_time() as _
); );
} }
} }
@@ -678,7 +678,7 @@ pub(crate) mod tests {
( (
nonce, nonce,
MessageDetails { MessageDetails {
dispatch_weight: 1, dispatch_weight: Weight::from_ref_time(1),
size: 1, size: 1,
reward: 1, reward: 1,
dispatch_fee_payment: DispatchFeePayment::AtSourceChain, dispatch_fee_payment: DispatchFeePayment::AtSourceChain,
@@ -879,9 +879,11 @@ pub(crate) mod tests {
total_dispatch_weight: Weight, total_dispatch_weight: Weight,
total_size: u32, total_size: u32,
) -> Result<TestSourceChainBalance, TestError> { ) -> Result<TestSourceChainBalance, TestError> {
Ok(BASE_MESSAGE_DELIVERY_TRANSACTION_COST * (nonces.end() - nonces.start() + 1) + Ok((Weight::from_ref_time(BASE_MESSAGE_DELIVERY_TRANSACTION_COST) *
(nonces.end() - nonces.start() + 1) +
total_dispatch_weight + total_dispatch_weight +
total_size as TestSourceChainBalance) Weight::from_ref_time(total_size as u64))
.ref_time())
} }
} }
@@ -916,7 +918,7 @@ pub(crate) mod tests {
max_unrewarded_relayer_entries_at_target: 4, max_unrewarded_relayer_entries_at_target: 4,
max_unconfirmed_nonces_at_target: 4, max_unconfirmed_nonces_at_target: 4,
max_messages_in_single_batch: 4, max_messages_in_single_batch: 4,
max_messages_weight_in_single_batch: 4, max_messages_weight_in_single_batch: Weight::from_ref_time(4),
max_messages_size_in_single_batch: 4, max_messages_size_in_single_batch: 4,
relay_strategy: AltruisticStrategy, relay_strategy: AltruisticStrategy,
}, },
@@ -295,7 +295,7 @@ impl<P: MessageLane, Strategy: RelayStrategy, SC, TC> MessageDeliveryStrategy<P,
.source_queue() .source_queue()
.iter() .iter()
.flat_map(|(_, range)| range.values().map(|details| details.dispatch_weight)) .flat_map(|(_, range)| range.values().map(|details| details.dispatch_weight))
.fold(0, |total, weight| total.saturating_add(weight)) .fold(Weight::from_ref_time(0), |total, weight| total.saturating_add(weight))
} }
} }
@@ -578,11 +578,11 @@ mod tests {
use super::*; use super::*;
const DEFAULT_DISPATCH_WEIGHT: Weight = 1; const DEFAULT_DISPATCH_WEIGHT: Weight = Weight::from_ref_time(1);
const DEFAULT_SIZE: u32 = 1; const DEFAULT_SIZE: u32 = 1;
const DEFAULT_REWARD: TestSourceChainBalance = CONFIRMATION_TRANSACTION_COST + const DEFAULT_REWARD: TestSourceChainBalance = CONFIRMATION_TRANSACTION_COST +
BASE_MESSAGE_DELIVERY_TRANSACTION_COST + BASE_MESSAGE_DELIVERY_TRANSACTION_COST +
DEFAULT_DISPATCH_WEIGHT + DEFAULT_DISPATCH_WEIGHT.ref_time() +
(DEFAULT_SIZE as TestSourceChainBalance); (DEFAULT_SIZE as TestSourceChainBalance);
type TestRaceState = RaceState<TestSourceHeaderId, TestTargetHeaderId, TestMessagesProof>; type TestRaceState = RaceState<TestSourceHeaderId, TestTargetHeaderId, TestMessagesProof>;
@@ -629,7 +629,7 @@ mod tests {
max_unrewarded_relayer_entries_at_target: 4, max_unrewarded_relayer_entries_at_target: 4,
max_unconfirmed_nonces_at_target: 4, max_unconfirmed_nonces_at_target: 4,
max_messages_in_single_batch: 4, max_messages_in_single_batch: 4,
max_messages_weight_in_single_batch: 4, max_messages_weight_in_single_batch: Weight::from_ref_time(4),
max_messages_size_in_single_batch: 4, max_messages_size_in_single_batch: 4,
latest_confirmed_nonces_at_source: vec![(header_id(1), 19)].into_iter().collect(), latest_confirmed_nonces_at_source: vec![(header_id(1), 19)].into_iter().collect(),
lane_source_client: TestSourceClient::default(), lane_source_client: TestSourceClient::default(),
@@ -667,10 +667,10 @@ mod tests {
(race_state, race_strategy) (race_state, race_strategy)
} }
fn proof_parameters(state_required: bool, weight: Weight) -> MessageProofParameters { fn proof_parameters(state_required: bool, weight: u32) -> MessageProofParameters {
MessageProofParameters { MessageProofParameters {
outbound_state_proof_required: state_required, outbound_state_proof_required: state_required,
dispatch_weight: weight, dispatch_weight: Weight::from_ref_time(weight as u64),
} }
} }
@@ -684,7 +684,7 @@ mod tests {
( (
idx, idx,
MessageDetails { MessageDetails {
dispatch_weight: idx, dispatch_weight: Weight::from_ref_time(idx),
size: idx as _, size: idx as _,
reward: idx as _, reward: idx as _,
dispatch_fee_payment: DispatchFeePayment::AtSourceChain, dispatch_fee_payment: DispatchFeePayment::AtSourceChain,
@@ -813,7 +813,7 @@ mod tests {
let (state, mut strategy) = prepare_strategy(); let (state, mut strategy) = prepare_strategy();
// not all queued messages may fit in the batch, because batch has max weight // not all queued messages may fit in the batch, because batch has max weight
strategy.max_messages_weight_in_single_batch = 3; strategy.max_messages_weight_in_single_batch = Weight::from_ref_time(3);
assert_eq!( assert_eq!(
strategy.select_nonces_to_deliver(state).await, strategy.select_nonces_to_deliver(state).await,
Some(((20..=22), proof_parameters(false, 3))) Some(((20..=22), proof_parameters(false, 3)))
@@ -827,7 +827,8 @@ mod tests {
// first message doesn't fit in the batch, because it has weight (10) that overflows max // first message doesn't fit in the batch, because it has weight (10) that overflows max
// weight (4) // weight (4)
strategy.strategy.source_queue_mut()[0].1.get_mut(&20).unwrap().dispatch_weight = 10; strategy.strategy.source_queue_mut()[0].1.get_mut(&20).unwrap().dispatch_weight =
Weight::from_ref_time(10);
assert_eq!( assert_eq!(
strategy.select_nonces_to_deliver(state).await, strategy.select_nonces_to_deliver(state).await,
Some(((20..=20), proof_parameters(false, 10))) Some(((20..=20), proof_parameters(false, 10)))
@@ -1023,7 +1024,7 @@ mod tests {
let nonces = source_nonces( let nonces = source_nonces(
24..=24, 24..=24,
19, 19,
DEFAULT_REWARD - DEFAULT_DISPATCH_WEIGHT, DEFAULT_REWARD - DEFAULT_DISPATCH_WEIGHT.ref_time(),
dispatch_fee_payment, dispatch_fee_payment,
); );
strategy.strategy.source_nonces_updated(header_id(2), nonces); strategy.strategy.source_nonces_updated(header_id(2), nonces);
@@ -1031,7 +1032,7 @@ mod tests {
strategy.max_unrewarded_relayer_entries_at_target = 100; strategy.max_unrewarded_relayer_entries_at_target = 100;
strategy.max_unconfirmed_nonces_at_target = 100; strategy.max_unconfirmed_nonces_at_target = 100;
strategy.max_messages_in_single_batch = 100; strategy.max_messages_in_single_batch = 100;
strategy.max_messages_weight_in_single_batch = 100; strategy.max_messages_weight_in_single_batch = Weight::from_ref_time(100);
strategy.max_messages_size_in_single_batch = 100; strategy.max_messages_size_in_single_batch = 100;
strategy.relay_strategy = MixStrategy::new(RelayerMode::Rational); strategy.relay_strategy = MixStrategy::new(RelayerMode::Rational);
@@ -1070,7 +1071,7 @@ mod tests {
strategy.max_unrewarded_relayer_entries_at_target = 100; strategy.max_unrewarded_relayer_entries_at_target = 100;
strategy.max_unconfirmed_nonces_at_target = 100; strategy.max_unconfirmed_nonces_at_target = 100;
strategy.max_messages_in_single_batch = 5; strategy.max_messages_in_single_batch = 5;
strategy.max_messages_weight_in_single_batch = 100; strategy.max_messages_weight_in_single_batch = Weight::from_ref_time(100);
strategy.max_messages_size_in_single_batch = 100; strategy.max_messages_size_in_single_batch = 100;
state.best_finalized_source_header_id_at_best_target = Some(header_id(2)); state.best_finalized_source_header_id_at_best_target = Some(header_id(2));
@@ -55,7 +55,7 @@ impl<Strategy: RelayStrategy> EnforcementStrategy<Strategy> {
let mut hard_selected_count = 0; let mut hard_selected_count = 0;
let mut soft_selected_count = 0; let mut soft_selected_count = 0;
let mut selected_weight: Weight = 0; let mut selected_weight = Weight::from_ref_time(0);
let mut selected_count: MessageNonce = 0; let mut selected_count: MessageNonce = 0;
let hard_selected_begin_nonce = let hard_selected_begin_nonce =
@@ -77,12 +77,12 @@ impl<Strategy: RelayStrategy> EnforcementStrategy<Strategy> {
hard_selected_begin_nonce, hard_selected_begin_nonce,
selected_prepaid_nonces: 0, selected_prepaid_nonces: 0,
selected_unpaid_weight: 0, selected_unpaid_weight: Weight::from_ref_time(0),
index: 0, index: 0,
nonce: 0, nonce: 0,
details: MessageDetails { details: MessageDetails {
dispatch_weight: 0, dispatch_weight: Weight::from_ref_time(0),
size: 0, size: 0,
reward: P::SourceChainBalance::zero(), reward: P::SourceChainBalance::zero(),
dispatch_fee_payment: DispatchFeePayment::AtSourceChain, dispatch_fee_payment: DispatchFeePayment::AtSourceChain,
@@ -105,9 +105,10 @@ impl<Strategy: RelayStrategy> EnforcementStrategy<Strategy> {
// transaction will be rejected by the target runtime, but at least we have tried. // transaction will be rejected by the target runtime, but at least we have tried.
// limit messages in the batch by weight // limit messages in the batch by weight
let new_selected_weight = match selected_weight.checked_add(details.dispatch_weight) { let new_selected_weight = match selected_weight.checked_add(&details.dispatch_weight) {
Some(new_selected_weight) Some(new_selected_weight)
if new_selected_weight <= reference.max_messages_weight_in_single_batch => if new_selected_weight.ref_time() <=
reference.max_messages_weight_in_single_batch.ref_time() =>
new_selected_weight, new_selected_weight,
new_selected_weight if selected_count == 0 => { new_selected_weight if selected_count == 0 => {
log::warn!( log::warn!(