diff --git a/bin/runtime-common/src/messages.rs b/bin/runtime-common/src/messages.rs index bf85b2e4f..d53887192 100644 --- a/bin/runtime-common/src/messages.rs +++ b/bin/runtime-common/src/messages.rs @@ -243,9 +243,7 @@ pub mod source { impl Size for FromBridgedChainMessagesDeliveryProof { fn size_hint(&self) -> u32 { u32::try_from( - self.storage_proof - .iter() - .fold(0usize, |sum, node| sum.saturating_add(node.len())), + self.storage_proof.iter().fold(0usize, |sum, node| sum.saturating_add(node.len())), ) .unwrap_or(u32::MAX) } @@ -310,7 +308,7 @@ pub mod source { ) -> Result<(), Self::Error> { // reject message if lane is blocked if !ThisChain::::is_message_accepted(submitter, lane) { - return Err(MESSAGE_REJECTED_BY_OUTBOUND_LANE) + return Err(MESSAGE_REJECTED_BY_OUTBOUND_LANE); } // reject message if there are too many pending messages at this lane @@ -319,7 +317,7 @@ pub mod source { .latest_generated_nonce .saturating_sub(lane_outbound_data.latest_received_nonce); if pending_messages > max_pending_messages { - return Err(TOO_MANY_PENDING_MESSAGES) + return Err(TOO_MANY_PENDING_MESSAGES); } // Do the dispatch-specific check. We assume that the target chain uses @@ -348,7 +346,7 @@ pub mod source { // compare with actual fee paid if *delivery_and_dispatch_fee < minimal_fee_in_this_tokens { - return Err(TOO_LOW_FEE) + return Err(TOO_LOW_FEE); } Ok(()) @@ -370,7 +368,7 @@ pub mod source { ) -> Result<(), &'static str> { let weight_limits = BridgedChain::::message_weight_limits(&payload.call); if !weight_limits.contains(&payload.weight.into()) { - return Err("Incorrect message weight declared") + return Err("Incorrect message weight declared"); } // The maximal size of extrinsic at Substrate-based chain depends on the @@ -384,7 +382,7 @@ pub mod source { // transaction also contains signatures and signed extensions. Because of this, we reserve // 1/3 of the the maximal extrinsic weight for this data. if payload.call.len() > maximal_message_size::() as usize { - return Err("The message is too large to be sent over the lane") + return Err("The message is too large to be sent over the lane"); } Ok(()) @@ -515,9 +513,7 @@ pub mod target { impl Size for FromBridgedChainMessagesProof { fn size_hint(&self) -> u32 { u32::try_from( - self.storage_proof - .iter() - .fold(0usize, |sum, node| sum.saturating_add(node.len())), + self.storage_proof.iter().fold(0usize, |sum, node| sum.saturating_add(node.len())), ) .unwrap_or(u32::MAX) } @@ -752,7 +748,7 @@ pub mod target { // (this bounds maximal capacity of messages vec below) let messages_in_the_proof = nonces_difference.saturating_add(1); if messages_in_the_proof != MessageNonce::from(messages_count) { - return Err(MessageProofError::MessagesCountMismatch) + return Err(MessageProofError::MessagesCountMismatch); } messages_in_the_proof @@ -791,7 +787,7 @@ pub mod target { // Now we may actually check if the proof is empty or not. if proved_lane_messages.lane_state.is_none() && proved_lane_messages.messages.is_empty() { - return Err(MessageProofError::Empty) + return Err(MessageProofError::Empty); } // We only support single lane messages in this schema @@ -823,13 +819,13 @@ mod tests { struct OnThisChainBridge; impl MessageBridge for OnThisChainBridge { - const RELAYER_FEE_PERCENT: u32 = 10; - const THIS_CHAIN_ID: ChainId = *b"this"; + type BridgedChain = BridgedChain; + type ThisChain = ThisChain; + const BRIDGED_CHAIN_ID: ChainId = *b"brdg"; const BRIDGED_MESSAGES_PALLET_NAME: &'static str = ""; - - type ThisChain = ThisChain; - type BridgedChain = BridgedChain; + const RELAYER_FEE_PERCENT: u32 = 10; + const THIS_CHAIN_ID: ChainId = *b"this"; fn bridged_balance_to_this_balance( bridged_balance: BridgedChainBalance, @@ -848,13 +844,13 @@ mod tests { struct OnBridgedChainBridge; impl MessageBridge for OnBridgedChainBridge { - const RELAYER_FEE_PERCENT: u32 = 20; - const THIS_CHAIN_ID: ChainId = *b"brdg"; + type BridgedChain = ThisChain; + type ThisChain = BridgedChain; + const BRIDGED_CHAIN_ID: ChainId = *b"this"; const BRIDGED_MESSAGES_PALLET_NAME: &'static str = ""; - - type ThisChain = BridgedChain; - type BridgedChain = ThisChain; + const RELAYER_FEE_PERCENT: u32 = 20; + const THIS_CHAIN_ID: ChainId = *b"brdg"; fn bridged_balance_to_this_balance( _this_balance: ThisChainBalance, @@ -978,17 +974,17 @@ mod tests { struct ThisChain; impl ChainWithMessages for ThisChain { - type Hash = (); type AccountId = ThisChainAccountId; - type Signer = ThisChainSigner; + type Balance = ThisChainBalance; + type Hash = (); type Signature = ThisChainSignature; + type Signer = ThisChainSigner; type Weight = frame_support::weights::Weight; - type Balance = ThisChainBalance; } impl ThisChainWithMessages for ThisChain { - type Origin = ThisChainOrigin; type Call = ThisChainCall; + type Origin = ThisChainOrigin; fn is_message_accepted(_send_origin: &Self::Origin, lane: &LaneId) -> bool { lane == TEST_LANE_ID @@ -1039,17 +1035,17 @@ mod tests { struct BridgedChain; impl ChainWithMessages for BridgedChain { - type Hash = (); type AccountId = BridgedChainAccountId; - type Signer = BridgedChainSigner; + type Balance = BridgedChainBalance; + type Hash = (); type Signature = BridgedChainSignature; + type Signer = BridgedChainSigner; type Weight = frame_support::weights::Weight; - type Balance = BridgedChainBalance; } impl ThisChainWithMessages for BridgedChain { - type Origin = BridgedChainOrigin; type Call = BridgedChainCall; + type Origin = BridgedChainOrigin; fn is_message_accepted(_send_origin: &Self::Origin, _lane: &LaneId) -> bool { unreachable!() diff --git a/bin/runtime-common/src/messages_benchmarking.rs b/bin/runtime-common/src/messages_benchmarking.rs index 7c9f50e8e..8e3e6e3fe 100644 --- a/bin/runtime-common/src/messages_benchmarking.rs +++ b/bin/runtime-common/src/messages_benchmarking.rs @@ -363,7 +363,7 @@ fn grow_trie(mut root: H::Out, mdb: &mut MemoryDB, trie_size: Proo .expect("record_all_keys should not fail in benchmarks"); let size: usize = proof_recorder.drain().into_iter().map(|n| n.data.len()).sum(); if size > minimal_trie_size as _ { - return root + return root; } let mut trie = TrieDBMutV1::::from_existing(mdb, &mut root) diff --git a/modules/dispatch/src/lib.rs b/modules/dispatch/src/lib.rs index 1e030b733..56b3c7a60 100644 --- a/modules/dispatch/src/lib.rs +++ b/modules/dispatch/src/lib.rs @@ -172,7 +172,7 @@ impl, I: 'static> MessageDispatch dispatch_result: false, unspent_weight: 0, dispatch_fee_paid_during_dispatch: false, - } + }; }, }; @@ -198,7 +198,7 @@ impl, I: 'static> MessageDispatch expected_version, message.spec_version, )); - return dispatch_result + return dispatch_result; } // now that we have spec version checked, let's decode the call @@ -212,7 +212,7 @@ impl, I: 'static> MessageDispatch id, ); Self::deposit_event(Event::MessageCallDecodeFailed(source_chain, id)); - return dispatch_result + return dispatch_result; }, }; @@ -245,7 +245,7 @@ impl, I: 'static> MessageDispatch target_signature, ); Self::deposit_event(Event::MessageSignatureMismatch(source_chain, id)); - return dispatch_result + return dispatch_result; } log::trace!(target: "runtime::bridge-dispatch", "Target Account: {:?}", &target_account); @@ -270,7 +270,7 @@ impl, I: 'static> MessageDispatch call, ); Self::deposit_event(Event::MessageCallRejected(source_chain, id)); - return dispatch_result + return dispatch_result; } // verify weight @@ -293,14 +293,14 @@ impl, I: 'static> MessageDispatch expected_weight, message.weight, )); - return dispatch_result + return dispatch_result; } // pay dispatch fee right before dispatch let pay_dispatch_fee_at_target_chain = message.dispatch_fee_payment == DispatchFeePayment::AtTargetChain; - if pay_dispatch_fee_at_target_chain && - pay_dispatch_fee(&origin_account, message.weight).is_err() + if pay_dispatch_fee_at_target_chain + && pay_dispatch_fee(&origin_account, message.weight).is_err() { log::trace!( target: "runtime::bridge-dispatch", @@ -315,7 +315,7 @@ impl, I: 'static> MessageDispatch origin_account, message.weight, )); - return dispatch_result + return dispatch_result; } dispatch_result.dispatch_fee_paid_during_dispatch = pay_dispatch_fee_at_target_chain; @@ -383,8 +383,8 @@ where }, CallOrigin::SourceAccount(ref source_account_id) => { ensure!( - sender_origin == &RawOrigin::Signed(source_account_id.clone()) || - sender_origin == &RawOrigin::Root, + sender_origin == &RawOrigin::Signed(source_account_id.clone()) + || sender_origin == &RawOrigin::Root, BadOrigin ); Ok(Some(source_account_id.clone())) @@ -496,42 +496,42 @@ mod tests { } impl frame_system::Config for TestRuntime { - type Origin = Origin; - type Index = u64; - type Call = Call; + type AccountData = (); + type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type BlockHashCount = BlockHashCount; + type BlockLength = (); type BlockNumber = u64; + type BlockWeights = (); + type Call = Call; + type DbWeight = (); + type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; type Header = Header; - type Event = Event; - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); + type Index = u64; + type Lookup = IdentityLookup; + type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); - type BaseCallFilter = frame_support::traits::Everything; - type SystemWeightInfo = (); - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type SS58Prefix = (); + type OnNewAccount = (); type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; + type Origin = Origin; + type PalletInfo = PalletInfo; + type SS58Prefix = (); + type SystemWeightInfo = (); + type Version = (); } impl Config for TestRuntime { - type Event = Event; + type AccountIdConverter = AccountIdConverter; type BridgeMessageId = BridgeMessageId; - type SourceChainAccountId = AccountId; - type TargetChainAccountPublic = TestAccountPublic; - type TargetChainSignature = TestSignature; type Call = Call; type CallFilter = TestCallFilter; type EncodedCall = EncodedCall; - type AccountIdConverter = AccountIdConverter; + type Event = Event; + type SourceChainAccountId = AccountId; + type TargetChainAccountPublic = TestAccountPublic; + type TargetChainSignature = TestSignature; } #[derive(Decode, Encode)] diff --git a/modules/fee-market/src/lib.rs b/modules/fee-market/src/lib.rs index 9a69fecee..f8f9b687b 100644 --- a/modules/fee-market/src/lib.rs +++ b/modules/fee-market/src/lib.rs @@ -444,7 +444,7 @@ impl, I: 'static> Pallet { } if count == 0 { - return None + return None; } Some((count, orders_locked_collateral)) } @@ -456,7 +456,7 @@ impl, I: 'static> Pallet { if let Some((_, orders_locked_collateral)) = Self::occupied(who) { let free_collateral = relayer_locked_collateral.saturating_sub(orders_locked_collateral); - return Self::collateral_to_order_capacity(free_collateral) + return Self::collateral_to_order_capacity(free_collateral); } Self::collateral_to_order_capacity(relayer_locked_collateral) } diff --git a/modules/fee-market/src/s2s/payment.rs b/modules/fee-market/src/s2s/payment.rs index 4fe12fef4..187c8fb76 100644 --- a/modules/fee-market/src/s2s/payment.rs +++ b/modules/fee-market/src/s2s/payment.rs @@ -62,13 +62,13 @@ where // if we'll accept some message that has declared that the `fee` has been paid but // it isn't actually paid, then it'll lead to problems with delivery confirmation // payments (see `pay_relayer_rewards` && `confirmation_relayer` in particular) - return Err(NON_ZERO_MESSAGE_FEE_CANT_BE_PAID_BY_NONE) + return Err(NON_ZERO_MESSAGE_FEE_CANT_BE_PAID_BY_NONE); }, None => { // message lane verifier has accepted the message before, so this message // is unpaid **by design** // => let's just do nothing - return Ok(()) + return Ok(()); }, }; @@ -255,7 +255,7 @@ pub(crate) fn do_slash, I: 'static>( report, ); log::trace!("Slash {:?} amount: {:?}", who, amount); - return amount + return amount; }, Err(e) => { crate::Pallet::::update_relayer_after_slash(who, locked_collateral, report); @@ -273,7 +273,7 @@ pub(crate) fn do_reward, I: 'static>( reward: BalanceOf, ) { if reward.is_zero() { - return + return; } let pay_result = >::Currency::transfer( diff --git a/modules/fee-market/src/tests.rs b/modules/fee-market/src/tests.rs index 643ab3435..0ca3f5eb4 100644 --- a/modules/fee-market/src/tests.rs +++ b/modules/fee-market/src/tests.rs @@ -66,41 +66,41 @@ frame_support::parameter_types! { pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 1, write: 2 }; } impl frame_system::Config for Test { + type AccountData = pallet_balances::AccountData; + type AccountId = AccountId; type BaseCallFilter = Everything; - type BlockWeights = (); + type BlockHashCount = (); type BlockLength = (); - type DbWeight = DbWeight; - type Origin = Origin; - type Index = u64; type BlockNumber = u64; - type Hash = H256; + type BlockWeights = (); type Call = Call; + type DbWeight = DbWeight; + type Event = Event; + type Hash = H256; type Hashing = BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; type Header = Header; - type Event = Event; - type BlockHashCount = (); - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); + type Index = u64; + type Lookup = IdentityLookup; + type MaxConsumers = ConstU32<16>; type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); + type OnNewAccount = (); type OnSetCode = (); - type MaxConsumers = ConstU32<16>; + type Origin = Origin; + type PalletInfo = PalletInfo; + type SS58Prefix = (); + type SystemWeightInfo = (); + type Version = (); } frame_support::parameter_types! { pub const ExistentialDeposit: u64 = 1; } impl pallet_balances::Config for Test { + type AccountStore = System; type Balance = Balance; type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = [u8; 8]; @@ -111,9 +111,9 @@ frame_support::parameter_types! { pub const MinimumPeriod: u64 = 1000; } impl pallet_timestamp::Config for Test { + type MinimumPeriod = MinimumPeriod; type Moment = u64; type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; type WeightInfo = (); } @@ -198,7 +198,6 @@ impl MessagesParameter for TestMessagesParameter { pub struct TestTargetHeaderChain; impl TargetHeaderChain for TestTargetHeaderChain { type Error = &'static str; - type MessagesDeliveryProof = TestMessagesDeliveryProof; fn verify_message(payload: &TestPayload) -> Result<(), Self::Error> { @@ -233,10 +232,10 @@ impl LaneMessageVerifier ) -> Result<(), Self::Error> { if let Some(market_fee) = FeeMarket::market_fee() { if *delivery_and_dispatch_fee < market_fee { - return Err(TEST_ERROR) + return Err(TEST_ERROR); } } else { - return Err(TEST_ERROR) + return Err(TEST_ERROR); } Ok(()) } @@ -275,7 +274,7 @@ impl MessageDeliveryAndDispatchPayment _relayer_fund_account: &AccountId, ) -> Result<(), Self::Error> { if frame_support::storage::unhashed::get(b":reject-message-fee:") == Some(true) { - return Err(TEST_ERROR) + return Err(TEST_ERROR); } let raw_origin: Result, _> = submitter.clone().into(); @@ -326,7 +325,6 @@ impl MessageDeliveryAndDispatchPayment pub struct TestSourceHeaderChain; impl SourceHeaderChain for TestSourceHeaderChain { type Error = &'static str; - type MessagesProof = TestMessagesProof; fn verify_messages_proof( @@ -379,31 +377,26 @@ frame_support::parameter_types! { } impl pallet_bridge_messages::Config for Test { + type AccountIdConverter = AccountIdConverter; + type BridgedChainId = TestBridgedChainId; type Event = Event; - type WeightInfo = (); - type Parameter = TestMessagesParameter; - type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; - type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; - type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane; - - type OutboundPayload = TestPayload; - type OutboundMessageFee = TestMessageFee; - - type InboundPayload = TestPayload; type InboundMessageFee = TestMessageFee; + type InboundPayload = TestPayload; type InboundRelayer = TestRelayer; - - type AccountIdConverter = AccountIdConverter; - - type TargetHeaderChain = TestTargetHeaderChain; type LaneMessageVerifier = TestLaneMessageVerifier; + type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; + type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane; + type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; type MessageDeliveryAndDispatchPayment = TestMessageDeliveryAndDispatchPayment; - type OnMessageAccepted = FeeMarketMessageAcceptedHandler; + type MessageDispatch = TestMessageDispatch; type OnDeliveryConfirmed = FeeMarketMessageConfirmedHandler; - + type OnMessageAccepted = FeeMarketMessageAcceptedHandler; + type OutboundMessageFee = TestMessageFee; + type OutboundPayload = TestPayload; + type Parameter = TestMessagesParameter; type SourceHeaderChain = TestSourceHeaderChain; - type MessageDispatch = TestMessageDispatch; - type BridgedChainId = TestBridgedChainId; + type TargetHeaderChain = TestTargetHeaderChain; + type WeightInfo = (); } impl SenderOrigin for Origin { @@ -442,19 +435,17 @@ impl, I: 'static> Slasher for TestSlasher { } impl Config for Test { - type TreasuryPalletId = TreasuryPalletId; - type LockId = FeeMarketLockId; - type CollateralPerOrder = CollateralPerOrder; - type MinimumRelayFee = MinimumRelayFee; - type Slot = Slot; - type AssignedRelayersRewardRatio = AssignedRelayersRewardRatio; - type MessageRelayersRewardRatio = MessageRelayersRewardRatio; + type CollateralPerOrder = CollateralPerOrder; type ConfirmRelayersRewardRatio = ConfirmRelayersRewardRatio; - - type Slasher = TestSlasher; type Currency = Balances; type Event = Event; + type LockId = FeeMarketLockId; + type MessageRelayersRewardRatio = MessageRelayersRewardRatio; + type MinimumRelayFee = MinimumRelayFee; + type Slasher = TestSlasher; + type Slot = Slot; + type TreasuryPalletId = TreasuryPalletId; type WeightInfo = (); } diff --git a/modules/fee-market/src/types.rs b/modules/fee-market/src/types.rs index 9fa9a0d37..281b6e250 100644 --- a/modules/fee-market/src/types.rs +++ b/modules/fee-market/src/types.rs @@ -133,7 +133,7 @@ where pub fn delivery_delay(&self) -> Option { if let (Some(confirm_time), Some(range_end)) = (self.confirm_time, self.range_end()) { if confirm_time > range_end { - return Some(confirm_time - range_end) + return Some(confirm_time - range_end); } } None @@ -145,7 +145,7 @@ where ) -> Option<(AccountId, Balance)> { for prior_relayer in self.relayers.iter() { if prior_relayer.valid_range.contains(&message_confirm_time) { - return Some((prior_relayer.id.clone(), prior_relayer.fee)) + return Some((prior_relayer.id.clone(), prior_relayer.fee)); } } None @@ -158,7 +158,7 @@ where { for prior_relayer in self.relayers.iter() { if prior_relayer.id == id { - return Some(prior_relayer.valid_range.clone()) + return Some(prior_relayer.valid_range.clone()); } } None diff --git a/modules/fee-market/src/weight.rs b/modules/fee-market/src/weight.rs index 5f71bb45a..d2fc0f9a4 100644 --- a/modules/fee-market/src/weight.rs +++ b/modules/fee-market/src/weight.rs @@ -70,26 +70,31 @@ impl WeightInfo for SubstrateWeight { .saturating_add(T::DbWeight::get().reads(13 as Weight)) .saturating_add(T::DbWeight::get().writes(7 as Weight)) } + fn update_locked_collateral() -> Weight { (117_829_000 as Weight) .saturating_add(T::DbWeight::get().reads(13 as Weight)) .saturating_add(T::DbWeight::get().writes(5 as Weight)) } + fn update_relay_fee() -> Weight { (95_137_000 as Weight) .saturating_add(T::DbWeight::get().reads(11 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } + fn cancel_enrollment() -> Weight { (117_809_000 as Weight) .saturating_add(T::DbWeight::get().reads(13 as Weight)) .saturating_add(T::DbWeight::get().writes(7 as Weight)) } + fn set_slash_protect() -> Weight { (18_584_000 as Weight) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } + fn set_assigned_relayers_number() -> Weight { (86_661_000 as Weight) .saturating_add(T::DbWeight::get().reads(10 as Weight)) @@ -104,26 +109,31 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(13 as Weight)) .saturating_add(RocksDbWeight::get().writes(7 as Weight)) } + fn update_locked_collateral() -> Weight { (117_829_000 as Weight) .saturating_add(RocksDbWeight::get().reads(13 as Weight)) .saturating_add(RocksDbWeight::get().writes(5 as Weight)) } + fn update_relay_fee() -> Weight { (95_137_000 as Weight) .saturating_add(RocksDbWeight::get().reads(11 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } + fn cancel_enrollment() -> Weight { (117_809_000 as Weight) .saturating_add(RocksDbWeight::get().reads(13 as Weight)) .saturating_add(RocksDbWeight::get().writes(7 as Weight)) } + fn set_slash_protect() -> Weight { (18_584_000 as Weight) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } + fn set_assigned_relayers_number() -> Weight { (86_661_000 as Weight) .saturating_add(RocksDbWeight::get().reads(10 as Weight)) diff --git a/modules/grandpa/src/mock.rs b/modules/grandpa/src/mock.rs index bfc749d52..3db37666e 100644 --- a/modules/grandpa/src/mock.rs +++ b/modules/grandpa/src/mock.rs @@ -54,30 +54,30 @@ parameter_types! { } impl frame_system::Config for TestRuntime { - type Origin = Origin; - type Index = u64; - type Call = Call; + type AccountData = (); + type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type BlockHashCount = BlockHashCount; + type BlockLength = (); type BlockNumber = u64; + type BlockWeights = (); + type Call = Call; + type DbWeight = (); + type Event = (); type Hash = H256; type Hashing = BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; type Header = Header; - type Event = (); - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); + type Index = u64; + type Lookup = IdentityLookup; + type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); - type BaseCallFilter = frame_support::traits::Everything; - type SystemWeightInfo = (); - type DbWeight = (); - type BlockWeights = (); - type BlockLength = (); - type SS58Prefix = (); + type OnNewAccount = (); type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; + type Origin = Origin; + type PalletInfo = PalletInfo; + type SS58Prefix = (); + type SystemWeightInfo = (); + type Version = (); } parameter_types! { @@ -89,8 +89,8 @@ parameter_types! { impl grandpa::Config for TestRuntime { type BridgedChain = TestBridgedChain; - type MaxRequests = MaxRequests; type HeadersToKeep = HeadersToKeep; + type MaxRequests = MaxRequests; type WeightInfo = (); } @@ -98,19 +98,19 @@ impl grandpa::Config for TestRuntime { pub struct TestBridgedChain; impl Chain for TestBridgedChain { + type AccountId = AccountId; + type Balance = u64; type BlockNumber = ::BlockNumber; type Hash = ::Hash; type Hasher = ::Hashing; type Header = ::Header; - - type AccountId = AccountId; - type Balance = u64; type Index = u64; type Signature = Signature; fn max_extrinsic_size() -> u32 { unreachable!() } + fn max_extrinsic_weight() -> Weight { unreachable!() } diff --git a/modules/messages/src/inbound_lane.rs b/modules/messages/src/inbound_lane.rs index 00875bb87..2481b1f15 100644 --- a/modules/messages/src/inbound_lane.rs +++ b/modules/messages/src/inbound_lane.rs @@ -81,10 +81,10 @@ impl InboundLane { if outbound_lane_data.latest_received_nonce > last_delivered_nonce { // this is something that should never happen if proofs are correct - return None + return None; } if outbound_lane_data.latest_received_nonce <= data.last_confirmed_nonce { - return None + return None; } let new_confirmed_nonce = outbound_lane_data.latest_received_nonce; @@ -127,18 +127,18 @@ impl InboundLane { let mut data = self.storage.data(); let is_correct_message = nonce == data.last_delivered_nonce() + 1; if !is_correct_message { - return ReceivalResult::InvalidNonce + return ReceivalResult::InvalidNonce; } // if there are more unrewarded relayer entries than we may accept, reject this message if data.relayers.len() as MessageNonce >= self.storage.max_unrewarded_relayer_entries() { - return ReceivalResult::TooManyUnrewardedRelayers + return ReceivalResult::TooManyUnrewardedRelayers; } // if there are more unconfirmed messages than we may accept, reject this message let unconfirmed_messages_count = nonce.saturating_sub(data.last_confirmed_nonce); if unconfirmed_messages_count > self.storage.max_unconfirmed_messages() { - return ReceivalResult::TooManyUnconfirmedMessages + return ReceivalResult::TooManyUnconfirmedMessages; } // then, dispatch message diff --git a/modules/messages/src/instant_payments.rs b/modules/messages/src/instant_payments.rs index 2a620a952..fca54dfd1 100644 --- a/modules/messages/src/instant_payments.rs +++ b/modules/messages/src/instant_payments.rs @@ -76,13 +76,13 @@ where // if we'll accept some message that has declared that the `fee` has been paid but // it isn't actually paid, then it'll lead to problems with delivery confirmation // payments (see `pay_relayer_rewards` && `confirmation_relayer` in particular) - return Err(NON_ZERO_MESSAGE_FEE_CANT_BE_PAID_BY_NONE) + return Err(NON_ZERO_MESSAGE_FEE_CANT_BE_PAID_BY_NONE); }, None => { // message lane verifier has accepted the message before, so this message // is unpaid **by design** // => let's just do nothing - return Ok(()) + return Ok(()); }, }; @@ -183,7 +183,7 @@ fn pay_relayers_rewards( // If delivery confirmation is submitted by this relayer, let's add confirmation fee // from other relayers to this relayer reward. confirmation_relayer_reward = confirmation_relayer_reward.saturating_add(reward.reward); - continue + continue; } pay_relayer_reward::(relayer_fund_account, &relayer, relayer_reward); @@ -207,7 +207,7 @@ fn pay_relayer_reward( Currency: CurrencyT, { if reward.is_zero() { - return + return; } let pay_result = Currency::transfer( diff --git a/modules/messages/src/lib.rs b/modules/messages/src/lib.rs index f0d409591..b092416be 100644 --- a/modules/messages/src/lib.rs +++ b/modules/messages/src/lib.rs @@ -441,7 +441,7 @@ pub mod pallet { dispatch_weight, dispatch_weight_left, ); - break + break; } total_messages += 1; @@ -466,9 +466,9 @@ pub mod pallet { !dispatch_result.dispatch_fee_paid_during_dispatch, ) }, - ReceivalResult::InvalidNonce | - ReceivalResult::TooManyUnrewardedRelayers | - ReceivalResult::TooManyUnconfirmedMessages => (dispatch_weight, true), + ReceivalResult::InvalidNonce + | ReceivalResult::TooManyUnrewardedRelayers + | ReceivalResult::TooManyUnconfirmedMessages => (dispatch_weight, true), }; let unspent_weight = sp_std::cmp::min(unspent_weight, dispatch_weight); @@ -545,10 +545,10 @@ pub mod pallet { // (we only care about total number of entries and messages, because this affects call // weight) ensure!( - total_unrewarded_messages(&lane_data.relayers).unwrap_or(MessageNonce::MAX) == - relayers_state.total_messages && - lane_data.relayers.len() as MessageNonce == - relayers_state.unrewarded_relayer_entries, + total_unrewarded_messages(&lane_data.relayers).unwrap_or(MessageNonce::MAX) + == relayers_state.total_messages + && lane_data.relayers.len() as MessageNonce + == relayers_state.unrewarded_relayer_entries, Error::::InvalidUnrewardedRelayersState ); @@ -2229,8 +2229,8 @@ mod tests { let weight_when_max_messages_are_pruned = send_regular_message(); assert_eq!( weight_when_max_messages_are_pruned, - when_zero_messages_are_pruned + - crate::mock::DbWeight::get().writes(max_messages_to_prune), + when_zero_messages_are_pruned + + crate::mock::DbWeight::get().writes(max_messages_to_prune), ); }); } diff --git a/modules/messages/src/mock.rs b/modules/messages/src/mock.rs index 5bf36f680..5d7a21afe 100644 --- a/modules/messages/src/mock.rs +++ b/modules/messages/src/mock.rs @@ -102,30 +102,30 @@ parameter_types! { } impl frame_system::Config for TestRuntime { - type Origin = Origin; - type Index = u64; - type Call = Call; + type AccountData = pallet_balances::AccountData; + type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type BlockHashCount = BlockHashCount; + type BlockLength = (); type BlockNumber = u64; + type BlockWeights = (); + type Call = Call; + type DbWeight = DbWeight; + type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; type Header = SubstrateHeader; - type Event = Event; - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); + type Index = u64; + type Lookup = IdentityLookup; + type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); - type BaseCallFilter = frame_support::traits::Everything; - type SystemWeightInfo = (); - type BlockWeights = (); - type BlockLength = (); - type DbWeight = DbWeight; - type SS58Prefix = (); + type OnNewAccount = (); type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; + type Origin = Origin; + type PalletInfo = PalletInfo; + type SS58Prefix = (); + type SystemWeightInfo = (); + type Version = (); } parameter_types! { @@ -133,15 +133,15 @@ parameter_types! { } impl pallet_balances::Config for TestRuntime { - type MaxLocks = (); + type AccountStore = frame_system::Pallet; type Balance = Balance; type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Pallet; - type WeightInfo = (); + type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = (); + type WeightInfo = (); } parameter_types! { @@ -167,31 +167,26 @@ impl MessagesParameter for TestMessagesParameter { } impl Config for TestRuntime { + type AccountIdConverter = AccountIdConverter; + type BridgedChainId = TestBridgedChainId; type Event = Event; - type WeightInfo = (); - type Parameter = TestMessagesParameter; - type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; - type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; - type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane; - - type OutboundPayload = TestPayload; - type OutboundMessageFee = TestMessageFee; - - type InboundPayload = TestPayload; type InboundMessageFee = TestMessageFee; + type InboundPayload = TestPayload; type InboundRelayer = TestRelayer; - - type AccountIdConverter = AccountIdConverter; - - type TargetHeaderChain = TestTargetHeaderChain; type LaneMessageVerifier = TestLaneMessageVerifier; + type MaxMessagesToPruneAtOnce = MaxMessagesToPruneAtOnce; + type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane; + type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; type MessageDeliveryAndDispatchPayment = TestMessageDeliveryAndDispatchPayment; - type OnMessageAccepted = TestOnMessageAccepted; + type MessageDispatch = TestMessageDispatch; type OnDeliveryConfirmed = (TestOnDeliveryConfirmed1, TestOnDeliveryConfirmed2); - + type OnMessageAccepted = TestOnMessageAccepted; + type OutboundMessageFee = TestMessageFee; + type OutboundPayload = TestPayload; + type Parameter = TestMessagesParameter; type SourceHeaderChain = TestSourceHeaderChain; - type MessageDispatch = TestMessageDispatch; - type BridgedChainId = TestBridgedChainId; + type TargetHeaderChain = TestTargetHeaderChain; + type WeightInfo = (); } impl SenderOrigin for Origin { @@ -282,7 +277,6 @@ pub struct TestTargetHeaderChain; impl TargetHeaderChain for TestTargetHeaderChain { type Error = &'static str; - type MessagesDeliveryProof = TestMessagesDeliveryProof; fn verify_message(payload: &TestPayload) -> Result<(), Self::Error> { @@ -359,7 +353,7 @@ impl MessageDeliveryAndDispatchPayment _relayer_fund_account: &AccountId, ) -> Result<(), Self::Error> { if frame_support::storage::unhashed::get(b":reject-message-fee:") == Some(true) { - return Err(TEST_ERROR) + return Err(TEST_ERROR); } let raw_origin: Result, _> = submitter.clone().into(); @@ -471,7 +465,6 @@ pub struct TestSourceHeaderChain; impl SourceHeaderChain for TestSourceHeaderChain { type Error = &'static str; - type MessagesProof = TestMessagesProof; fn verify_messages_proof( diff --git a/modules/messages/src/outbound_lane.rs b/modules/messages/src/outbound_lane.rs index 041dec214..df5bb88ee 100644 --- a/modules/messages/src/outbound_lane.rs +++ b/modules/messages/src/outbound_lane.rs @@ -107,10 +107,10 @@ impl OutboundLane { ) -> ReceivalConfirmationResult { let mut data = self.storage.data(); if latest_delivered_nonce <= data.latest_received_nonce { - return ReceivalConfirmationResult::NoNewConfirmations + return ReceivalConfirmationResult::NoNewConfirmations; } if latest_delivered_nonce > data.latest_generated_nonce { - return ReceivalConfirmationResult::FailedToConfirmFutureMessages + return ReceivalConfirmationResult::FailedToConfirmFutureMessages; } if latest_delivered_nonce - data.latest_received_nonce > max_allowed_messages { // that the relayer has declared correct number of messages that the proof contains (it @@ -120,7 +120,7 @@ impl OutboundLane { // weight formula accounts, so we can't allow that. return ReceivalConfirmationResult::TryingToConfirmMoreMessagesThanExpected( latest_delivered_nonce - data.latest_received_nonce, - ) + ); } let dispatch_results = match extract_dispatch_results( @@ -149,8 +149,8 @@ impl OutboundLane { pub fn prune_messages(&mut self, max_messages_to_prune: MessageNonce) -> MessageNonce { let mut pruned_messages = 0; let mut data = self.storage.data(); - while pruned_messages < max_messages_to_prune && - data.oldest_unpruned_nonce <= data.latest_received_nonce + while pruned_messages < max_messages_to_prune + && data.oldest_unpruned_nonce <= data.latest_received_nonce { self.storage.remove_message(&data.oldest_unpruned_nonce); @@ -186,14 +186,14 @@ fn extract_dispatch_results( // unrewarded relayer entry must have at least 1 unconfirmed message // (guaranteed by the `InboundLane::receive_message()`) if entry.messages.end < entry.messages.begin { - return Err(ReceivalConfirmationResult::EmptyUnrewardedRelayerEntry) + return Err(ReceivalConfirmationResult::EmptyUnrewardedRelayerEntry); } // every entry must confirm range of messages that follows previous entry range // (guaranteed by the `InboundLane::receive_message()`) if let Some(last_entry_end) = last_entry_end { let expected_entry_begin = last_entry_end.checked_add(1); if expected_entry_begin != Some(entry.messages.begin) { - return Err(ReceivalConfirmationResult::NonConsecutiveUnrewardedRelayerEntries) + return Err(ReceivalConfirmationResult::NonConsecutiveUnrewardedRelayerEntries); } } last_entry_end = Some(entry.messages.end); @@ -203,14 +203,14 @@ fn extract_dispatch_results( // technically this will be detected in the next loop iteration as // `InvalidNumberOfDispatchResults` but to guarantee safety of loop operations below // this is detected now - return Err(ReceivalConfirmationResult::FailedToConfirmFutureMessages) + return Err(ReceivalConfirmationResult::FailedToConfirmFutureMessages); } // entry must have single dispatch result for every message // (guaranteed by the `InboundLane::receive_message()`) - if entry.messages.dispatch_results.len() as MessageNonce != - entry.messages.end - entry.messages.begin + 1 + if entry.messages.dispatch_results.len() as MessageNonce + != entry.messages.end - entry.messages.begin + 1 { - return Err(ReceivalConfirmationResult::InvalidNumberOfDispatchResults) + return Err(ReceivalConfirmationResult::InvalidNumberOfDispatchResults); } // now we know that the entry is valid @@ -220,7 +220,7 @@ fn extract_dispatch_results( let new_messages_end = sp_std::cmp::min(entry.messages.end, latest_received_nonce); let new_messages_range = new_messages_begin..=new_messages_end; if new_messages_range.is_empty() { - continue + continue; } // now we know that entry brings new confirmations @@ -249,9 +249,7 @@ mod tests { fn unrewarded_relayers( nonces: RangeInclusive, ) -> VecDeque> { - vec![unrewarded_relayer(*nonces.start(), *nonces.end(), 0)] - .into_iter() - .collect() + vec![unrewarded_relayer(*nonces.start(), *nonces.end(), 0)].into_iter().collect() } fn delivered_messages(nonces: RangeInclusive) -> DeliveredMessages { diff --git a/modules/messages/src/weights.rs b/modules/messages/src/weights.rs index 462f768a0..b6256eec9 100644 --- a/modules/messages/src/weights.rs +++ b/modules/messages/src/weights.rs @@ -72,67 +72,80 @@ impl WeightInfo for MillauWeight { .saturating_add(T::DbWeight::get().reads(7 as Weight)) .saturating_add(T::DbWeight::get().writes(12 as Weight)) } + fn send_1_kb_message_worst_case() -> Weight { (128_391_000 as Weight) .saturating_add(T::DbWeight::get().reads(7 as Weight)) .saturating_add(T::DbWeight::get().writes(12 as Weight)) } + fn send_16_kb_message_worst_case() -> Weight { (149_149_000 as Weight) .saturating_add(T::DbWeight::get().reads(7 as Weight)) .saturating_add(T::DbWeight::get().writes(12 as Weight)) } + fn maximal_increase_message_fee() -> Weight { (6_015_058_000 as Weight) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } + fn increase_message_fee(i: u32) -> Weight { (0 as Weight) .saturating_add((2_000 as Weight).saturating_mul(i as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } + fn receive_single_message_proof() -> Weight { (179_892_000 as Weight) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } + fn receive_two_messages_proof() -> Weight { (291_793_000 as Weight) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } + fn receive_single_message_proof_with_outbound_lane_state() -> Weight { (192_191_000 as Weight) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } + fn receive_single_message_proof_1_kb() -> Weight { (202_104_000 as Weight) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } + fn receive_single_message_proof_16_kb() -> Weight { (357_144_000 as Weight) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } + fn receive_single_prepaid_message_proof() -> Weight { (122_648_000 as Weight) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } + fn receive_delivery_proof_for_single_message() -> Weight { (107_631_000 as Weight) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } + fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { (113_885_000 as Weight) .saturating_add(T::DbWeight::get().reads(7 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } + fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { (155_151_000 as Weight) .saturating_add(T::DbWeight::get().reads(8 as Weight)) @@ -147,67 +160,80 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(7 as Weight)) .saturating_add(RocksDbWeight::get().writes(12 as Weight)) } + fn send_1_kb_message_worst_case() -> Weight { (128_391_000 as Weight) .saturating_add(RocksDbWeight::get().reads(7 as Weight)) .saturating_add(RocksDbWeight::get().writes(12 as Weight)) } + fn send_16_kb_message_worst_case() -> Weight { (149_149_000 as Weight) .saturating_add(RocksDbWeight::get().reads(7 as Weight)) .saturating_add(RocksDbWeight::get().writes(12 as Weight)) } + fn maximal_increase_message_fee() -> Weight { (6_015_058_000 as Weight) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } + fn increase_message_fee(i: u32) -> Weight { (0 as Weight) .saturating_add((2_000 as Weight).saturating_mul(i as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } + fn receive_single_message_proof() -> Weight { (179_892_000 as Weight) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } + fn receive_two_messages_proof() -> Weight { (291_793_000 as Weight) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } + fn receive_single_message_proof_with_outbound_lane_state() -> Weight { (192_191_000 as Weight) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } + fn receive_single_message_proof_1_kb() -> Weight { (202_104_000 as Weight) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } + fn receive_single_message_proof_16_kb() -> Weight { (357_144_000 as Weight) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } + fn receive_single_prepaid_message_proof() -> Weight { (122_648_000 as Weight) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } + fn receive_delivery_proof_for_single_message() -> Weight { (107_631_000 as Weight) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } + fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { (113_885_000 as Weight) .saturating_add(RocksDbWeight::get().reads(7 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } + fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { (155_151_000 as Weight) .saturating_add(RocksDbWeight::get().reads(8 as Weight)) diff --git a/modules/messages/src/weights_ext.rs b/modules/messages/src/weights_ext.rs index 483a22eda..5699ec5b2 100644 --- a/modules/messages/src/weights_ext.rs +++ b/modules/messages/src/weights_ext.rs @@ -61,8 +61,8 @@ pub fn ensure_weights_are_correct( 0, ); assert!( - actual_single_regular_message_delivery_tx_weight <= - expected_default_message_delivery_tx_weight, + actual_single_regular_message_delivery_tx_weight + <= expected_default_message_delivery_tx_weight, "Default message delivery transaction weight {} is larger than expected weight {}", actual_single_regular_message_delivery_tx_weight, expected_default_message_delivery_tx_weight, @@ -94,8 +94,8 @@ pub fn ensure_weights_are_correct( db_weight, ); assert!( - actual_messages_delivery_confirmation_tx_weight <= - expected_messages_delivery_confirmation_tx_weight, + actual_messages_delivery_confirmation_tx_weight + <= expected_messages_delivery_confirmation_tx_weight, "Messages delivery confirmation transaction weight {} is larger than expected weight {}", actual_messages_delivery_confirmation_tx_weight, expected_messages_delivery_confirmation_tx_weight, @@ -359,9 +359,9 @@ pub trait WeightInfoExt: WeightInfo { /// is less than that cost). fn storage_proof_size_overhead(proof_size: u32) -> Weight { let proof_size_in_bytes = proof_size as Weight; - let byte_weight = (Self::receive_single_message_proof_16_kb() - - Self::receive_single_message_proof_1_kb()) / - (15 * 1024); + let byte_weight = (Self::receive_single_message_proof_16_kb() + - Self::receive_single_message_proof_1_kb()) + / (15 * 1024); proof_size_in_bytes * byte_weight } diff --git a/modules/parachains/src/lib.rs b/modules/parachains/src/lib.rs index 3f5d214f6..4d3066fb6 100644 --- a/modules/parachains/src/lib.rs +++ b/modules/parachains/src/lib.rs @@ -221,7 +221,7 @@ pub mod pallet { stored_best_head.at_relay_block_number, updated_at_relay_block_number, ); - return Err(()) + return Err(()); } stored_best_head.next_imported_hash_position @@ -238,7 +238,7 @@ pub mod pallet { stored_best_head.at_relay_block_number, updated_at_relay_block_number, ); - return Err(()) + return Err(()); }, }; @@ -248,8 +248,8 @@ pub mod pallet { let updated_best_para_head = BestParaHead { at_relay_block_number: updated_at_relay_block_number, head_hash: updated_head_hash, - next_imported_hash_position: (next_imported_hash_position + 1) % - T::HeadsToKeep::get(), + next_imported_hash_position: (next_imported_hash_position + 1) + % T::HeadsToKeep::get(), }; ImportedParaHashes::::insert( parachain, diff --git a/modules/parachains/src/mock.rs b/modules/parachains/src/mock.rs index fcd157020..141a1e49e 100644 --- a/modules/parachains/src/mock.rs +++ b/modules/parachains/src/mock.rs @@ -54,30 +54,30 @@ parameter_types! { } impl frame_system::Config for TestRuntime { - type Origin = Origin; - type Index = u64; - type Call = Call; + type AccountData = (); + type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type BlockHashCount = BlockHashCount; + type BlockLength = (); type BlockNumber = TestNumber; + type BlockWeights = (); + type Call = Call; + type DbWeight = (); + type Event = (); type Hash = H256; type Hashing = BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; type Header = Header; - type Event = (); - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); + type Index = u64; + type Lookup = IdentityLookup; + type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); - type BaseCallFilter = frame_support::traits::Everything; - type SystemWeightInfo = (); - type DbWeight = (); - type BlockWeights = (); - type BlockLength = (); - type SS58Prefix = (); + type OnNewAccount = (); type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; + type Origin = Origin; + type PalletInfo = PalletInfo; + type SS58Prefix = (); + type SystemWeightInfo = (); + type Version = (); } parameter_types! { @@ -89,15 +89,15 @@ parameter_types! { impl pallet_bridge_grandpa::Config for TestRuntime { type BridgedChain = TestBridgedChain; - type MaxRequests = MaxRequests; type HeadersToKeep = HeadersToKeep; + type MaxRequests = MaxRequests; type WeightInfo = (); } impl pallet_bridge_grandpa::Config for TestRuntime { type BridgedChain = TestBridgedChain; - type MaxRequests = MaxRequests; type HeadersToKeep = HeadersToKeep; + type MaxRequests = MaxRequests; type WeightInfo = (); } @@ -114,13 +114,12 @@ impl pallet_bridge_parachains::Config for TestRuntime { pub struct TestBridgedChain; impl Chain for TestBridgedChain { + type AccountId = AccountId; + type Balance = u32; type BlockNumber = crate::RelayBlockNumber; type Hash = crate::RelayBlockHash; type Hasher = crate::RelayBlockHasher; type Header = RelayBlockHeader; - - type AccountId = AccountId; - type Balance = u32; type Index = u32; type Signature = sp_runtime::testing::TestSignature; @@ -137,13 +136,12 @@ impl Chain for TestBridgedChain { pub struct OtherBridgedChain; impl Chain for OtherBridgedChain { + type AccountId = AccountId; + type Balance = u32; type BlockNumber = u64; type Hash = crate::RelayBlockHash; type Hasher = crate::RelayBlockHasher; type Header = sp_runtime::generic::Header; - - type AccountId = AccountId; - type Balance = u32; type Index = u32; type Signature = sp_runtime::testing::TestSignature; diff --git a/modules/shift-session-manager/src/lib.rs b/modules/shift-session-manager/src/lib.rs index 9cf844125..4a6a14ffd 100644 --- a/modules/shift-session-manager/src/lib.rs +++ b/modules/shift-session-manager/src/lib.rs @@ -51,11 +51,13 @@ pub mod pallet { impl pallet_session::SessionManager for Pallet { fn end_session(_: sp_staking::SessionIndex) {} + fn start_session(_: sp_staking::SessionIndex) {} + fn new_session(session_index: sp_staking::SessionIndex) -> Option> { // we don't want to add even more fields to genesis config => just return None if session_index == 0 || session_index == 1 { - return None + return None; } // the idea that on first call (i.e. when session 1 ends) we're reading current @@ -140,30 +142,30 @@ mod tests { } impl frame_system::Config for TestRuntime { - type Origin = Origin; - type Index = u64; - type Call = Call; + type AccountData = (); + type AccountId = AccountId; + type BaseCallFilter = frame_support::traits::Everything; + type BlockHashCount = BlockHashCount; + type BlockLength = (); type BlockNumber = u64; + type BlockWeights = (); + type Call = Call; + type DbWeight = (); + type Event = (); type Hash = H256; type Hashing = BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; type Header = Header; - type Event = (); - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); + type Index = u64; + type Lookup = IdentityLookup; + type MaxConsumers = frame_support::traits::ConstU32<16>; type OnKilledAccount = (); - type BaseCallFilter = frame_support::traits::Everything; - type SystemWeightInfo = (); - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type SS58Prefix = (); + type OnNewAccount = (); type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; + type Origin = Origin; + type PalletInfo = PalletInfo; + type SS58Prefix = (); + type SystemWeightInfo = (); + type Version = (); } parameter_types! { @@ -173,13 +175,13 @@ mod tests { impl pallet_session::Config for TestRuntime { type Event = (); - type ValidatorId = ::AccountId; - type ValidatorIdOf = ConvertInto; - type ShouldEndSession = pallet_session::PeriodicSessions; + type Keys = UintAuthorityId; type NextSessionRotation = pallet_session::PeriodicSessions; - type SessionManager = (); type SessionHandler = TestSessionHandler; - type Keys = UintAuthorityId; + type SessionManager = (); + type ShouldEndSession = pallet_session::PeriodicSessions; + type ValidatorId = ::AccountId; + type ValidatorIdOf = ConvertInto; type WeightInfo = (); } @@ -219,9 +221,7 @@ mod tests { } }); - pallet_session::GenesisConfig:: { keys } - .assimilate_storage(&mut t) - .unwrap(); + pallet_session::GenesisConfig:: { keys }.assimilate_storage(&mut t).unwrap(); TestExternalities::new(t) } diff --git a/primitives/chain-kusama/src/lib.rs b/primitives/chain-kusama/src/lib.rs index a0a5990ca..d362fd164 100644 --- a/primitives/chain-kusama/src/lib.rs +++ b/primitives/chain-kusama/src/lib.rs @@ -47,6 +47,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { pub struct WeightToFee; impl WeightToFeePolynomial for WeightToFee { type Balance = Balance; + fn polynomial() -> WeightToFeeCoefficients { const CENTS: Balance = 1_000_000_000_000 / 30_000; // in Kusama, extrinsic base weight (smallest non-zero weight) is mapped to 1/10 CENT: diff --git a/primitives/chain-polkadot/src/lib.rs b/primitives/chain-polkadot/src/lib.rs index d95e29c8b..7194eb090 100644 --- a/primitives/chain-polkadot/src/lib.rs +++ b/primitives/chain-polkadot/src/lib.rs @@ -47,6 +47,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { pub struct WeightToFee; impl WeightToFeePolynomial for WeightToFee { type Balance = Balance; + fn polynomial() -> WeightToFeeCoefficients { const CENTS: Balance = 10_000_000_000 / 100; // in Polkadot, extrinsic base weight (smallest non-zero weight) is mapped to 1/10 CENT: diff --git a/primitives/chain-rococo/src/lib.rs b/primitives/chain-rococo/src/lib.rs index 127e75d5f..a4108443b 100644 --- a/primitives/chain-rococo/src/lib.rs +++ b/primitives/chain-rococo/src/lib.rs @@ -54,6 +54,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { pub struct WeightToFee; impl WeightToFeePolynomial for WeightToFee { type Balance = Balance; + fn polynomial() -> WeightToFeeCoefficients { const CENTS: Balance = 1_000_000_000_000 / 100; let p = CENTS; diff --git a/primitives/darwinia-core/src/lib.rs b/primitives/darwinia-core/src/lib.rs index bac2a4659..70d285db8 100644 --- a/primitives/darwinia-core/src/lib.rs +++ b/primitives/darwinia-core/src/lib.rs @@ -277,13 +277,13 @@ impl SignedExtensionT for SignedExtensions where Call: Clone + Debug + Eq + PartialEq + Sync + Send + Codec + StaticTypeInfo + Dispatchable, { - const IDENTIFIER: &'static str = "Not needed."; - type AccountId = AccountId; - type Call = Call; type AdditionalSigned = AdditionalSigned; + type Call = Call; type Pre = (); + const IDENTIFIER: &'static str = "Not needed."; + fn additional_signed(&self) -> Result { // we shall not ever see this error in relay, because we are never signing decoded // transactions. Instead we're constructing and signing new transactions. So the error code @@ -307,13 +307,12 @@ where #[derive(RuntimeDebug)] pub struct DarwiniaLike; impl Chain for DarwiniaLike { + type AccountId = AccountId; + type Balance = Balance; type BlockNumber = BlockNumber; type Hash = Hash; type Hasher = Hashing; type Header = Header; - - type AccountId = AccountId; - type Balance = Balance; type Index = Nonce; type Signature = Signature; @@ -322,10 +321,7 @@ impl Chain for DarwiniaLike { } fn max_extrinsic_weight() -> Weight { - RuntimeBlockWeights::get() - .get(DispatchClass::Normal) - .max_extrinsic - .unwrap_or(Weight::MAX) + RuntimeBlockWeights::get().get(DispatchClass::Normal).max_extrinsic.unwrap_or(Weight::MAX) } } diff --git a/primitives/header-chain/src/justification.rs b/primitives/header-chain/src/justification.rs index ff841d70f..bc9ab0046 100644 --- a/primitives/header-chain/src/justification.rs +++ b/primitives/header-chain/src/justification.rs @@ -92,7 +92,7 @@ where { // ensure that it is justification for the expected header if (justification.commit.target_hash, justification.commit.target_number) != finalized_target { - return Err(Error::InvalidJustificationTarget) + return Err(Error::InvalidJustificationTarget); } let mut chain = AncestryChain::new(&justification.votes_ancestries); @@ -106,7 +106,7 @@ where None => { // just ignore precommit from unknown authority as // `finality_grandpa::import_precommit` does - continue + continue; }, }; @@ -116,14 +116,14 @@ where // `finality-grandpa` crate (mostly related to reporting equivocations). But the only thing // that we care about is that only first vote from the authority is accepted if !votes.insert(signed.id.clone()) { - continue + continue; } // everything below this line can't just `continue`, because state is already altered // precommits aren't allowed for block lower than the target if signed.precommit.target_number < justification.commit.target_number { - return Err(Error::PrecommitIsNotCommitDescendant) + return Err(Error::PrecommitIsNotCommitDescendant); } // all precommits must be descendants of target block chain = chain @@ -151,13 +151,13 @@ where authorities_set_id, &mut signature_buffer, ) { - return Err(Error::InvalidAuthoritySignature) + return Err(Error::InvalidAuthoritySignature); } } // check that there are no extra headers in the justification if !chain.unvisited.is_empty() { - return Err(Error::ExtraHeadersInVotesAncestries) + return Err(Error::ExtraHeadersInVotesAncestries); } // check that the cumulative weight of validators voted for the justification target (or one @@ -203,7 +203,7 @@ impl AncestryChain
{ let mut current_hash = *precommit_target; loop { if current_hash == *commit_target { - break + break; } let is_visited_before = !self.unvisited.remove(¤t_hash); @@ -214,7 +214,7 @@ impl AncestryChain
{ // container `is_visited_before` means that it has been visited before in // some of previous calls => since we assume that previous call has finished // with `true`, this also will be finished with `true` - return Ok(self) + return Ok(self); } *parent_hash diff --git a/primitives/header-chain/tests/implementation_match.rs b/primitives/header-chain/tests/implementation_match.rs index 51275bbd6..39c388541 100644 --- a/primitives/header-chain/tests/implementation_match.rs +++ b/primitives/header-chain/tests/implementation_match.rs @@ -53,7 +53,7 @@ impl finality_grandpa::Chain for AncestryChain { let mut current_hash = block; loop { if current_hash == base { - break + break; } match self.0.parents.get(¤t_hash).cloned() { Some(parent_hash) => { diff --git a/primitives/messages/src/lib.rs b/primitives/messages/src/lib.rs index cef28ecb3..b4daf0a8e 100644 --- a/primitives/messages/src/lib.rs +++ b/primitives/messages/src/lib.rs @@ -169,10 +169,7 @@ impl InboundLaneData { /// Nonce of the last message that has been delivered to this (target) chain. pub fn last_delivered_nonce(&self) -> MessageNonce { - self.relayers - .back() - .map(|entry| entry.messages.end) - .unwrap_or(self.last_confirmed_nonce) + self.relayers.back().map(|entry| entry.messages.end).unwrap_or(self.last_confirmed_nonce) } } diff --git a/primitives/messages/src/source_chain.rs b/primitives/messages/src/source_chain.rs index fa7b3bb85..2f0c43790 100644 --- a/primitives/messages/src/source_chain.rs +++ b/primitives/messages/src/source_chain.rs @@ -245,7 +245,6 @@ const ALL_OUTBOUND_MESSAGES_REJECTED: &str = impl TargetHeaderChain for ForbidOutboundMessages { type Error = &'static str; - type MessagesDeliveryProof = (); fn verify_message(_payload: &Payload) -> Result<(), Self::Error> { diff --git a/primitives/polkadot-core/src/lib.rs b/primitives/polkadot-core/src/lib.rs index 8db1af2fd..d1114d4e4 100644 --- a/primitives/polkadot-core/src/lib.rs +++ b/primitives/polkadot-core/src/lib.rs @@ -338,23 +338,22 @@ where + StaticTypeInfo, Call: Dispatchable, { - const IDENTIFIER: &'static str = "Not needed."; - type AccountId = AccountId; - type Call = Call; type AdditionalSigned = AdditionalSigned; + type Call = Call; type Pre = (); + const IDENTIFIER: &'static str = "Not needed."; + fn additional_signed( &self, ) -> Result { // we shall not ever see this error in relay, because we are never signing decoded // transactions. Instead we're constructing and signing new transactions. So the error code // is kinda random here - self.additional_signed - .ok_or(frame_support::unsigned::TransactionValidityError::Unknown( - frame_support::unsigned::UnknownTransaction::Custom(0xFF), - )) + self.additional_signed.ok_or(frame_support::unsigned::TransactionValidityError::Unknown( + frame_support::unsigned::UnknownTransaction::Custom(0xFF), + )) } fn pre_dispatch( @@ -373,13 +372,12 @@ where pub struct PolkadotLike; impl Chain for PolkadotLike { + type AccountId = AccountId; + type Balance = Balance; type BlockNumber = BlockNumber; type Hash = Hash; type Hasher = Hasher; type Header = Header; - - type AccountId = AccountId; - type Balance = Balance; type Index = Index; type Signature = Signature; @@ -388,10 +386,7 @@ impl Chain for PolkadotLike { } fn max_extrinsic_weight() -> Weight { - BlockWeights::get() - .get(DispatchClass::Normal) - .max_extrinsic - .unwrap_or(Weight::MAX) + BlockWeights::get().get(DispatchClass::Normal).max_extrinsic.unwrap_or(Weight::MAX) } } diff --git a/primitives/runtime/src/storage_proof.rs b/primitives/runtime/src/storage_proof.rs index 4a99ab621..8e9c14481 100644 --- a/primitives/runtime/src/storage_proof.rs +++ b/primitives/runtime/src/storage_proof.rs @@ -42,7 +42,7 @@ where pub fn new(root: H::Out, proof: StorageProof) -> Result { let db = proof.into_memory_db(); if !db.contains(&root, EMPTY_PREFIX) { - return Err(Error::StorageRootMismatch) + return Err(Error::StorageRootMismatch); } let checker = StorageProofChecker { root, db }; @@ -86,9 +86,7 @@ pub fn craft_valid_storage_proof() -> (sp_core::H256, StorageProof) { )); let root = backend.storage_root(std::iter::empty(), state_version).0; let proof = StorageProof::new( - prove_read(backend, &[&b"key1"[..], &b"key2"[..], &b"key22"[..]]) - .unwrap() - .iter_nodes(), + prove_read(backend, &[&b"key1"[..], &b"key2"[..], &b"key22"[..]]).unwrap().iter_nodes(), ); (root, proof) diff --git a/relays/client-kusama/src/lib.rs b/relays/client-kusama/src/lib.rs index e228f2dc2..47da76924 100644 --- a/relays/client-kusama/src/lib.rs +++ b/relays/client-kusama/src/lib.rs @@ -37,13 +37,12 @@ pub type HeaderId = relay_utils::HeaderId = Some("kusama"); + type Call = crate::runtime::Call; + type SignedBlock = bp_kusama::SignedBlock; + type WeightToFee = bp_kusama::WeightToFee; + + const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6); const BEST_FINALIZED_HEADER_ID_METHOD: &'static str = bp_kusama::BEST_FINALIZED_KUSAMA_HEADER_METHOD; - const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6); - const STORAGE_PROOF_OVERHEAD: u32 = bp_kusama::EXTRA_STORAGE_PROOF_SIZE; const MAXIMAL_ENCODED_ACCOUNT_ID_SIZE: u32 = bp_kusama::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE; - - type SignedBlock = bp_kusama::SignedBlock; - type Call = crate::runtime::Call; - type WeightToFee = bp_kusama::WeightToFee; + const NAME: &'static str = "Kusama"; + const STORAGE_PROOF_OVERHEAD: u32 = bp_kusama::EXTRA_STORAGE_PROOF_SIZE; + const TOKEN_ID: Option<&'static str> = Some("kusama"); } impl ChainWithGrandpa for Kusama { @@ -75,17 +74,18 @@ impl ChainWithGrandpa for Kusama { } impl ChainWithMessages for Kusama { - const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str = - bp_kusama::WITH_KUSAMA_MESSAGES_PALLET_NAME; - const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str = - bp_kusama::TO_KUSAMA_MESSAGE_DETAILS_METHOD; - const PAY_INBOUND_DISPATCH_FEE_WEIGHT_AT_CHAIN: Weight = - bp_kusama::PAY_INBOUND_DISPATCH_FEE_WEIGHT; - const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = - bp_kusama::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; + type WeightInfo = (); + const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = bp_kusama::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; - type WeightInfo = (); + const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = + bp_kusama::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; + const PAY_INBOUND_DISPATCH_FEE_WEIGHT_AT_CHAIN: Weight = + bp_kusama::PAY_INBOUND_DISPATCH_FEE_WEIGHT; + const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str = + bp_kusama::TO_KUSAMA_MESSAGE_DETAILS_METHOD; + const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str = + bp_kusama::WITH_KUSAMA_MESSAGES_PALLET_NAME; } impl ChainWithBalances for Kusama { @@ -95,8 +95,8 @@ impl ChainWithBalances for Kusama { } impl TransactionSignScheme for Kusama { - type Chain = Kusama; type AccountKeyPair = sp_core::sr25519::Pair; + type Chain = Kusama; type SignedTransaction = crate::runtime::UncheckedExtrinsic; fn sign_transaction(param: SignParam) -> Result { diff --git a/relays/client-kusama/src/runtime.rs b/relays/client-kusama/src/runtime.rs index 59a919e6c..485ce1138 100644 --- a/relays/client-kusama/src/runtime.rs +++ b/relays/client-kusama/src/runtime.rs @@ -155,9 +155,9 @@ pub enum BridgePolkadotMessagesParameter { } impl sp_runtime::traits::Dispatchable for Call { - type Origin = (); type Config = (); type Info = (); + type Origin = (); type PostInfo = (); fn dispatch(self, _origin: Self::Origin) -> sp_runtime::DispatchResultWithInfo { diff --git a/relays/client-polkadot/src/lib.rs b/relays/client-polkadot/src/lib.rs index d4ada45e3..b18c5b3bb 100644 --- a/relays/client-polkadot/src/lib.rs +++ b/relays/client-polkadot/src/lib.rs @@ -37,13 +37,12 @@ pub type HeaderId = relay_utils::HeaderId = Some("polkadot"); + type Call = crate::runtime::Call; + type SignedBlock = bp_polkadot::SignedBlock; + type WeightToFee = bp_polkadot::WeightToFee; + + const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6); const BEST_FINALIZED_HEADER_ID_METHOD: &'static str = bp_polkadot::BEST_FINALIZED_POLKADOT_HEADER_METHOD; - const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6); - const STORAGE_PROOF_OVERHEAD: u32 = bp_polkadot::EXTRA_STORAGE_PROOF_SIZE; const MAXIMAL_ENCODED_ACCOUNT_ID_SIZE: u32 = bp_polkadot::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE; - - type SignedBlock = bp_polkadot::SignedBlock; - type Call = crate::runtime::Call; - type WeightToFee = bp_polkadot::WeightToFee; + const NAME: &'static str = "Polkadot"; + const STORAGE_PROOF_OVERHEAD: u32 = bp_polkadot::EXTRA_STORAGE_PROOF_SIZE; + const TOKEN_ID: Option<&'static str> = Some("polkadot"); } impl ChainWithGrandpa for Polkadot { @@ -76,17 +75,18 @@ impl ChainWithGrandpa for Polkadot { } impl ChainWithMessages for Polkadot { - const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str = - bp_polkadot::WITH_POLKADOT_MESSAGES_PALLET_NAME; - const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str = - bp_polkadot::TO_POLKADOT_MESSAGE_DETAILS_METHOD; - const PAY_INBOUND_DISPATCH_FEE_WEIGHT_AT_CHAIN: Weight = - bp_polkadot::PAY_INBOUND_DISPATCH_FEE_WEIGHT; - const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = - bp_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; + type WeightInfo = (); + const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = bp_polkadot::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; - type WeightInfo = (); + const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = + bp_polkadot::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; + const PAY_INBOUND_DISPATCH_FEE_WEIGHT_AT_CHAIN: Weight = + bp_polkadot::PAY_INBOUND_DISPATCH_FEE_WEIGHT; + const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str = + bp_polkadot::TO_POLKADOT_MESSAGE_DETAILS_METHOD; + const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str = + bp_polkadot::WITH_POLKADOT_MESSAGES_PALLET_NAME; } impl ChainWithBalances for Polkadot { @@ -96,8 +96,8 @@ impl ChainWithBalances for Polkadot { } impl TransactionSignScheme for Polkadot { - type Chain = Polkadot; type AccountKeyPair = sp_core::sr25519::Pair; + type Chain = Polkadot; type SignedTransaction = crate::runtime::UncheckedExtrinsic; fn sign_transaction(param: SignParam) -> Result { diff --git a/relays/client-polkadot/src/runtime.rs b/relays/client-polkadot/src/runtime.rs index fa45115a6..613f55c21 100644 --- a/relays/client-polkadot/src/runtime.rs +++ b/relays/client-polkadot/src/runtime.rs @@ -155,9 +155,9 @@ pub enum BridgeKusamaMessagesParameter { } impl sp_runtime::traits::Dispatchable for Call { - type Origin = (); type Config = (); type Info = (); + type Origin = (); type PostInfo = (); fn dispatch(self, _origin: Self::Origin) -> sp_runtime::DispatchResultWithInfo { diff --git a/relays/client-rococo/src/lib.rs b/relays/client-rococo/src/lib.rs index f63041df9..4380621c2 100644 --- a/relays/client-rococo/src/lib.rs +++ b/relays/client-rococo/src/lib.rs @@ -40,13 +40,12 @@ pub type SyncHeader = relay_substrate_client::SyncHeader; pub struct Rococo; impl ChainBase for Rococo { + type AccountId = bp_rococo::AccountId; + type Balance = bp_rococo::Balance; type BlockNumber = bp_rococo::BlockNumber; type Hash = bp_rococo::Hash; type Hasher = bp_rococo::Hashing; type Header = bp_rococo::Header; - - type AccountId = bp_rococo::AccountId; - type Balance = bp_rococo::Balance; type Index = bp_rococo::Nonce; type Signature = bp_rococo::Signature; @@ -60,17 +59,17 @@ impl ChainBase for Rococo { } impl Chain for Rococo { - const NAME: &'static str = "Rococo"; - const TOKEN_ID: Option<&'static str> = None; + type Call = crate::runtime::Call; + type SignedBlock = bp_rococo::SignedBlock; + type WeightToFee = bp_rococo::WeightToFee; + + const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6); const BEST_FINALIZED_HEADER_ID_METHOD: &'static str = bp_rococo::BEST_FINALIZED_ROCOCO_HEADER_METHOD; - const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(6); - const STORAGE_PROOF_OVERHEAD: u32 = bp_rococo::EXTRA_STORAGE_PROOF_SIZE; const MAXIMAL_ENCODED_ACCOUNT_ID_SIZE: u32 = bp_rococo::MAXIMAL_ENCODED_ACCOUNT_ID_SIZE; - - type SignedBlock = bp_rococo::SignedBlock; - type Call = crate::runtime::Call; - type WeightToFee = bp_rococo::WeightToFee; + const NAME: &'static str = "Rococo"; + const STORAGE_PROOF_OVERHEAD: u32 = bp_rococo::EXTRA_STORAGE_PROOF_SIZE; + const TOKEN_ID: Option<&'static str> = None; } impl ChainWithGrandpa for Rococo { @@ -78,17 +77,18 @@ impl ChainWithGrandpa for Rococo { } impl ChainWithMessages for Rococo { - const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str = - bp_rococo::WITH_ROCOCO_MESSAGES_PALLET_NAME; - const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str = - bp_rococo::TO_ROCOCO_MESSAGE_DETAILS_METHOD; - const PAY_INBOUND_DISPATCH_FEE_WEIGHT_AT_CHAIN: Weight = - bp_rococo::PAY_INBOUND_DISPATCH_FEE_WEIGHT; - const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = - bp_rococo::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; + type WeightInfo = (); + const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = bp_rococo::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; - type WeightInfo = (); + const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = + bp_rococo::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; + const PAY_INBOUND_DISPATCH_FEE_WEIGHT_AT_CHAIN: Weight = + bp_rococo::PAY_INBOUND_DISPATCH_FEE_WEIGHT; + const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str = + bp_rococo::TO_ROCOCO_MESSAGE_DETAILS_METHOD; + const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str = + bp_rococo::WITH_ROCOCO_MESSAGES_PALLET_NAME; } impl ChainWithBalances for Rococo { @@ -98,8 +98,8 @@ impl ChainWithBalances for Rococo { } impl TransactionSignScheme for Rococo { - type Chain = Rococo; type AccountKeyPair = sp_core::sr25519::Pair; + type Chain = Rococo; type SignedTransaction = crate::runtime::UncheckedExtrinsic; fn sign_transaction(param: SignParam) -> Result { diff --git a/relays/client-rococo/src/runtime.rs b/relays/client-rococo/src/runtime.rs index b13808059..b3fb90fe0 100644 --- a/relays/client-rococo/src/runtime.rs +++ b/relays/client-rococo/src/runtime.rs @@ -134,9 +134,9 @@ pub enum BridgeWococoMessagesCall { } impl sp_runtime::traits::Dispatchable for Call { - type Origin = (); type Config = (); type Info = (); + type Origin = (); type PostInfo = (); fn dispatch(self, _origin: Self::Origin) -> sp_runtime::DispatchResultWithInfo { diff --git a/relays/client-substrate/src/chain.rs b/relays/client-substrate/src/chain.rs index 60adfb0a8..57732bbd7 100644 --- a/relays/client-substrate/src/chain.rs +++ b/relays/client-substrate/src/chain.rs @@ -212,8 +212,6 @@ impl BlockWithJustification for SignedBlock } fn justification(&self) -> Option<&EncodedJustification> { - self.justifications - .as_ref() - .and_then(|j| j.get(sp_finality_grandpa::GRANDPA_ENGINE_ID)) + self.justifications.as_ref().and_then(|j| j.get(sp_finality_grandpa::GRANDPA_ENGINE_ID)) } } diff --git a/relays/client-substrate/src/client.rs b/relays/client-substrate/src/client.rs index 1e48bc333..8179492cf 100644 --- a/relays/client-substrate/src/client.rs +++ b/relays/client-substrate/src/client.rs @@ -758,7 +758,7 @@ impl Subscription { match subscription.next().await { Some(Ok(item)) => if sender.send(Some(item)).await.is_err() { - break + break; }, Some(Err(e)) => { log::trace!( @@ -769,7 +769,7 @@ impl Subscription { e, ); let _ = sender.send(None).await; - break + break; }, None => { log::trace!( @@ -779,7 +779,7 @@ impl Subscription { item_type, ); let _ = sender.send(None).await; - break + break; }, } } diff --git a/relays/client-substrate/src/guard.rs b/relays/client-substrate/src/guard.rs index 359a3f69d..e1f9b0d31 100644 --- a/relays/client-substrate/src/guard.rs +++ b/relays/client-substrate/src/guard.rs @@ -208,37 +208,37 @@ mod tests { struct TestChain; impl bp_runtime::Chain for TestChain { + type AccountId = u32; + type Balance = u32; type BlockNumber = u32; type Hash = sp_core::H256; type Hasher = sp_runtime::traits::BlakeTwo256; type Header = sp_runtime::generic::Header; - - type AccountId = u32; - type Balance = u32; type Index = u32; type Signature = sp_runtime::testing::TestSignature; fn max_extrinsic_size() -> u32 { unreachable!() } + fn max_extrinsic_weight() -> Weight { unreachable!() } } impl Chain for TestChain { - const NAME: &'static str = "Test"; - const TOKEN_ID: Option<&'static str> = None; - const BEST_FINALIZED_HEADER_ID_METHOD: &'static str = "BestTestHeader"; - const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_millis(1); - const STORAGE_PROOF_OVERHEAD: u32 = 0; - const MAXIMAL_ENCODED_ACCOUNT_ID_SIZE: u32 = 0; - + type Call = (); type SignedBlock = sp_runtime::generic::SignedBlock< sp_runtime::generic::Block, >; - type Call = (); type WeightToFee = IdentityFee; + + const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_millis(1); + const BEST_FINALIZED_HEADER_ID_METHOD: &'static str = "BestTestHeader"; + const MAXIMAL_ENCODED_ACCOUNT_ID_SIZE: u32 = 0; + const NAME: &'static str = "Test"; + const STORAGE_PROOF_OVERHEAD: u32 = 0; + const TOKEN_ID: Option<&'static str> = None; } impl ChainWithBalances for TestChain { diff --git a/relays/client-substrate/src/metrics/float_storage_value.rs b/relays/client-substrate/src/metrics/float_storage_value.rs index 7bb92693b..7b5c56e1e 100644 --- a/relays/client-substrate/src/metrics/float_storage_value.rs +++ b/relays/client-substrate/src/metrics/float_storage_value.rs @@ -121,8 +121,8 @@ impl StandaloneMetric for FloatStorageValueMetri .and_then(|maybe_storage_value| { self.value_converter.decode(maybe_storage_value).map(|maybe_fixed_point_value| { maybe_fixed_point_value.map(|fixed_point_value| { - fixed_point_value.into_inner().unique_saturated_into() as f64 / - V::Value::DIV.unique_saturated_into() as f64 + fixed_point_value.into_inner().unique_saturated_into() as f64 + / V::Value::DIV.unique_saturated_into() as f64 }) }) }) diff --git a/relays/client-substrate/src/metrics/storage_proof_overhead.rs b/relays/client-substrate/src/metrics/storage_proof_overhead.rs index f1c770ed2..ec3f7ffa0 100644 --- a/relays/client-substrate/src/metrics/storage_proof_overhead.rs +++ b/relays/client-substrate/src/metrics/storage_proof_overhead.rs @@ -58,10 +58,8 @@ impl StorageProofOverheadMetric { let best_header_hash = self.client.best_finalized_header_hash().await?; let best_header = self.client.header_by_hash(best_header_hash).await?; - let storage_proof = self - .client - .prove_storage(vec![StorageKey(CODE.to_vec())], best_header_hash) - .await?; + let storage_proof = + self.client.prove_storage(vec![StorageKey(CODE.to_vec())], best_header_hash).await?; let storage_proof_size: usize = storage_proof.clone().iter_nodes().map(|n| n.len()).sum(); let storage_value_reader = bp_runtime::StorageProofChecker::::new( @@ -93,9 +91,7 @@ impl StandaloneMetric for StorageProofOverheadMetric { async fn update(&self) { relay_utils::metrics::set_gauge_value( &self.metric, - self.compute_storage_proof_overhead() - .await - .map(|overhead| Some(overhead as u64)), + self.compute_storage_proof_overhead().await.map(|overhead| Some(overhead as u64)), ); } } diff --git a/relays/finality/src/finality_loop.rs b/relays/finality/src/finality_loop.rs index c29a5d5fe..c1ba3410d 100644 --- a/relays/finality/src/finality_loop.rs +++ b/relays/finality/src/finality_loop.rs @@ -306,9 +306,8 @@ where target_client.best_finalized_source_block_id().await.map_err(Error::Target)?; let best_number_at_target = best_id_at_target.0; - let different_hash_at_source = ensure_same_fork::(&best_id_at_target, source_client) - .await - .map_err(Error::Source)?; + let different_hash_at_source = + ensure_same_fork::(&best_id_at_target, source_client).await.map_err(Error::Source)?; let using_same_fork = different_hash_at_source.is_none(); if let Some(ref different_hash_at_source) = different_hash_at_source { log::error!( @@ -344,9 +343,9 @@ where P::TARGET_NAME, ); - return Err(Error::Stalled) + return Err(Error::Stalled); } else { - return Ok(Some(last_transaction)) + return Ok(Some(last_transaction)); } } @@ -421,7 +420,7 @@ where _ if sync_params.only_mandatory_headers => { // we are not reading finality proofs from the stream, so eventually it'll break // but we don't care about transient proofs at all, so it is acceptable - return Ok(None) + return Ok(None); }, SelectedFinalityProof::Regular(unjustified_headers, header, finality_proof) => (unjustified_headers, Some((header, finality_proof))), @@ -499,16 +498,14 @@ pub(crate) async fn read_missing_headers< let mut selected_finality_proof = None; let mut header_number = best_number_at_target + One::one(); while header_number <= best_number_at_source { - let (header, finality_proof) = source_client - .header_and_finality_proof(header_number) - .await - .map_err(Error::Source)?; + let (header, finality_proof) = + source_client.header_and_finality_proof(header_number).await.map_err(Error::Source)?; let is_mandatory = header.is_mandatory(); match (is_mandatory, finality_proof) { (true, Some(finality_proof)) => { log::trace!(target: "bridge", "Header {:?} is mandatory", header_number); - return Ok(SelectedFinalityProof::Mandatory(header, finality_proof)) + return Ok(SelectedFinalityProof::Mandatory(header, finality_proof)); }, (true, None) => return Err(Error::MissingMandatoryFinalityProof(header.number())), (false, Some(finality_proof)) => { @@ -555,7 +552,7 @@ pub(crate) fn read_finality_proofs_from_stream< Some(Some(finality_proof)) => finality_proof, Some(None) => { finality_proofs_stream.needs_restart = true; - break + break; }, None => break, }; @@ -596,7 +593,7 @@ pub(crate) fn select_better_recent_finality_proof( P::SOURCE_NAME, selected_finality_proof.as_ref().map(|(h, _)| h.number()), ); - return selected_finality_proof + return selected_finality_proof; } const NOT_EMPTY_PROOF: &str = "we have checked that the vec is not empty; qed"; @@ -635,7 +632,7 @@ pub(crate) fn select_better_recent_finality_proof( if has_selected_finality_proof { "improved" } else { "not improved" }, ); if !has_selected_finality_proof { - return selected_finality_proof + return selected_finality_proof; } // now remove all obsolete headers and extract selected header @@ -671,15 +668,15 @@ fn print_sync_progress( let (prev_time, prev_best_number_at_target) = progress_context; let now = Instant::now(); - let need_update = now - prev_time > Duration::from_secs(10) || - prev_best_number_at_target + let need_update = now - prev_time > Duration::from_secs(10) + || prev_best_number_at_target .map(|prev_best_number_at_target| { best_number_at_target.saturating_sub(prev_best_number_at_target) > 10.into() }) .unwrap_or(true); if !need_update { - return (prev_time, prev_best_number_at_target) + return (prev_time, prev_best_number_at_target); } log::info!( diff --git a/relays/finality/src/finality_loop_tests.rs b/relays/finality/src/finality_loop_tests.rs index 478d8e1be..2c2ae2bc4 100644 --- a/relays/finality/src/finality_loop_tests.rs +++ b/relays/finality/src/finality_loop_tests.rs @@ -61,13 +61,13 @@ impl MaybeConnectionError for TestError { struct TestFinalitySyncPipeline; impl FinalitySyncPipeline for TestFinalitySyncPipeline { - const SOURCE_NAME: &'static str = "TestSource"; - const TARGET_NAME: &'static str = "TestTarget"; - + type FinalityProof = TestFinalityProof; type Hash = TestHash; - type Number = TestNumber; type Header = TestSourceHeader; - type FinalityProof = TestFinalityProof; + type Number = TestNumber; + + const SOURCE_NAME: &'static str = "TestSource"; + const TARGET_NAME: &'static str = "TestTarget"; } #[derive(Debug, Clone, PartialEq)] @@ -448,9 +448,8 @@ fn read_finality_proofs_from_stream_works() { assert!(!stream.needs_restart); // when stream has entry with target, it is added to the recent proofs container - let mut stream = futures::stream::iter(vec![TestFinalityProof(4)]) - .chain(futures::stream::pending()) - .into(); + let mut stream = + futures::stream::iter(vec![TestFinalityProof(4)]).chain(futures::stream::pending()).into(); read_finality_proofs_from_stream::( &mut stream, &mut recent_finality_proofs, diff --git a/relays/messages/src/message_lane_loop.rs b/relays/messages/src/message_lane_loop.rs index c1778d5d1..5764be3fb 100644 --- a/relays/messages/src/message_lane_loop.rs +++ b/relays/messages/src/message_lane_loop.rs @@ -500,18 +500,16 @@ pub(crate) mod tests { pub struct TestMessageLane; impl MessageLane for TestMessageLane { - const SOURCE_NAME: &'static str = "TestSource"; - const TARGET_NAME: &'static str = "TestTarget"; - type MessagesProof = TestMessagesProof; type MessagesReceivingProof = TestMessagesReceivingProof; - type SourceChainBalance = TestSourceChainBalance; - type SourceHeaderNumber = TestSourceHeaderNumber; type SourceHeaderHash = TestSourceHeaderHash; - - type TargetHeaderNumber = TestTargetHeaderNumber; + type SourceHeaderNumber = TestSourceHeaderNumber; type TargetHeaderHash = TestTargetHeaderHash; + type TargetHeaderNumber = TestTargetHeaderNumber; + + const SOURCE_NAME: &'static str = "TestSource"; + const TARGET_NAME: &'static str = "TestTarget"; } #[derive(Debug, Default, Clone)] @@ -569,7 +567,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_source_fails { - return Err(TestError) + return Err(TestError); } Ok(data.source_state.clone()) } @@ -581,7 +579,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_source_fails { - return Err(TestError) + return Err(TestError); } Ok((id, data.source_latest_generated_nonce)) } @@ -702,7 +700,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_target_fails { - return Err(TestError) + return Err(TestError); } Ok(data.target_state.clone()) } @@ -714,7 +712,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_target_fails { - return Err(TestError) + return Err(TestError); } Ok((id, data.target_latest_received_nonce)) } @@ -740,7 +738,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_target_fails { - return Err(TestError) + return Err(TestError); } Ok((id, data.target_latest_confirmed_received_nonce)) } @@ -761,7 +759,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_target_fails { - return Err(TestError) + return Err(TestError); } data.target_state.best_self = HeaderId(data.target_state.best_self.0 + 1, data.target_state.best_self.1 + 1); @@ -789,9 +787,9 @@ pub(crate) mod tests { total_dispatch_weight: Weight, total_size: u32, ) -> Result { - Ok(BASE_MESSAGE_DELIVERY_TRANSACTION_COST * (nonces.end() - nonces.start() + 1) + - total_dispatch_weight + - total_size as TestSourceChainBalance) + Ok(BASE_MESSAGE_DELIVERY_TRANSACTION_COST * (nonces.end() - nonces.start() + 1) + + total_dispatch_weight + + total_size as TestSourceChainBalance) } } @@ -913,8 +911,8 @@ pub(crate) mod tests { // headers relay must only be started when we need new target headers at source node if data.target_to_source_header_required.is_some() { assert!( - data.source_state.best_finalized_peer_at_best_self.0 < - data.target_state.best_self.0 + data.source_state.best_finalized_peer_at_best_self.0 + < data.target_state.best_self.0 ); data.target_to_source_header_required = None; } @@ -933,8 +931,8 @@ pub(crate) mod tests { // headers relay must only be started when we need new source headers at target node if data.source_to_target_header_required.is_some() { assert!( - data.target_state.best_finalized_peer_at_best_self.0 < - data.source_state.best_self.0 + data.target_state.best_finalized_peer_at_best_self.0 + < data.source_state.best_self.0 ); data.source_to_target_header_required = None; } diff --git a/relays/messages/src/message_race_delivery.rs b/relays/messages/src/message_race_delivery.rs index dc994364f..896e37075 100644 --- a/relays/messages/src/message_race_delivery.rs +++ b/relays/messages/src/message_race_delivery.rs @@ -83,11 +83,10 @@ pub async fn run( struct MessageDeliveryRace

(std::marker::PhantomData

); impl MessageRace for MessageDeliveryRace

{ - type SourceHeaderId = SourceHeaderIdOf

; - type TargetHeaderId = TargetHeaderIdOf

; - type MessageNonce = MessageNonce; type Proof = P::MessagesProof; + type SourceHeaderId = SourceHeaderIdOf

; + type TargetHeaderId = TargetHeaderIdOf

; fn source_name() -> String { format!("{}::MessagesDelivery", P::SOURCE_NAME) @@ -306,8 +305,8 @@ where SC: MessageLaneSourceClient

, TC: MessageLaneTargetClient

, { - type SourceNoncesRange = MessageDetailsMap; type ProofParameters = MessageProofParameters; + type SourceNoncesRange = MessageDetailsMap; type TargetNoncesData = DeliveryRaceTargetNoncesData; fn is_empty(&self) -> bool { @@ -442,7 +441,7 @@ where self.max_unconfirmed_nonces_at_target, ); - return None + return None; }, _ => (), } @@ -462,8 +461,8 @@ where // "unrewarded relayers" set. If we are unable to prove new rewards to the target node, then // we should wait for confirmations race. let unrewarded_relayer_entries_limit_reached = - target_nonces.nonces_data.unrewarded_relayers.unrewarded_relayer_entries >= - self.max_unrewarded_relayer_entries_at_target; + target_nonces.nonces_data.unrewarded_relayers.unrewarded_relayer_entries + >= self.max_unrewarded_relayer_entries_at_target; if unrewarded_relayer_entries_limit_reached { // so there are already too many unrewarded relayer entries in the set // @@ -471,10 +470,10 @@ where // be paid let number_of_rewards_being_proved = latest_confirmed_nonce_at_source.saturating_sub(latest_confirmed_nonce_at_target); - let enough_rewards_being_proved = number_of_rewards_being_proved >= - target_nonces.nonces_data.unrewarded_relayers.messages_in_oldest_entry; + let enough_rewards_being_proved = number_of_rewards_being_proved + >= target_nonces.nonces_data.unrewarded_relayers.messages_in_oldest_entry; if !enough_rewards_being_proved { - return None + return None; } } @@ -577,10 +576,10 @@ mod tests { const DEFAULT_DISPATCH_WEIGHT: Weight = 1; const DEFAULT_SIZE: u32 = 1; - const DEFAULT_REWARD: TestSourceChainBalance = CONFIRMATION_TRANSACTION_COST + - BASE_MESSAGE_DELIVERY_TRANSACTION_COST + - DEFAULT_DISPATCH_WEIGHT + - (DEFAULT_SIZE as TestSourceChainBalance); + const DEFAULT_REWARD: TestSourceChainBalance = CONFIRMATION_TRANSACTION_COST + + BASE_MESSAGE_DELIVERY_TRANSACTION_COST + + DEFAULT_DISPATCH_WEIGHT + + (DEFAULT_SIZE as TestSourceChainBalance); type TestRaceState = RaceState; type TestStrategy = @@ -652,12 +651,8 @@ mod tests { ); let target_nonces = TargetClientNonces { latest_nonce: 19, nonces_data: () }; - race_strategy - .strategy - .best_target_nonces_updated(target_nonces.clone(), &mut race_state); - race_strategy - .strategy - .finalized_target_nonces_updated(target_nonces, &mut race_state); + race_strategy.strategy.best_target_nonces_updated(target_nonces.clone(), &mut race_state); + race_strategy.strategy.finalized_target_nonces_updated(target_nonces, &mut race_state); (race_state, race_strategy) } @@ -720,8 +715,8 @@ mod tests { // we need to wait until confirmations will be delivered by receiving race strategy.latest_confirmed_nonces_at_source = vec![( header_id(1), - strategy.target_nonces.as_ref().unwrap().latest_nonce - - strategy.max_unconfirmed_nonces_at_target, + strategy.target_nonces.as_ref().unwrap().latest_nonce + - strategy.max_unconfirmed_nonces_at_target, )] .into_iter() .collect(); diff --git a/relays/messages/src/message_race_loop.rs b/relays/messages/src/message_race_loop.rs index a7254f70e..314008daa 100644 --- a/relays/messages/src/message_race_loop.rs +++ b/relays/messages/src/message_race_loop.rs @@ -439,10 +439,10 @@ pub async fn run, TC: TargetClient

>( strategy, ); - return Err(FailedClient::Both) - } else if race_state.nonces_to_submit.is_none() && - race_state.nonces_submitted.is_none() && - strategy.is_empty() + return Err(FailedClient::Both); + } else if race_state.nonces_to_submit.is_none() + && race_state.nonces_submitted.is_none() + && strategy.is_empty() { stall_countdown = Instant::now(); } @@ -551,7 +551,7 @@ where let need_update = now_time.saturating_duration_since(prev_time) > Duration::from_secs(10); if !need_update { - return prev_time + return prev_time; } let now_best_nonce_at_source = strategy.best_at_source(); @@ -577,12 +577,9 @@ where { let best_finalized_source_header_id_at_best_target = race_state.best_finalized_source_header_id_at_best_target.clone()?; - strategy - .select_nonces_to_deliver(race_state) - .await - .map(|(nonces_range, proof_parameters)| { - (best_finalized_source_header_id_at_best_target, nonces_range, proof_parameters) - }) + strategy.select_nonces_to_deliver(race_state).await.map(|(nonces_range, proof_parameters)| { + (best_finalized_source_header_id_at_best_target, nonces_range, proof_parameters) + }) } #[cfg(test)] diff --git a/relays/messages/src/message_race_receiving.rs b/relays/messages/src/message_race_receiving.rs index 5aa36cbd9..a23add589 100644 --- a/relays/messages/src/message_race_receiving.rs +++ b/relays/messages/src/message_race_receiving.rs @@ -75,11 +75,10 @@ pub async fn run( struct ReceivingConfirmationsRace

(std::marker::PhantomData

); impl MessageRace for ReceivingConfirmationsRace

{ - type SourceHeaderId = TargetHeaderIdOf

; - type TargetHeaderId = SourceHeaderIdOf

; - type MessageNonce = MessageNonce; type Proof = P::MessagesReceivingProof; + type SourceHeaderId = TargetHeaderIdOf

; + type TargetHeaderId = SourceHeaderIdOf

; fn source_name() -> String { format!("{}::ReceivingConfirmationsDelivery", P::TARGET_NAME) diff --git a/relays/messages/src/message_race_strategy.rs b/relays/messages/src/message_race_strategy.rs index 9b9091b97..b660c5f11 100644 --- a/relays/messages/src/message_race_strategy.rs +++ b/relays/messages/src/message_race_strategy.rs @@ -111,12 +111,12 @@ impl< // if we have already selected nonces that we want to submit, do nothing if race_state.nonces_to_submit.is_some() { - return None + return None; } // if we already submitted some nonces, do nothing if race_state.nonces_submitted.is_some() { - return None + return None; } // 1) we want to deliver all nonces, starting from `target_nonce + 1` @@ -140,7 +140,7 @@ impl< while let Some((queued_at, queued_range)) = self.source_queue.pop_front() { if let Some(range_to_requeue) = queued_range.greater_than(nonce) { self.source_queue.push_front((queued_at, range_to_requeue)); - break + break; } } } @@ -175,8 +175,8 @@ impl< TargetHeaderNumber: Debug + Send, Proof: Debug + Send, { - type SourceNoncesRange = SourceNoncesRange; type ProofParameters = (); + type SourceNoncesRange = SourceNoncesRange; type TargetNoncesData = (); fn is_empty(&self) -> bool { @@ -239,7 +239,7 @@ impl< if let Some(best_target_nonce) = self.best_target_nonce { if nonce < best_target_nonce { - return + return; } } @@ -249,7 +249,7 @@ impl< }); if let Some((at_block, subrange)) = maybe_subrange { self.source_queue.push_front((at_block, subrange)); - break + break; } } diff --git a/relays/messages/src/metrics.rs b/relays/messages/src/metrics.rs index 4decb7e09..db300b477 100644 --- a/relays/messages/src/metrics.rs +++ b/relays/messages/src/metrics.rs @@ -70,8 +70,8 @@ impl MessageLaneLoopMetrics { source_client_state.best_finalized_peer_at_best_self.0.into(), ); self.target_to_source_finality_metrics.update_using_same_fork( - source_client_state.best_finalized_peer_at_best_self.1 == - source_client_state.actual_best_finalized_peer_at_best_self.1, + source_client_state.best_finalized_peer_at_best_self.1 + == source_client_state.actual_best_finalized_peer_at_best_self.1, ); } @@ -83,8 +83,8 @@ impl MessageLaneLoopMetrics { target_client_state.best_finalized_peer_at_best_self.0.into(), ); self.source_to_target_finality_metrics.update_using_same_fork( - target_client_state.best_finalized_peer_at_best_self.1 == - target_client_state.actual_best_finalized_peer_at_best_self.1, + target_client_state.best_finalized_peer_at_best_self.1 + == target_client_state.actual_best_finalized_peer_at_best_self.1, ); } diff --git a/relays/messages/src/relay_strategy/enforcement_strategy.rs b/relays/messages/src/relay_strategy/enforcement_strategy.rs index 1e9ef5bdb..def6665be 100644 --- a/relays/messages/src/relay_strategy/enforcement_strategy.rs +++ b/relays/messages/src/relay_strategy/enforcement_strategy.rs @@ -142,7 +142,7 @@ impl EnforcementStrategy { // limit number of messages in the batch let new_selected_count = selected_count + 1; if new_selected_count > reference.max_messages_in_this_batch { - break + break; } relay_reference.selected_size = new_selected_size; @@ -197,8 +197,8 @@ impl EnforcementStrategy { } if hard_selected_count != 0 { - if relay_reference.selected_reward != P::SourceChainBalance::zero() && - relay_reference.selected_cost != P::SourceChainBalance::zero() + if relay_reference.selected_reward != P::SourceChainBalance::zero() + && relay_reference.selected_cost != P::SourceChainBalance::zero() { log::trace!( target: "bridge", diff --git a/relays/messages/src/relay_strategy/rational_strategy.rs b/relays/messages/src/relay_strategy/rational_strategy.rs index fd0a1ffaf..ea4f39d0a 100644 --- a/relays/messages/src/relay_strategy/rational_strategy.rs +++ b/relays/messages/src/relay_strategy/rational_strategy.rs @@ -54,8 +54,8 @@ impl RelayStrategy for RationalStrategy { let delivery_transaction_cost = match reference .lane_target_client .estimate_delivery_transaction_in_source_tokens( - reference.hard_selected_begin_nonce..= - (reference.hard_selected_begin_nonce + reference.index as MessageNonce), + reference.hard_selected_begin_nonce + ..=(reference.hard_selected_begin_nonce + reference.index as MessageNonce), reference.selected_prepaid_nonces, reference.selected_unpaid_weight, reference.selected_size as u32, @@ -69,7 +69,7 @@ impl RelayStrategy for RationalStrategy { "Failed to estimate delivery transaction cost: {:?}. No nonces selected for delivery", err, ); - return false + return false; }, }; @@ -78,9 +78,8 @@ impl RelayStrategy for RationalStrategy { let is_total_reward_less_than_cost = reference.total_reward < reference.total_cost; let prev_total_cost = reference.total_cost; let prev_total_reward = reference.total_reward; - reference.total_confirmations_cost = reference - .total_confirmations_cost - .saturating_add(&confirmation_transaction_cost); + reference.total_confirmations_cost = + reference.total_confirmations_cost.saturating_add(&confirmation_transaction_cost); reference.total_reward = reference.total_reward.saturating_add(&reference.details.reward); reference.total_cost = reference.total_confirmations_cost.saturating_add(&delivery_transaction_cost); @@ -114,7 +113,7 @@ impl RelayStrategy for RationalStrategy { if reference.total_reward >= reference.total_cost { reference.selected_reward = reference.total_reward; reference.selected_cost = reference.total_cost; - return true + return true; } false diff --git a/relays/utils/src/metrics/float_json_value.rs b/relays/utils/src/metrics/float_json_value.rs index 7535cbef9..569acc429 100644 --- a/relays/utils/src/metrics/float_json_value.rs +++ b/relays/utils/src/metrics/float_json_value.rs @@ -112,7 +112,7 @@ fn parse_service_response(json_path: &str, response: &str) -> error::Result .and_then(|v| v.as_f64()) .ok_or_else(|| Error::MissingResponseValue(response.to_owned()))?; if !selected_value.is_normal() || selected_value < 0.0 { - return Err(Error::ParseFloat(selected_value)) + return Err(Error::ParseFloat(selected_value)); } Ok(selected_value) diff --git a/relays/utils/src/relay_loop.rs b/relays/utils/src/relay_loop.rs index 521a6345d..bf2ea2e45 100644 --- a/relays/utils/src/relay_loop.rs +++ b/relays/utils/src/relay_loop.rs @@ -196,7 +196,7 @@ impl LoopMetrics { "Failed to create tokio runtime. Prometheus meterics are not available: {:?}", err, ); - return + return; }, }; @@ -244,7 +244,7 @@ pub async fn reconnect_failed_client( reconnect_delay.as_secs(), error, ); - continue + continue; }, } } @@ -258,11 +258,11 @@ pub async fn reconnect_failed_client( reconnect_delay.as_secs(), error, ); - continue + continue; }, } } - break + break; } } diff --git a/rustfmt.toml b/rustfmt.toml index 082150daf..cb425c63b 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,24 +1,27 @@ # Basic -hard_tabs = true -max_width = 100 -use_small_heuristics = "Max" +edition = "2021" +hard_tabs = true +max_width = 100 +tab_spaces = 4 # Imports imports_granularity = "Crate" -reorder_imports = true -# Consistency -newline_style = "Unix" +reorder_imports = true # Format comments comment_width = 100 wrap_comments = true + # Misc -chain_width = 80 -spaces_around_ranges = false -binop_separator = "Back" -reorder_impl_items = false -match_arm_leading_pipes = "Preserve" -match_arm_blocks = false +match_arm_blocks = false match_block_trailing_comma = true -trailing_comma = "Vertical" -trailing_semicolon = false -use_field_init_shorthand = true +newline_style = "Unix" +reorder_impl_items = true +reorder_modules = true +use_field_init_shorthand = true +use_small_heuristics = "Max" + +# Wait for stablization +# format_code_in_doc_comments = true +# Could give it a try +# group_imports = "StdExternalCrate" +# inline_attribute_width = 100 \ No newline at end of file