Token swap pallet benchmarks (#1174)

* token swap benchmarks

* spellcheck
This commit is contained in:
Svyatoslav Nikolsky
2021-10-08 12:35:11 +03:00
committed by Bastian Köcher
parent c0df990b90
commit 4b525f4fe1
14 changed files with 500 additions and 49 deletions
+6
View File
@@ -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",
]
@@ -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 <http://www.gnu.org/licenses/>.
//! 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<I: 'static>: crate::Config<I> {
/// Initialize environment for token swap.
fn initialize_environment();
}
benchmarks_instance_pallet! {
where_clause {
where
BridgedAccountPublicOf<T, I>: Default + Parameter,
BridgedAccountSignatureOf<T, I>: 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::<T, I>("source_account_at_this_chain", 0);
let swap: TokenSwapOf<T, I> = test_swap::<T, I>(sender.clone(), true);
let target_public_at_bridged_chain = target_public_at_bridged_chain::<T, I>();
let swap_delivery_and_dispatch_fee = swap_delivery_and_dispatch_fee::<T, I>();
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::<T, I>();
}: 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::<T, I>::contains_key(test_swap_hash::<T, I>(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::<T, I>::insert(
test_swap_hash::<T, I>(sender.clone(), false),
TokenSwapState::Confirmed,
);
let swap: TokenSwapOf<T, I> = test_swap::<T, I>(sender.clone(), false);
let claimer = target_account_at_this_chain::<T, I>(&swap);
let token_swap_account = swap_account_id::<T, I>(&swap);
T::ThisCurrency::make_free_balance_be(&token_swap_account, ThisChainBalance::<T, I>::max_value());
}: claim_swap(RawOrigin::Signed(claimer), swap)
verify {
assert!(!crate::PendingSwaps::<T, I>::contains_key(test_swap_hash::<T, I>(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::<T, I>::insert(
test_swap_hash::<T, I>(sender.clone(), false),
TokenSwapState::Failed,
);
let swap: TokenSwapOf<T, I> = test_swap::<T, I>(sender.clone(), false);
let token_swap_account = swap_account_id::<T, I>(&swap);
T::ThisCurrency::make_free_balance_be(&token_swap_account, ThisChainBalance::<T, I>::max_value());
}: cancel_swap(RawOrigin::Signed(sender.clone()), swap)
verify {
assert!(!crate::PendingSwaps::<T, I>::contains_key(test_swap_hash::<T, I>(sender, false)));
}
}
/// Returns test token swap.
fn test_swap<T: Config<I>, I: 'static>(sender: T::AccountId, is_create: bool) -> TokenSwapOf<T, I> {
TokenSwap {
swap_type: TokenSwapType::LockClaimUntilBlock(
if is_create { 10u32.into() } else { 0u32.into() },
0.into(),
),
source_balance_at_this_chain: source_balance_to_swap::<T, I>(),
source_account_at_this_chain: sender,
target_balance_at_bridged_chain: target_balance_to_swap::<T, I>(),
target_account_at_bridged_chain: target_account_at_bridged_chain::<T, I>(),
}
}
/// Returns test token swap hash.
fn test_swap_hash<T: Config<I>, I: 'static>(sender: T::AccountId, is_create: bool) -> H256 {
test_swap::<T, I>(sender, is_create).using_encoded(blake2_256).into()
}
/// Account that has some balance.
fn funded_account<T: Config<I>, 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::<T, I>::max_value());
account
}
/// Currency transfer message fee.
fn swap_delivery_and_dispatch_fee<T: Config<I>, I: 'static>() -> ThisChainBalance<T, I> {
ThisChainBalance::<T, I>::max_value() / 4u32.into()
}
/// Balance at the source chain that we're going to swap.
fn source_balance_to_swap<T: Config<I>, I: 'static>() -> ThisChainBalance<T, I> {
ThisChainBalance::<T, I>::max_value() / 2u32.into()
}
/// Balance at the target chain that we're going to swap.
fn target_balance_to_swap<T: Config<I>, I: 'static>() -> BridgedBalanceOf<T, I> {
BridgedBalanceOf::<T, I>::max_value() / 2u32.into()
}
/// Public key of `target_account_at_bridged_chain`.
fn target_public_at_bridged_chain<T: Config<I>, I: 'static>() -> BridgedAccountPublicOf<T, I>
where
BridgedAccountPublicOf<T, I>: Default,
{
Default::default()
}
/// Signature of `target_account_at_bridged_chain` over message.
fn bridged_currency_transfer_signature<T: Config<I>, I: 'static>() -> BridgedAccountSignatureOf<T, I>
where
BridgedAccountSignatureOf<T, I>: Default,
{
Default::default()
}
/// Account at the bridged chain that is participating in the swap.
fn target_account_at_bridged_chain<T: Config<I>, I: 'static>() -> BridgedAccountIdOf<T, I> {
Default::default()
}
+38 -12
View File
@@ -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<I: 'static = ()>: frame_system::Config {
/// The overarching event type.
type Event: From<Event<Self, I>> + IsType<<Self as frame_system::Config>::Event>;
/// Benchmarks results from runtime we're plugged into.
type WeightInfo: WeightInfoExt;
/// Id of the bridge with the Bridged chain.
type BridgedChainId: Get<ChainId>;
@@ -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<T>,
@@ -220,6 +238,9 @@ pub mod pallet {
Error::<T, I>::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::<T, I>(&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::<T, I>::FailedToTransferToSwapAccount.into(),
Error::<T, I>::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::<T, I>::FailedToSendTransferMessage.into(),
Error::<T, I>::FailedToSendTransferMessage,
))
},
};
@@ -323,7 +344,7 @@ pub mod pallet {
);
return sp_runtime::TransactionOutcome::Rollback(Err(
Error::<T, I>::SwapAlreadyStarted.into(),
Error::<T, I>::SwapAlreadyStarted,
))
}
@@ -335,12 +356,17 @@ pub mod pallet {
);
// remember that we're waiting for the transfer message delivery confirmation
PendingMessages::<T, I>::insert(transfer_message_nonce, swap_hash);
PendingMessages::<T, I>::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(().into()))
sp_runtime::TransactionOutcome::Commit(Ok(sent_message.weight))
})?;
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<T>,
swap: TokenSwapOf<T, I>,
@@ -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<T>,
swap: TokenSwapOf<T, I>,
+7 -3
View File
@@ -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<AccountId, Balance, MessagePayloadOf<TestRuntime, ()>> for T
lane: LaneId,
message: MessagePayloadOf<TestRuntime, ()>,
delivery_and_dispatch_fee: Balance,
) -> Result<MessageNonce, Self::Error> {
) -> Result<SendMessageArtifacts, Self::Error> {
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!(),
}
+93
View File
@@ -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 <http://www.gnu.org/licenses/>.
//! 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<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for MillauWeight<T> {
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))
}
}
@@ -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 <http://www.gnu.org/licenses/>.
//! 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<T: frame_system::Config> WeightInfoExt for crate::weights::MillauWeight<T> {
fn send_message_weight(message: &impl Size, db_weight: RuntimeDbWeight) -> Weight {
<() as pallet_bridge_messages::WeightInfoExt>::send_message_weight(message, db_weight)
}
}