Replace bitmask with bitflags (#7159)

Signed-off-by: koushiro <koushiro.cqx@gmail.com>
This commit is contained in:
Qinxuan Chen
2020-10-29 20:19:59 +08:00
committed by GitHub
parent c8a245e5e0
commit bd450c24ff
15 changed files with 67 additions and 80 deletions
+1 -7
View File
@@ -465,12 +465,6 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
[[package]]
name = "bitmask"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5da9b3d9f6f585199287a473f4f8dfab6566cf827d15c00c219f53c645687ead"
[[package]]
name = "bitvec"
version = "0.17.4"
@@ -1648,7 +1642,7 @@ dependencies = [
name = "frame-support"
version = "2.0.0"
dependencies = [
"bitmask",
"bitflags",
"frame-metadata",
"frame-support-procedural",
"frame-system",
+8 -8
View File
@@ -163,7 +163,7 @@ use frame_support::{
StorageValue, Parameter, decl_event, decl_storage, decl_module, decl_error, ensure,
traits::{
Currency, OnKilledAccount, OnUnbalanced, TryDrop, StoredMap,
WithdrawReason, WithdrawReasons, LockIdentifier, LockableCurrency, ExistenceRequirement,
WithdrawReasons, LockIdentifier, LockableCurrency, ExistenceRequirement,
Imbalance, SignedImbalance, ReservableCurrency, Get, ExistenceRequirement::KeepAlive,
ExistenceRequirement::AllowDeath, IsDeadAccount, BalanceStatus as Status,
}
@@ -292,9 +292,9 @@ pub enum Reasons {
impl From<WithdrawReasons> for Reasons {
fn from(r: WithdrawReasons) -> Reasons {
if r == WithdrawReasons::from(WithdrawReason::TransactionPayment) {
if r == WithdrawReasons::from(WithdrawReasons::TRANSACTION_PAYMENT) {
Reasons::Fee
} else if r.contains(WithdrawReason::TransactionPayment) {
} else if r.contains(WithdrawReasons::TRANSACTION_PAYMENT) {
Reasons::All
} else {
Reasons::Misc
@@ -1011,7 +1011,7 @@ impl<T: Trait<I>, I: Instance> Currency<T::AccountId> for Module<T, I> where
Self::ensure_can_withdraw(
transactor,
value,
WithdrawReason::Transfer.into(),
WithdrawReasons::TRANSFER,
from_account.free,
)?;
@@ -1170,7 +1170,7 @@ impl<T: Trait<I>, I: Instance> ReservableCurrency<T::AccountId> for Module<T, I>
Self::account(who).free
.checked_sub(&value)
.map_or(false, |new_balance|
Self::ensure_can_withdraw(who, value, WithdrawReason::Reserve.into(), new_balance).is_ok()
Self::ensure_can_withdraw(who, value, WithdrawReasons::RESERVE, new_balance).is_ok()
)
}
@@ -1187,7 +1187,7 @@ impl<T: Trait<I>, I: Instance> ReservableCurrency<T::AccountId> for Module<T, I>
Self::try_mutate_account(who, |account, _| -> DispatchResult {
account.free = account.free.checked_sub(&value).ok_or(Error::<T, I>::InsufficientBalance)?;
account.reserved = account.reserved.checked_add(&value).ok_or(Error::<T, I>::Overflow)?;
Self::ensure_can_withdraw(&who, value.clone(), WithdrawReason::Reserve.into(), account.free)
Self::ensure_can_withdraw(&who, value.clone(), WithdrawReasons::RESERVE, account.free)
})?;
Self::deposit_event(RawEvent::Reserved(who.clone(), value));
@@ -1303,7 +1303,7 @@ where
amount: T::Balance,
reasons: WithdrawReasons,
) {
if amount.is_zero() || reasons.is_none() { return }
if amount.is_zero() || reasons.is_empty() { return }
let mut new_lock = Some(BalanceLock { id, amount, reasons: reasons.into() });
let mut locks = Self::locks(who).into_iter()
.filter_map(|l| if l.id == id { new_lock.take() } else { Some(l) })
@@ -1322,7 +1322,7 @@ where
amount: T::Balance,
reasons: WithdrawReasons,
) {
if amount.is_zero() || reasons.is_none() { return }
if amount.is_zero() || reasons.is_empty() { return }
let mut new_lock = Some(BalanceLock { id, amount, reasons: reasons.into() });
let mut locks = Self::locks(who).into_iter().filter_map(|l|
if l.id == id {
+7 -7
View File
@@ -42,7 +42,7 @@ macro_rules! decl_tests {
use frame_support::{
assert_noop, assert_ok, assert_err,
traits::{
LockableCurrency, LockIdentifier, WithdrawReason, WithdrawReasons,
LockableCurrency, LockIdentifier, WithdrawReasons,
Currency, ReservableCurrency, ExistenceRequirement::AllowDeath, StoredMap
}
};
@@ -133,7 +133,7 @@ macro_rules! decl_tests {
#[test]
fn combination_locking_should_work() {
<$ext_builder>::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, u64::max_value(), WithdrawReasons::none());
Balances::set_lock(ID_1, &1, u64::max_value(), WithdrawReasons::empty());
Balances::set_lock(ID_2, &1, 0, WithdrawReasons::all());
assert_ok!(<Balances as Currency<_>>::transfer(&1, &2, 1, AllowDeath));
});
@@ -168,7 +168,7 @@ macro_rules! decl_tests {
.build()
.execute_with(|| {
pallet_transaction_payment::NextFeeMultiplier::put(Multiplier::saturating_from_integer(1));
Balances::set_lock(ID_1, &1, 10, WithdrawReason::Reserve.into());
Balances::set_lock(ID_1, &1, 10, WithdrawReasons::RESERVE);
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 1, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
@@ -192,7 +192,7 @@ macro_rules! decl_tests {
1,
).is_ok());
Balances::set_lock(ID_1, &1, 10, WithdrawReason::TransactionPayment.into());
Balances::set_lock(ID_1, &1, 10, WithdrawReasons::TRANSACTION_PAYMENT);
assert_ok!(<Balances as Currency<_>>::transfer(&1, &2, 1, AllowDeath));
assert_ok!(<Balances as ReservableCurrency<_>>::reserve(&1, 1));
assert!(<ChargeTransactionPayment<$test> as SignedExtension>::pre_dispatch(
@@ -237,17 +237,17 @@ macro_rules! decl_tests {
#[test]
fn lock_reasons_extension_should_work() {
<$ext_builder>::default().existential_deposit(1).monied(true).build().execute_with(|| {
Balances::set_lock(ID_1, &1, 10, WithdrawReason::Transfer.into());
Balances::set_lock(ID_1, &1, 10, WithdrawReasons::TRANSFER);
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 6, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
);
Balances::extend_lock(ID_1, &1, 10, WithdrawReasons::none());
Balances::extend_lock(ID_1, &1, 10, WithdrawReasons::empty());
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 6, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
);
Balances::extend_lock(ID_1, &1, 10, WithdrawReason::Reserve.into());
Balances::extend_lock(ID_1, &1, 10, WithdrawReasons::RESERVE);
assert_noop!(
<Balances as Currency<_>>::transfer(&1, &2, 6, AllowDeath),
Error::<$test, _>::LiquidityRestrictions
+3 -3
View File
@@ -23,7 +23,7 @@ use crate::{
use sp_std::prelude::*;
use sp_io::hashing::blake2_256;
use frame_support::storage::child;
use frame_support::traits::{Currency, ExistenceRequirement, Get, OnUnbalanced, WithdrawReason};
use frame_support::traits::{Currency, ExistenceRequirement, Get, OnUnbalanced, WithdrawReasons};
use frame_support::StorageMap;
use pallet_contracts_primitives::{ContractAccessError, RentProjection, RentProjectionResult};
use sp_runtime::traits::{Bounded, CheckedDiv, CheckedMul, SaturatedConversion, Saturating, Zero};
@@ -54,7 +54,7 @@ impl<T: Trait> OutstandingAmount<T> {
if let Ok(imbalance) = T::Currency::withdraw(
account,
self.amount,
WithdrawReason::Fee.into(),
WithdrawReasons::FEE,
ExistenceRequirement::KeepAlive,
) {
// This should never fail. However, let's err on the safe side.
@@ -192,7 +192,7 @@ fn consider_case<T: Trait>(
let can_withdraw_rent = T::Currency::ensure_can_withdraw(
account,
dues_limited,
WithdrawReason::Fee.into(),
WithdrawReasons::FEE,
free_balance.saturating_sub(dues_limited),
)
.is_ok();
+4 -4
View File
@@ -162,7 +162,7 @@ use frame_support::{
decl_module, decl_storage, decl_event, decl_error, ensure, Parameter,
weights::{Weight, DispatchClass, Pays},
traits::{
Currency, ReservableCurrency, LockableCurrency, WithdrawReason, LockIdentifier, Get,
Currency, ReservableCurrency, LockableCurrency, WithdrawReasons, LockIdentifier, Get,
OnUnbalanced, BalanceStatus, schedule::{Named as ScheduleNamed, DispatchTime}, EnsureOrigin
},
dispatch::DispatchResultWithPostInfo,
@@ -1278,7 +1278,7 @@ impl<T: Trait> Module<T> {
DEMOCRACY_ID,
who,
vote.balance(),
WithdrawReason::Transfer.into()
WithdrawReasons::TRANSFER
);
ReferendumInfoOf::<T>::insert(ref_index, ReferendumInfo::Ongoing(status));
Ok(())
@@ -1410,7 +1410,7 @@ impl<T: Trait> Module<T> {
DEMOCRACY_ID,
&who,
balance,
WithdrawReason::Transfer.into()
WithdrawReasons::TRANSFER
);
Ok(votes)
})?;
@@ -1461,7 +1461,7 @@ impl<T: Trait> Module<T> {
if lock_needed.is_zero() {
T::Currency::remove_lock(DEMOCRACY_ID, who);
} else {
T::Currency::set_lock(DEMOCRACY_ID, who, lock_needed, WithdrawReason::Transfer.into());
T::Currency::set_lock(DEMOCRACY_ID, who, lock_needed, WithdrawReasons::TRANSFER);
}
}
@@ -92,7 +92,7 @@ use frame_support::{
traits::{
BalanceStatus, ChangeMembers, Contains, ContainsLengthBound, Currency, CurrencyToVote, Get,
InitializeMembers, LockIdentifier, LockableCurrency, OnUnbalanced, ReservableCurrency,
WithdrawReason, WithdrawReasons,
WithdrawReasons,
},
weights::Weight,
};
@@ -365,7 +365,7 @@ decl_module! {
T::ModuleId::get(),
&who,
locked_balance,
WithdrawReasons::except(WithdrawReason::TransactionPayment),
WithdrawReasons::except(WithdrawReasons::TRANSACTION_PAYMENT),
);
Voting::<T>::insert(&who, (locked_balance, votes));
+2 -2
View File
@@ -41,7 +41,7 @@ use frame_support::{
weights::{Weight, DispatchClass},
traits::{
Currency, ExistenceRequirement, Get, LockableCurrency, LockIdentifier, BalanceStatus,
OnUnbalanced, ReservableCurrency, WithdrawReason, WithdrawReasons, ChangeMembers,
OnUnbalanced, ReservableCurrency, WithdrawReasons, ChangeMembers,
}
};
use codec::{Encode, Decode};
@@ -871,7 +871,7 @@ impl<T: Trait> Module<T> {
let imbalance = T::Currency::withdraw(
&who,
T::VotingFee::get(),
WithdrawReason::Fee.into(),
WithdrawReasons::FEE,
ExistenceRequirement::KeepAlive,
)?;
T::BadVoterIndex::on_unbalanced(imbalance);
+3 -3
View File
@@ -488,7 +488,7 @@ mod tests {
use frame_support::{
parameter_types,
weights::{Weight, RuntimeDbWeight, IdentityFee, WeightToFeePolynomial},
traits::{Currency, LockIdentifier, LockableCurrency, WithdrawReasons, WithdrawReason},
traits::{Currency, LockIdentifier, LockableCurrency, WithdrawReasons},
};
use frame_system::{Call as SystemCall, ChainContext, LastRuntimeUpgradeInfo};
use pallet_balances::Call as BalancesCall;
@@ -950,7 +950,7 @@ mod tests {
Digest::default(),
));
if lock == WithdrawReasons::except(WithdrawReason::TransactionPayment) {
if lock == WithdrawReasons::except(WithdrawReasons::TRANSACTION_PAYMENT) {
assert!(Executive::apply_extrinsic(xt).unwrap().is_ok());
// tx fee has been deducted.
assert_eq!(<pallet_balances::Module<Runtime>>::total_balance(&1), 111 - fee);
@@ -965,7 +965,7 @@ mod tests {
};
execute_with_lock(WithdrawReasons::all());
execute_with_lock(WithdrawReasons::except(WithdrawReason::TransactionPayment));
execute_with_lock(WithdrawReasons::except(WithdrawReasons::TRANSACTION_PAYMENT));
}
#[test]
+1 -2
View File
@@ -28,7 +28,7 @@ frame-support-procedural = { version = "2.0.0", default-features = false, path =
paste = "0.1.6"
once_cell = { version = "1", default-features = false, optional = true }
sp-state-machine = { version = "0.8.0", optional = true, path = "../../primitives/state-machine" }
bitmask = { version = "0.5.0", default-features = false }
bitflags = "1.2"
impl-trait-for-tuples = "0.1.3"
smallvec = "1.4.1"
@@ -43,7 +43,6 @@ sp-api = { version = "2.0.0", default-features = false, path = "../../primitives
default = ["std"]
std = [
"once_cell",
"bitmask/std",
"serde",
"sp-io/std",
"codec/std",
-3
View File
@@ -22,9 +22,6 @@
/// Export ourself as `frame_support` to make tests happy.
extern crate self as frame_support;
#[macro_use]
extern crate bitmask;
#[doc(hidden)]
pub use sp_tracing;
+27 -30
View File
@@ -33,6 +33,7 @@ use sp_runtime::{
use crate::dispatch::Parameter;
use crate::storage::StorageMap;
use crate::weights::Weight;
use bitflags::bitflags;
use impl_trait_for_tuples::impl_for_tuples;
/// Re-expected for the macro.
@@ -1184,24 +1185,39 @@ pub trait VestingSchedule<AccountId> {
fn remove_vesting_schedule(who: &AccountId);
}
bitmask! {
bitflags! {
/// Reasons for moving funds out of an account.
#[derive(Encode, Decode)]
pub mask WithdrawReasons: i8 where
/// Reason for moving funds out of an account.
#[derive(Encode, Decode)]
flags WithdrawReason {
pub struct WithdrawReasons: i8 {
/// In order to pay for (system) transaction costs.
TransactionPayment = 0b00000001,
const TRANSACTION_PAYMENT = 0b00000001;
/// In order to transfer ownership.
Transfer = 0b00000010,
const TRANSFER = 0b00000010;
/// In order to reserve some funds for a later return or repatriation.
Reserve = 0b00000100,
const RESERVE = 0b00000100;
/// In order to pay some other (higher-level) fees.
Fee = 0b00001000,
const FEE = 0b00001000;
/// In order to tip a validator for transaction inclusion.
Tip = 0b00010000,
const TIP = 0b00010000;
}
}
impl WithdrawReasons {
/// Choose all variants except for `one`.
///
/// ```rust
/// # use frame_support::traits::WithdrawReasons;
/// # fn main() {
/// assert_eq!(
/// WithdrawReasons::FEE | WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE | WithdrawReasons::TIP,
/// WithdrawReasons::except(WithdrawReasons::TRANSACTION_PAYMENT),
/// );
/// # }
/// ```
pub fn except(one: WithdrawReasons) -> WithdrawReasons {
let mut flags = Self::all();
flags.toggle(one);
flags
}
}
@@ -1217,25 +1233,6 @@ pub trait UnixTime {
fn now() -> core::time::Duration;
}
impl WithdrawReasons {
/// Choose all variants except for `one`.
///
/// ```rust
/// # use frame_support::traits::{WithdrawReason, WithdrawReasons};
/// # fn main() {
/// assert_eq!(
/// WithdrawReason::Fee | WithdrawReason::Transfer | WithdrawReason::Reserve | WithdrawReason::Tip,
/// WithdrawReasons::except(WithdrawReason::TransactionPayment),
/// );
/// # }
/// ```
pub fn except(one: WithdrawReason) -> WithdrawReasons {
let mut mask = Self::all();
mask.toggle(one);
mask
}
}
/// Trait for type that can handle incremental changes to a set of account IDs.
pub trait ChangeMembers<AccountId: Clone + Ord> {
/// A number of members `incoming` just joined the set and replaced some `outgoing` ones. The
@@ -36,7 +36,7 @@ use sp_std::prelude::*;
use codec::{Encode, Decode};
use frame_support::{
decl_storage, decl_module,
traits::{Currency, Get, OnUnbalanced, ExistenceRequirement, WithdrawReason, Imbalance},
traits::{Currency, Get, OnUnbalanced, ExistenceRequirement, WithdrawReasons, Imbalance},
weights::{
Weight, DispatchInfo, PostDispatchInfo, GetDispatchInfo, Pays, WeightToFeePolynomial,
WeightToFeeCoefficient,
@@ -457,9 +457,9 @@ impl<T: Trait + Send + Sync> ChargeTransactionPayment<T> where
who,
fee,
if tip.is_zero() {
WithdrawReason::TransactionPayment.into()
WithdrawReasons::TRANSACTION_PAYMENT
} else {
WithdrawReason::TransactionPayment | WithdrawReason::Tip
WithdrawReasons::TRANSACTION_PAYMENT | WithdrawReasons::TIP
},
ExistenceRequirement::KeepAlive,
) {
+2 -2
View File
@@ -142,7 +142,7 @@ use sp_std::prelude::*;
use frame_support::{decl_module, decl_storage, decl_event, ensure, print, decl_error, Parameter};
use frame_support::traits::{
Currency, Get, Imbalance, OnUnbalanced, ExistenceRequirement::{KeepAlive, AllowDeath},
ReservableCurrency, WithdrawReason
ReservableCurrency, WithdrawReasons
};
use sp_runtime::{Permill, ModuleId, Percent, RuntimeDebug, DispatchResult, traits::{
Zero, StaticLookup, AccountIdConversion, Saturating, Hash, BadOrigin
@@ -1346,7 +1346,7 @@ impl<T: Trait<I>, I: Instance> Module<T, I> {
if let Err(problem) = T::Currency::settle(
&account_id,
imbalance,
WithdrawReason::Transfer.into(),
WithdrawReasons::TRANSFER,
KeepAlive
) {
print("Inconsistent state - couldn't settle imbalance for funds spent by treasury");
+1 -1
View File
@@ -35,7 +35,7 @@ fn add_locks<T: Trait>(who: &T::AccountId, n: u8) {
for id in 0..n {
let lock_id = [id; 8];
let locked = 100u32;
let reasons = WithdrawReason::Transfer | WithdrawReason::Reserve;
let reasons = WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE;
T::Currency::set_lock(lock_id, who, locked.into(), reasons);
}
}
+3 -3
View File
@@ -58,7 +58,7 @@ use sp_runtime::{DispatchResult, RuntimeDebug, traits::{
}};
use frame_support::{decl_module, decl_event, decl_storage, decl_error, ensure};
use frame_support::traits::{
Currency, LockableCurrency, VestingSchedule, WithdrawReason, LockIdentifier,
Currency, LockableCurrency, VestingSchedule, WithdrawReasons, LockIdentifier,
ExistenceRequirement, Get,
};
use frame_system::{ensure_signed, ensure_root};
@@ -148,7 +148,7 @@ decl_storage! {
per_block: per_block,
starting_block: begin
});
let reasons = WithdrawReason::Transfer | WithdrawReason::Reserve;
let reasons = WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE;
T::Currency::set_lock(VESTING_ID, who, locked, reasons);
}
})
@@ -322,7 +322,7 @@ impl<T: Trait> Module<T> {
Vesting::<T>::remove(&who);
Self::deposit_event(RawEvent::VestingCompleted(who));
} else {
let reasons = WithdrawReason::Transfer | WithdrawReason::Reserve;
let reasons = WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE;
T::Currency::set_lock(VESTING_ID, &who, locked_now, reasons);
Self::deposit_event(RawEvent::VestingUpdated(who, locked_now));
}