Skip to content

Commit

Permalink
Merge pull request #248 from mangata-finance/feature/fix-xyk-benchmarks
Browse files Browse the repository at this point in the history
xyk & pallet bootstrap benchmarks
  • Loading branch information
mateuszaaa authored May 13, 2022
2 parents bb756d3 + c7db4d1 commit 87cd9ec
Show file tree
Hide file tree
Showing 23 changed files with 2,195 additions and 495 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
![Language](https://img.shields.io/github/languages/top/mangata-finance/mangata-node)

## Description
Reliable decentralized exchange (DEX) blockchain - interoperable with other blockchains using Polkadot. The exchange is using a consensus algorithm that solves MEV/frontrunning problems and makes all participants' access to trading opportunities equal.

Reliable decentralized exchange (DEX) blockchain - interoperable with other blockchains using Polkadot. The exchange is using a consensus algorithm that solves MEV/frontrunning problems and makes all participants' access to trading opportunities equal.

The design of the blockchain guarantees fixed-fees that provides greater control of trading costs and higher arbitrage opportunity.
Assets on the exchange will serve multiple purposes- at the first iteration, they are the block producer’s stake and exchange liquidity at the same time, and more comes later.
Expand Down Expand Up @@ -48,11 +49,14 @@ Find manual setup instructions at the
Recommended rustc version for the build is `nightly-2021-10-19`

Environment variables for ethereum apps should be set up before the build:

```bash
ETH_APP_ID=0xdd514baa317bf095ddba2c0a847765feb389c6a0
ERC20_APP_ID=0x00e392c04743359e39f00cd268a5390d27ef6b44
```

build node:

```bash
rustup target add wasm32-unknown-unknown
cargo build --release
Expand Down Expand Up @@ -99,18 +103,23 @@ docker-compose -f devops/multi-validator-docker-compose.yml up
### VS code

Export RUSTFLAGS

```bash
export RUSTFLAGS="-g"
```

Build node:

```bash
cargo build --release
```

Run node:

```bash
RUSTFLAGS="-g" cargo run -j12 --release -- --tmp --dev
```
Go to VS code and attach the process!

Go to VS code and attach the process!

# Mangata Substrate Cumulus Parachain
9 changes: 2 additions & 7 deletions node/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,12 @@ use codec::Encode;
use cumulus_primitives_core::ParaId;
use hex::FromHex;
use hex_literal::hex;
use mangata_runtime::{
AccountId, AuraId, BlockNumber, IssuanceInfo, Signature, VersionedMultiLocation, KSM_TOKEN_ID,
};
use mangata_runtime::{AccountId, AuraId, Signature, VersionedMultiLocation, KSM_TOKEN_ID};
use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};
use sc_service::ChainType;
use serde::{Deserialize, Serialize};
use sp_core::{sr25519, ByteArray, Pair, Public, H160};
use sp_runtime::{
traits::{IdentifyAccount, Verify},
Perbill,
};
use sp_runtime::traits::{IdentifyAccount, Verify};

pub mod public_testnet_keys {
pub const ALICE_SR25519: &str =
Expand Down
2 changes: 1 addition & 1 deletion pallets/asset-registry/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,5 @@ benchmarks! {
assert_eq!(Pallet::<T>::location_to_currency_ids(MultiLocation::try_from(location).unwrap()), Some(next_currency_id));
}

impl_benchmark_test_suite!(Pallet, crate::tests::new_test_ext(), crate::tests::Test)
impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Runtime)
}
20 changes: 15 additions & 5 deletions pallets/bootstrap/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ benchmarks! {
}
let ksm_provision_amount = 100_000_u128;
let mga_provision_amount = ksm_provision_amount * T::KsmToMgaRatioDenominator::get() / T::KsmToMgaRatioNumerator::get();
<T as Config>::Currency::mint(<T as Config>::MGATokenId::get().into(), &caller, MILION.into()).expect("Token creation failed");
<T as Config>::Currency::mint(<T as Config>::KSMTokenId::get().into(), &caller, MILION.into()).expect("Token creation failed");

BootstrapPallet::<T>::start_ido(RawOrigin::Root.into(), 10_u32.into(), 10_u32, 10_u32).unwrap();
// jump to public phase
Expand All @@ -58,18 +60,24 @@ benchmarks! {
assert_eq!(BootstrapPallet::<T>::provisions(caller, <T as Config>::KSMTokenId::get()), ksm_provision_amount);
}


provision_vested {
let caller: T::AccountId = whitelisted_caller();
let mut token_id = 0;
while token_id < <T as Config>::MGATokenId::get() ||
token_id < <T as Config>::KSMTokenId::get() {
token_id = <T as Config>::Currency::create(&caller, MILION.into()).expect("Token creation failed").into();
}
<T as Config>::Currency::mint(<T as Config>::MGATokenId::get().into(), &caller, MILION.into()).expect("Token creation failed");
<T as Config>::Currency::mint(<T as Config>::KSMTokenId::get().into(), &caller, MILION.into()).expect("Token creation failed");
let ksm_provision_amount = 100_000_u128;
let mga_provision_amount = ksm_provision_amount * T::KsmToMgaRatioDenominator::get() / T::KsmToMgaRatioNumerator::get();
let lock = 100_u128;

<T as Config>::VestingProvider::lock_tokens(&caller, <T as Config>::KSMTokenId::get().into(), ksm_provision_amount.into(), lock.into()).unwrap();
let lock = 100_000_000_u128;

frame_system::Pallet::<T>::set_block_number(1_u32.into());
<T as Config>::VestingProvider::lock_tokens(&caller, <T as Config>::KSMTokenId::get().into(), (ksm_provision_amount*2).into(), lock.into()).unwrap();
frame_system::Pallet::<T>::set_block_number(2_u32.into());

BootstrapPallet::<T>::start_ido(RawOrigin::Root.into(), 10_u32.into(), 10_u32, 10_u32).unwrap();
// jump to public phase
Expand All @@ -78,7 +86,7 @@ benchmarks! {

}: provision_vested(RawOrigin::Signed(caller.clone().into()), <T as Config>::KSMTokenId::get(), ksm_provision_amount)
verify {
assert_eq!(BootstrapPallet::<T>::vested_provisions(caller, <T as Config>::KSMTokenId::get()), (ksm_provision_amount, lock + 1));
assert_eq!(BootstrapPallet::<T>::vested_provisions(caller, <T as Config>::KSMTokenId::get()).0, (ksm_provision_amount));
}

claim_rewards {
Expand All @@ -88,6 +96,8 @@ benchmarks! {
token_id < <T as Config>::KSMTokenId::get() {
token_id = <T as Config>::Currency::create(&caller, MILION.into()).expect("Token creation failed").into();
}
<T as Config>::Currency::mint(<T as Config>::MGATokenId::get().into(), &caller, MILION.into()).expect("Token creation failed");
<T as Config>::Currency::mint(<T as Config>::KSMTokenId::get().into(), &caller, MILION.into()).expect("Token creation failed");
let ksm_provision_amount = 100_000_u128;
let ksm_vested_provision_amount = 300_000_u128;
let mga_provision_amount = ksm_provision_amount * T::KsmToMgaRatioDenominator::get() / T::KsmToMgaRatioNumerator::get();
Expand All @@ -97,8 +107,8 @@ benchmarks! {
let total_provision = total_ksm_provision + total_mga_provision;
let lock = 150_u128;

<T as Config>::VestingProvider::lock_tokens(&caller, <T as Config>::KSMTokenId::get().into(), ksm_vested_provision_amount.into(), lock.into()).unwrap();
<T as Config>::VestingProvider::lock_tokens(&caller, <T as Config>::MGATokenId::get().into(), mga_vested_provision_amount.into(), lock.into()).unwrap();
<T as Config>::VestingProvider::lock_tokens(&caller, <T as Config>::KSMTokenId::get().into(), (ksm_provision_amount + ksm_vested_provision_amount).into(), lock.into()).unwrap();
<T as Config>::VestingProvider::lock_tokens(&caller, <T as Config>::MGATokenId::get().into(), (mga_provision_amount + mga_vested_provision_amount).into(), lock.into()).unwrap();

BootstrapPallet::<T>::start_ido(RawOrigin::Root.into(), 10_u32.into(), 10_u32, 10_u32).unwrap();
BootstrapPallet::<T>::on_initialize(20_u32.into());
Expand Down
20 changes: 15 additions & 5 deletions pallets/bootstrap/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,11 @@ mod benchmarking;
#[cfg(test)]
mod tests;

pub mod weights;
pub use weights::WeightInfo;

pub use pallet::*;
const PALLET_ID: PalletId = PalletId(*b"12345678");
const PALLET_ID: PalletId = PalletId(*b"bootstrp");

use core::fmt::Debug;

Expand Down Expand Up @@ -65,34 +68,39 @@ pub mod pallet {
#[pallet::hooks]
impl<T: Config> Hooks<T::BlockNumber> for Pallet<T> {
fn on_initialize(n: T::BlockNumber) -> Weight {
let phase = Phase::<T>::get();
let phase = Phase::<T>::get(); // R:1
if phase == BootstrapPhase::Finished {
return T::DbWeight::get().reads(1)
}

if let Some((start, whitelist_length, public_length)) = BootstrapSchedule::<T>::get() {
// R:1
// NOTE: arythmetics protected by invariant check in Bootstrap::start_ido
let whitelist_start = start;
let public_start = start + whitelist_length.into();
let finished = start + whitelist_length.into() + public_length.into();

if n >= finished {
Phase::<T>::put(BootstrapPhase::Finished);
Phase::<T>::put(BootstrapPhase::Finished); // 1 WRINTE
log!(info, "bootstrap event finished");
let (mga_valuation, ksm_valuation) = Valuations::<T>::get();
// XykFunctionsTrait R: 11 W:12
// PoolCreateApi::pool_create R:2 +
// ---------------------------------
// R: 13 W 12
if let Some((liq_asset_id, issuance)) = T::PoolCreateApi::pool_create(
Self::vault_address(),
T::KSMTokenId::get(),
ksm_valuation,
T::MGATokenId::get(),
mga_valuation,
) {
MintedLiquidity::<T>::put((liq_asset_id, issuance));
MintedLiquidity::<T>::put((liq_asset_id, issuance)); // W:1
} else {
log!(error, "cannot create pool!");
}
// TODO: include cost of pool_create call
T::DbWeight::get().reads_writes(3, 2)
T::DbWeight::get().reads_writes(15, 13)
} else if n >= public_start {
Phase::<T>::put(BootstrapPhase::Public);
log!(info, "starting public phase");
Expand Down Expand Up @@ -134,6 +142,8 @@ pub mod pallet {
type KsmToMgaRatioDenominator: Get<u128>;

type VestingProvider: MultiTokenVestingLocks<Self::AccountId>;

type WeightInfo: WeightInfo;
}

#[pallet::storage]
Expand Down
67 changes: 43 additions & 24 deletions pallets/bootstrap/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use frame_support::{
use mangata_primitives::{Amount, Balance, TokenId};
use orml_tokens::{MultiTokenCurrency, MultiTokenCurrencyAdapter};
use orml_traits::parameter_type_with_key;
use pallet_issuance::PoolPromoteApi;
use sp_runtime::{Perbill, Percent};
// use pallet_xyk::Pallet;

pub(crate) type AccountId = u128;
Expand Down Expand Up @@ -105,28 +105,6 @@ parameter_types! {
pub FakeLiquidityMiningIssuanceVault: AccountId = LiquidityMiningIssuanceVaultId::get().into_account();
}

pub struct MockPromotedPoolApi;

impl MockPromotedPoolApi {}

impl PoolPromoteApi for MockPromotedPoolApi {
fn promote_pool(_liquidity_token_id: TokenId) -> bool {
false
}

fn get_pool_rewards(_liquidity_token_id: TokenId) -> Option<Balance> {
None
}

fn claim_pool_rewards(_liquidity_token_id: TokenId, _claimed_amount: Balance) -> bool {
false
}

fn len() -> usize {
0
}
}

parameter_types! {
pub const MinVestedTransfer: Balance = 0;
}
Expand All @@ -149,7 +127,7 @@ impl pallet_xyk::Config for Test {
type TreasuryPalletId = TreasuryPalletId;
type BnbTreasurySubAccDerive = BnbTreasurySubAccDerive;
type LiquidityMiningIssuanceVault = FakeLiquidityMiningIssuanceVault;
type PoolPromoteApi = MockPromotedPoolApi;
type PoolPromoteApi = Issuance;
type PoolFeePercentage = ConstU128<20>;
type TreasuryFeePercentage = ConstU128<5>;
type BuyAndBurnFeePercentage = ConstU128<5>;
Expand All @@ -158,6 +136,45 @@ impl pallet_xyk::Config for Test {
type VestingProvider = Vesting;
}

parameter_types! {
pub LiquidityMiningIssuanceVault: AccountId = LiquidityMiningIssuanceVaultId::get().into_account();
pub const StakingIssuanceVaultId: PalletId = PalletId(*b"py/stkiv");
pub StakingIssuanceVault: AccountId = StakingIssuanceVaultId::get().into_account();
pub const MgaTokenId: TokenId = 0u32;


pub const TotalCrowdloanAllocation: Balance = 200_000_000;
pub const IssuanceCap: Balance = 4_000_000_000;
pub const LinearIssuanceBlocks: u32 = 22_222u32;
pub const LiquidityMiningSplit: Perbill = Perbill::from_parts(555555556);
pub const StakingSplit: Perbill = Perbill::from_parts(444444444);
pub const ImmediateTGEReleasePercent: Percent = Percent::from_percent(20);
pub const TGEReleasePeriod: u32 = 100u32; // 2 years
pub const TGEReleaseBegin: u32 = 10u32; // Two weeks into chain start
pub const BlocksPerRound: u32 = 5u32;
pub const HistoryLimit: u32 = 10u32;
}

impl pallet_issuance::Config for Test {
type Event = Event;
type NativeCurrencyId = MgaTokenId;
type Tokens = orml_tokens::MultiTokenCurrencyAdapter<Test>;
type BlocksPerRound = BlocksPerRound;
type HistoryLimit = HistoryLimit;
type LiquidityMiningIssuanceVault = LiquidityMiningIssuanceVault;
type StakingIssuanceVault = StakingIssuanceVault;
type TotalCrowdloanAllocation = TotalCrowdloanAllocation;
type IssuanceCap = IssuanceCap;
type LinearIssuanceBlocks = LinearIssuanceBlocks;
type LiquidityMiningSplit = LiquidityMiningSplit;
type StakingSplit = StakingSplit;
type ImmediateTGEReleasePercent = ImmediateTGEReleasePercent;
type TGEReleasePeriod = TGEReleasePeriod;
type TGEReleaseBegin = TGEReleaseBegin;
type VestingProvider = Vesting;
type WeightInfo = ();
}

mockall::mock! {
pub PoolCreateApi {}

Expand All @@ -180,6 +197,7 @@ impl pallet_bootstrap::Config for Test {
type KsmToMgaRatioNumerator = KsmToMgaNumerator;
type KsmToMgaRatioDenominator = KsmToMgaDenominator;
type VestingProvider = Vesting;
type WeightInfo = ();
}

#[cfg(feature = "runtime-benchmarks")]
Expand Down Expand Up @@ -232,6 +250,7 @@ construct_runtime!(
Xyk: pallet_xyk::{Pallet, Call, Storage, Event<T>, Config<T>},
Bootstrap: pallet_bootstrap::{Pallet, Call, Storage, Event<T>},
Vesting: pallet_vesting_mangata::{Pallet, Call, Storage, Event<T>},
Issuance: pallet_issuance::{Pallet, Event<T>, Storage},
}
);

Expand Down
40 changes: 40 additions & 0 deletions pallets/bootstrap/src/weights.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(clippy::unnecessary_cast)]

use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
use sp_std::marker::PhantomData;

/// Weight functions needed for pallet_bootstrap.
pub trait WeightInfo {
fn start_ido() -> Weight;
fn provision() -> Weight;
fn provision_vested() -> Weight;
fn claim_rewards() -> Weight;
}


// For backwards compatibility and tests
impl WeightInfo for () {
fn start_ido() -> Weight {
(23_396_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
fn provision() -> Weight {
(103_365_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(7 as Weight))
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
fn provision_vested() -> Weight {
(150_718_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(9 as Weight))
.saturating_add(RocksDbWeight::get().writes(7 as Weight))
}
fn claim_rewards() -> Weight {
(273_011_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(13 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
}
}
4 changes: 3 additions & 1 deletion pallets/issuance/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ version = '2.0.0'
targets = ['x86_64-unknown-linux-gnu']

[dependencies]
log = { version = "0.4.14", default-features = false }
serde = { version = "1.0.126", optional = true }
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
scale-info = { version = "1.0", default-features = false, features = ["derive"] }
Expand All @@ -20,6 +21,7 @@ sp-std = { default-features = false, version = '4.0.0-dev' , git = "https://gith
sp-runtime = { git = "https://github.com/mangata-finance/substrate", default-features = false, branch = "mangata-dev" }
pallet-vesting-mangata = { git = "https://github.com/mangata-finance/substrate", default-features = false, branch = "mangata-dev" }
frame-benchmarking = { git = "https://github.com/mangata-finance/substrate", branch = "mangata-dev", optional = true, default-features = false }
cfg-if = "1.0.0"

[dev-dependencies]
sp-core = { default-features = false, version = '4.1.0-dev' , git = "https://github.com/mangata-finance/substrate", branch = "mangata-dev" }
Expand All @@ -43,4 +45,4 @@ runtime-benchmarks = [
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"frame-benchmarking/runtime-benchmarks",
]
]
Loading

0 comments on commit 87cd9ec

Please # to comment.