Merge commit '392447f5c8f986ded2559a78457f4cd87942f393' into update-bridges-subtree-r/w

This commit is contained in:
antonio-dropulic
2021-12-01 09:46:14 +01:00
321 changed files with 28385 additions and 10466 deletions
@@ -0,0 +1,59 @@
[package]
name = "pallet-bridge-token-swap"
description = "An Substrate pallet that allows parties on different chains (bridged using messages pallet) to swap their tokens"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[dependencies]
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
log = { version = "0.4.14", default-features = false }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
serde = { version = "1.0", optional = true }
# Bridge dependencies
bp-message-dispatch = { path = "../../primitives/message-dispatch", default-features = false }
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 }
sp-io = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
[dev-dependencies]
pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master" }
[features]
default = ["std"]
std = [
"codec/std",
"bp-message-dispatch/std",
"bp-messages/std",
"bp-runtime/std",
"bp-token-swap/std",
"frame-support/std",
"frame-system/std",
"log/std",
"pallet-bridge-dispatch/std",
"pallet-bridge-messages/std",
"scale-info/std",
"serde",
"sp-core/std",
"sp-io/std",
"sp-runtime/std",
"sp-std/std",
]
runtime-benchmarks = [
"frame-benchmarking",
]
@@ -0,0 +1,195 @@
// 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,
TokenSwapCreationOf, TokenSwapOf,
};
use bp_token_swap::{TokenSwap, TokenSwapCreation, 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 swap_creation: TokenSwapCreationOf<T, I> = test_swap_creation::<T, I>();
}: create_swap(
RawOrigin::Signed(sender.clone()),
swap,
Box::new(swap_creation)
)
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()
}
/// Returns test token swap creation params.
fn test_swap_creation<T: Config<I>, I: 'static>() -> TokenSwapCreationOf<T, I>
where
BridgedAccountPublicOf<T, I>: Default,
BridgedAccountSignatureOf<T, I>: Default,
{
TokenSwapCreation {
target_public_at_bridged_chain: target_public_at_bridged_chain::<T, I>(),
swap_delivery_and_dispatch_fee: swap_delivery_and_dispatch_fee::<T, I>(),
bridged_chain_spec_version: 0,
bridged_currency_transfer: Vec::new(),
bridged_currency_transfer_weight: 0,
bridged_currency_transfer_signature: bridged_currency_transfer_signature::<T, I>(),
}
}
/// 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()
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,187 @@
// 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/>.
use crate as pallet_bridge_token_swap;
use crate::MessagePayloadOf;
use bp_messages::{
source_chain::{MessagesBridge, SendMessageArtifacts},
LaneId, MessageNonce,
};
use bp_runtime::ChainId;
use frame_support::weights::Weight;
use sp_core::H256;
use sp_runtime::{
testing::Header as SubstrateHeader,
traits::{BlakeTwo256, IdentityLookup},
Perbill,
};
pub type AccountId = u64;
pub type Balance = u64;
pub type Block = frame_system::mocking::MockBlock<TestRuntime>;
pub type BridgedAccountId = u64;
pub type BridgedAccountPublic = sp_runtime::testing::UintAuthorityId;
pub type BridgedAccountSignature = sp_runtime::testing::TestSignature;
pub type BridgedBalance = u64;
pub type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<TestRuntime>;
pub const OK_TRANSFER_CALL: u8 = 1;
pub const BAD_TRANSFER_CALL: u8 = 2;
pub const MESSAGE_NONCE: MessageNonce = 3;
pub const THIS_CHAIN_ACCOUNT: AccountId = 1;
pub const THIS_CHAIN_ACCOUNT_BALANCE: Balance = 100_000;
pub const SWAP_DELIVERY_AND_DISPATCH_FEE: Balance = 1;
frame_support::construct_runtime! {
pub enum TestRuntime where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Call, Event<T>},
TokenSwap: pallet_bridge_token_swap::{Pallet, Call, Event<T>},
}
}
frame_support::parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: Weight = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl frame_system::Config for TestRuntime {
type Origin = Origin;
type Index = u64;
type Call = Call;
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = SubstrateHeader;
type Event = Event;
type BlockHashCount = BlockHashCount;
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
type BaseCallFilter = frame_support::traits::Everything;
type SystemWeightInfo = ();
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type SS58Prefix = ();
type OnSetCode = ();
}
frame_support::parameter_types! {
pub const ExistentialDeposit: u64 = 10;
pub const MaxReserves: u32 = 50;
}
impl pallet_balances::Config for TestRuntime {
type MaxLocks = ();
type Balance = Balance;
type DustRemoval = ();
type Event = Event;
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = frame_system::Pallet<TestRuntime>;
type WeightInfo = ();
type MaxReserves = MaxReserves;
type ReserveIdentifier = [u8; 8];
}
frame_support::parameter_types! {
pub const BridgedChainId: ChainId = *b"inst";
pub const OutboundMessageLaneId: LaneId = *b"lane";
}
impl pallet_bridge_token_swap::Config for TestRuntime {
type Event = Event;
type WeightInfo = ();
type BridgedChainId = BridgedChainId;
type OutboundMessageLaneId = OutboundMessageLaneId;
type MessagesBridge = TestMessagesBridge;
type ThisCurrency = pallet_balances::Pallet<TestRuntime>;
type FromSwapToThisAccountIdConverter = TestAccountConverter;
type BridgedChain = BridgedChain;
type FromBridgedToThisAccountIdConverter = TestAccountConverter;
}
pub struct BridgedChain;
impl bp_runtime::Chain for BridgedChain {
type BlockNumber = u64;
type Hash = H256;
type Hasher = BlakeTwo256;
type Header = sp_runtime::generic::Header<u64, BlakeTwo256>;
type AccountId = BridgedAccountId;
type Balance = BridgedBalance;
type Index = u64;
type Signature = BridgedAccountSignature;
}
pub struct TestMessagesBridge;
impl MessagesBridge<AccountId, Balance, MessagePayloadOf<TestRuntime, ()>> for TestMessagesBridge {
type Error = ();
fn send_message(
sender: frame_system::RawOrigin<AccountId>,
lane: LaneId,
message: MessagePayloadOf<TestRuntime, ()>,
delivery_and_dispatch_fee: Balance,
) -> 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(SendMessageArtifacts { nonce: MESSAGE_NONCE, weight: 0 }),
BAD_TRANSFER_CALL => Err(()),
_ => unreachable!(),
}
}
}
pub struct TestAccountConverter;
impl sp_runtime::traits::Convert<H256, AccountId> for TestAccountConverter {
fn convert(hash: H256) -> AccountId {
hash.to_low_u64_ne()
}
}
/// Run pallet test.
pub fn run_test<T>(test: impl FnOnce() -> T) -> T {
let mut t = frame_system::GenesisConfig::default().build_storage::<TestRuntime>().unwrap();
pallet_balances::GenesisConfig::<TestRuntime> {
balances: vec![(THIS_CHAIN_ACCOUNT, THIS_CHAIN_ACCOUNT_BALANCE)],
}
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(test)
}
@@ -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)
}
}