diff --git a/.github/workflows/mangata-dev.yml b/.github/workflows/mangata-dev.yml index 9b5fadac2d782..2f5598bf8585f 100644 --- a/.github/workflows/mangata-dev.yml +++ b/.github/workflows/mangata-dev.yml @@ -6,36 +6,64 @@ on: push: branches: [ mangata-dev ] -name: build +name: CI + +env: + TOOLCHAIN: nightly-2022-05-11 + jobs: - check: - name: Rust project + fmt: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - name: Install newset Cargo + - name: Install ${{ env.TOOLCHAIN }} uses: actions-rs/toolchain@v1 with: - toolchain: nightly-2022-05-11 + toolchain: ${{ env.TOOLCHAIN }} default: true - - name: Install nightly-2022-05-11 with wasm + components: rustfmt + target: wasm32-unknown-unknown + - name: Check formatting + uses: actions-rs/cargo@v1 + with: + toolchain: ${{ env.TOOLCHAIN }} + command: fmt + args: --all -- --check + + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install ${{ env.TOOLCHAIN }} uses: actions-rs/toolchain@v1 with: - toolchain: nightly-2022-05-11 + toolchain: ${{ env.TOOLCHAIN }} + default: true + components: rustfmt target: wasm32-unknown-unknown - - name: Check Cargo version - run: | - cargo --version - - name: Build UT + - name: Check formatting uses: actions-rs/cargo@v1 with: - toolchain: nightly-2022-05-11 - command: test - args: --release -j2 --no-run - - name: Run UT + toolchain: ${{ env.TOOLCHAIN }} + command: build + args: --release + + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install ${{ env.TOOLCHAIN }} + uses: actions-rs/toolchain@v1 + with: + toolchain: ${{ env.TOOLCHAIN }} + default: true + components: rustfmt + target: wasm32-unknown-unknown + - name: Check formatting uses: actions-rs/cargo@v1 with: - toolchain: nightly-2022-05-11 + toolchain: ${{ env.TOOLCHAIN }} command: test - args: --release + args: -p sc-block-builder-ver -p sc-basic-authorship-ver -p frame-executive -p frame-system -p sc-consensus-slots -p sc-consensus-aura + diff --git a/client/basic-authorship-ver/src/basic_authorship.rs b/client/basic-authorship-ver/src/basic_authorship.rs index 9f9cda8bc088a..8413a273d3659 100644 --- a/client/basic-authorship-ver/src/basic_authorship.rs +++ b/client/basic-authorship-ver/src/basic_authorship.rs @@ -34,9 +34,7 @@ use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_INFO}; use sc_transaction_pool_api::{InPoolTransaction, TransactionPool}; use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_blockchain::{ApplyExtrinsicFailed::Validity, Error::ApplyExtrinsicFailed, HeaderBackend}; -use sp_consensus::{ - DisableProofRecording, EnableProofRecording, ProofRecording, Proposal, -}; +use sp_consensus::{DisableProofRecording, EnableProofRecording, ProofRecording, Proposal}; use sp_core::traits::SpawnNamed; use sp_inherents::InherentData; use sp_runtime::{ diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 5e476ec680ae6..5a39ed7e099c3 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -45,8 +45,7 @@ use scale_info::TypeInfo; use sp_io::storage; use sp_runtime::{traits::Hash, RuntimeDebug}; -use sp_std::vec; -use sp_std::{marker::PhantomData, prelude::*, result}; +use sp_std::{marker::PhantomData, prelude::*, result, vec}; use frame_support::{ codec::{Decode, Encode, MaxEncodedLen}, @@ -753,7 +752,7 @@ impl, I: 'static> Pallet { if position_yes.is_none() { voting.ayes.push(who.clone()); } else { - return Err(Error::::DuplicateVote.into()); + return Err(Error::::DuplicateVote.into()) } if let Some(pos) = position_no { voting.nays.swap_remove(pos); @@ -762,7 +761,7 @@ impl, I: 'static> Pallet { if position_no.is_none() { voting.nays.push(who.clone()); } else { - return Err(Error::::DuplicateVote.into()); + return Err(Error::::DuplicateVote.into()) } if let Some(pos) = position_yes { voting.ayes.swap_remove(pos); @@ -816,7 +815,7 @@ impl, I: 'static> Pallet { ), Pays::Yes, ) - .into()); + .into()) } else if disapproved { Self::deposit_event(Event::Closed { proposal_hash, yes: yes_votes, no: no_votes }); let proposal_count = Self::do_disapprove_proposal(proposal_hash); @@ -824,7 +823,7 @@ impl, I: 'static> Pallet { Some(T::WeightInfo::close_early_disapproved(seats, proposal_count)), Pays::No, ) - .into()); + .into()) } // Only allow actual closing of the proposal after the voting period has ended. diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index 576f10fc27c8b..a1807f2007d0e 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -382,9 +382,9 @@ where // Check that `parent_hash` is correct. let n = header.number().clone(); assert!( - n > System::BlockNumber::zero() - && >::block_hash(n - System::BlockNumber::one()) - == *header.parent_hash(), + n > System::BlockNumber::zero() && + >::block_hash(n - System::BlockNumber::one()) == + *header.parent_hash(), "Parent hash should be valid.", ); @@ -978,8 +978,8 @@ mod tests { .assimilate_storage(&mut t) .unwrap(); let xt = TestXt::new(call_transfer(2, 69), sign_extra(1, 0, 0)); - let weight = xt.get_dispatch_info().weight - + ::BlockWeights::get() + let weight = xt.get_dispatch_info().weight + + ::BlockWeights::get() .get(DispatchClass::Normal) .base_extrinsic; let fee: Balance = @@ -1199,8 +1199,8 @@ mod tests { assert!(Executive::apply_extrinsic(x2.clone()).unwrap().is_ok()); // default weight for `TestXt` == encoded length. - let extrinsic_weight = len as Weight - + ::BlockWeights::get() + let extrinsic_weight = len as Weight + + ::BlockWeights::get() .get(DispatchClass::Normal) .base_extrinsic; assert_eq!( @@ -1271,8 +1271,8 @@ mod tests { Call::System(SystemCall::remark { remark: vec![1u8] }), sign_extra(1, 0, 0), ); - let weight = xt.get_dispatch_info().weight - + ::BlockWeights::get() + let weight = xt.get_dispatch_info().weight + + ::BlockWeights::get() .get(DispatchClass::Normal) .base_extrinsic; let fee: Balance = @@ -1519,10 +1519,9 @@ mod tests { // Weights are recorded correctly assert_eq!( frame_system::Pallet::::block_weight().total(), - custom_runtime_upgrade_weight - + runtime_upgrade_weight - + on_initialize_weight - + base_block_weight, + custom_runtime_upgrade_weight + + runtime_upgrade_weight + + on_initialize_weight + base_block_weight, ); }); } diff --git a/frame/support/src/traits/tokens/currency.rs b/frame/support/src/traits/tokens/currency.rs index 047739c2a99f6..715758a959448 100644 --- a/frame/support/src/traits/tokens/currency.rs +++ b/frame/support/src/traits/tokens/currency.rs @@ -26,12 +26,11 @@ use crate::{ traits::Get, }; use codec::{FullCodec, MaxEncodedLen}; -use sp_runtime::traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize, Member}; +use frame_support::Parameter; use mangata_types::{Balance as BalancePrimitive, TokenId}; -use sp_std::fmt::Debug; use scale_info::TypeInfo; -use frame_support::Parameter; -use sp_std::result; +use sp_runtime::traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize, Member}; +use sp_std::{fmt::Debug, result}; mod reservable; pub use reservable::{NamedReservableCurrency, ReservableCurrency}; @@ -46,40 +45,40 @@ pub trait MultiTokenImbalanceWithZeroTrait { pub trait MultiTokenCurrency { /// The balance of an account. type Balance: AtLeast32BitUnsigned - + FullCodec - + Copy - + MaybeSerializeDeserialize - + Debug - + Default - + MaxEncodedLen - + TypeInfo - + From - + Into; + + FullCodec + + Copy + + MaybeSerializeDeserialize + + Debug + + Default + + MaxEncodedLen + + TypeInfo + + From + + Into; type CurrencyId: Parameter - + Member - + Copy - + MaybeSerializeDeserialize - + Ord - + Default - + AtLeast32BitUnsigned - + FullCodec - + MaxEncodedLen - + TypeInfo - + From - + Into; + + Member + + Copy + + MaybeSerializeDeserialize + + Ord + + Default + + AtLeast32BitUnsigned + + FullCodec + + MaxEncodedLen + + TypeInfo + + From + + Into; /// The opaque token type for an imbalance. This is returned by unbalanced /// operations and must be dealt with. It may be dropped but cannot be /// cloned. type PositiveImbalance: Imbalance - + MultiTokenImbalanceWithZeroTrait; + + MultiTokenImbalanceWithZeroTrait; /// The opaque token type for an imbalance. This is returned by unbalanced /// operations and must be dealt with. It may be dropped but cannot be /// cloned. type NegativeImbalance: Imbalance - + MultiTokenImbalanceWithZeroTrait; + + MultiTokenImbalanceWithZeroTrait; // PUBLIC IMMUTABLES @@ -123,10 +122,7 @@ pub trait MultiTokenCurrency { currency_id: Self::CurrencyId, amount: Self::Balance, ) -> (Self::PositiveImbalance, Self::NegativeImbalance) { - ( - Self::burn(currency_id, amount.clone()), - Self::issue(currency_id, amount), - ) + (Self::burn(currency_id, amount.clone()), Self::issue(currency_id, amount)) } /// The 'free' balance of a given account. @@ -217,7 +213,11 @@ pub trait MultiTokenCurrency { /// Similar to deposit_creating, only accepts a `NegativeImbalance` and /// returns nothing on success. - fn resolve_creating(currency_id: Self::CurrencyId, who: &AccountId, value: Self::NegativeImbalance) { + fn resolve_creating( + currency_id: Self::CurrencyId, + who: &AccountId, + value: Self::NegativeImbalance, + ) { let v = value.peek(); drop(value.offset(Self::deposit_creating(currency_id, who, v))); } diff --git a/frame/transaction-payment-mangata/asset-tx-payment/src/lib.rs b/frame/transaction-payment-mangata/asset-tx-payment/src/lib.rs index 43ca55e729cb6..f60c4aee2d3a0 100644 --- a/frame/transaction-payment-mangata/asset-tx-payment/src/lib.rs +++ b/frame/transaction-payment-mangata/asset-tx-payment/src/lib.rs @@ -22,10 +22,10 @@ //! It does this by extending transactions to include an optional `AssetId` that specifies the asset //! to be used for payment (defaulting to the native token on `None`). It expects an -//! [`OnChargeAssetTransaction`] implementation analogously to [`pallet-transaction-payment-mangata`]. The -//! included [`FungiblesAdapter`] (implementing [`OnChargeAssetTransaction`]) determines the fee -//! amount by converting the fee calculated by [`pallet-transaction-payment-mangata`] into the desired -//! asset. +//! [`OnChargeAssetTransaction`] implementation analogously to +//! [`pallet-transaction-payment-mangata`]. The included [`FungiblesAdapter`] (implementing +//! [`OnChargeAssetTransaction`]) determines the fee amount by converting the fee calculated by +//! [`pallet-transaction-payment-mangata`] into the desired asset. //! //! ## Integration @@ -127,8 +127,9 @@ pub mod pallet { /// Require the transactor pay for themselves and maybe include a tip to gain additional priority /// in the queue. Allows paying via both `Currency` as well as `fungibles::Balanced`. /// -/// Wraps the transaction logic in [`pallet_transaction_payment_mangata`] and extends it with assets. -/// An asset id of `None` falls back to the underlying transaction payment via the native currency. +/// Wraps the transaction logic in [`pallet_transaction_payment_mangata`] and extends it with +/// assets. An asset id of `None` falls back to the underlying transaction payment via the native +/// currency. #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] #[scale_info(skip_type_params(T))] pub struct ChargeAssetTxPayment { @@ -159,7 +160,9 @@ where info: &DispatchInfoOf, len: usize, ) -> Result<(BalanceOf, InitialPayment), TransactionValidityError> { - let fee = pallet_transaction_payment_mangata::Pallet::::compute_fee(len as u32, info, self.tip); + let fee = pallet_transaction_payment_mangata::Pallet::::compute_fee( + len as u32, info, self.tip, + ); debug_assert!(self.tip <= fee, "tip should be included in the computed fee"); if fee.is_zero() { Ok((fee, InitialPayment::Nothing)) @@ -262,9 +265,10 @@ where )?; }, InitialPayment::Asset(already_withdrawn) => { - let actual_fee = pallet_transaction_payment_mangata::Pallet::::compute_actual_fee( - len as u32, info, post_info, tip, - ); + let actual_fee = + pallet_transaction_payment_mangata::Pallet::::compute_actual_fee( + len as u32, info, post_info, tip, + ); T::OnChargeAssetTransaction::correct_and_deposit_fee( &who, info, diff --git a/frame/transaction-payment-mangata/rpc/src/lib.rs b/frame/transaction-payment-mangata/rpc/src/lib.rs index 2ee035e9a00b1..4e06da77382e6 100644 --- a/frame/transaction-payment-mangata/rpc/src/lib.rs +++ b/frame/transaction-payment-mangata/rpc/src/lib.rs @@ -25,7 +25,9 @@ use jsonrpsee::{ proc_macros::rpc, types::error::{CallError, ErrorCode, ErrorObject}, }; -use pallet_transaction_payment_rpc_runtime_api_mangata::{FeeDetails, InclusionFee, RuntimeDispatchInfo}; +use pallet_transaction_payment_rpc_runtime_api_mangata::{ + FeeDetails, InclusionFee, RuntimeDispatchInfo, +}; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_core::Bytes; diff --git a/frame/uniques/src/lib.rs b/frame/uniques/src/lib.rs index 0dc1f250402df..974919fa4adb9 100644 --- a/frame/uniques/src/lib.rs +++ b/frame/uniques/src/lib.rs @@ -114,7 +114,7 @@ pub mod pallet { type CreateOrigin: EnsureOriginWithArg< Self::Origin, Self::CollectionId, - Success = Self::AccountId + Success = Self::AccountId, >; /// Locker trait to enable Locking mechanism downstream. diff --git a/frame/vesting-mangata/src/lib.rs b/frame/vesting-mangata/src/lib.rs index fe9567292c4ff..5b47aa43270ef 100644 --- a/frame/vesting-mangata/src/lib.rs +++ b/frame/vesting-mangata/src/lib.rs @@ -57,10 +57,12 @@ use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ ensure, pallet_prelude::*, - traits::{ExistenceRequirement, Get, LockIdentifier, WithdrawReasons}, + traits::{ + tokens::currency::{MultiTokenCurrency, MultiTokenLockableCurrency}, + ExistenceRequirement, Get, LockIdentifier, WithdrawReasons, + }, }; use frame_system::{ensure_root, ensure_signed, pallet_prelude::*}; -use frame_support::traits::tokens::currency::{MultiTokenCurrency, MultiTokenLockableCurrency}; pub use pallet::*; use scale_info::TypeInfo; use sp_runtime::{ @@ -70,7 +72,7 @@ use sp_runtime::{ }, RuntimeDebug, }; -use sp_std::{convert::{TryInto}, fmt::Debug, prelude::*}; +use sp_std::{convert::TryInto, fmt::Debug, prelude::*}; pub use vesting_info::*; pub use weights::WeightInfo; @@ -393,7 +395,7 @@ pub mod pallet { ) -> DispatchResult { let who = ensure_signed(origin)?; if schedule1_index == schedule2_index { - return Ok(()); + return Ok(()) }; let schedule1_index = schedule1_index as usize; let schedule2_index = schedule2_index as usize; @@ -429,14 +431,22 @@ pub mod pallet { } impl Pallet { - - pub fn get_vesting_locked_at(who: &T::AccountId, token_id: TokenIdOf, at_block_number: Option) -> Result, T::BlockNumber>, BalanceOf)>, DispatchError> - { + pub fn get_vesting_locked_at( + who: &T::AccountId, + token_id: TokenIdOf, + at_block_number: Option, + ) -> Result, T::BlockNumber>, BalanceOf)>, DispatchError> { let at_block_number = at_block_number.unwrap_or(>::block_number()); - Ok(Self::vesting(&who, token_id).ok_or(Error::::NotVesting)? + Ok(Self::vesting(&who, token_id) + .ok_or(Error::::NotVesting)? .to_vec() .into_iter() - .map(|x| (x.into(), BalanceOf::::from(x.locked_at::(at_block_number)))) + .map(|x| { + ( + x.into(), + BalanceOf::::from(x.locked_at::(at_block_number)), + ) + }) .collect::, T::BlockNumber>, BalanceOf)>>()) } @@ -499,7 +509,7 @@ impl Pallet { // Validate user inputs. ensure!(schedule.locked() >= T::MinVestedTransfer::get(), Error::::AmountLow); if !schedule.is_valid() { - return Err(Error::::InvalidScheduleParams.into()); + return Err(Error::::InvalidScheduleParams.into()) }; let target = T::Lookup::lookup(target)?; let source = T::Lookup::lookup(source)?; @@ -513,7 +523,13 @@ impl Pallet { token_id, )?; - T::Tokens::ensure_can_withdraw(token_id, &source, schedule.locked(), WithdrawReasons::all(), Default::default())?; + T::Tokens::ensure_can_withdraw( + token_id, + &source, + schedule.locked(), + WithdrawReasons::all(), + Default::default(), + )?; T::Tokens::transfer( token_id, @@ -663,8 +679,8 @@ impl Pallet { }; debug_assert!( - locked_now > Zero::zero() && schedules.len() > 0 - || locked_now == Zero::zero() && schedules.len() == 0 + locked_now > Zero::zero() && schedules.len() > 0 || + locked_now == Zero::zero() && schedules.len() == 0 ); Ok((schedules, locked_now)) @@ -686,7 +702,10 @@ pub trait MultiTokenVestingLocks { who: &AccountId, token_id: >::CurrencyId, unlock_amount: >::Balance, - ) -> Result<(BlockNumber, >::Balance), DispatchError>; + ) -> Result< + (BlockNumber, >::Balance), + DispatchError, + >; /// Finds the vesting schedule with the provided index /// Removes that old vesting schedule, adds a new one with new_locked and new_per_block @@ -696,8 +715,17 @@ pub trait MultiTokenVestingLocks { who: &AccountId, token_id: >::CurrencyId, vesting_index: u32, - unlock_some_amount_or_all: Option<>::Balance>, - ) -> Result<(>::Balance, BlockNumber, >::Balance), DispatchError>; + unlock_some_amount_or_all: Option< + >::Balance, + >, + ) -> Result< + ( + >::Balance, + BlockNumber, + >::Balance, + ), + DispatchError, + >; /// Constructs a vesting schedule based on the given data starting from now /// And places it into the appropriate (who, token_id) storage @@ -742,21 +770,20 @@ where for (i, schedule) in schedules.clone().into_iter().enumerate() { let schedule_locked_at = schedule.locked_at::(now); match (schedule_locked_at >= unlock_amount, selected_schedule) { - (true, None) => { + (true, None) => selected_schedule = Some(( i, schedule, schedule_locked_at, schedule.ending_block_as_balance::(), - )) - }, + )), (true, Some(currently_selected_schedule)) => { let schedule_ending_block_as_balance = schedule.ending_block_as_balance::(); if currently_selected_schedule .1 - .ending_block_as_balance::() - > schedule_ending_block_as_balance + .ending_block_as_balance::() > + schedule_ending_block_as_balance { selected_schedule = Some(( i, @@ -829,7 +856,7 @@ where token_id: TokenIdOf, vesting_index: u32, unlock_some_amount_or_all: Option>, - ) -> Result<(BalanceOf, T::BlockNumber, BalanceOf), DispatchError>{ + ) -> Result<(BalanceOf, T::BlockNumber, BalanceOf), DispatchError> { let now = >::block_number(); // First we get the schedules of who @@ -850,21 +877,21 @@ where for (i, schedule) in schedules.clone().into_iter().enumerate() { let schedule_locked_at = schedule.locked_at::(now); - let schedule_locked_at_satisfied: bool = if let Some(unlock_amount) = unlock_some_amount_or_all{ - schedule_locked_at >= unlock_amount - } else { - true - }; + let schedule_locked_at_satisfied: bool = + if let Some(unlock_amount) = unlock_some_amount_or_all { + schedule_locked_at >= unlock_amount + } else { + true + }; match (i == vesting_index as usize && schedule_locked_at_satisfied, selected_schedule) { - (true, None) => { + (true, None) => selected_schedule = Some(( i, schedule, schedule_locked_at, schedule.ending_block_as_balance::(), - )) - }, + )), _ => (), } } @@ -888,7 +915,6 @@ where ) .collect::>(); - let start_block = now.max(selected_schedule.1.starting_block()); let new_locked = if let Some(unlock_amount) = unlock_some_amount_or_all { @@ -935,9 +961,16 @@ where starting_block: Option, ending_block_as_balance: BalanceOf, ) -> DispatchResult { - let starting_block: T::BlockNumber = starting_block.unwrap_or(>::block_number()); + let starting_block: T::BlockNumber = + starting_block.unwrap_or(>::block_number()); - T::Tokens::ensure_can_withdraw(token_id, who, lock_amount, WithdrawReasons::all(), Default::default())?; + T::Tokens::ensure_can_withdraw( + token_id, + who, + lock_amount, + WithdrawReasons::all(), + Default::default(), + )?; let length_as_balance = ending_block_as_balance .saturating_sub(T::BlockNumberToBalance::convert(starting_block)) @@ -1052,13 +1085,13 @@ where token_id: TokenIdOf, ) -> DispatchResult { if locked.is_zero() { - return Ok(()); + return Ok(()) } let vesting_schedule = VestingInfo::new(locked, per_block, starting_block); // Check for `per_block` or `locked` of 0. if !vesting_schedule.is_valid() { - return Err(Error::::InvalidScheduleParams.into()); + return Err(Error::::InvalidScheduleParams.into()) }; let mut schedules = Self::vesting(who, token_id).unwrap_or_default(); @@ -1087,12 +1120,12 @@ where ) -> DispatchResult { // Check for `per_block` or `locked` of 0. if !VestingInfo::new(locked, per_block, starting_block).is_valid() { - return Err(Error::::InvalidScheduleParams.into()); + return Err(Error::::InvalidScheduleParams.into()) } ensure!( - (Vesting::::decode_len(who, token_id).unwrap_or_default() as u32) - < T::MAX_VESTING_SCHEDULES, + (Vesting::::decode_len(who, token_id).unwrap_or_default() as u32) < + T::MAX_VESTING_SCHEDULES, Error::::AtMaxVestingSchedules ); diff --git a/frame/vesting-mangata/src/tests.rs b/frame/vesting-mangata/src/tests.rs index bb82102cd906d..f1b688946a08d 100644 --- a/frame/vesting-mangata/src/tests.rs +++ b/frame/vesting-mangata/src/tests.rs @@ -792,8 +792,8 @@ fn merging_shifts_other_schedules_index() { // The merged schedule will have the max possible starting block, let sched3_start = sched1.starting_block().max(sched2.starting_block()); // `locked` equal to the sum of the two schedules locked through the current block, - let sched3_locked = sched2.locked_at::<::BlockNumberToBalance>(cur_block) - + sched0.locked_at::<::BlockNumberToBalance>(cur_block); + let sched3_locked = sched2.locked_at::<::BlockNumberToBalance>(cur_block) + + sched0.locked_at::<::BlockNumberToBalance>(cur_block); // and will end at the max possible block. let sched3_end = sched2 .ending_block_as_balance::<::BlockNumberToBalance>() @@ -823,9 +823,9 @@ fn merge_ongoing_and_yet_to_be_started_schedules() { assert_eq!(Vesting::vesting(&2, NATIVE_CURRENCY_ID).unwrap(), vec![sched0]); // Fast forward to half way through the life of sched1. - let mut cur_block = (sched0.starting_block() as Balance - + sched0.ending_block_as_balance::<::BlockNumberToBalance>()) - / 2; + let mut cur_block = (sched0.starting_block() as Balance + + sched0.ending_block_as_balance::<::BlockNumberToBalance>()) / + 2; assert_eq!(cur_block, 20); System::set_block_number( cur_block.saturated_into::<::BlockNumber>(), @@ -838,9 +838,10 @@ fn merge_ongoing_and_yet_to_be_started_schedules() { Vesting::vest(Some(2).into(), NATIVE_CURRENCY_ID).unwrap(); // After vesting the usable balance increases by the unlocked amount. - let sched0_vested_now = sched0.locked() - - sched0 - .locked_at::<::BlockNumberToBalance>(cur_block.try_into().unwrap()); + let sched0_vested_now = sched0.locked() - + sched0.locked_at::<::BlockNumberToBalance>( + cur_block.try_into().unwrap(), + ); usable_balance += sched0_vested_now; assert_eq!(usable_native_balance::(2), usable_balance); @@ -868,9 +869,10 @@ fn merge_ongoing_and_yet_to_be_started_schedules() { let sched2_start = sched1.starting_block(); // `locked` equal to the sum of the two schedules locked through the current block, let sched2_locked = sched0 - .locked_at::<::BlockNumberToBalance>(cur_block.try_into().unwrap()) - + sched1 - .locked_at::<::BlockNumberToBalance>(cur_block.try_into().unwrap()); + .locked_at::<::BlockNumberToBalance>(cur_block.try_into().unwrap()) + + sched1.locked_at::<::BlockNumberToBalance>( + cur_block.try_into().unwrap(), + ); // and will end at the max possible block. let sched2_end = sched0 .ending_block_as_balance::<::BlockNumberToBalance>() @@ -933,12 +935,14 @@ fn merge_finished_and_ongoing_schedules() { // sched0 has finished, so its funds are fully unlocked. let sched0_unlocked_now = sched0.locked(); // The remaining schedules are ongoing, so their funds are partially unlocked. - let sched1_unlocked_now = sched1.locked() - - sched1 - .locked_at::<::BlockNumberToBalance>(cur_block.try_into().unwrap()); - let sched2_unlocked_now = sched2.locked() - - sched2 - .locked_at::<::BlockNumberToBalance>(cur_block.try_into().unwrap()); + let sched1_unlocked_now = sched1.locked() - + sched1.locked_at::<::BlockNumberToBalance>( + cur_block.try_into().unwrap(), + ); + let sched2_unlocked_now = sched2.locked() - + sched2.locked_at::<::BlockNumberToBalance>( + cur_block.try_into().unwrap(), + ); // Since merging also vests all the schedules, the users usable balance after merging // includes all pre-existing schedules unlocked through the current block, including @@ -1240,8 +1244,8 @@ fn vested_transfer_less_than_existential_deposit_fails() { ExtBuilder::default().existential_deposit(4 * ED).build().execute_with(|| { // MinVestedTransfer is less the ED. assert!( - ::Tokens::minimum_balance(NATIVE_CURRENCY_ID) - > ::MinVestedTransfer::get().into() + ::Tokens::minimum_balance(NATIVE_CURRENCY_ID) > + ::MinVestedTransfer::get().into() ); let sched = VestingInfo::::BlockNumber>::new( @@ -1251,8 +1255,8 @@ fn vested_transfer_less_than_existential_deposit_fails() { ); // The new account balance with the schedule's locked amount would be less than ED. assert!( - Tokens::free_balance(0u32, &99) + sched.locked() - < ::Tokens::minimum_balance(NATIVE_CURRENCY_ID) + Tokens::free_balance(0u32, &99) + sched.locked() < + ::Tokens::minimum_balance(NATIVE_CURRENCY_ID) ); // vested_transfer fails. @@ -1286,7 +1290,7 @@ fn lock_tokens_works() { assert_ok!( as MultiTokenVestingLocks< ::AccountId, - ::BlockNumber + ::BlockNumber, >>::lock_tokens(&999, NATIVE_CURRENCY_ID, 10000, None, 11)); assert_noop!( @@ -1315,7 +1319,7 @@ fn lock_tokens_works() { assert_ok!( as MultiTokenVestingLocks< ::AccountId, - ::BlockNumber + ::BlockNumber, >>::lock_tokens(&999, NATIVE_CURRENCY_ID, 10000, None, 21)); assert_noop!( @@ -1347,48 +1351,115 @@ fn lock_tokens_works() { fn unlock_tokens_works() { ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { let now = >::block_number(); - assert_ok!(orml_tokens::MultiTokenCurrencyAdapter::::mint(NATIVE_CURRENCY_ID, &999, 10000)); + assert_ok!(orml_tokens::MultiTokenCurrencyAdapter::::mint( + NATIVE_CURRENCY_ID, + &999, + 10000 + )); - assert_ok!( as MultiTokenVestingLocks<::AccountId, ::BlockNumber>>::lock_tokens(&999, NATIVE_CURRENCY_ID, 10000, None, 11)); + assert_ok!( as MultiTokenVestingLocks< + ::AccountId, + ::BlockNumber, + >>::lock_tokens(&999, NATIVE_CURRENCY_ID, 10000, None, 11)); - assert_noop!(orml_tokens::MultiTokenCurrencyAdapter::::ensure_can_withdraw(NATIVE_CURRENCY_ID, &999, 1, WithdrawReasons::TRANSFER, Default::default()), orml_tokens::Error::::LiquidityRestrictions); - assert_eq!(Vesting::vesting(&999, NATIVE_CURRENCY_ID).unwrap(), - vec![ - VestingInfo::::BlockNumber>::new(10000, 1000, now), - ] + assert_noop!( + orml_tokens::MultiTokenCurrencyAdapter::::ensure_can_withdraw( + NATIVE_CURRENCY_ID, + &999, + 1, + WithdrawReasons::TRANSFER, + Default::default() + ), + orml_tokens::Error::::LiquidityRestrictions + ); + assert_eq!( + Vesting::vesting(&999, NATIVE_CURRENCY_ID).unwrap(), + vec![VestingInfo::::BlockNumber>::new( + 10000, 1000, now + ),] ); - assert_ok!(orml_tokens::MultiTokenCurrencyAdapter::::mint(NATIVE_CURRENCY_ID, &999, 10000)); + assert_ok!(orml_tokens::MultiTokenCurrencyAdapter::::mint( + NATIVE_CURRENCY_ID, + &999, + 10000 + )); - assert_ok!( as MultiTokenVestingLocks<::AccountId, ::BlockNumber>>::lock_tokens(&999, NATIVE_CURRENCY_ID, 10000, None, 21)); + assert_ok!( as MultiTokenVestingLocks< + ::AccountId, + ::BlockNumber, + >>::lock_tokens(&999, NATIVE_CURRENCY_ID, 10000, None, 21)); - assert_noop!(orml_tokens::MultiTokenCurrencyAdapter::::ensure_can_withdraw(NATIVE_CURRENCY_ID, &999, 1, WithdrawReasons::TRANSFER, Default::default()), orml_tokens::Error::::LiquidityRestrictions); + assert_noop!( + orml_tokens::MultiTokenCurrencyAdapter::::ensure_can_withdraw( + NATIVE_CURRENCY_ID, + &999, + 1, + WithdrawReasons::TRANSFER, + Default::default() + ), + orml_tokens::Error::::LiquidityRestrictions + ); - assert_eq!(Vesting::vesting(&999, NATIVE_CURRENCY_ID).unwrap(), + assert_eq!( + Vesting::vesting(&999, NATIVE_CURRENCY_ID).unwrap(), vec![ - VestingInfo::::BlockNumber>::new(10000, 1000, now), - VestingInfo::::BlockNumber>::new(10000, 500, now), + VestingInfo::::BlockNumber>::new( + 10000, 1000, now + ), + VestingInfo::::BlockNumber>::new( + 10000, 500, now + ), ] ); let cur_block = 6; System::set_block_number(cur_block); - assert_eq!( as MultiTokenVestingLocks<::AccountId, ::BlockNumber>>::unlock_tokens(&999, NATIVE_CURRENCY_ID, 6000).unwrap().1, 21); + assert_eq!( + as MultiTokenVestingLocks< + ::AccountId, + ::BlockNumber, + >>::unlock_tokens(&999, NATIVE_CURRENCY_ID, 6000) + .unwrap() + .1, + 21 + ); - assert_eq!(Vesting::vesting(&999, NATIVE_CURRENCY_ID).unwrap(), + assert_eq!( + Vesting::vesting(&999, NATIVE_CURRENCY_ID).unwrap(), vec![ - VestingInfo::::BlockNumber>::new(10000, 1000, now), - VestingInfo::::BlockNumber>::new(1500, 100, 6), + VestingInfo::::BlockNumber>::new( + 10000, 1000, now + ), + VestingInfo::::BlockNumber>::new( + 1500, 100, 6 + ), ] ); assert_eq!( - VestingInfo::::BlockNumber>::new(1500, 100, 6).locked_at::<::BlockNumberToBalance>(cur_block), 1500 + VestingInfo::::BlockNumber>::new(1500, 100, 6) + .locked_at::<::BlockNumberToBalance>(cur_block), + 1500 ); - assert_ok!(orml_tokens::MultiTokenCurrencyAdapter::::ensure_can_withdraw(NATIVE_CURRENCY_ID, &999, 13500, WithdrawReasons::TRANSFER, Default::default())); - assert_noop!(orml_tokens::MultiTokenCurrencyAdapter::::ensure_can_withdraw(NATIVE_CURRENCY_ID, &999, 13501, WithdrawReasons::TRANSFER, Default::default()), orml_tokens::Error::::LiquidityRestrictions); - + assert_ok!(orml_tokens::MultiTokenCurrencyAdapter::::ensure_can_withdraw( + NATIVE_CURRENCY_ID, + &999, + 13500, + WithdrawReasons::TRANSFER, + Default::default() + )); + assert_noop!( + orml_tokens::MultiTokenCurrencyAdapter::::ensure_can_withdraw( + NATIVE_CURRENCY_ID, + &999, + 13501, + WithdrawReasons::TRANSFER, + Default::default() + ), + orml_tokens::Error::::LiquidityRestrictions + ); }); } diff --git a/frame/vesting-mangata/src/vesting_info.rs b/frame/vesting-mangata/src/vesting_info.rs index c910a7f48b69b..81bffa199fd72 100644 --- a/frame/vesting-mangata/src/vesting_info.rs +++ b/frame/vesting-mangata/src/vesting_info.rs @@ -99,8 +99,8 @@ where // the block after starting. One::one() } else { - self.locked / self.per_block() - + if (self.locked % self.per_block()).is_zero() { + self.locked / self.per_block() + + if (self.locked % self.per_block()).is_zero() { Zero::zero() } else { // `per_block` does not perfectly divide `locked`, so we need an extra block to