From ecc712d68cb7865d85b945fd15ee031cd83d896c Mon Sep 17 00:00:00 2001 From: Svyatoslav Nikolsky Date: Fri, 8 Oct 2021 12:35:11 +0300 Subject: [PATCH] Token swap pallet benchmarks (#1174) * token swap benchmarks * spellcheck --- bridges/bin/millau/node/Cargo.toml | 5 +- bridges/bin/millau/runtime/Cargo.toml | 11 +- bridges/bin/millau/runtime/src/lib.rs | 65 ++++++ bridges/modules/grandpa/src/weights.rs | 6 +- bridges/modules/messages/src/lib.rs | 31 +-- bridges/modules/messages/src/weights.rs | 6 +- bridges/modules/token-swap/Cargo.toml | 6 + .../modules/token-swap/src/benchmarking.rs | 188 ++++++++++++++++++ bridges/modules/token-swap/src/lib.rs | 50 +++-- bridges/modules/token-swap/src/mock.rs | 10 +- bridges/modules/token-swap/src/weights.rs | 93 +++++++++ bridges/modules/token-swap/src/weights_ext.rs | 42 ++++ .../primitives/messages/src/source_chain.rs | 30 ++- bridges/primitives/runtime/src/lib.rs | 6 + 14 files changed, 500 insertions(+), 49 deletions(-) create mode 100644 bridges/modules/token-swap/src/benchmarking.rs create mode 100644 bridges/modules/token-swap/src/weights.rs create mode 100644 bridges/modules/token-swap/src/weights_ext.rs diff --git a/bridges/bin/millau/node/Cargo.toml b/bridges/bin/millau/node/Cargo.toml index 3307d6031dd49..b650bd478a62b 100644 --- a/bridges/bin/millau/node/Cargo.toml +++ b/bridges/bin/millau/node/Cargo.toml @@ -54,9 +54,6 @@ frame-benchmarking-cli = { git = "https://github.com/paritytech/substrate", bran [features] default = [] - -# TODO: https://github.com/paritytech/parity-bridges-common/issues/390 -# I've left the feature flag here to test our CI configuration runtime-benchmarks = [ - # "millau-runtime/runtime-benchmarks", + "millau-runtime/runtime-benchmarks", ] diff --git a/bridges/bin/millau/runtime/Cargo.toml b/bridges/bin/millau/runtime/Cargo.toml index 68d10168e4b6e..7e2a5491f5b15 100644 --- a/bridges/bin/millau/runtime/Cargo.toml +++ b/bridges/bin/millau/runtime/Cargo.toml @@ -8,6 +8,7 @@ repository = "https://github.com/paritytech/parity-bridges-common/" license = "GPL-3.0-or-later WITH Classpath-exception-2.0" [dependencies] +hex-literal = "0.3" codec = { package = "parity-scale-codec", version = "2.2.0", default-features = false, features = ["derive"] } serde = { version = "1.0", optional = true, features = ["derive"] } @@ -28,6 +29,7 @@ pallet-shift-session-manager = { path = "../../../modules/shift-session-manager" # Substrate Dependencies +frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false, optional = true } frame-executive = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } frame-system = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } @@ -102,6 +104,9 @@ std = [ "sp-trie/std", "sp-version/std", ] -# TODO: https://github.com/paritytech/parity-bridges-common/issues/390 -# I've left the feature flag here to test our CI configuration -runtime-benchmarks = [] +runtime-benchmarks = [ + "frame-benchmarking", + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-bridge-token-swap/runtime-benchmarks", +] diff --git a/bridges/bin/millau/runtime/src/lib.rs b/bridges/bin/millau/runtime/src/lib.rs index 7385e8ecec894..161816c2d940e 100644 --- a/bridges/bin/millau/runtime/src/lib.rs +++ b/bridges/bin/millau/runtime/src/lib.rs @@ -425,10 +425,14 @@ pub type WithRialtoTokenSwapInstance = (); impl pallet_bridge_token_swap::Config for Runtime { type Event = Event; + type WeightInfo = (); type BridgedChainId = RialtoChainId; type OutboundMessageLaneId = TokenSwapMessagesLane; + #[cfg(not(feature = "runtime-benchmarks"))] type MessagesBridge = pallet_bridge_messages::Pallet; + #[cfg(feature = "runtime-benchmarks")] + type MessagesBridge = bp_messages::source_chain::NoopMessagesBridge; type ThisCurrency = pallet_balances::Pallet; type FromSwapToThisAccountIdConverter = bp_rialto::AccountIdConverter; @@ -704,6 +708,67 @@ impl_runtime_apis! { BridgeRialtoMessages::inbound_unrewarded_relayers_state(lane) } } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(extra: bool) -> ( + Vec, + Vec, + ) { + use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList}; + use frame_support::traits::StorageInfoTrait; + + let mut list = Vec::::new(); + + list_benchmark!(list, extra, pallet_bridge_token_swap, BridgeRialtoTokenSwap); + + let storage_info = AllPalletsWithSystem::storage_info(); + + return (list, storage_info) + } + + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig, + ) -> Result, sp_runtime::RuntimeString> { + use frame_benchmarking::{Benchmarking, BenchmarkBatch, TrackedStorageKey, add_benchmark}; + + let whitelist: Vec = vec![ + // Block Number + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), + // Execution Phase + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), + // Event Count + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), + // System Events + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), + // Caller 0 Account + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da946c154ffd9992e395af90b5b13cc6f295c77033fce8a9045824a6690bbf99c6db269502f0a8d1d2a008542d5690a0749").to_vec().into(), + ]; + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + + use pallet_bridge_token_swap::benchmarking::Config as TokenSwapConfig; + + impl TokenSwapConfig for Runtime { + fn initialize_environment() { + let relayers_fund_account = pallet_bridge_messages::relayer_fund_account_id::< + bp_millau::AccountId, + bp_millau::AccountIdConverter, + >(); + pallet_balances::Pallet::::make_free_balance_be( + &relayers_fund_account, + Balance::MAX / 100, + ); + } + } + + add_benchmark!(params, batches, pallet_bridge_token_swap, BridgeRialtoTokenSwap); + + if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } + Ok(batches) + } + } } /// Rialto account ownership digest from Millau. diff --git a/bridges/modules/grandpa/src/weights.rs b/bridges/modules/grandpa/src/weights.rs index 18d88049f16a8..c0cce2c5258d1 100644 --- a/bridges/modules/grandpa/src/weights.rs +++ b/bridges/modules/grandpa/src/weights.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity Bridges Common. If not, see . -//! Autogenerated weights for pallet_bridge_grandpa +//! Autogenerated weights for `pallet_bridge_grandpa` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 //! DATE: 2021-06-03, STEPS: [50, ], REPEAT: 20 @@ -46,12 +46,12 @@ use frame_support::{ }; use sp_std::marker::PhantomData; -/// Weight functions needed for pallet_bridge_grandpa. +/// Weight functions needed for `pallet_bridge_grandpa`. pub trait WeightInfo { fn submit_finality_proof(p: u32, v: u32) -> Weight; } -/// Weights for pallet_bridge_grandpa using the Rialto node and recommended hardware. +/// Weights for `pallet_bridge_grandpa` using the Rialto node and recommended hardware. pub struct RialtoWeight(PhantomData); impl WeightInfo for RialtoWeight { fn submit_finality_proof(p: u32, v: u32) -> Weight { diff --git a/bridges/modules/messages/src/lib.rs b/bridges/modules/messages/src/lib.rs index ce56fc3f87a79..8d2e239781cbb 100644 --- a/bridges/modules/messages/src/lib.rs +++ b/bridges/modules/messages/src/lib.rs @@ -51,7 +51,7 @@ use crate::{ use bp_messages::{ source_chain::{ LaneMessageVerifier, MessageDeliveryAndDispatchPayment, OnDeliveryConfirmed, - OnMessageAccepted, TargetHeaderChain, + OnMessageAccepted, SendMessageArtifacts, TargetHeaderChain, }, target_chain::{ DispatchMessage, MessageDispatch, ProvedLaneMessages, ProvedMessages, SourceHeaderChain, @@ -281,7 +281,10 @@ pub mod pallet { payload, delivery_and_dispatch_fee, ) - .map(|sent_message| sent_message.post_dispatch_info) + .map(|sent_message| PostDispatchInfo { + actual_weight: Some(sent_message.weight), + pays_fee: Pays::Yes, + }) } /// Pay additional fee for the message. @@ -853,27 +856,21 @@ where lane: LaneId, message: T::OutboundPayload, delivery_and_dispatch_fee: T::OutboundMessageFee, - ) -> Result { + ) -> Result { crate::send_message::(sender, lane, message, delivery_and_dispatch_fee) - .map(|sent_message| sent_message.nonce) } } -/// Message that has been sent. -struct SentMessage { - /// Nonce of the message. - pub nonce: MessageNonce, - /// Post-dispatch call info. - pub post_dispatch_info: PostDispatchInfo, -} - /// Function that actually sends message. fn send_message, I: 'static>( submitter: bp_messages::source_chain::Sender, lane_id: LaneId, payload: T::OutboundPayload, delivery_and_dispatch_fee: T::OutboundMessageFee, -) -> sp_std::result::Result> { +) -> sp_std::result::Result< + SendMessageArtifacts, + sp_runtime::DispatchErrorWithPostInfo, +> { ensure_normal_operating_mode::()?; // initially, actual (post-dispatch) weight is equal to pre-dispatch weight @@ -986,13 +983,7 @@ fn send_message, I: 'static>( Pallet::::deposit_event(Event::MessageAccepted(lane_id, nonce)); - Ok(SentMessage { - nonce, - post_dispatch_info: PostDispatchInfo { - actual_weight: Some(actual_weight), - pays_fee: Pays::Yes, - }, - }) + Ok(SendMessageArtifacts { nonce, weight: actual_weight }) } /// Ensure that the origin is either root, or `PalletOwner`. diff --git a/bridges/modules/messages/src/weights.rs b/bridges/modules/messages/src/weights.rs index b3028c8fcc4f2..9dce11168fbbc 100644 --- a/bridges/modules/messages/src/weights.rs +++ b/bridges/modules/messages/src/weights.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity Bridges Common. If not, see . -//! Autogenerated weights for pallet_bridge_messages +//! Autogenerated weights for `pallet_bridge_messages` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 //! DATE: 2021-06-18, STEPS: [50, ], REPEAT: 20 @@ -46,7 +46,7 @@ use frame_support::{ }; use sp_std::marker::PhantomData; -/// Weight functions needed for pallet_bridge_messages. +/// Weight functions needed for `pallet_bridge_messages`. pub trait WeightInfo { fn send_minimal_message_worst_case() -> Weight; fn send_1_kb_message_worst_case() -> Weight; @@ -71,7 +71,7 @@ pub trait WeightInfo { fn receive_delivery_proof_for_multiple_messages_by_multiple_relayers(i: u32) -> Weight; } -/// Weights for pallet_bridge_messages using the Rialto node and recommended hardware. +/// Weights for `pallet_bridge_messages` using the Rialto node and recommended hardware. pub struct RialtoWeight(PhantomData); impl WeightInfo for RialtoWeight { fn send_minimal_message_worst_case() -> Weight { diff --git a/bridges/modules/token-swap/Cargo.toml b/bridges/modules/token-swap/Cargo.toml index 0266fd51f7691..b68eed6d59e08 100644 --- a/bridges/modules/token-swap/Cargo.toml +++ b/bridges/modules/token-swap/Cargo.toml @@ -18,9 +18,11 @@ bp-messages = { path = "../../primitives/messages", default-features = false } bp-runtime = { path = "../../primitives/runtime", default-features = false } bp-token-swap = { path = "../../primitives/token-swap", default-features = false } pallet-bridge-dispatch = { path = "../dispatch", default-features = false } +pallet-bridge-messages = { path = "../messages", default-features = false } # Substrate Dependencies +frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false, optional = true } frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } frame-system = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } sp-core = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } @@ -43,9 +45,13 @@ std = [ "frame-system/std", "log/std", "pallet-bridge-dispatch/std", + "pallet-bridge-messages/std", "serde", "sp-core/std", "sp-io/std", "sp-runtime/std", "sp-std/std", ] +runtime-benchmarks = [ + "frame-benchmarking", +] diff --git a/bridges/modules/token-swap/src/benchmarking.rs b/bridges/modules/token-swap/src/benchmarking.rs new file mode 100644 index 0000000000000..0dd8922d157f4 --- /dev/null +++ b/bridges/modules/token-swap/src/benchmarking.rs @@ -0,0 +1,188 @@ +// Copyright 2019-2021 Parity Technologies (UK) Ltd. +// This file is part of Parity Bridges Common. + +// Parity Bridges Common is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity Bridges Common is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity Bridges Common. If not, see . + +//! Token-swap pallet benchmarking. + +use crate::{ + swap_account_id, target_account_at_this_chain, BridgedAccountIdOf, BridgedAccountPublicOf, + BridgedAccountSignatureOf, BridgedBalanceOf, Call, Pallet, ThisChainBalance, TokenSwapOf, +}; + +use bp_token_swap::{TokenSwap, TokenSwapState, TokenSwapType}; +use codec::Encode; +use frame_benchmarking::{account, benchmarks_instance_pallet}; +use frame_support::{traits::Currency, Parameter}; +use frame_system::RawOrigin; +use sp_core::H256; +use sp_io::hashing::blake2_256; +use sp_runtime::traits::Bounded; +use sp_std::vec::Vec; + +const SEED: u32 = 0; + +/// Trait that must be implemented by runtime. +pub trait Config: crate::Config { + /// Initialize environment for token swap. + fn initialize_environment(); +} + +benchmarks_instance_pallet! { + where_clause { + where + BridgedAccountPublicOf: Default + Parameter, + BridgedAccountSignatureOf: Default, + } + + // + // Benchmarks that are used directly by the runtime. + // + + // Benchmark `create_swap` extrinsic. + // + // This benchmark assumes that message is **NOT** actually sent. Instead we're using `send_message_weight` + // from the `WeightInfoExt` trait. + // + // There aren't any factors that affect `create_swap` performance, so everything + // is straightforward here. + create_swap { + T::initialize_environment(); + + let sender = funded_account::("source_account_at_this_chain", 0); + let swap: TokenSwapOf = test_swap::(sender.clone(), true); + let target_public_at_bridged_chain = target_public_at_bridged_chain::(); + let swap_delivery_and_dispatch_fee = swap_delivery_and_dispatch_fee::(); + let bridged_chain_spec_version = 0; + let bridged_currency_transfer = Vec::new(); + let bridged_currency_transfer_weight = 0; + let bridged_currency_transfer_signature = bridged_currency_transfer_signature::(); + }: create_swap( + RawOrigin::Signed(sender.clone()), + swap, + target_public_at_bridged_chain, + swap_delivery_and_dispatch_fee, + bridged_chain_spec_version, + bridged_currency_transfer, + bridged_currency_transfer_weight, + bridged_currency_transfer_signature + ) + verify { + assert!(crate::PendingSwaps::::contains_key(test_swap_hash::(sender, true))); + } + + // Benchmark `claim_swap` extrinsic with the worst possible conditions: + // + // * swap is locked until some block, so current block number is read. + claim_swap { + T::initialize_environment(); + + let sender: T::AccountId = account("source_account_at_this_chain", 0, SEED); + crate::PendingSwaps::::insert( + test_swap_hash::(sender.clone(), false), + TokenSwapState::Confirmed, + ); + + let swap: TokenSwapOf = test_swap::(sender.clone(), false); + let claimer = target_account_at_this_chain::(&swap); + let token_swap_account = swap_account_id::(&swap); + T::ThisCurrency::make_free_balance_be(&token_swap_account, ThisChainBalance::::max_value()); + }: claim_swap(RawOrigin::Signed(claimer), swap) + verify { + assert!(!crate::PendingSwaps::::contains_key(test_swap_hash::(sender, false))); + } + + // Benchmark `cancel_swap` extrinsic with the worst possible conditions: + // + // * swap is locked until some block, so current block number is read. + cancel_swap { + T::initialize_environment(); + + let sender: T::AccountId = account("source_account_at_this_chain", 0, SEED); + crate::PendingSwaps::::insert( + test_swap_hash::(sender.clone(), false), + TokenSwapState::Failed, + ); + + let swap: TokenSwapOf = test_swap::(sender.clone(), false); + let token_swap_account = swap_account_id::(&swap); + T::ThisCurrency::make_free_balance_be(&token_swap_account, ThisChainBalance::::max_value()); + + }: cancel_swap(RawOrigin::Signed(sender.clone()), swap) + verify { + assert!(!crate::PendingSwaps::::contains_key(test_swap_hash::(sender, false))); + } +} + +/// Returns test token swap. +fn test_swap, I: 'static>(sender: T::AccountId, is_create: bool) -> TokenSwapOf { + TokenSwap { + swap_type: TokenSwapType::LockClaimUntilBlock( + if is_create { 10u32.into() } else { 0u32.into() }, + 0.into(), + ), + source_balance_at_this_chain: source_balance_to_swap::(), + source_account_at_this_chain: sender, + target_balance_at_bridged_chain: target_balance_to_swap::(), + target_account_at_bridged_chain: target_account_at_bridged_chain::(), + } +} + +/// Returns test token swap hash. +fn test_swap_hash, I: 'static>(sender: T::AccountId, is_create: bool) -> H256 { + test_swap::(sender, is_create).using_encoded(blake2_256).into() +} + +/// Account that has some balance. +fn funded_account, I: 'static>(name: &'static str, index: u32) -> T::AccountId { + let account: T::AccountId = account(name, index, SEED); + T::ThisCurrency::make_free_balance_be(&account, ThisChainBalance::::max_value()); + account +} + +/// Currency transfer message fee. +fn swap_delivery_and_dispatch_fee, I: 'static>() -> ThisChainBalance { + ThisChainBalance::::max_value() / 4u32.into() +} + +/// Balance at the source chain that we're going to swap. +fn source_balance_to_swap, I: 'static>() -> ThisChainBalance { + ThisChainBalance::::max_value() / 2u32.into() +} + +/// Balance at the target chain that we're going to swap. +fn target_balance_to_swap, I: 'static>() -> BridgedBalanceOf { + BridgedBalanceOf::::max_value() / 2u32.into() +} + +/// Public key of `target_account_at_bridged_chain`. +fn target_public_at_bridged_chain, I: 'static>() -> BridgedAccountPublicOf +where + BridgedAccountPublicOf: Default, +{ + Default::default() +} + +/// Signature of `target_account_at_bridged_chain` over message. +fn bridged_currency_transfer_signature, I: 'static>() -> BridgedAccountSignatureOf +where + BridgedAccountSignatureOf: Default, +{ + Default::default() +} + +/// Account at the bridged chain that is participating in the swap. +fn target_account_at_bridged_chain, I: 'static>() -> BridgedAccountIdOf { + Default::default() +} diff --git a/bridges/modules/token-swap/src/lib.rs b/bridges/modules/token-swap/src/lib.rs index 9469df3aaceeb..3a49d431c7786 100644 --- a/bridges/modules/token-swap/src/lib.rs +++ b/bridges/modules/token-swap/src/lib.rs @@ -62,15 +62,25 @@ use codec::Encode; use frame_support::{ fail, traits::{Currency, ExistenceRequirement}, + weights::PostDispatchInfo, }; use sp_core::H256; use sp_io::hashing::blake2_256; use sp_runtime::traits::{Convert, Saturating}; use sp_std::vec::Vec; +use weights::WeightInfo; + +pub use weights_ext::WeightInfoExt; #[cfg(test)] mod mock; +#[cfg(feature = "runtime-benchmarks")] +pub mod benchmarking; + +pub mod weights; +pub mod weights_ext; + pub use pallet::*; /// Name of the `PendingSwaps` storage map. @@ -88,6 +98,8 @@ pub mod pallet { pub trait Config: frame_system::Config { /// The overarching event type. type Event: From> + IsType<::Event>; + /// Benchmarks results from runtime we're plugged into. + type WeightInfo: WeightInfoExt; /// Id of the bridge with the Bridged chain. type BridgedChainId: Get; @@ -200,7 +212,13 @@ pub mod pallet { /// Violating rule#1 will lead to losing your `source_balance_at_this_chain` tokens. /// Violating other rules will lead to losing message fees for this and other transactions + /// losing fees for message transfer. - #[pallet::weight(0)] + #[pallet::weight( + T::WeightInfo::create_swap() + .saturating_add(T::WeightInfo::send_message_weight( + &&bridged_currency_transfer[..], + T::DbWeight::get(), + )) + )] #[allow(clippy::too_many_arguments)] pub fn create_swap( origin: OriginFor, @@ -220,6 +238,9 @@ pub mod pallet { Error::::MismatchedSwapSourceOrigin, ); + // remember weight components + let base_weight = T::WeightInfo::create_swap(); + // we can't exchange less than existential deposit (the temporary `swap_account` account // won't be created then) // @@ -242,7 +263,7 @@ pub mod pallet { } let swap_account = swap_account_id::(&swap); - frame_support::storage::with_transaction(|| { + let actual_send_message_weight = frame_support::storage::with_transaction(|| { // funds are transferred from This account to the temporary Swap account let transfer_result = T::ThisCurrency::transfer( &swap.source_account_at_this_chain, @@ -265,7 +286,7 @@ pub mod pallet { ); return sp_runtime::TransactionOutcome::Rollback(Err( - Error::::FailedToTransferToSwapAccount.into(), + Error::::FailedToTransferToSwapAccount, )) } @@ -288,8 +309,8 @@ pub mod pallet { }, swap_delivery_and_dispatch_fee, ); - let transfer_message_nonce = match send_message_result { - Ok(transfer_message_nonce) => transfer_message_nonce, + let sent_message = match send_message_result { + Ok(sent_message) => sent_message, Err(err) => { log::error!( target: "runtime::bridge-token-swap", @@ -299,7 +320,7 @@ pub mod pallet { ); return sp_runtime::TransactionOutcome::Rollback(Err( - Error::::FailedToSendTransferMessage.into(), + Error::::FailedToSendTransferMessage, )) }, }; @@ -323,7 +344,7 @@ pub mod pallet { ); return sp_runtime::TransactionOutcome::Rollback(Err( - Error::::SwapAlreadyStarted.into(), + Error::::SwapAlreadyStarted, )) } @@ -335,12 +356,17 @@ pub mod pallet { ); // remember that we're waiting for the transfer message delivery confirmation - PendingMessages::::insert(transfer_message_nonce, swap_hash); + PendingMessages::::insert(sent_message.nonce, swap_hash); // finally - emit the event - Self::deposit_event(Event::SwapStarted(swap_hash, transfer_message_nonce)); + Self::deposit_event(Event::SwapStarted(swap_hash, sent_message.nonce)); + + sp_runtime::TransactionOutcome::Commit(Ok(sent_message.weight)) + })?; - sp_runtime::TransactionOutcome::Commit(Ok(().into())) + Ok(PostDispatchInfo { + actual_weight: Some(base_weight.saturating_add(actual_send_message_weight)), + pays_fee: Pays::Yes, }) } @@ -352,7 +378,7 @@ pub mod pallet { /// `pallet_bridge_dispatch::CallOrigin::SourceAccount(target_account_at_bridged_chain)`. /// /// This should be called only when successful transfer confirmation has been received. - #[pallet::weight(0)] + #[pallet::weight(T::WeightInfo::claim_swap())] pub fn claim_swap( origin: OriginFor, swap: TokenSwapOf, @@ -388,7 +414,7 @@ pub mod pallet { /// /// This should be called only when transfer has failed at Bridged chain and we have /// received notification about that. - #[pallet::weight(0)] + #[pallet::weight(T::WeightInfo::cancel_swap())] pub fn cancel_swap( origin: OriginFor, swap: TokenSwapOf, diff --git a/bridges/modules/token-swap/src/mock.rs b/bridges/modules/token-swap/src/mock.rs index 16894d9850ba0..63edb323e1a4c 100644 --- a/bridges/modules/token-swap/src/mock.rs +++ b/bridges/modules/token-swap/src/mock.rs @@ -17,7 +17,10 @@ use crate as pallet_bridge_token_swap; use crate::MessagePayloadOf; -use bp_messages::{source_chain::MessagesBridge, LaneId, MessageNonce}; +use bp_messages::{ + source_chain::{MessagesBridge, SendMessageArtifacts}, + LaneId, MessageNonce, +}; use bp_runtime::ChainId; use frame_support::weights::Weight; use sp_core::H256; @@ -114,6 +117,7 @@ frame_support::parameter_types! { impl pallet_bridge_token_swap::Config for TestRuntime { type Event = Event; + type WeightInfo = (); type BridgedChainId = BridgedChainId; type OutboundMessageLaneId = OutboundMessageLaneId; @@ -150,12 +154,12 @@ impl MessagesBridge> for T lane: LaneId, message: MessagePayloadOf, delivery_and_dispatch_fee: Balance, - ) -> Result { + ) -> Result { assert_ne!(sender, frame_system::RawOrigin::Signed(THIS_CHAIN_ACCOUNT)); assert_eq!(lane, OutboundMessageLaneId::get()); assert_eq!(delivery_and_dispatch_fee, SWAP_DELIVERY_AND_DISPATCH_FEE); match message.call[0] { - OK_TRANSFER_CALL => Ok(MESSAGE_NONCE), + OK_TRANSFER_CALL => Ok(SendMessageArtifacts { nonce: MESSAGE_NONCE, weight: 0 }), BAD_TRANSFER_CALL => Err(()), _ => unreachable!(), } diff --git a/bridges/modules/token-swap/src/weights.rs b/bridges/modules/token-swap/src/weights.rs new file mode 100644 index 0000000000000..06cb6b85cf336 --- /dev/null +++ b/bridges/modules/token-swap/src/weights.rs @@ -0,0 +1,93 @@ +// Copyright 2019-2021 Parity Technologies (UK) Ltd. +// This file is part of Parity Bridges Common. + +// Parity Bridges Common is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity Bridges Common is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity Bridges Common. If not, see . + +//! Autogenerated weights for `pallet_bridge_token_swap` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2021-10-06, STEPS: 50, REPEAT: 20 +//! LOW RANGE: [], HIGH RANGE: [] +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled +//! CHAIN: Some("dev"), DB CACHE: 128 + +// Executed Command: +// target/release/millau-bridge-node +// benchmark +// --chain=dev +// --steps=50 +// --repeat=20 +// --pallet=pallet_bridge_token_swap +// --extrinsic=* +// --execution=wasm +// --wasm-execution=Compiled +// --heap-pages=4096 +// --output=./modules/token-swap/src/weights.rs +// --template=./.maintain/millau-weight-template.hbs + +#![allow(clippy::all)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{ + traits::Get, + weights::{constants::RocksDbWeight, Weight}, +}; +use sp_std::marker::PhantomData; + +/// Weight functions needed for `pallet_bridge_token_swap`. +pub trait WeightInfo { + fn create_swap() -> Weight; + fn claim_swap() -> Weight; + fn cancel_swap() -> Weight; +} + +/// Weights for `pallet_bridge_token_swap` using the Millau node and recommended hardware. +pub struct MillauWeight(PhantomData); +impl WeightInfo for MillauWeight { + fn create_swap() -> Weight { + (116_040_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + fn claim_swap() -> Weight { + (102_882_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + fn cancel_swap() -> Weight { + (99_434_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } +} + +// For backwards compatibility and tests +impl WeightInfo for () { + fn create_swap() -> Weight { + (116_040_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + fn claim_swap() -> Weight { + (102_882_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + fn cancel_swap() -> Weight { + (99_434_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } +} diff --git a/bridges/modules/token-swap/src/weights_ext.rs b/bridges/modules/token-swap/src/weights_ext.rs new file mode 100644 index 0000000000000..2d27c76cbe685 --- /dev/null +++ b/bridges/modules/token-swap/src/weights_ext.rs @@ -0,0 +1,42 @@ +// Copyright 2019-2021 Parity Technologies (UK) Ltd. +// This file is part of Parity Bridges Common. + +// Parity Bridges Common is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity Bridges Common is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity Bridges Common. If not, see . + +//! Weight-related utilities. + +use crate::weights::WeightInfo; + +use bp_runtime::Size; +use frame_support::weights::{RuntimeDbWeight, Weight}; + +/// Extended weight info. +pub trait WeightInfoExt: WeightInfo { + // Functions that are directly mapped to extrinsics weights. + + /// Weight of message send extrinsic. + fn send_message_weight(message: &impl Size, db_weight: RuntimeDbWeight) -> Weight; +} + +impl WeightInfoExt for () { + fn send_message_weight(message: &impl Size, db_weight: RuntimeDbWeight) -> Weight { + <() as pallet_bridge_messages::WeightInfoExt>::send_message_weight(message, db_weight) + } +} + +impl WeightInfoExt for crate::weights::MillauWeight { + fn send_message_weight(message: &impl Size, db_weight: RuntimeDbWeight) -> Weight { + <() as pallet_bridge_messages::WeightInfoExt>::send_message_weight(message, db_weight) + } +} diff --git a/bridges/primitives/messages/src/source_chain.rs b/bridges/primitives/messages/src/source_chain.rs index 1745180f94cc6..1ff05abf131ea 100644 --- a/bridges/primitives/messages/src/source_chain.rs +++ b/bridges/primitives/messages/src/source_chain.rs @@ -135,6 +135,15 @@ pub trait MessageDeliveryAndDispatchPayment { ); } +/// Send message artifacts. +#[derive(RuntimeDebug, PartialEq)] +pub struct SendMessageArtifacts { + /// Nonce of the message. + pub nonce: MessageNonce, + /// Actual weight of send message call. + pub weight: Weight, +} + /// Messages bridge API to be used from other pallets. pub trait MessagesBridge { /// Error type. @@ -148,7 +157,26 @@ pub trait MessagesBridge { lane: LaneId, message: Payload, delivery_and_dispatch_fee: Balance, - ) -> Result; + ) -> Result; +} + +/// Bridge that does nothing when message is being sent. +#[derive(RuntimeDebug, PartialEq)] +pub struct NoopMessagesBridge; + +impl MessagesBridge + for NoopMessagesBridge +{ + type Error = &'static str; + + fn send_message( + _sender: Sender, + _lane: LaneId, + _message: Payload, + _delivery_and_dispatch_fee: Balance, + ) -> Result { + Ok(SendMessageArtifacts { nonce: 0, weight: 0 }) + } } /// Handler for messages delivery confirmation. diff --git a/bridges/primitives/runtime/src/lib.rs b/bridges/primitives/runtime/src/lib.rs index 63fc2393e7836..9a3470a2570c3 100644 --- a/bridges/primitives/runtime/src/lib.rs +++ b/bridges/primitives/runtime/src/lib.rs @@ -131,6 +131,12 @@ pub trait Size { fn size_hint(&self) -> u32; } +impl Size for &[u8] { + fn size_hint(&self) -> u32 { + self.len() as _ + } +} + impl Size for () { fn size_hint(&self) -> u32 { 0