diff --git a/Cargo.lock b/Cargo.lock index c1e527100..432b343cf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -868,6 +868,7 @@ dependencies = [ name = "darwinia-kton" version = "0.2.0" dependencies = [ + "darwinia-balances 0.2.0", "darwinia-support 0.2.0", "parity-scale-codec 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.103 (registry+https://github.com/rust-lang/crates.io-index)", @@ -888,6 +889,7 @@ dependencies = [ "darwinia-kton 0.2.0", "darwinia-support 0.2.0", "parity-scale-codec 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "regex 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.103 (registry+https://github.com/rust-lang/crates.io-index)", "sr-io 2.0.0 (git+https://github.com/darwinia-network/substrate.git?branch=darwinia-develop)", "sr-primitives 2.0.0 (git+https://github.com/darwinia-network/substrate.git?branch=darwinia-develop)", diff --git a/node/runtime/src/constants.rs b/node/runtime/src/constants.rs index 658dc7724..fd9f97469 100644 --- a/node/runtime/src/constants.rs +++ b/node/runtime/src/constants.rs @@ -49,9 +49,9 @@ pub mod time { /// // Develop - pub const MILLISECS_PER_BLOCK: Moment = 1000; + // pub const MILLISECS_PER_BLOCK: Moment = 1000; // Production - // pub const MILLISECS_PER_BLOCK: Moment = 3000; + pub const MILLISECS_PER_BLOCK: Moment = 3000; pub const SECS_PER_BLOCK: Moment = MILLISECS_PER_BLOCK / 1000; pub const SLOT_DURATION: Moment = MILLISECS_PER_BLOCK; @@ -60,9 +60,9 @@ pub mod time { pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4); // Develop - pub const EPOCH_DURATION_IN_BLOCKS: BlockNumber = MINUTES; + // pub const EPOCH_DURATION_IN_BLOCKS: BlockNumber = MINUTES; // Production - // pub const EPOCH_DURATION_IN_BLOCKS: BlockNumber = 10 * MINUTES; + pub const EPOCH_DURATION_IN_BLOCKS: BlockNumber = 10 * MINUTES; pub const EPOCH_DURATION_IN_SLOTS: u64 = { const SLOT_FILL_RATE: f64 = MILLISECS_PER_BLOCK as f64 / SLOT_DURATION as f64; @@ -73,6 +73,12 @@ pub mod time { pub const MINUTES: BlockNumber = 60 / (SECS_PER_BLOCK as BlockNumber); pub const HOURS: BlockNumber = MINUTES * 60; pub const DAYS: BlockNumber = HOURS * 24; + + pub const SESSION_DURATION: BlockNumber = EPOCH_DURATION_IN_SLOTS as _; + // Develop + // pub const SESSION_PER_ERA: sr_staking_primitives::SessionIndex = 1; + // Production + pub const SESSION_PER_ERA: sr_staking_primitives::SessionIndex = 5; } // CRITICAL NOTE: The system module maintains two constants: a _maximum_ block weight and a _ratio_ diff --git a/node/runtime/src/lib.rs b/node/runtime/src/lib.rs index 96b91dd98..5498a6541 100644 --- a/node/runtime/src/lib.rs +++ b/node/runtime/src/lib.rs @@ -137,27 +137,18 @@ impl indices::Trait for Runtime { } parameter_types! { - pub const ExistentialDeposit: Balance = 1 * COIN; - pub const TransferFee: Balance = 1 * MICRO; - pub const CreationFee: Balance = 1 * MICRO; -} -impl balances::Trait for Runtime { - type Balance = Balance; - type OnFreeBalanceZero = ((Staking, Contracts), Session); - type OnNewAccount = Indices; - type TransferPayment = (); - type DustRemoval = (); - type Event = Event; - type ExistentialDeposit = ExistentialDeposit; - type TransferFee = TransferFee; - type CreationFee = CreationFee; -} - -parameter_types! { - pub const TransactionBaseFee: Balance = 1 * MICRO; - pub const TransactionByteFee: Balance = 10 * MICRO; + // Develop + pub const TransactionBaseFee: Balance = MICRO; + pub const TransactionByteFee: Balance = MICRO; // setting this to zero will disable the weight fee. - pub const WeightFeeCoefficient: Balance = 1_000; + pub const WeightFeeCoefficient: Balance = MICRO; + + // Production +// pub const TransactionBaseFee: Balance = 1 * MICRO; +// pub const TransactionByteFee: Balance = 10 * MICRO; +// // setting this to zero will disable the weight fee. +// pub const WeightFeeCoefficient: Balance = 1 * MICRO; + // for a sane configuration, this should always be less than `AvailableBlockRatio`. pub const TargetBlockFullness: Perbill = Perbill::from_percent(25); } @@ -246,7 +237,7 @@ impl offences::Trait for Runtime { type SubmitTransaction = TransactionSubmitter; parameter_types! { - pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_SLOTS as _; + pub const SessionDuration: BlockNumber = SESSION_DURATION; } impl im_online::Trait for Runtime { type AuthorityId = ImOnlineId; @@ -272,15 +263,27 @@ impl finality_tracker::Trait for Runtime { } parameter_types! { - pub const ContractTransferFee: Balance = 1 * MICRO; - pub const ContractCreationFee: Balance = 1 * MICRO; - pub const ContractTransactionBaseFee: Balance = 1 * MICRO; - pub const ContractTransactionByteFee: Balance = 10 * MICRO; - pub const ContractFee: Balance = 1 * MICRO; - pub const TombstoneDeposit: Balance = 1 * COIN; - pub const RentByteFee: Balance = 1 * COIN; - pub const RentDepositOffset: Balance = 1000 * COIN; - pub const SurchargeReward: Balance = 150 * COIN; + // Develop + pub const ContractTransferFee: Balance = MICRO; + pub const ContractCreationFee: Balance = MICRO; + pub const ContractTransactionBaseFee: Balance = MICRO; + pub const ContractTransactionByteFee: Balance = MICRO; + pub const ContractFee: Balance = MICRO; + pub const TombstoneDeposit: Balance = MICRO; + pub const RentByteFee: Balance = MICRO; + pub const RentDepositOffset: Balance = MICRO; + pub const SurchargeReward: Balance = MICRO; + + // Production +// pub const ContractTransferFee: Balance = 1 * MICRO; +// pub const ContractCreationFee: Balance = 1 * MICRO; +// pub const ContractTransactionBaseFee: Balance = 1 * MICRO; +// pub const ContractTransactionByteFee: Balance = 10 * MICRO; +// pub const ContractFee: Balance = 1 * MICRO; +// pub const TombstoneDeposit: Balance = 1 * COIN; +// pub const RentByteFee: Balance = 1 * COIN; +// pub const RentDepositOffset: Balance = 1000 * COIN; +// pub const SurchargeReward: Balance = 150 * COIN; } impl contracts::Trait for Runtime { type Currency = Balances; @@ -341,20 +344,31 @@ impl system::offchain::CreateTransaction for Runtim } } -impl kton::Trait for Runtime { +parameter_types! { + pub const ExistentialDeposit: Balance = 1 * COIN; + pub const TransferFee: Balance = 1 * MICRO; + pub const CreationFee: Balance = 1 * MICRO; +} +impl balances::Trait for Runtime { type Balance = Balance; + type OnFreeBalanceZero = ((Staking, Contracts), Session); + type OnNewAccount = Indices; + type TransferPayment = (); + type DustRemoval = (); + type Event = Event; + type ExistentialDeposit = ExistentialDeposit; + type TransferFee = TransferFee; + type CreationFee = CreationFee; +} +impl kton::Trait for Runtime { type Event = Event; - type OnMinted = (); - type OnRemoval = (); } parameter_types! { - // Develop - pub const SessionsPerEra: sr_staking_primitives::SessionIndex = 1; - // Production - // pub const SessionsPerEra: sr_staking_primitives::SessionIndex = 6; + pub const SessionsPerEra: sr_staking_primitives::SessionIndex = SESSION_PER_ERA; // about 14 days = 14 * 24 * 60 * 60 * 1000 pub const BondingDuration: Moment = 1_209_600_000; + pub const BondingDurationInEra: staking::EraIndex = 4032; // decimal 9 pub const HardCap: Balance = 10_000_000_000 * COIN; // date in Los Angeles*: 11/19/2019, 2:33:20 AM @@ -364,19 +378,20 @@ parameter_types! { pub const GenesisTime: Moment = 1_574_156_000_000; } impl staking::Trait for Runtime { - type Ring = Balances; - type Kton = Kton; type Time = Timestamp; type CurrencyToVote = CurrencyToVoteHandler; - type RingRewardRemainder = (); type Event = Event; - type RingReward = (); - type KtonReward = (); - type RingSlash = (); - type KtonSlash = (); type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; + type BondingDurationInEra = BondingDurationInEra; type SessionInterface = Self; + type Ring = Balances; + type RingRewardRemainder = (); + type RingSlash = (); + type RingReward = (); + type Kton = Kton; + type KtonSlash = (); + type KtonReward = (); type Cap = HardCap; type GenesisTime = GenesisTime; diff --git a/srml/balances/src/lib.rs b/srml/balances/src/lib.rs index 2b0c918f9..90ede3946 100644 --- a/srml/balances/src/lib.rs +++ b/srml/balances/src/lib.rs @@ -16,6 +16,11 @@ #![cfg_attr(not(feature = "std"), no_std)] +#[cfg(all(feature = "std", test))] +mod mock; +#[cfg(all(feature = "std", test))] +mod tests; + use codec::{Codec, Decode, Encode}; use rstd::{cmp, fmt::Debug, mem, prelude::*, result}; use sr_primitives::{ @@ -37,14 +42,11 @@ use support::{ }; use system::{ensure_root, ensure_signed, IsDeadAccount, OnNewAccount}; -#[cfg(all(feature = "std", test))] -mod mock; -#[cfg(all(feature = "std", test))] -mod tests; - use darwinia_support::{BalanceLock, LockIdentifier, LockableCurrency, WithdrawLock, WithdrawReason, WithdrawReasons}; use imbalances::{NegativeImbalance, PositiveImbalance}; +pub type Balance = u128; + pub trait Subtrait: system::Trait + timestamp::Trait { /// The balance of an account. type Balance: Parameter @@ -387,7 +389,7 @@ impl, I: Instance> Module { /// /// NOTE: LOW-LEVEL: This will not attempt to maintain total issuance. It is expected that /// the caller will do this. - fn set_reserved_balance(who: &T::AccountId, balance: T::Balance) -> UpdateBalanceOutcome { + pub fn set_reserved_balance(who: &T::AccountId, balance: T::Balance) -> UpdateBalanceOutcome { if balance < T::ExistentialDeposit::get() { >::insert(who, balance); Self::on_reserved_too_low(who); @@ -406,7 +408,7 @@ impl, I: Instance> Module { /// /// NOTE: LOW-LEVEL: This will not attempt to maintain total issuance. It is expected that /// the caller will do this. - fn set_free_balance(who: &T::AccountId, balance: T::Balance) -> UpdateBalanceOutcome { + pub fn set_free_balance(who: &T::AccountId, balance: T::Balance) -> UpdateBalanceOutcome { // Commented out for now - but consider it instructive. // assert!(!Self::total_balance(who).is_zero()); // assert!(Self::free_balance(who) > T::ExistentialDeposit::get()); @@ -423,7 +425,7 @@ impl, I: Instance> Module { /// Register a new account (with existential balance). /// /// This just calls appropriate hooks. It doesn't (necessarily) make any state changes. - fn new_account(who: &T::AccountId, balance: T::Balance) { + pub fn new_account(who: &T::AccountId, balance: T::Balance) { T::OnNewAccount::on_new_account(&who); Self::deposit_event(RawEvent::NewAccount(who.clone(), balance.clone())); } @@ -431,7 +433,7 @@ impl, I: Instance> Module { /// Unregister an account. /// /// This just removes the nonce and leaves an event. - fn reap_account(who: &T::AccountId) { + pub fn reap_account(who: &T::AccountId) { >::remove(who); Self::deposit_event(RawEvent::ReapedAccount(who.clone())); } @@ -440,7 +442,7 @@ impl, I: Instance> Module { /// free side and the account completely if its reserved size is already dead. /// /// Will maintain total issuance. - fn on_free_too_low(who: &T::AccountId) { + pub fn on_free_too_low(who: &T::AccountId) { let dust = >::take(who); >::remove(who); @@ -460,7 +462,7 @@ impl, I: Instance> Module { /// reserved side and the account completely if its free size is already dead. /// /// Will maintain total issuance. - fn on_reserved_too_low(who: &T::AccountId) { + pub fn on_reserved_too_low(who: &T::AccountId) { let dust = >::take(who); // underflow should never happen, but it if does, there's nothing to be done here. @@ -476,7 +478,7 @@ impl, I: Instance> Module { // wrapping these imbalances in a private module is necessary to ensure absolute privacy // of the inner member. -mod imbalances { +pub mod imbalances { use super::{result, DefaultInstance, Imbalance, Instance, Saturating, StorageValue, Subtrait, Trait, Zero}; use rstd::mem; diff --git a/srml/balances/src/mock.rs b/srml/balances/src/mock.rs index ee4057050..b1a121186 100644 --- a/srml/balances/src/mock.rs +++ b/srml/balances/src/mock.rs @@ -28,33 +28,45 @@ use support::{impl_outer_origin, parameter_types, traits::Get}; use crate::*; +/// The AccountId alias in this test module. +pub type AccountId = u64; +pub type BlockNumber = u64; +pub type Moment = u64; + +pub type System = system::Module; +pub type Timestamp = timestamp::Module; + +pub type Balances = Module; + +pub const CALL: &::Call = &(); + impl_outer_origin! { - pub enum Origin for Runtime {} + pub enum Origin for Test {} } thread_local! { - static EXISTENTIAL_DEPOSIT: RefCell = RefCell::new(0); - static TRANSFER_FEE: RefCell = RefCell::new(0); - static CREATION_FEE: RefCell = RefCell::new(0); + static EXISTENTIAL_DEPOSIT: RefCell = RefCell::new(0); + static TRANSFER_FEE: RefCell = RefCell::new(0); + static CREATION_FEE: RefCell = RefCell::new(0); } pub struct ExistentialDeposit; -impl Get for ExistentialDeposit { - fn get() -> u64 { +impl Get for ExistentialDeposit { + fn get() -> Balance { EXISTENTIAL_DEPOSIT.with(|v| *v.borrow()) } } pub struct TransferFee; -impl Get for TransferFee { - fn get() -> u64 { +impl Get for TransferFee { + fn get() -> Balance { TRANSFER_FEE.with(|v| *v.borrow()) } } pub struct CreationFee; -impl Get for CreationFee { - fn get() -> u64 { +impl Get for CreationFee { + fn get() -> Balance { CREATION_FEE.with(|v| *v.borrow()) } } @@ -63,8 +75,8 @@ impl Get for CreationFee { #[derive(Clone, PartialEq, Eq, Debug)] pub struct Test; parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: u32 = 1024; + pub const BlockHashCount: BlockNumber = 250; + pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } @@ -87,8 +99,8 @@ impl system::Trait for Test { } parameter_types! { - pub const TransactionBaseFee: u64 = 0; - pub const TransactionByteFee: u64 = 1; + pub const TransactionBaseFee: Balance = 0; + pub const TransactionByteFee: Balance = 1; } impl transaction_payment::Trait for Test { type Currency = Module; @@ -100,11 +112,11 @@ impl transaction_payment::Trait for Test { } parameter_types! { - pub const MinimumPeriod: u64 = 5; + pub const MinimumPeriod: Moment = 5; } impl timestamp::Trait for Test { - type Moment = u64; + type Moment = Moment; type OnTimestampSet = (); type MinimumPeriod = MinimumPeriod; } @@ -122,9 +134,9 @@ impl Trait for Test { } pub struct ExtBuilder { - existential_deposit: u64, - transfer_fee: u64, - creation_fee: u64, + existential_deposit: Balance, + transfer_fee: Balance, + creation_fee: Balance, monied: bool, vesting: bool, } @@ -140,16 +152,16 @@ impl Default for ExtBuilder { } } impl ExtBuilder { - pub fn existential_deposit(mut self, existential_deposit: u64) -> Self { + pub fn existential_deposit(mut self, existential_deposit: Balance) -> Self { self.existential_deposit = existential_deposit; self } #[allow(dead_code)] - pub fn transfer_fee(mut self, transfer_fee: u64) -> Self { + pub fn transfer_fee(mut self, transfer_fee: Balance) -> Self { self.transfer_fee = transfer_fee; self } - pub fn creation_fee(mut self, creation_fee: u64) -> Self { + pub fn creation_fee(mut self, creation_fee: Balance) -> Self { self.creation_fee = creation_fee; self } @@ -200,13 +212,6 @@ impl ExtBuilder { } } -pub type System = system::Module; -pub type Timestamp = timestamp::Module; - -pub type Balances = Module; - -pub const CALL: &::Call = &(); - /// create a transaction info struct from weight. Handy to avoid building the whole struct. pub fn info_from_weight(w: Weight) -> DispatchInfo { DispatchInfo { diff --git a/srml/balances/src/tests.rs b/srml/balances/src/tests.rs index 8d1c5d7bf..22074c77f 100644 --- a/srml/balances/src/tests.rs +++ b/srml/balances/src/tests.rs @@ -43,7 +43,7 @@ fn basic_locking_should_work() { &1, WithdrawLock::Normal(NormalLock { amount: 9, - until: u64::max_value(), + until: Moment::max_value(), }), WithdrawReasons::all(), ); @@ -66,7 +66,7 @@ fn partial_locking_should_work() { &1, WithdrawLock::Normal(NormalLock { amount: 5, - until: u64::max_value(), + until: Moment::max_value(), }), WithdrawReasons::all(), ); @@ -85,8 +85,8 @@ fn lock_removal_should_work() { ID_1, &1, WithdrawLock::Normal(NormalLock { - amount: u64::max_value(), - until: u64::max_value(), + amount: Balance::max_value(), + until: Moment::max_value(), }), WithdrawReasons::all(), ); @@ -106,8 +106,8 @@ fn lock_replacement_should_work() { ID_1, &1, WithdrawLock::Normal(NormalLock { - amount: u64::max_value(), - until: u64::max_value(), + amount: Balance::max_value(), + until: Moment::max_value(), }), WithdrawReasons::all(), ); @@ -116,7 +116,7 @@ fn lock_replacement_should_work() { &1, WithdrawLock::Normal(NormalLock { amount: 5, - until: u64::max_value(), + until: Moment::max_value(), }), WithdrawReasons::all(), ); @@ -136,7 +136,7 @@ fn double_locking_should_work() { &1, WithdrawLock::Normal(NormalLock { amount: 5, - until: u64::max_value(), + until: Moment::max_value(), }), WithdrawReasons::all(), ); @@ -145,7 +145,7 @@ fn double_locking_should_work() { &1, WithdrawLock::Normal(NormalLock { amount: 5, - until: u64::max_value(), + until: Moment::max_value(), }), WithdrawReasons::all(), ); @@ -164,7 +164,7 @@ fn combination_locking_should_work() { ID_1, &1, WithdrawLock::Normal(NormalLock { - amount: u64::max_value(), + amount: Balance::max_value(), until: 0, }), WithdrawReasons::all(), @@ -174,7 +174,7 @@ fn combination_locking_should_work() { &1, WithdrawLock::Normal(NormalLock { amount: 0, - until: u64::max_value(), + until: Moment::max_value(), }), WithdrawReasons::all(), ); @@ -201,7 +201,7 @@ fn combination_locking_should_work() { // &1, // WithdrawLock::Normal(NormalLock { // amount: 5, -// until: u64::max_value(), +// until: Moment::max_value(), // }), // WithdrawReasons::all() // ); @@ -224,7 +224,7 @@ fn lock_reasons_should_work() { &1, WithdrawLock::Normal(NormalLock { amount: 10, - until: u64::max_value(), + until: Moment::max_value(), }), WithdrawReason::Transfer.into(), ); @@ -248,7 +248,7 @@ fn lock_reasons_should_work() { &1, WithdrawLock::Normal(NormalLock { amount: 10, - until: u64::max_value(), + until: Moment::max_value(), }), WithdrawReason::Reserve.into(), ); @@ -271,7 +271,7 @@ fn lock_reasons_should_work() { &1, WithdrawLock::Normal(NormalLock { amount: 10, - until: u64::max_value(), + until: Moment::max_value(), }), WithdrawReason::TransactionPayment.into(), ); @@ -324,7 +324,7 @@ fn lock_block_number_should_work() { // &1, // WithdrawLock::Normal(NormalLock { // amount: 10, -// until: u64::max_value(), +// until: Moment::max_value(), // }), // WithdrawReasons::all() // ); @@ -622,15 +622,15 @@ fn transferring_incomplete_reserved_balance_should_work() { #[test] fn transferring_too_high_value_should_not_panic() { ExtBuilder::default().build().execute_with(|| { - >::insert(1, u64::max_value()); + >::insert(1, Balance::max_value()); >::insert(2, 1); assert_err!( - Balances::transfer(Some(1).into(), 2, u64::max_value()), + Balances::transfer(Some(1).into(), 2, Balance::max_value()), "destination balance too high to receive value", ); - assert_eq!(Balances::free_balance(&1), u64::max_value()); + assert_eq!(Balances::free_balance(&1), Balance::max_value()); assert_eq!(Balances::free_balance(&2), 1); }); } @@ -689,7 +689,7 @@ fn account_removal_on_free_too_low() { fn transfer_overflow_isnt_exploitable() { ExtBuilder::default().creation_fee(50).build().execute_with(|| { // Craft a value that will overflow if summed with `creation_fee`. - let evil_value = u64::max_value() - 49; + let evil_value = Balance::max_value() - 49; assert_err!( Balances::transfer(Some(1).into(), 5, evil_value), diff --git a/srml/eth-relay/src/mock.rs b/srml/eth-relay/src/mock.rs index 4dbdea82c..2ea7fb7ae 100644 --- a/srml/eth-relay/src/mock.rs +++ b/srml/eth-relay/src/mock.rs @@ -1,61 +1,40 @@ //! Test utilities -use std::cell::RefCell; - use primitives::H256; -use sr_primitives::{testing::Header, traits::IdentityLookup, Perbill}; +use sr_primitives::{testing::Header, traits::IdentityLookup, weights::Weight, Perbill}; use support::{impl_outer_origin, parameter_types}; use crate::*; -impl_outer_origin! { - pub enum Origin for Runtime {} -} +/// The AccountId alias in this test module. +pub type AccountId = u64; +pub type BlockNumber = u64; -thread_local! { - static EXISTENTIAL_DEPOSIT: RefCell = RefCell::new(0); - static TRANSFER_FEE: RefCell = RefCell::new(0); - static CREATION_FEE: RefCell = RefCell::new(0); -} +pub type System = system::Module; -//pub struct ExistentialDeposit; -//impl Get for ExistentialDeposit { -// fn get() -> u64 { -// EXISTENTIAL_DEPOSIT.with(|v| *v.borrow()) -// } -//} -// -//pub struct TransferFee; -//impl Get for TransferFee { -// fn get() -> u64 { -// TRANSFER_FEE.with(|v| *v.borrow()) -// } -//} -// -//pub struct CreationFee; -//impl Get for CreationFee { -// fn get() -> u64 { -// CREATION_FEE.with(|v| *v.borrow()) -// } -//} +pub type EthRelay = Module; + +impl_outer_origin! { + pub enum Origin for Test {} +} // Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted. #[derive(Clone, PartialEq, Eq, Debug)] -pub struct Runtime; +pub struct Test; parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: u32 = 1024; + pub const BlockHashCount: BlockNumber = 250; + pub const MaximumBlockWeight: Weight = 1024; pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } -impl system::Trait for Runtime { +impl system::Trait for Test { type Origin = Origin; type Call = (); type Index = u64; - type BlockNumber = u64; + type BlockNumber = BlockNumber; type Hash = H256; type Hashing = ::sr_primitives::traits::BlakeTwo256; - type AccountId = u64; + type AccountId = AccountId; type Lookup = IdentityLookup; type Header = Header; type Event = (); @@ -65,93 +44,27 @@ impl system::Trait for Runtime { type AvailableBlockRatio = AvailableBlockRatio; type Version = (); } -parameter_types! { - pub const TransactionBaseFee: u64 = 0; - pub const TransactionByteFee: u64 = 1; -} parameter_types! { // pub const EthMainet: u64 = 0; pub const EthRopsten: u64 = 1; } -impl Trait for Runtime { +impl Trait for Test { type Event = (); type EthNetwork = EthRopsten; } -parameter_types! { - pub const MinimumPeriod: u64 = 5; -} - -pub struct ExtBuilder { - existential_deposit: u64, - transfer_fee: u64, - creation_fee: u64, - monied: bool, - vesting: bool, -} +pub struct ExtBuilder; impl Default for ExtBuilder { fn default() -> Self { - Self { - existential_deposit: 0, - transfer_fee: 0, - creation_fee: 0, - monied: false, - vesting: false, - } + Self } } impl ExtBuilder { - pub fn existential_deposit(mut self, existential_deposit: u64) -> Self { - self.existential_deposit = existential_deposit; - self - } - #[allow(dead_code)] - pub fn transfer_fee(mut self, transfer_fee: u64) -> Self { - self.transfer_fee = transfer_fee; - self - } - #[allow(dead_code)] - pub fn creation_fee(mut self, creation_fee: u64) -> Self { - self.creation_fee = creation_fee; - self - } - #[allow(dead_code)] - pub fn monied(mut self, monied: bool) -> Self { - self.monied = monied; - if self.existential_deposit == 0 { - self.existential_deposit = 1; - } - self - } - #[allow(dead_code)] - pub fn vesting(mut self, vesting: bool) -> Self { - self.vesting = vesting; - self - } - pub fn set_associated_consts(&self) { - EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit); - TRANSFER_FEE.with(|v| *v.borrow_mut() = self.transfer_fee); - CREATION_FEE.with(|v| *v.borrow_mut() = self.creation_fee); - } pub fn build(self) -> runtime_io::TestExternalities { - self.set_associated_consts(); - let t = system::GenesisConfig::default().build_storage::().unwrap(); + let t = system::GenesisConfig::default().build_storage::().unwrap(); t.into() } } - -pub type System = system::Module; -pub type EthRelay = Module; - -//pub const CALL: &::Call = &(); - -// create a transaction info struct from weight. Handy to avoid building the whole struct. -//pub fn info_from_weight(w: Weight) -> DispatchInfo { -// DispatchInfo { -// weight: w, -// ..Default::default() -// } -//} diff --git a/srml/eth-relay/src/tests.rs b/srml/eth-relay/src/tests.rs index 0e5908f66..dcb17704d 100644 --- a/srml/eth-relay/src/tests.rs +++ b/srml/eth-relay/src/tests.rs @@ -1,5 +1,4 @@ //! Tests for the module. - use std::str::FromStr; use hex_literal::hex; @@ -15,8 +14,6 @@ use crate::{mock::*, *}; #[test] fn verify_receipt_proof() { ExtBuilder::default() - .existential_deposit(256 * 1) - .monied(true) .build() .execute_with(|| { System::inc_account_nonce(&2); @@ -77,7 +74,7 @@ fn verify_receipt_proof() { #[test] fn relay_header() { - ExtBuilder::default().monied(true).build().execute_with(|| { + ExtBuilder::default().build().execute_with(|| { // 6760579 let mixh1 = H256::from(hex!("1e2fc5a540b8f1cdaf50de52c388b1f53856cc61eb3ad20d91b9fcc2de3e3e2a")); let nonce1 = H64::from(hex!("339140bca72c49cd")); diff --git a/srml/kton/Cargo.toml b/srml/kton/Cargo.toml index b1af31eac..7aeadf14b 100644 --- a/srml/kton/Cargo.toml +++ b/srml/kton/Cargo.toml @@ -11,13 +11,14 @@ serde = { version = "1.0.101", optional = true } # github.com rstd = { package = "sr-std", git = "https://github.com/darwinia-network/substrate.git", branch = "darwinia-develop", default-features = false } -srml-support = { git = "https://github.com/darwinia-network/substrate.git", branch = "darwinia-develop", default-features = false } +support = { package = "srml-support", git = "https://github.com/darwinia-network/substrate.git", branch = "darwinia-develop", default-features = false } sr-primitives = { git = "https://github.com/darwinia-network/substrate.git", branch = "darwinia-develop", default-features = false } system = { package = "srml-system", git = "https://github.com/darwinia-network/substrate.git", branch = "darwinia-develop", default-features = false } timestamp = { package = "srml-timestamp", git = "https://github.com/darwinia-network/substrate.git", branch = "darwinia-develop", default-features = false } # darwinia darwinia-support = { path = "../support", default-features = false } +ring = { package = "darwinia-balances", path = "../balances", default-features = false } [dev-dependencies] runtime_io = { package = "sr-io", git = "https://github.com/darwinia-network/substrate.git", branch = "darwinia-develop" } @@ -30,10 +31,14 @@ std = [ "serde", "rstd/std", - "srml-support/std", "sr-primitives/std", + "support/std", "system/std", "timestamp/std", "darwinia-support/std", + "ring/std", ] + +# test +transfer-fee = ["std"] diff --git a/srml/kton/src/lib.rs b/srml/kton/src/lib.rs index 1f6e61e31..5c00f8eed 100644 --- a/srml/kton/src/lib.rs +++ b/srml/kton/src/lib.rs @@ -1,89 +1,46 @@ #![cfg_attr(not(feature = "std"), no_std)] -use codec::{Codec, Decode, Encode}; +#[allow(unused)] +#[cfg(all(feature = "std", test))] +mod mock; +#[cfg(all(feature = "std", test))] +mod tests; + #[cfg(not(feature = "std"))] use rstd::borrow::ToOwned; use rstd::{cmp, fmt::Debug, mem, prelude::*, result}; use sr_primitives::{ traits::{ - Bounded, CheckedAdd, CheckedSub, MaybeSerializeDeserialize, Member, Saturating, SimpleArithmetic, StaticLookup, - Zero, + Bounded, CheckedAdd, CheckedSub, MaybeSerializeDeserialize, SaturatedConversion, Saturating, StaticLookup, Zero, }, weights::SimpleDispatchInfo, - RuntimeDebug, }; -use srml_support::{ +use support::{ decl_event, decl_module, decl_storage, dispatch::Result, - traits::{Currency, ExistenceRequirement, Imbalance, OnUnbalanced, SignedImbalance, UpdateBalanceOutcome}, - Parameter, StorageMap, StorageValue, + traits::{Currency, ExistenceRequirement, Get, Imbalance, OnUnbalanced, SignedImbalance, UpdateBalanceOutcome}, + StorageMap, StorageValue, }; use system::{ensure_root, ensure_signed}; use darwinia_support::{BalanceLock, LockIdentifier, LockableCurrency, WithdrawLock, WithdrawReason, WithdrawReasons}; use imbalances::{NegativeImbalance, PositiveImbalance}; +use ring::{imbalances::NegativeImbalance as NegativeImbalanceRing, Balance, VestingSchedule}; -#[allow(unused)] -#[cfg(all(feature = "std", test))] -mod mock; -#[cfg(all(feature = "std", test))] -mod tests; - -pub trait Trait: timestamp::Trait { - type Balance: Parameter - + Member - + SimpleArithmetic - + Codec - + Default - + Copy - + MaybeSerializeDeserialize - + From; - +pub trait Trait: ring::Trait { + /// The overarching event type. type Event: From> + Into<::Event>; - - type OnMinted: OnUnbalanced>; - type OnRemoval: OnUnbalanced>; } decl_event!( pub enum Event where - < T as system::Trait>::AccountId, - < T as Trait>::Balance, + ::AccountId, { /// Transfer succeeded (from, to, value, fees). - TokenTransfer(AccountId, AccountId, Balance), + Transfer(AccountId, AccountId, Balance, Balance), } ); -/// Struct to encode the vesting schedule of an individual account. -#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug)] -pub struct VestingSchedule { - /// Locked amount at genesis. - pub locked: Balance, - /// Amount that gets unlocked every block after `starting_block`. - pub per_block: Balance, - /// Starting block for unbondings(vesting). - pub starting_block: BlockNumber, -} - -impl VestingSchedule { - /// Amount locked at block `n`. - pub fn locked_at(&self, n: BlockNumber) -> Balance - where - Balance: From, - { - // Number of blocks that count toward vesting - // Saturating to 0 when n < starting_block - let vested_block_count = n.saturating_sub(self.starting_block); - // Return amount that is still locked in vesting - if let Some(x) = Balance::from(vested_block_count).checked_mul(&self.per_block) { - self.locked.max(x) - x - } else { - Zero::zero() - } - } -} - decl_storage! { trait Store for Module as Kton { /// The total units issued in the system. @@ -515,26 +472,39 @@ where value: Self::Balance, _existence_requirement: ExistenceRequirement, ) -> Result { - let new_from_balance = if let Some(b) = Self::free_balance(transactor).checked_sub(&value) { - b - } else { - return Err("balance too low to send value"); - }; + let fee = ::TransferFee::get(); - Self::ensure_can_withdraw(transactor, value, WithdrawReason::Transfer.into(), new_from_balance)?; + let new_from_ring = >::get(transactor) + .checked_sub(&fee) + .ok_or("Transfer Fee - NOT ENOUGH RING")?; + >::ensure_can_withdraw(transactor, fee, WithdrawReason::Fee.into(), new_from_ring)?; - // NOTE: total stake being stored in the same type means that this could never overflow - // but better to be safe than sorry. - let new_to_balance = if let Some(b) = Self::free_balance(dest).checked_add(&value) { - b - } else { - return Err("destination balance too high to receive value"); - }; + let new_from_kton = Self::free_balance(transactor) + .checked_sub(&value) + .ok_or("balance too low to send value")?; + Self::ensure_can_withdraw(transactor, value, WithdrawReason::Transfer.into(), new_from_kton)?; + + let new_to_kton = Self::free_balance(dest) + .checked_add(&value) + .ok_or("destination balance too high to receive value")?; if transactor != dest { - Self::set_free_balance(transactor, new_from_balance); - Self::set_free_balance(dest, new_to_balance); - Self::deposit_event(RawEvent::TokenTransfer(transactor.to_owned(), dest.to_owned(), value)); + if new_from_ring < as Currency<::AccountId>>::minimum_balance() { + return Err("transfer would kill account"); + } + + >::set_free_balance(transactor, new_from_ring); + Self::set_free_balance(transactor, new_from_kton); + Self::set_free_balance(dest, new_to_kton); + + ::TransferPayment::on_unbalanced(NegativeImbalanceRing::new(fee)); + + Self::deposit_event(RawEvent::Transfer( + transactor.to_owned(), + dest.to_owned(), + value.saturated_into(), + fee.saturated_into(), + )); } Ok(()) diff --git a/srml/kton/src/mock.rs b/srml/kton/src/mock.rs index 358ffb3aa..e74f68c9d 100644 --- a/srml/kton/src/mock.rs +++ b/srml/kton/src/mock.rs @@ -4,20 +4,21 @@ use sr_primitives::{ weights::Weight, Perbill, }; -use srml_support::{impl_outer_origin, parameter_types}; use substrate_primitives::H256; +use support::{impl_outer_origin, parameter_types}; use crate::*; /// The AccountId alias in this test module. pub type AccountId = u64; -pub type Balance = u128; pub type BlockNumber = u64; pub type Moment = u64; pub type System = system::Module; pub type Timestamp = timestamp::Module; +#[cfg(feature = "transfer-fee")] +pub type Ring = ring::Module; pub type Kton = Module; pub const NANO: Balance = 1; @@ -57,7 +58,7 @@ impl system::Trait for Test { } parameter_types! { - pub const MinimumPeriod: u64 = 5; + pub const MinimumPeriod: Moment = 5; } impl timestamp::Trait for Test { type Moment = u64; @@ -65,11 +66,28 @@ impl timestamp::Trait for Test { type MinimumPeriod = MinimumPeriod; } -impl Trait for Test { +#[cfg(feature = "transfer-fee")] +parameter_types! { + pub const TransferFee: Balance = 1 * MICRO; +} +#[cfg(not(feature = "transfer-fee"))] +parameter_types! { + pub const TransferFee: Balance = 0; +} +impl ring::Trait for Test { type Balance = Balance; + type OnFreeBalanceZero = (); + type OnNewAccount = (); + type TransferPayment = (); + type DustRemoval = (); + type Event = (); + type ExistentialDeposit = (); + type TransferFee = TransferFee; + type CreationFee = (); +} + +impl Trait for Test { type Event = (); - type OnMinted = (); - type OnRemoval = (); } pub struct ExtBuilder { diff --git a/srml/kton/src/tests.rs b/srml/kton/src/tests.rs index d15c7a132..6980abd76 100644 --- a/srml/kton/src/tests.rs +++ b/srml/kton/src/tests.rs @@ -1,4 +1,4 @@ -use srml_support::{assert_err, assert_ok, traits::Currency}; +use support::{assert_err, assert_ok, traits::Currency}; use crate::{mock::*, *}; use darwinia_support::{LockIdentifier, NormalLock, WithdrawLock, WithdrawReasons}; @@ -7,219 +7,256 @@ const ID_1: LockIdentifier = *b"1 "; const ID_2: LockIdentifier = *b"2 "; const ID_3: LockIdentifier = *b"3 "; -#[test] -fn transfer_should_work() { - ExtBuilder::default().build().execute_with(|| { - let _ = Kton::deposit_creating(&666, 100); +#[cfg(feature = "transfer-fee")] +mod with_transfer_fee { + use super::*; - assert_ok!(Kton::transfer(Origin::signed(666), 777, 50)); - assert_eq!(Kton::total_balance(&666), 50); - assert_eq!(Kton::total_balance(&777), 50); + #[test] + fn transfer_should_work() { + ExtBuilder::default().build().execute_with(|| { + let _ = Kton::deposit_creating(&666, 100); - assert_ok!(Kton::transfer(Origin::signed(666), 777, 50)); - assert_eq!(Kton::total_balance(&666), 0); - assert_eq!(Kton::total_balance(&777), 100); + assert_err!( + Kton::transfer(Origin::signed(666), 777, 50), + "Transfer Fee - NOT ENOUGH RING", + ); - assert_ok!(Kton::transfer(Origin::signed(666), 777, 0)); - }); -} + let _ = Ring::deposit_creating(&666, 1 * MICRO); + assert_ok!(Kton::transfer(Origin::signed(666), 777, 50)); + assert_eq!(Kton::total_balance(&666), 50); + assert_eq!(Kton::total_balance(&777), 50); + + assert_err!( + Kton::transfer(Origin::signed(666), 777, 50), + "Transfer Fee - NOT ENOUGH RING", + ); -// TODO -#[test] -fn transfer_should_fail() { - ExtBuilder::default().vesting(true).build().execute_with(|| { - let _ = Kton::deposit_creating(&777, 1); - assert_err!( - Kton::transfer(Origin::signed(666), 777, 50), - "balance too low to send value", - ); - - let _ = Kton::deposit_creating(&666, Balance::max_value()); - assert_err!( - Kton::transfer(Origin::signed(777), 666, 1), - "destination balance too high to receive value", - ); - - assert_err!( - Kton::transfer(Origin::signed(2), 777, Kton::vesting_balance(&2)), - "vesting balance too high to send value", - ); - Kton::set_lock( - ID_1, - &777, - WithdrawLock::Normal(NormalLock { - amount: Balance::max_value(), - until: Moment::max_value(), - }), - WithdrawReasons::all(), - ); - assert_err!( - Kton::transfer(Origin::signed(777), 1, 1), - "account liquidity restrictions prevent withdrawal", - ); - }); + let _ = Ring::deposit_creating(&666, 1 * MICRO); + assert_ok!(Kton::transfer(Origin::signed(666), 777, 50)); + assert_eq!(Kton::total_balance(&666), 0); + assert_eq!(Kton::total_balance(&777), 100); + }); + } } -#[test] -fn set_lock_should_work() { - ExtBuilder::default().build().execute_with(|| { - let lock_ids = [[0; 8], [1; 8], [2; 8], [3; 8]]; - let balance_per_lock = Kton::free_balance(&1) / (lock_ids.len() as Balance); +#[cfg(not(feature = "transfer-fee"))] +mod without_transfer_fee { + use super::*; + + #[test] + fn transfer_should_work() { + ExtBuilder::default().build().execute_with(|| { + let _ = Kton::deposit_creating(&666, 100); + + assert_ok!(Kton::transfer(Origin::signed(666), 777, 50)); + assert_eq!(Kton::total_balance(&666), 50); + assert_eq!(Kton::total_balance(&777), 50); + + assert_ok!(Kton::transfer(Origin::signed(666), 777, 50)); + assert_eq!(Kton::total_balance(&666), 0); + assert_eq!(Kton::total_balance(&777), 100); + + assert_ok!(Kton::transfer(Origin::signed(666), 777, 0)); + }); + } + + // TODO + #[test] + fn transfer_should_fail() { + ExtBuilder::default().vesting(true).build().execute_with(|| { + let _ = Kton::deposit_creating(&777, 1); + assert_err!( + Kton::transfer(Origin::signed(666), 777, 50), + "balance too low to send value", + ); + + let _ = Kton::deposit_creating(&666, Balance::max_value()); + assert_err!( + Kton::transfer(Origin::signed(777), 666, 1), + "destination balance too high to receive value", + ); + + assert_err!( + Kton::transfer(Origin::signed(2), 777, Kton::vesting_balance(&2)), + "vesting balance too high to send value", + ); + Kton::set_lock( + ID_1, + &777, + WithdrawLock::Normal(NormalLock { + amount: Balance::max_value(), + until: Moment::max_value(), + }), + WithdrawReasons::all(), + ); + assert_err!( + Kton::transfer(Origin::signed(777), 1, 1), + "account liquidity restrictions prevent withdrawal", + ); + }); + } + + #[test] + fn set_lock_should_work() { + ExtBuilder::default().build().execute_with(|| { + let lock_ids = [[0; 8], [1; 8], [2; 8], [3; 8]]; + let balance_per_lock = Kton::free_balance(&1) / (lock_ids.len() as Balance); + + // account `1`'s vesting length + System::set_block_number(4); + + { + let mut locks = vec![]; + for lock_id in lock_ids.iter() { + Kton::set_lock( + *lock_id, + &1, + WithdrawLock::Normal(NormalLock { + amount: balance_per_lock, + until: Moment::max_value(), + }), + WithdrawReasons::all(), + ); + locks.push(BalanceLock { + id: *lock_id, + withdraw_lock: WithdrawLock::Normal(NormalLock { + amount: balance_per_lock, + until: Moment::max_value(), + }), + reasons: WithdrawReasons::all(), + }); + assert_eq!(Kton::locks(&1), locks); + } + } + + for _ in 0..lock_ids.len() - 1 { + assert_ok!(Kton::transfer(Origin::signed(1), 2, balance_per_lock)); + } + assert_err!( + Kton::transfer(Origin::signed(1), 2, balance_per_lock), + "account liquidity restrictions prevent withdrawal" + ); + }); + } + + #[test] + fn remove_lock_should_work() { + ExtBuilder::default().build().execute_with(|| { + Timestamp::set_timestamp(0); + let ts: u64 = Timestamp::now().into(); + Kton::set_lock( + ID_1, + &2, + WithdrawLock::Normal(NormalLock { + amount: Balance::max_value(), + until: Moment::max_value(), + }), + WithdrawReasons::all(), + ); + assert_err!( + Kton::transfer(Origin::signed(2), 1, 1), + "account liquidity restrictions prevent withdrawal" + ); + + // unexpired + Kton::set_lock( + ID_2, + &2, + WithdrawLock::Normal(NormalLock { + amount: Balance::max_value(), + until: ts + 1, + }), + WithdrawReasons::all(), + ); + Kton::remove_lock(ID_1, &2); + Timestamp::set_timestamp(ts); + assert_err!( + Kton::transfer(Origin::signed(2), 1, 1), + "account liquidity restrictions prevent withdrawal" + ); + Kton::remove_lock(ID_2, &2); + assert_ok!(Kton::transfer(Origin::signed(2), 1, 1)); - // account `1`'s vesting length - System::set_block_number(4); + // expired + Kton::set_lock( + ID_3, + &2, + WithdrawLock::Normal(NormalLock { + amount: Balance::max_value(), + until: ts, + }), + WithdrawReasons::all(), + ); + assert_ok!(Kton::transfer(Origin::signed(2), 1, 1)); + }); + } - { + #[test] + fn update_lock_should_work() { + ExtBuilder::default().build().execute_with(|| { let mut locks = vec![]; - for lock_id in lock_ids.iter() { + for id in 0..10 { + // until > 1 + locks.push(BalanceLock { + id: [id; 8], + withdraw_lock: WithdrawLock::Normal(NormalLock { amount: 1, until: 2 }), + reasons: WithdrawReasons::none(), + }); Kton::set_lock( - *lock_id, + [id; 8], &1, - WithdrawLock::Normal(NormalLock { - amount: balance_per_lock, - until: Moment::max_value(), - }), - WithdrawReasons::all(), + WithdrawLock::Normal(NormalLock { amount: 1, until: 2 }), + WithdrawReasons::none(), ); - locks.push(BalanceLock { - id: *lock_id, - withdraw_lock: WithdrawLock::Normal(NormalLock { - amount: balance_per_lock, - until: Moment::max_value(), - }), + } + let update_id = 4; + for amount in 32767..65535 { + let until = amount as Moment + 1; + locks[update_id as usize] = BalanceLock { + id: [update_id; 8], + withdraw_lock: WithdrawLock::Normal(NormalLock { amount, until }), reasons: WithdrawReasons::all(), - }); + }; + Kton::set_lock( + [update_id; 8], + &1, + WithdrawLock::Normal(NormalLock { amount, until }), + WithdrawReasons::all(), + ); assert_eq!(Kton::locks(&1), locks); } - } - - for _ in 0..lock_ids.len() - 1 { - assert_ok!(Kton::transfer(Origin::signed(1), 2, balance_per_lock)); - } - assert_err!( - Kton::transfer(Origin::signed(1), 2, balance_per_lock), - "account liquidity restrictions prevent withdrawal" - ); - }); -} + }); + } -#[test] -fn remove_lock_should_work() { - ExtBuilder::default().build().execute_with(|| { - Timestamp::set_timestamp(0); - let ts: u64 = Timestamp::now().into(); - Kton::set_lock( - ID_1, - &2, - WithdrawLock::Normal(NormalLock { - amount: Balance::max_value(), - until: Moment::max_value(), - }), - WithdrawReasons::all(), - ); - assert_err!( - Kton::transfer(Origin::signed(2), 1, 1), - "account liquidity restrictions prevent withdrawal" - ); - - // unexpired - Kton::set_lock( - ID_2, - &2, - WithdrawLock::Normal(NormalLock { - amount: Balance::max_value(), - until: ts + 1, - }), - WithdrawReasons::all(), - ); - Kton::remove_lock(ID_1, &2); - Timestamp::set_timestamp(ts); - assert_err!( - Kton::transfer(Origin::signed(2), 1, 1), - "account liquidity restrictions prevent withdrawal" - ); - Kton::remove_lock(ID_2, &2); - assert_ok!(Kton::transfer(Origin::signed(2), 1, 1)); - - // expired - Kton::set_lock( - ID_3, - &2, - WithdrawLock::Normal(NormalLock { - amount: Balance::max_value(), - until: ts, - }), - WithdrawReasons::all(), - ); - assert_ok!(Kton::transfer(Origin::signed(2), 1, 1)); - }); -} - -#[test] -fn update_lock_should_work() { - ExtBuilder::default().build().execute_with(|| { - let mut locks = vec![]; - for id in 0..10 { - // until > 1 - locks.push(BalanceLock { - id: [id; 8], - withdraw_lock: WithdrawLock::Normal(NormalLock { amount: 1, until: 2 }), - reasons: WithdrawReasons::none(), - }); + #[test] + fn combination_locking_should_work() { + ExtBuilder::default().build().execute_with(|| { + let _ = Kton::deposit_creating(&1001, 10); Kton::set_lock( - [id; 8], - &1, - WithdrawLock::Normal(NormalLock { amount: 1, until: 2 }), + ID_1, + &1001, + WithdrawLock::Normal(NormalLock { + amount: Balance::max_value(), + until: 0, + }), WithdrawReasons::none(), ); - } - let update_id = 4; - for amount in 32767..65535 { - let until = amount as Moment + 1; - locks[update_id as usize] = BalanceLock { - id: [update_id; 8], - withdraw_lock: WithdrawLock::Normal(NormalLock { amount, until }), - reasons: WithdrawReasons::all(), - }; Kton::set_lock( - [update_id; 8], - &1, - WithdrawLock::Normal(NormalLock { amount, until }), + ID_2, + &1001, + WithdrawLock::Normal(NormalLock { + amount: 0, + until: Moment::max_value(), + }), + WithdrawReasons::none(), + ); + Kton::set_lock( + ID_3, + &1001, + WithdrawLock::Normal(NormalLock { amount: 0, until: 0 }), WithdrawReasons::all(), ); - assert_eq!(Kton::locks(&1), locks); - } - }); -} - -#[test] -fn combination_locking_should_work() { - ExtBuilder::default().build().execute_with(|| { - let _ = Kton::deposit_creating(&1001, 10); - Kton::set_lock( - ID_1, - &1001, - WithdrawLock::Normal(NormalLock { - amount: Balance::max_value(), - until: 0, - }), - WithdrawReasons::none(), - ); - Kton::set_lock( - ID_2, - &1001, - WithdrawLock::Normal(NormalLock { - amount: 0, - until: Moment::max_value(), - }), - WithdrawReasons::none(), - ); - Kton::set_lock( - ID_3, - &1001, - WithdrawLock::Normal(NormalLock { amount: 0, until: 0 }), - WithdrawReasons::all(), - ); - assert_ok!(Kton::transfer(Origin::signed(1001), 1002, 1)); - }); + assert_ok!(Kton::transfer(Origin::signed(1001), 1002, 1)); + }); + } } diff --git a/srml/staking/Cargo.toml b/srml/staking/Cargo.toml index 42e2b6d36..f9672b31c 100644 --- a/srml/staking/Cargo.toml +++ b/srml/staking/Cargo.toml @@ -7,6 +7,7 @@ edition = "2018" [dependencies] # crates.io codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] } +regex = { version = "1.3.1", optional = true } serde = { version = "1.0.101", optional = true } # github.com @@ -35,6 +36,7 @@ equalize = [] default = ["std", "equalize"] std = [ "codec/std", + "regex/std", "serde", "authorship/std", diff --git a/srml/staking/src/lib.rs b/srml/staking/src/lib.rs index 7d0e6db2e..87c4cb3df 100644 --- a/srml/staking/src/lib.rs +++ b/srml/staking/src/lib.rs @@ -31,8 +31,11 @@ mod err { pub const CLAIM_DEPOSITS_EXPIRE_TIME_INVALID: &'static str = "Claim Deposits With Punish - NOTHING TO CLAIM AT THIS TIME"; - pub const NODE_NAME_INVALID: &'static str = "Node Name - INVALID"; pub const TARGETS_INVALID: &'static str = "Targets - CAN NOT BE EMPTY"; + + pub const NODE_NAME_REACH_MAX: &'static str = "Node Name - REACH MAX LENGTH 32"; + pub const NODE_NAME_CONTAINS_INVALID_CHARS: &'static str = "Node Name - CONTAINS INVALID CHARS SUCH AS '.' AND '@'"; + pub const NODE_NAME_CONTAINS_URLS: &'static str = "Node Name - CONTAINS URLS"; } #[allow(unused)] @@ -43,6 +46,8 @@ mod tests; use codec::{Decode, Encode, HasCompact}; use phragmen::{build_support_map, elect, equalize, ExtendedBalance as Power, PhragmenStakedAssignment}; +#[cfg(feature = "std")] +use regex::bytes::Regex; use rstd::{borrow::ToOwned, prelude::*, result}; use session::{historical::OnSessionEnding, SelectInitialValidators}; use sr_primitives::{ @@ -89,6 +94,7 @@ const DEFAULT_MINIMUM_VALIDATOR_COUNT: u32 = 4; const MAX_NOMINATIONS: usize = 16; const MAX_UNLOCKING_CHUNKS: u32 = 32; const MONTH_IN_MILLISECONDS: Moment = 30 * 24 * 60 * 60 * 1000; +const NODE_NAME_MAX_LENGTH: usize = 32; const STAKING_ID: LockIdentifier = *b"staking "; /// Reward points of an era. Used to split era total payout between validators. @@ -155,14 +161,58 @@ pub struct ValidatorPrefs { } impl ValidatorPrefs { - // TODO - /// Filter Ad, curse words... - fn node_name_is_valid(&self) -> bool { - if self.node_name.is_empty() { - return false; + /// Check whether a node name is considered as valid + fn check_node_name(&self) -> result::Result<(), &'static str> { + let name = self.node_name.as_slice(); + + { + if name.len() >= NODE_NAME_MAX_LENGTH { + return Err(err::NODE_NAME_REACH_MAX); + } } - true + #[cfg(not(feature = "std"))] + { + if name.contains(&b'.') || name.contains(&b'@') { + return Err(err::NODE_NAME_CONTAINS_INVALID_CHARS); + } + + if name.starts_with("http".as_bytes()) + || name.starts_with("https".as_bytes()) + || name.starts_with("www".as_bytes()) + || name.ends_with("com".as_bytes()) + || name.ends_with("cn".as_bytes()) + || name.ends_with("io".as_bytes()) + || name.ends_with("org".as_bytes()) + || name.ends_with("xyz".as_bytes()) + { + return Err(err::NODE_NAME_CONTAINS_URLS); + } + } + + // TODO: https://github.com/rust-lang/regex/issues/476 + #[cfg(feature = "std")] + { + let invalid_chars = r"[\\.@]"; + let re = Regex::new(invalid_chars).unwrap(); + if re.is_match(&name) { + return Err(err::NODE_NAME_CONTAINS_INVALID_CHARS); + } + + let invalid_patterns = r"^(https?|www)"; + let re = Regex::new(invalid_patterns).unwrap(); + if re.is_match(&name) { + return Err(err::NODE_NAME_CONTAINS_URLS); + } + + let invalid_patterns = r"(com|cn|io|org|xyz)$"; + let re = Regex::new(invalid_patterns).unwrap(); + if re.is_match(&name) { + return Err(err::NODE_NAME_CONTAINS_URLS); + } + } + + Ok(()) } } @@ -175,9 +225,9 @@ impl Default for ValidatorPrefs { } } -/// To unify *Ring* and *Kton* balance. +/// To unify *Ring* and *Kton* balances. #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] -pub enum StakingBalance +pub enum StakingBalances where Ring: HasCompact, Kton: HasCompact, @@ -186,13 +236,13 @@ where Kton(Kton), } -impl Default for StakingBalance +impl Default for StakingBalances where Ring: Default + HasCompact, Kton: Default + HasCompact, { fn default() -> Self { - StakingBalance::Ring(Default::default()) + StakingBalances::Ring(Default::default()) } } @@ -311,11 +361,6 @@ where } pub trait Trait: timestamp::Trait + session::Trait { - /// The staking balances. - type Ring: LockableCurrency; - /// The staking balances. - type Kton: LockableCurrency; - /// Time used for computing era duration. type Time: Time; @@ -326,33 +371,39 @@ pub trait Trait: timestamp::Trait + session::Trait { /// The post-processing needs it but will be moved to off-chain. TODO: #2908 type CurrencyToVote: Convert + Convert; - /// Tokens have been minted and are unused for validator-reward. - type RingRewardRemainder: OnUnbalanced>; - /// The overarching event type. type Event: From> + Into<::Event>; - /// Handler for the unbalanced increment when rewarding a staker. - type RingReward: OnUnbalanced>; - /// Handler for the unbalanced increment when rewarding a staker. - type KtonReward: OnUnbalanced>; - - /// Handler for the unbalanced reduction when slashing a staker. - type RingSlash: OnUnbalanced>; - /// Handler for the unbalanced reduction when slashing a staker. - type KtonSlash: OnUnbalanced>; - /// Number of sessions per era. type SessionsPerEra: Get; - /// Number of seconds that staked funds must remain bonded for. + /// Number of `Moment` that staked funds must remain bonded for. type BondingDuration: Get; + /// Number of eras that staked funds must remain bonded for. + type BondingDurationInEra: Get; /// Interface for interacting with a session module. type SessionInterface: self::SessionInterface; - // custom + /// The staking balances. + type Ring: LockableCurrency; + /// Tokens have been minted and are unused for validator-reward. + type RingRewardRemainder: OnUnbalanced>; + /// Handler for the unbalanced reduction when slashing a staker. + type RingSlash: OnUnbalanced>; + /// Handler for the unbalanced increment when rewarding a staker. + type RingReward: OnUnbalanced>; + + /// The staking balances. + type Kton: LockableCurrency; + /// Handler for the unbalanced reduction when slashing a staker. + type KtonSlash: OnUnbalanced>; + /// Handler for the unbalanced increment when rewarding a staker. + type KtonReward: OnUnbalanced>; + + // TODO: doc type Cap: Get<>::Balance>; + // TODO: doc type GenesisTime: Get>; } @@ -460,7 +511,7 @@ decl_storage! { let _ = >::bond( T::Origin::from(Some(stash.clone()).into()), T::Lookup::unlookup(controller.clone()), - StakingBalance::Ring(ring), + StakingBalances::Ring(ring), RewardDestination::Stash, 0, ); @@ -469,7 +520,7 @@ decl_storage! { >::validate( T::Origin::from(Some(controller.clone()).into()), ValidatorPrefs { - node_name: "Darwinia Node".bytes().collect(), + node_name: "Darwinia Node".into(), ..Default::default() }, ) @@ -508,11 +559,11 @@ decl_event!( /// Bond succeed. /// `amount`, `now`, `duration` in month - Bond(Balance, Moment, Moment), + Bond(StakingBalances, Moment, Moment), /// Unbond succeed. /// `amount`, `now` - Unbond(Balance, Moment), + Unbond(StakingBalances, Moment), // Develop // Print(u128), @@ -524,9 +575,12 @@ decl_module! { /// Number of sessions per era. const SessionsPerEra: SessionIndex = T::SessionsPerEra::get(); - /// Number of eras that staked funds must remain bonded for. + /// Number of `Moment` that staked funds must remain bonded for. const BondingDuration: T::Moment = T::BondingDuration::get(); + /// Number of eras that staked funds must remain bonded for. + const BondingDurationInEra: EraIndex = T::BondingDurationInEra::get(); + fn deposit_event() = default; fn on_finalize() { @@ -555,7 +609,7 @@ decl_module! { fn bond( origin, controller: ::Source, - value: StakingBalance, Kton>, + value: StakingBalances, Kton>, payee: RewardDestination, promise_month: Moment ) { @@ -574,32 +628,37 @@ decl_module! { stash: stash.clone(), ..Default::default() }; - let bond_amount; let now = >::now().saturated_into::(); let promise_month = promise_month.min(36); match value { - StakingBalance::Ring(r) => { + StakingBalances::Ring(r) => { let stash_balance = T::Ring::free_balance(&stash); let value = r.min(stash_balance); - bond_amount = value.saturated_into(); Self::bond_helper_in_ring(&stash, &controller, value, promise_month, ledger); >::mutate(|r| *r += value); + >::deposit_event(RawEvent::Bond( + StakingBalances::Ring(value.saturated_into()), + now, + promise_month, + )); }, - StakingBalance::Kton(k) => { + StakingBalances::Kton(k) => { let stash_balance = T::Kton::free_balance(&stash); let value = k.min(stash_balance); - bond_amount = value.saturated_into(); Self::bond_helper_in_kton(&controller, value, ledger); >::mutate(|k| *k += value); + >::deposit_event(RawEvent::Bond( + StakingBalances::Kton(value.saturated_into()), + now, + promise_month, + )); }, } - - >::deposit_event(RawEvent::Bond(bond_amount, now, promise_month)); } /// Add some extra amount that have appeared in the stash `free_balance` into the balance up @@ -619,7 +678,7 @@ decl_module! { #[weight = SimpleDispatchInfo::FixedNormal(500_000)] fn bond_extra( origin, - value: StakingBalance, Kton>, + value: StakingBalances, Kton>, promise_month: Moment ) { let stash = ensure_signed(origin)?; @@ -629,7 +688,7 @@ decl_module! { let promise_month = promise_month.min(36); match value { - StakingBalance::Ring(r) => { + StakingBalances::Ring(r) => { let stash_balance = T::Ring::free_balance(&stash); if let Some(extra) = stash_balance.checked_sub(&ledger.active_ring) { let extra = extra.min(r); @@ -637,10 +696,14 @@ decl_module! { Self::bond_helper_in_ring(&stash, &controller, extra, promise_month, ledger); >::mutate(|r| *r += extra); - >::deposit_event(RawEvent::Bond(extra.saturated_into(), now, promise_month)); + >::deposit_event(RawEvent::Bond( + StakingBalances::Ring(extra.saturated_into()), + now, + promise_month, + )); } }, - StakingBalance::Kton(k) => { + StakingBalances::Kton(k) => { let stash_balance = T::Kton::free_balance(&stash); if let Some(extra) = stash_balance.checked_sub(&ledger.active_kton) { let extra = extra.min(k); @@ -648,7 +711,11 @@ decl_module! { Self::bond_helper_in_kton(&controller, extra, ledger); >::mutate(|k| *k += extra); - >::deposit_event(RawEvent::Bond(extra.saturated_into(), now, promise_month)); + >::deposit_event(RawEvent::Bond( + StakingBalances::Kton(extra.saturated_into()), + now, + promise_month, + )); } }, } @@ -684,7 +751,11 @@ decl_module! { }); >::insert(&controller, ledger); - >::deposit_event(RawEvent::Bond(value.saturated_into(), now.saturated_into::(), promise_month)); + >::deposit_event(RawEvent::Bond( + StakingBalances::Ring(value.saturated_into()), + now.saturated_into::(), + promise_month, + )); } /// for normal_ring or normal_kton, follow the original substrate pattern @@ -711,7 +782,7 @@ decl_module! { /// - One DB entry. /// #[weight = SimpleDispatchInfo::FixedNormal(400_000)] - fn unbond(origin, value: StakingBalance, Kton>) { + fn unbond(origin, value: StakingBalances, Kton>) { let controller = ensure_signed(origin)?; let mut ledger = Self::clear_mature_deposits(Self::ledger(&controller).ok_or(err::CONTROLLER_INVALID)?); let StakingLedger { @@ -739,7 +810,7 @@ decl_module! { ); match value { - StakingBalance::Ring(r) => { + StakingBalances::Ring(r) => { // only active normal ring can be unbond // active_ring = active_normal_ring + active_deposit_ring let active_normal_ring = *active_ring - *active_deposit_ring; @@ -755,10 +826,13 @@ decl_module! { Self::update_ledger(&controller, &mut ledger, value); >::mutate(|r| *r -= available_unbond_ring); - >::deposit_event(RawEvent::Unbond(available_unbond_ring.saturated_into(), now.saturated_into::())); + >::deposit_event(RawEvent::Unbond( + StakingBalances::Ring(available_unbond_ring.saturated_into()), + now.saturated_into::(), + )); } }, - StakingBalance::Kton(k) => { + StakingBalances::Kton(k) => { let unbond_kton = k.min(*active_kton); if !unbond_kton.is_zero() { @@ -771,7 +845,10 @@ decl_module! { Self::update_ledger(&controller, &mut ledger, value); >::mutate(|k| *k -= unbond_kton); - >::deposit_event(RawEvent::Unbond(unbond_kton.saturated_into(), now.saturated_into::())); + >::deposit_event(RawEvent::Unbond( + StakingBalances::Kton(unbond_kton.saturated_into()), + now.saturated_into::(), + )); } }, } @@ -860,7 +937,7 @@ decl_module! { let controller = ensure_signed(origin)?; let ledger = Self::ledger(&controller).ok_or(err::CONTROLLER_INVALID)?; - ensure!(prefs.node_name_is_valid(), err::NODE_NAME_INVALID); + prefs.check_node_name()?; let stash = &ledger.stash; let mut prefs = prefs; @@ -1088,7 +1165,7 @@ impl Module { } ledger.active_ring = ledger.active_ring.saturating_add(value); - Self::update_ledger(&controller, &mut ledger, StakingBalance::Ring(value)); + Self::update_ledger(&controller, &mut ledger, StakingBalances::Ring(value)); } // TODO: doc @@ -1099,7 +1176,7 @@ impl Module { ) { ledger.active_kton += value; - Self::update_ledger(&controller, &mut ledger, StakingBalance::Kton(value)); + Self::update_ledger(&controller, &mut ledger, StakingBalances::Kton(value)); } // TODO: there is reserve balance in Balance.Slash, we assuming it is zero for now. @@ -1112,14 +1189,14 @@ impl Module { let (ring_imbalance, _) = if !ledger.active_ring.is_zero() { let slashable_ring = slash_ratio * ledger.active_ring; - let value_slashed = Self::slash_helper(&controller, &mut ledger, StakingBalance::Ring(slashable_ring)); + let value_slashed = Self::slash_helper(&controller, &mut ledger, StakingBalances::Ring(slashable_ring)); T::Ring::slash(stash, value_slashed.0) } else { (>::zero(), Zero::zero()) }; let (kton_imbalance, _) = if !ledger.active_kton.is_zero() { let slashable_kton = slash_ratio * ledger.active_kton; - let value_slashed = Self::slash_helper(&controller, &mut ledger, StakingBalance::Kton(slashable_kton)); + let value_slashed = Self::slash_helper(&controller, &mut ledger, StakingBalances::Kton(slashable_kton)); T::Kton::slash(stash, value_slashed.1) } else { (>::zero(), Zero::zero()) @@ -1154,10 +1231,10 @@ impl Module { fn update_ledger( controller: &T::AccountId, ledger: &mut StakingLedger, Kton, T::Moment>, - staking_balance: StakingBalance, Kton>, + staking_balance: StakingBalances, Kton>, ) { match staking_balance { - StakingBalance::Ring(_r) => { + StakingBalances::Ring(_r) => { ledger.ring_staking_lock.staking_amount = ledger.active_ring; T::Ring::set_lock( @@ -1167,7 +1244,7 @@ impl Module { WithdrawReasons::all(), ); } - StakingBalance::Kton(_k) => { + StakingBalances::Kton(_k) => { ledger.kton_staking_lock.staking_amount = ledger.active_kton; T::Kton::set_lock( @@ -1256,10 +1333,10 @@ impl Module { fn slash_helper( controller: &T::AccountId, ledger: &mut StakingLedger, Kton, T::Moment>, - value: StakingBalance, Kton>, + value: StakingBalances, Kton>, ) -> (Ring, Kton) { match value { - StakingBalance::Ring(r) => { + StakingBalances::Ring(r) => { let StakingLedger { active_ring, active_deposit_ring, @@ -1305,10 +1382,10 @@ impl Module { }); } - Self::update_ledger(controller, ledger, StakingBalance::Ring(0.into())); + Self::update_ledger(controller, ledger, StakingBalances::Ring(0.into())); (total_value, 0.into()) } - StakingBalance::Kton(k) => { + StakingBalances::Kton(k) => { // check one more time // TODO: may be removed later let active_value = k.min(ledger.active_kton); @@ -1317,7 +1394,7 @@ impl Module { >::mutate(|k| *k -= active_value); - Self::update_ledger(controller, ledger, StakingBalance::Kton(0.into())); + Self::update_ledger(controller, ledger, StakingBalances::Kton(0.into())); (0.into(), active_value) } } @@ -1444,10 +1521,7 @@ impl Module { CurrentEraStartSessionIndex::mutate(|v| { *v = start_session_index; }); - let bonding_era = { - const BONDING_DURATION_ERA_TO_SECS_RATIO: Moment = 300; - (T::BondingDuration::get().saturated_into::() / BONDING_DURATION_ERA_TO_SECS_RATIO) as EraIndex - }; + let bonding_era = T::BondingDurationInEra::get(); if current_era > bonding_era { let first_kept = current_era - bonding_era; diff --git a/srml/staking/src/mock.rs b/srml/staking/src/mock.rs index f575085a0..c2b72efe6 100644 --- a/srml/staking/src/mock.rs +++ b/srml/staking/src/mock.rs @@ -136,22 +136,6 @@ impl system::Trait for Test { type Version = (); } -parameter_types! { - pub const TransferFee: Balance = 0; - pub const CreationFee: Balance = 0; -} -impl balances::Trait for Test { - type Balance = Balance; - type OnFreeBalanceZero = Staking; - type OnNewAccount = (); - type TransferPayment = (); - type DustRemoval = (); - type Event = (); - type ExistentialDeposit = ExistentialDeposit; - type TransferFee = TransferFee; - type CreationFee = CreationFee; -} - parameter_types! { pub const Period: BlockNumber = 1; pub const Offset: BlockNumber = 0; @@ -183,7 +167,7 @@ impl authorship::Trait for Test { } parameter_types! { - pub const MinimumPeriod: u64 = 5; + pub const MinimumPeriod: Moment = 5; } impl timestamp::Trait for Test { type Moment = u64; @@ -191,33 +175,47 @@ impl timestamp::Trait for Test { type MinimumPeriod = MinimumPeriod; } -impl kton::Trait for Test { +parameter_types! { + pub const TransferFee: Balance = 0; + pub const CreationFee: Balance = 0; +} +impl balances::Trait for Test { type Balance = Balance; + type OnFreeBalanceZero = Staking; + type OnNewAccount = (); + type TransferPayment = (); + type DustRemoval = (); + type Event = (); + type ExistentialDeposit = ExistentialDeposit; + type TransferFee = TransferFee; + type CreationFee = CreationFee; +} +impl kton::Trait for Test { type Event = (); - type OnMinted = (); - type OnRemoval = (); } parameter_types! { pub const SessionsPerEra: SessionIndex = 3; pub const BondingDuration: Moment = 60; + pub const BondingDurationInEra: EraIndex = 60; pub const CAP: Balance = 10_000_000_000 * COIN; pub const GenesisTime: Moment = 0; } impl Trait for Test { - type Ring = Ring; - type Kton = Kton; type Time = Timestamp; type CurrencyToVote = CurrencyToVoteHandler; - type RingRewardRemainder = (); type Event = (); - type RingReward = (); - type KtonReward = (); - type RingSlash = (); - type KtonSlash = (); type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; + type BondingDurationInEra = BondingDurationInEra; type SessionInterface = Self; + type Ring = Ring; + type RingRewardRemainder = (); + type RingSlash = (); + type RingReward = (); + type Kton = Kton; + type KtonSlash = (); + type KtonReward = (); type Cap = CAP; type GenesisTime = GenesisTime; @@ -433,14 +431,14 @@ pub fn bond_validator(acc: u64, val: Balance) { assert_ok!(Staking::bond( Origin::signed(acc + 1), acc, - StakingBalance::Ring(val), + StakingBalances::Ring(val), RewardDestination::Controller, 0, )); assert_ok!(Staking::validate( Origin::signed(acc), ValidatorPrefs { - node_name: "StakingTest".as_bytes().to_vec(), + node_name: "Staking Test".into(), ..Default::default() } )); @@ -453,7 +451,7 @@ pub fn bond_nominator(acc: u64, val: Balance, target: Vec) { assert_ok!(Staking::bond( Origin::signed(acc + 1), acc, - StakingBalance::Ring(val), + StakingBalances::Ring(val), RewardDestination::Controller, 0, )); diff --git a/srml/staking/src/tests.rs b/srml/staking/src/tests.rs index 35bc07bde..734f5c445 100644 --- a/srml/staking/src/tests.rs +++ b/srml/staking/src/tests.rs @@ -4,7 +4,11 @@ use srml_support::{ traits::{Currency, ReservableCurrency}, }; -use crate::{mock::*, *}; +use crate::{ + // Explicit import `Kton` and `Ring` to overwrite same name in crate. + mock::{Kton, Ring, *}, + *, +}; use darwinia_support::{BalanceLock, NormalLock, StakingLock, WithdrawLock, WithdrawReasons}; /// gen_paired_account!(a(1), b(2), m(12)); @@ -35,13 +39,13 @@ macro_rules! gen_paired_account { assert_ok!(Staking::bond( Origin::signed($stash), $controller, - StakingBalance::Ring(50 * COIN), + StakingBalances::Ring(50 * COIN), RewardDestination::Stash, $how_long, )); assert_ok!(Staking::bond_extra( Origin::signed($stash), - StakingBalance::Kton(50 * COIN), + StakingBalances::Kton(50 * COIN), $how_long )); }; @@ -56,13 +60,13 @@ macro_rules! gen_paired_account { assert_ok!(Staking::bond( Origin::signed($stash), $controller, - StakingBalance::Ring(50 * COIN), + StakingBalances::Ring(50 * COIN), RewardDestination::Stash, $how_long, )); assert_ok!(Staking::bond_extra( Origin::signed($stash), - StakingBalance::Kton(50 * COIN), + StakingBalances::Kton(50 * COIN), $how_long, )); }; @@ -148,7 +152,7 @@ fn basic_setup_works() { // ValidatorPrefs are default. { let validator_prefs = ValidatorPrefs { - node_name: "Darwinia Node".bytes().collect(), + node_name: "Darwinia Node".into(), ..Default::default() }; assert_eq!( @@ -288,7 +292,7 @@ fn change_controller_works() { Staking::validate( Origin::signed(10), ValidatorPrefs { - node_name: "Darwinia Node".bytes().collect(), + node_name: "Darwinia Node".into(), ..Default::default() } ), @@ -297,7 +301,7 @@ fn change_controller_works() { assert_ok!(Staking::validate( Origin::signed(5), ValidatorPrefs { - node_name: "Darwinia Node".bytes().collect(), + node_name: "Darwinia Node".into(), ..Default::default() } )); @@ -451,11 +455,11 @@ fn staking_should_work() { // --- Block 1: start_session(1); // Add a new candidate for being a validator. account 3 controlled by 4. - assert_ok!(Staking::bond(Origin::signed(3), 4, StakingBalance::Ring(1500), RewardDestination::Controller, 0)); + assert_ok!(Staking::bond(Origin::signed(3), 4, StakingBalances::Ring(1500), RewardDestination::Controller, 0)); assert_ok!(Staking::validate( Origin::signed(4), ValidatorPrefs { - node_name: "Darwinia Node".bytes().collect(), + node_name: "Darwinia Node".into(), ..Default::default() }, )); @@ -859,7 +863,7 @@ fn double_staking_should_fail() { assert_ok!(Staking::bond( Origin::signed(1), 2, - StakingBalance::Ring(arbitrary_value), + StakingBalances::Ring(arbitrary_value), RewardDestination::default(), 0, )); @@ -868,7 +872,7 @@ fn double_staking_should_fail() { Staking::bond( Origin::signed(1), 4, - StakingBalance::Ring(arbitrary_value), + StakingBalances::Ring(arbitrary_value), RewardDestination::default(), 0, ), @@ -891,7 +895,7 @@ fn double_controlling_should_fail() { assert_ok!(Staking::bond( Origin::signed(1), 2, - StakingBalance::Ring(arbitrary_value), + StakingBalances::Ring(arbitrary_value), RewardDestination::default(), 0, )); @@ -900,7 +904,7 @@ fn double_controlling_should_fail() { Staking::bond( Origin::signed(3), 2, - StakingBalance::Ring(arbitrary_value), + StakingBalances::Ring(arbitrary_value), RewardDestination::default(), 0, ), @@ -1266,7 +1270,7 @@ fn bond_extra_works() { let _ = Ring::make_free_balance_be(&11, 1000000); // Call the bond_extra function from controller, add only 100 - assert_ok!(Staking::bond_extra(Origin::signed(11), StakingBalance::Ring(100), 12)); + assert_ok!(Staking::bond_extra(Origin::signed(11), StakingBalances::Ring(100), 12)); // There should be 100 more `total` and `active` in the ledger assert_eq!( Staking::ledger(&10).unwrap(), @@ -1291,7 +1295,7 @@ fn bond_extra_works() { // Call the bond_extra function with a large number, should handle it assert_ok!(Staking::bond_extra( Origin::signed(11), - StakingBalance::Ring(Balance::max_value()), + StakingBalances::Ring(Balance::max_value()), 0, )); // The full amount of the funds should now be in the total and active @@ -1478,17 +1482,17 @@ fn too_many_unbond_calls_should_not_work() { ExtBuilder::default().build().execute_with(|| { // Locked at Moment(60). for _ in 0..MAX_UNLOCKING_CHUNKS - 1 { - assert_ok!(Staking::unbond(Origin::signed(10), StakingBalance::Ring(1))); + assert_ok!(Staking::unbond(Origin::signed(10), StakingBalances::Ring(1))); } Timestamp::set_timestamp(1); // Locked at MomentT(61). - assert_ok!(Staking::unbond(Origin::signed(10), StakingBalance::Ring(1))); + assert_ok!(Staking::unbond(Origin::signed(10), StakingBalances::Ring(1))); // Can't do more. assert_noop!( - Staking::unbond(Origin::signed(10), StakingBalance::Ring(1)), + Staking::unbond(Origin::signed(10), StakingBalances::Ring(1)), err::UNLOCK_CHUNKS_REACH_MAX, ); @@ -1496,7 +1500,7 @@ fn too_many_unbond_calls_should_not_work() { Timestamp::set_timestamp(BondingDuration::get()); // Can add again. - assert_ok!(Staking::unbond(Origin::signed(10), StakingBalance::Ring(1))); + assert_ok!(Staking::unbond(Origin::signed(10), StakingBalances::Ring(1))); assert_eq!(Staking::ledger(&10).unwrap().ring_staking_lock.unbondings.len(), 2); }) } @@ -1696,7 +1700,7 @@ fn switching_roles() { assert_ok!(Staking::bond( Origin::signed(1), 2, - StakingBalance::Ring(2000), + StakingBalances::Ring(2000), RewardDestination::Controller, 0, )); @@ -1705,7 +1709,7 @@ fn switching_roles() { assert_ok!(Staking::bond( Origin::signed(3), 4, - StakingBalance::Ring(500), + StakingBalances::Ring(500), RewardDestination::Controller, 0, )); @@ -1715,14 +1719,14 @@ fn switching_roles() { assert_ok!(Staking::bond( Origin::signed(5), 6, - StakingBalance::Ring(1000), + StakingBalances::Ring(1000), RewardDestination::Controller, 0, )); assert_ok!(Staking::validate( Origin::signed(6), ValidatorPrefs { - node_name: "Darwinia Node".bytes().collect(), + node_name: "Darwinia Node".into(), ..Default::default() }, )); @@ -1749,7 +1753,7 @@ fn switching_roles() { assert_ok!(Staking::validate( Origin::signed(2), ValidatorPrefs { - node_name: "Darwinia Node".bytes().collect(), + node_name: "Darwinia Node".into(), ..Default::default() }, )); @@ -1793,7 +1797,7 @@ fn wrong_vote_is_null() { assert_ok!(Staking::bond( Origin::signed(1), 2, - StakingBalance::Ring(2000), + StakingBalances::Ring(2000), RewardDestination::default(), 0, )); @@ -1827,13 +1831,13 @@ fn bond_with_no_staked_value() { assert_ok!(Staking::bond( Origin::signed(1), 2, - StakingBalance::Ring(5), + StakingBalances::Ring(5), RewardDestination::Controller, 0, )); // assert_eq!(Ring::locks(&1)[0].amount, 5); - assert_ok!(Staking::unbond(Origin::signed(2), StakingBalance::Ring(5))); + assert_ok!(Staking::unbond(Origin::signed(2), StakingBalances::Ring(5))); assert_eq!( Staking::ledger(2), Some(StakingLedger { @@ -2033,7 +2037,7 @@ fn unbonded_balance_is_not_slashable() { // Total amount staked is slashable. assert_eq!(Staking::ledger(&10).unwrap().active_ring, 1000); - assert_ok!(Staking::unbond(Origin::signed(10), StakingBalance::Ring(800))); + assert_ok!(Staking::unbond(Origin::signed(10), StakingBalances::Ring(800))); // Only the active portion. assert_eq!(Staking::ledger(&10).unwrap().active_ring, 200); @@ -2232,7 +2236,7 @@ fn normal_kton_should_work() { assert_ok!(Staking::bond( Origin::signed(stash), controller, - StakingBalance::Kton(10 * COIN), + StakingBalances::Kton(10 * COIN), RewardDestination::Stash, 0, )); @@ -2272,7 +2276,7 @@ fn normal_kton_should_work() { assert_ok!(Staking::bond( Origin::signed(stash), controller, - StakingBalance::Kton(10 * COIN), + StakingBalances::Kton(10 * COIN), RewardDestination::Stash, 12, )); @@ -2303,7 +2307,7 @@ fn time_deposit_ring_unbond_and_withdraw_automatically_should_work() { let unbond_value = 10; assert_ok!(Staking::unbond( Origin::signed(controller), - StakingBalance::Ring(unbond_value), + StakingBalances::Ring(unbond_value), )); assert_eq!( Ring::locks(stash), @@ -2340,7 +2344,7 @@ fn time_deposit_ring_unbond_and_withdraw_automatically_should_work() { let unbond_start = 30; Timestamp::set_timestamp(unbond_start); - assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalance::Ring(COIN))); + assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalances::Ring(COIN))); assert_eq!( Ring::locks(stash), @@ -2411,7 +2415,7 @@ fn normal_unbond_should_work() { assert_ok!(Staking::bond_extra( Origin::signed(stash), - StakingBalance::Ring(value), + StakingBalances::Ring(value), promise_month, )); assert_eq!( @@ -2438,7 +2442,7 @@ fn normal_unbond_should_work() { // bond += 20_000_000 assert_ok!(Staking::bond_extra( Origin::signed(stash), - StakingBalance::Kton(COIN), + StakingBalances::Kton(COIN), 0, )); ledger.active_kton += kton_free_balance; @@ -2447,7 +2451,7 @@ fn normal_unbond_should_work() { assert_ok!(Staking::unbond( Origin::signed(controller), - StakingBalance::Kton(kton_free_balance) + StakingBalances::Kton(kton_free_balance) )); ledger.active_kton = 0; ledger.kton_staking_lock.staking_amount = 0; @@ -2487,7 +2491,7 @@ fn punished_claim_should_work() { assert_ok!(Staking::bond( Origin::signed(stash), controller, - StakingBalance::Ring(bond_value), + StakingBalances::Ring(bond_value), RewardDestination::Stash, promise_month, )); @@ -2520,7 +2524,7 @@ fn transform_to_deposited_ring_should_work() { assert_ok!(Staking::bond( Origin::signed(stash), controller, - StakingBalance::Ring(COIN), + StakingBalances::Ring(COIN), RewardDestination::Stash, 0, )); @@ -2547,7 +2551,7 @@ fn expired_ring_should_capable_to_promise_again() { assert_ok!(Staking::bond( Origin::signed(stash), controller, - StakingBalance::Ring(10), + StakingBalances::Ring(10), RewardDestination::Stash, 12, )); @@ -2623,7 +2627,7 @@ fn inflation_should_be_correct() { } #[test] -fn validator_prefs_should_work() { +fn validator_payment_ratio_should_work() { ExtBuilder::default().build().execute_with(|| { gen_paired_account!(validator_stash(123), validator_controller(456), 0); gen_paired_account!(nominator_stash(345), nominator_controller(678), 0); @@ -2661,6 +2665,52 @@ fn validator_prefs_should_work() { }); } +#[test] +fn check_node_name_should_work() { + for node_name in [[0; 33].as_ref(), &[1; 34], &[2; 35]].iter() { + let validator_prefs = ValidatorPrefs { + node_name: (*node_name).to_vec(), + ..Default::default() + }; + assert_err!(validator_prefs.check_node_name(), err::NODE_NAME_REACH_MAX); + } + + for node_name in ["hello@darwinia.network"].iter() { + let validator_prefs = ValidatorPrefs { + node_name: (*node_name).into(), + ..Default::default() + }; + assert_err!(validator_prefs.check_node_name(), err::NODE_NAME_CONTAINS_INVALID_CHARS); + } + + for node_name in [ + "com", + "http", + "https", + "itering com", + "http darwinia", + "https darwinia", + "http darwinia network", + "https darwinia network", + ] + .iter() + { + let validator_prefs = ValidatorPrefs { + node_name: (*node_name).into(), + ..Default::default() + }; + assert_err!(validator_prefs.check_node_name(), err::NODE_NAME_CONTAINS_URLS); + } + + for node_name in ["Darwinia Node"].iter() { + let validator_prefs = ValidatorPrefs { + node_name: (*node_name).into(), + ..Default::default() + }; + assert_ok!(validator_prefs.check_node_name()); + } +} + //#[test] //fn reward_and_slash_should_work() { // // ExtBuilder::default().build().execute_with(|| { @@ -2728,17 +2778,17 @@ fn slash_should_not_touch_unbondings() { let _ = Ring::deposit_creating(&stash, 1000); assert_ok!(Staking::bond_extra( Origin::signed(stash), - StakingBalance::Ring(1000), + StakingBalances::Ring(1000), 0, )); let _ = Kton::deposit_creating(&stash, 1000); assert_ok!(Staking::bond_extra( Origin::signed(stash), - StakingBalance::Kton(1000), + StakingBalances::Kton(1000), 0, )); - assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalance::Ring(10))); + assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalances::Ring(10))); let ledger = Staking::ledger(controller).unwrap(); let unbondings = ( ledger.ring_staking_lock.unbondings.clone(), @@ -2779,7 +2829,7 @@ fn check_stash_already_bonded_and_controller_already_paired() { Staking::bond( Origin::signed(11), unpaired_controller, - StakingBalance::Ring(COIN), + StakingBalances::Ring(COIN), RewardDestination::Stash, 0, ), @@ -2789,7 +2839,7 @@ fn check_stash_already_bonded_and_controller_already_paired() { Staking::bond( Origin::signed(unpaired_stash), 10, - StakingBalance::Ring(COIN), + StakingBalances::Ring(COIN), RewardDestination::Stash, 0, ), @@ -2815,20 +2865,20 @@ fn pool_should_be_increased_and_decreased_correctly() { // unbond: 50Ring 50Kton assert_ok!(Staking::unbond( Origin::signed(controller_1), - StakingBalance::Ring(50 * COIN) + StakingBalances::Ring(50 * COIN) )); assert_ok!(Staking::unbond( Origin::signed(controller_1), - StakingBalance::Kton(25 * COIN) + StakingBalances::Kton(25 * COIN) )); // not yet expired: promise for 12 months assert_ok!(Staking::unbond( Origin::signed(controller_2), - StakingBalance::Ring(50 * COIN) + StakingBalances::Ring(50 * COIN) )); assert_ok!(Staking::unbond( Origin::signed(controller_2), - StakingBalance::Kton(25 * COIN) + StakingBalances::Kton(25 * COIN) )); ring_pool -= 50 * COIN; kton_pool -= 50 * COIN; @@ -2844,7 +2894,7 @@ fn pool_should_be_increased_and_decreased_correctly() { Timestamp::set_timestamp(promise_month * MONTH_IN_MILLISECONDS); assert_ok!(Staking::unbond( Origin::signed(controller_2), - StakingBalance::Ring(125 * COIN / 10), + StakingBalances::Ring(125 * COIN / 10), )); ring_pool -= 125 * COIN / 10; assert_eq!(Staking::ring_pool(), ring_pool); @@ -2884,18 +2934,18 @@ fn unbond_over_max_unbondings_chunks_should_fail() { assert_ok!(Staking::bond( Origin::signed(stash), controller, - StakingBalance::Ring(COIN), + StakingBalances::Ring(COIN), RewardDestination::Stash, 0, )); for ts in 0..MAX_UNLOCKING_CHUNKS { Timestamp::set_timestamp(ts as u64); - assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalance::Ring(1))); + assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalances::Ring(1))); } assert_err!( - Staking::unbond(Origin::signed(controller), StakingBalance::Ring(1)), + Staking::unbond(Origin::signed(controller), StakingBalances::Ring(1)), err::UNLOCK_CHUNKS_REACH_MAX, ); }); @@ -2910,7 +2960,7 @@ fn promise_extra_should_not_remove_unexpired_items() { assert_ok!(Staking::bond_extra( Origin::signed(stash), - StakingBalance::Ring(5 * COIN), + StakingBalances::Ring(5 * COIN), 0, )); for _ in 0..expired_items_len { @@ -2945,8 +2995,8 @@ fn unbond_zero() { let ledger = Staking::ledger(controller).unwrap(); Timestamp::set_timestamp(promise_month * MONTH_IN_MILLISECONDS); - assert_ok!(Staking::unbond(Origin::signed(10), StakingBalance::Ring(0))); - assert_ok!(Staking::unbond(Origin::signed(10), StakingBalance::Kton(0))); + assert_ok!(Staking::unbond(Origin::signed(10), StakingBalances::Ring(0))); + assert_ok!(Staking::unbond(Origin::signed(10), StakingBalances::Kton(0))); assert_eq!(Staking::ledger(controller).unwrap(), ledger); }); } @@ -2966,18 +3016,18 @@ fn yakio_q1() { assert_ok!(Staking::bond( Origin::signed(stash), controller, - StakingBalance::Ring(10_000), + StakingBalances::Ring(10_000), RewardDestination::Stash, 12, )); assert_ok!(Staking::bond_extra( Origin::signed(stash), - StakingBalance::Ring(10_000), + StakingBalances::Ring(10_000), 36, )); assert_eq!(Kton::free_balance(&stash), 4); - assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalance::Kton(1), 36)); + assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalances::Kton(1), 36)); assert_eq!(Staking::ledger(controller).unwrap().active_kton, 1); assert_ok!(Staking::nominate(Origin::signed(controller), vec![controller])); @@ -3061,7 +3111,7 @@ fn xavier_q1() { assert_ok!(Staking::bond( Origin::signed(stash), controller, - StakingBalance::Kton(5), + StakingBalances::Kton(5), RewardDestination::Stash, 0, )); @@ -3083,7 +3133,7 @@ fn xavier_q1() { // println!(); Timestamp::set_timestamp(1); - assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalance::Kton(5), 0)); + assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalances::Kton(5), 0)); assert_eq!(Timestamp::get(), 1); assert_eq!(Kton::free_balance(stash), 10); assert_eq!( @@ -3103,7 +3153,7 @@ fn xavier_q1() { let unbond_start = 2; Timestamp::set_timestamp(unbond_start); - assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalance::Kton(9))); + assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalances::Kton(9))); assert_eq!(Timestamp::get(), 2); assert_eq!(Kton::free_balance(stash), 10); assert_eq!( @@ -3159,7 +3209,7 @@ fn xavier_q1() { ); let _ = Kton::deposit_creating(&stash, 20); - assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalance::Kton(19), 0)); + assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalances::Kton(19), 0)); assert_eq!(Kton::free_balance(stash), 29); assert_eq!( Kton::locks(stash), @@ -3211,7 +3261,7 @@ fn xavier_q1() { assert_ok!(Staking::bond( Origin::signed(stash), controller, - StakingBalance::Ring(5), + StakingBalances::Ring(5), RewardDestination::Stash, 0, )); @@ -3233,7 +3283,7 @@ fn xavier_q1() { // println!(); Timestamp::set_timestamp(1); - assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalance::Ring(5), 0)); + assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalances::Ring(5), 0)); assert_eq!(Timestamp::get(), 1); assert_eq!(Ring::free_balance(stash), 10); assert_eq!( @@ -3253,7 +3303,7 @@ fn xavier_q1() { let unbond_start = 2; Timestamp::set_timestamp(unbond_start); - assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalance::Ring(9))); + assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalances::Ring(9))); assert_eq!(Timestamp::get(), 2); assert_eq!(Ring::free_balance(stash), 10); assert_eq!( @@ -3309,7 +3359,7 @@ fn xavier_q1() { ); let _ = Ring::deposit_creating(&stash, 20); - assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalance::Ring(19), 0)); + assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalances::Ring(19), 0)); assert_eq!(Ring::free_balance(stash), 29); assert_eq!( Ring::locks(stash), @@ -3364,7 +3414,7 @@ fn xavier_q2() { assert_ok!(Staking::bond( Origin::signed(stash), controller, - StakingBalance::Kton(5), + StakingBalances::Kton(5), RewardDestination::Stash, 0, )); @@ -3385,7 +3435,7 @@ fn xavier_q2() { // println!(); Timestamp::set_timestamp(1); - assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalance::Kton(4), 0)); + assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalances::Kton(4), 0)); assert_eq!(Timestamp::get(), 1); assert_eq!(Kton::free_balance(stash), 10); assert_eq!( @@ -3407,7 +3457,7 @@ fn xavier_q2() { Timestamp::set_timestamp(unbond_start_1); assert_ok!(Staking::unbond( Origin::signed(controller), - StakingBalance::Kton(unbond_value_1), + StakingBalances::Kton(unbond_value_1), )); assert_eq!(Timestamp::get(), unbond_start_1); assert_eq!(Kton::free_balance(stash), 10); @@ -3431,7 +3481,7 @@ fn xavier_q2() { let (unbond_start_2, unbond_value_2) = (3, 6); Timestamp::set_timestamp(unbond_start_2); - assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalance::Kton(6))); + assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalances::Kton(6))); assert_eq!(Timestamp::get(), unbond_start_2); assert_eq!(Kton::free_balance(stash), 10); assert_eq!( @@ -3535,7 +3585,7 @@ fn xavier_q2() { let _ = Kton::deposit_creating(&stash, 1); // println!("Staking Ledger: {:#?}", Staking::ledger(controller).unwrap()); assert_eq!(Kton::free_balance(stash), 2); - assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalance::Kton(1), 0)); + assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalances::Kton(1), 0)); assert_eq!( Kton::locks(stash), vec![BalanceLock { @@ -3567,7 +3617,7 @@ fn xavier_q2() { assert_ok!(Staking::bond( Origin::signed(stash), controller, - StakingBalance::Ring(5), + StakingBalances::Ring(5), RewardDestination::Stash, 0, )); @@ -3588,7 +3638,7 @@ fn xavier_q2() { // println!(); Timestamp::set_timestamp(1); - assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalance::Ring(4), 0)); + assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalances::Ring(4), 0)); assert_eq!(Timestamp::get(), 1); assert_eq!(Ring::free_balance(stash), 10); assert_eq!( @@ -3610,7 +3660,7 @@ fn xavier_q2() { Timestamp::set_timestamp(unbond_start_1); assert_ok!(Staking::unbond( Origin::signed(controller), - StakingBalance::Ring(unbond_value_1) + StakingBalances::Ring(unbond_value_1) )); assert_eq!(Timestamp::get(), unbond_start_1); assert_eq!(Ring::free_balance(stash), 10); @@ -3634,7 +3684,7 @@ fn xavier_q2() { let (unbond_start_2, unbond_value_2) = (3, 6); Timestamp::set_timestamp(unbond_start_2); - assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalance::Ring(6))); + assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalances::Ring(6))); assert_eq!(Timestamp::get(), unbond_start_2); assert_eq!(Ring::free_balance(stash), 10); assert_eq!( @@ -3738,7 +3788,7 @@ fn xavier_q2() { let _ = Ring::deposit_creating(&stash, 1); // println!("Staking Ledger: {:#?}", Staking::ledger(controller).unwrap()); assert_eq!(Ring::free_balance(stash), 2); - assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalance::Ring(1), 0)); + assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalances::Ring(1), 0)); assert_eq!( Ring::locks(stash), vec![BalanceLock { @@ -3773,7 +3823,7 @@ fn xavier_q3() { assert_ok!(Staking::bond( Origin::signed(stash), controller, - StakingBalance::Kton(5), + StakingBalances::Kton(5), RewardDestination::Stash, 0, )); @@ -3797,7 +3847,7 @@ fn xavier_q3() { // println!("StakingLedger: {:#?}", Staking::ledger(controller)); // println!(); - assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalance::Kton(5))); + assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalances::Kton(5))); assert_eq!( Staking::ledger(controller).unwrap(), StakingLedger { @@ -3818,7 +3868,7 @@ fn xavier_q3() { // println!(); Timestamp::set_timestamp(61); - assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalance::Kton(1), 0)); + assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalances::Kton(1), 0)); assert_eq!(Timestamp::get(), 61); assert_eq!( Staking::ledger(controller).unwrap(), @@ -3849,7 +3899,7 @@ fn xavier_q3() { assert_ok!(Staking::bond( Origin::signed(stash), controller, - StakingBalance::Ring(5), + StakingBalances::Ring(5), RewardDestination::Stash, 0, )); @@ -3873,7 +3923,7 @@ fn xavier_q3() { // println!("StakingLedger: {:#?}", Staking::ledger(controller)); // println!(); - assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalance::Ring(5))); + assert_ok!(Staking::unbond(Origin::signed(controller), StakingBalances::Ring(5))); assert_eq!( Staking::ledger(controller).unwrap(), StakingLedger { @@ -3894,7 +3944,7 @@ fn xavier_q3() { // println!(); Timestamp::set_timestamp(61); - assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalance::Ring(1), 0)); + assert_ok!(Staking::bond_extra(Origin::signed(stash), StakingBalances::Ring(1), 0)); assert_eq!(Timestamp::get(), 61); assert_eq!( Staking::ledger(controller).unwrap(), diff --git a/types.json b/types.json index 01e4f9c27..861e26747 100644 --- a/types.json +++ b/types.json @@ -95,7 +95,7 @@ "amount": "Compact", "own_slash": "Compact" }, - "StakingBalance": { + "StakingBalances": { "_enum": { "Ring": "Balance", "Kton": "Balance"