mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-13 21:01:05 +00:00
Aggregate all liquidity restrictions in a single place (#1921)
* Clean up session key rotation * Fix build * Bump version * Introduce feature to balances. * Move staking locking logic over to central point * ^^^ rest * First part of assimilation * More assimilation * More assimilation * Fix most tests * Fix build * Move Balances to new locking system * :q! * Bump runtime version * Build runtime * Convenience function * Test fix. * Whitespace * Improve type legibility. * Fix comment. * More tests. * More tests. * Bump version * Caps * Whitespace * Whitespace * Remove unneeded function.
This commit is contained in:
@@ -6,7 +6,7 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
hex-literal = "0.1.0"
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
parity-codec = { version = "3.1", default-features = false }
|
||||
# Needed for various traits. In our case, `OnFinalise`.
|
||||
primitives = { package = "sr-primitives", path = "../../core/sr-primitives", default-features = false }
|
||||
@@ -23,7 +23,7 @@ runtime_io = { package = "sr-io", path = "../../core/sr-io" }
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"parity-codec/std",
|
||||
"primitives/std",
|
||||
"srml-support/std",
|
||||
|
||||
@@ -7,7 +7,8 @@ edition = "2018"
|
||||
[dependencies]
|
||||
hex-literal = "0.1.0"
|
||||
parity-codec = { version = "3.1", default-features = false, features = ["derive"] }
|
||||
serde = { version = "1.0", default-features = false }
|
||||
parity-codec-derive = { version = "3.1", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
inherents = { package = "substrate-inherents", path = "../../core/inherents", default-features = false }
|
||||
rstd = { package = "sr-std", path = "../../core/sr-std", default-features = false }
|
||||
primitives = { package = "sr-primitives", path = "../../core/sr-primitives", default-features = false }
|
||||
@@ -27,7 +28,7 @@ consensus = { package = "srml-consensus", path = "../consensus" }
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"parity-codec/std",
|
||||
"rstd/std",
|
||||
"srml-support/std",
|
||||
|
||||
@@ -6,7 +6,7 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
hex-literal = "0.1.0"
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
safe-mix = { version = "1.0", default-features = false}
|
||||
parity-codec = { version = "3.1", default-features = false, features = ["derive"] }
|
||||
substrate-keyring = { path = "../../core/keyring", optional = true }
|
||||
@@ -22,7 +22,7 @@ substrate-primitives = { path = "../../core/primitives" }
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"safe-mix/std",
|
||||
"substrate-keyring",
|
||||
"parity-codec/std",
|
||||
|
||||
@@ -29,7 +29,8 @@ use rstd::{cmp, result};
|
||||
use parity_codec::{Codec, Encode, Decode};
|
||||
use srml_support::{StorageValue, StorageMap, Parameter, decl_event, decl_storage, decl_module, ensure};
|
||||
use srml_support::traits::{
|
||||
UpdateBalanceOutcome, Currency, EnsureAccountLiquid, OnFreeBalanceZero, TransferAsset, WithdrawReason, ArithmeticType
|
||||
UpdateBalanceOutcome, Currency, OnFreeBalanceZero, TransferAsset,
|
||||
WithdrawReason, WithdrawReasons, ArithmeticType, LockIdentifier, LockableCurrency
|
||||
};
|
||||
use srml_support::dispatch::Result;
|
||||
use primitives::traits::{
|
||||
@@ -53,9 +54,6 @@ pub trait Trait: system::Trait {
|
||||
/// Handler for when a new account is created.
|
||||
type OnNewAccount: OnNewAccount<Self::AccountId>;
|
||||
|
||||
/// A function that returns true iff a given account can transfer its funds to another account.
|
||||
type EnsureAccountLiquid: EnsureAccountLiquid<Self::AccountId, Self::Balance>;
|
||||
|
||||
/// The overarching event type.
|
||||
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
|
||||
}
|
||||
@@ -99,6 +97,15 @@ impl<Balance: SimpleArithmetic + Copy + As<u64>> VestingSchedule<Balance> {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Encode, Decode, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "std", derive(Debug))]
|
||||
pub struct BalanceLock<Balance, BlockNumber> {
|
||||
pub id: LockIdentifier,
|
||||
pub amount: Balance,
|
||||
pub until: BlockNumber,
|
||||
pub reasons: WithdrawReasons,
|
||||
}
|
||||
|
||||
decl_storage! {
|
||||
trait Store for Module<T: Trait> as Balances {
|
||||
/// The total amount of stake on the system.
|
||||
@@ -160,6 +167,9 @@ decl_storage! {
|
||||
/// `system::AccountNonce` is also deleted if `FreeBalance` is also zero (it also gets
|
||||
/// collapsed to zero if it ever becomes less than `ExistentialDeposit`.
|
||||
pub ReservedBalance get(reserved_balance): map T::AccountId => T::Balance;
|
||||
|
||||
/// Any liquidity locks on some account balances.
|
||||
pub Locks get(locks): map T::AccountId => Vec<BalanceLock<T::Balance, T::BlockNumber>>;
|
||||
}
|
||||
add_extra_genesis {
|
||||
config(balances): Vec<(T::AccountId, T::Balance)>;
|
||||
@@ -285,16 +295,14 @@ impl<T: Trait> Module<T> {
|
||||
None => return Err("got overflow after adding a fee to value"),
|
||||
};
|
||||
|
||||
let vesting_balance = Self::vesting_balance(transactor);
|
||||
let new_from_balance = match from_balance.checked_sub(&liability) {
|
||||
None => return Err("balance too low to send value"),
|
||||
Some(b) if b < vesting_balance => return Err("vesting balance too high to send value"),
|
||||
Some(b) => b,
|
||||
};
|
||||
if would_create && value < Self::existential_deposit() {
|
||||
return Err("value too low to create account");
|
||||
}
|
||||
T::EnsureAccountLiquid::ensure_account_can_withdraw(transactor, value, WithdrawReason::Transfer)?;
|
||||
Self::ensure_account_can_withdraw(transactor, value, WithdrawReason::Transfer, new_from_balance)?;
|
||||
|
||||
// NOTE: total stake being stored in the same type means that this could never overflow
|
||||
// but better to be safe than sorry.
|
||||
@@ -313,7 +321,6 @@ impl<T: Trait> Module<T> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
/// Register a new account (with existential balance).
|
||||
fn new_account(who: &T::AccountId, balance: T::Balance) {
|
||||
T::OnNewAccount::on_new_account(&who);
|
||||
@@ -329,6 +336,7 @@ impl<T: Trait> Module<T> {
|
||||
fn on_free_too_low(who: &T::AccountId) {
|
||||
Self::decrease_total_stake_by(Self::free_balance(who));
|
||||
<FreeBalance<T>>::remove(who);
|
||||
<Locks<T>>::remove(who);
|
||||
|
||||
T::OnFreeBalanceZero::on_free_balance_zero(who);
|
||||
|
||||
@@ -359,6 +367,35 @@ impl<T: Trait> Module<T> {
|
||||
<TotalIssuance<T>>::put(v);
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `Ok` iff the account is able to make a withdrawal of the given amount
|
||||
/// for the given reason.
|
||||
///
|
||||
/// `Err(...)` with the reason why not otherwise.
|
||||
pub fn ensure_account_can_withdraw(
|
||||
who: &T::AccountId,
|
||||
_amount: T::Balance,
|
||||
reason: WithdrawReason,
|
||||
new_balance: T::Balance,
|
||||
) -> Result {
|
||||
match reason {
|
||||
WithdrawReason::Reserve | WithdrawReason::Transfer if Self::vesting_balance(who) > new_balance =>
|
||||
return Err("vesting balance too high to send value"),
|
||||
_ => {}
|
||||
}
|
||||
let locks = Self::locks(who);
|
||||
if locks.is_empty() {
|
||||
return Ok(())
|
||||
}
|
||||
let now = <system::Module<T>>::block_number();
|
||||
if Self::locks(who).into_iter()
|
||||
.all(|l| now >= l.until || new_balance >= l.amount || !l.reasons.contains(reason))
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err("account liquidity restrictions prevent withdrawal")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Trait> Currency<T::AccountId> for Module<T>
|
||||
@@ -376,11 +413,11 @@ where
|
||||
}
|
||||
|
||||
fn can_reserve(who: &T::AccountId, value: Self::Balance) -> bool {
|
||||
if T::EnsureAccountLiquid::ensure_account_can_withdraw(who, value, WithdrawReason::Reserve).is_ok() {
|
||||
Self::free_balance(who) >= value
|
||||
} else {
|
||||
false
|
||||
}
|
||||
Self::free_balance(who)
|
||||
.checked_sub(&value)
|
||||
.map_or(false, |new_balance|
|
||||
Self::ensure_account_can_withdraw(who, value, WithdrawReason::Reserve, new_balance).is_ok()
|
||||
)
|
||||
}
|
||||
|
||||
fn total_issuance() -> Self::Balance {
|
||||
@@ -429,9 +466,10 @@ where
|
||||
if b < value {
|
||||
return Err("not enough free funds")
|
||||
}
|
||||
T::EnsureAccountLiquid::ensure_account_can_withdraw(who, value, WithdrawReason::Reserve)?;
|
||||
let new_balance = b - value;
|
||||
Self::ensure_account_can_withdraw(who, value, WithdrawReason::Reserve, new_balance)?;
|
||||
Self::set_reserved_balance(who, Self::reserved_balance(who) + value);
|
||||
Self::set_free_balance(who, b - value);
|
||||
Self::set_free_balance(who, new_balance);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -479,6 +517,80 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Trait> LockableCurrency<T::AccountId> for Module<T>
|
||||
where
|
||||
T::Balance: MaybeSerializeDebug
|
||||
{
|
||||
type Moment = T::BlockNumber;
|
||||
|
||||
fn set_lock(
|
||||
id: LockIdentifier,
|
||||
who: &T::AccountId,
|
||||
amount: T::Balance,
|
||||
until: T::BlockNumber,
|
||||
reasons: WithdrawReasons,
|
||||
) {
|
||||
let now = <system::Module<T>>::block_number();
|
||||
let mut new_lock = Some(BalanceLock { id, amount, until, reasons });
|
||||
let mut locks = Self::locks(who).into_iter().filter_map(|l|
|
||||
if l.id == id {
|
||||
new_lock.take()
|
||||
} else if l.until > now {
|
||||
Some(l)
|
||||
} else {
|
||||
None
|
||||
}).collect::<Vec<_>>();
|
||||
if let Some(lock) = new_lock {
|
||||
locks.push(lock)
|
||||
}
|
||||
<Locks<T>>::insert(who, locks);
|
||||
}
|
||||
|
||||
fn extend_lock(
|
||||
id: LockIdentifier,
|
||||
who: &T::AccountId,
|
||||
amount: T::Balance,
|
||||
until: T::BlockNumber,
|
||||
reasons: WithdrawReasons,
|
||||
) {
|
||||
let now = <system::Module<T>>::block_number();
|
||||
let mut new_lock = Some(BalanceLock { id, amount, until, reasons });
|
||||
let mut locks = Self::locks(who).into_iter().filter_map(|l|
|
||||
if l.id == id {
|
||||
new_lock.take().map(|nl| {
|
||||
BalanceLock {
|
||||
id: l.id,
|
||||
amount: l.amount.max(nl.amount),
|
||||
until: l.until.max(nl.until),
|
||||
reasons: l.reasons | nl.reasons,
|
||||
}
|
||||
})
|
||||
} else if l.until > now {
|
||||
Some(l)
|
||||
} else {
|
||||
None
|
||||
}).collect::<Vec<_>>();
|
||||
if let Some(lock) = new_lock {
|
||||
locks.push(lock)
|
||||
}
|
||||
<Locks<T>>::insert(who, locks);
|
||||
}
|
||||
|
||||
fn remove_lock(
|
||||
id: LockIdentifier,
|
||||
who: &T::AccountId,
|
||||
) {
|
||||
let now = <system::Module<T>>::block_number();
|
||||
let locks = Self::locks(who).into_iter().filter_map(|l|
|
||||
if l.until > now && l.id != id {
|
||||
Some(l)
|
||||
} else {
|
||||
None
|
||||
}).collect::<Vec<_>>();
|
||||
<Locks<T>>::insert(who, locks);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Trait> TransferAsset<T::AccountId> for Module<T> {
|
||||
type Amount = T::Balance;
|
||||
|
||||
@@ -487,10 +599,11 @@ impl<T: Trait> TransferAsset<T::AccountId> for Module<T> {
|
||||
}
|
||||
|
||||
fn withdraw(who: &T::AccountId, value: T::Balance, reason: WithdrawReason) -> Result {
|
||||
T::EnsureAccountLiquid::ensure_account_can_withdraw(who, value, reason)?;
|
||||
let b = Self::free_balance(who);
|
||||
ensure!(b >= value, "account has too few funds");
|
||||
Self::set_free_balance(who, b - value);
|
||||
let new_balance = b - value;
|
||||
Self::ensure_account_can_withdraw(who, value, reason, new_balance)?;
|
||||
Self::set_free_balance(who, new_balance);
|
||||
Self::decrease_total_stake_by(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -49,7 +49,6 @@ impl Trait for Runtime {
|
||||
type Balance = u64;
|
||||
type OnFreeBalanceZero = ();
|
||||
type OnNewAccount = ();
|
||||
type EnsureAccountLiquid = ();
|
||||
type Event = ();
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,136 @@
|
||||
use super::*;
|
||||
use mock::{Balances, ExtBuilder, Runtime, System};
|
||||
use runtime_io::with_externalities;
|
||||
use srml_support::{assert_noop, assert_ok, assert_err};
|
||||
use srml_support::{
|
||||
assert_noop, assert_ok, assert_err,
|
||||
traits::{LockableCurrency, LockIdentifier, WithdrawReason, WithdrawReasons, Currency, TransferAsset}
|
||||
};
|
||||
|
||||
const ID_1: LockIdentifier = *b"1 ";
|
||||
const ID_2: LockIdentifier = *b"2 ";
|
||||
const ID_3: LockIdentifier = *b"3 ";
|
||||
|
||||
#[test]
|
||||
fn basic_locking_should_work() {
|
||||
with_externalities(&mut ExtBuilder::default().monied(true).build(), || {
|
||||
assert_eq!(Balances::free_balance(&1), 10);
|
||||
Balances::set_lock(ID_1, &1, 9, u64::max_value(), WithdrawReasons::all());
|
||||
assert_noop!(<Balances as TransferAsset<_>>::transfer(&1, &2, 5), "account liquidity restrictions prevent withdrawal");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_locking_should_work() {
|
||||
with_externalities(&mut ExtBuilder::default().monied(true).build(), || {
|
||||
Balances::set_lock(ID_1, &1, 5, u64::max_value(), WithdrawReasons::all());
|
||||
assert_ok!(<Balances as TransferAsset<_>>::transfer(&1, &2, 1));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_removal_should_work() {
|
||||
with_externalities(&mut ExtBuilder::default().monied(true).build(), || {
|
||||
Balances::set_lock(ID_1, &1, u64::max_value(), u64::max_value(), WithdrawReasons::all());
|
||||
Balances::remove_lock(ID_1, &1);
|
||||
assert_ok!(<Balances as TransferAsset<_>>::transfer(&1, &2, 1));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_replacement_should_work() {
|
||||
with_externalities(&mut ExtBuilder::default().monied(true).build(), || {
|
||||
Balances::set_lock(ID_1, &1, u64::max_value(), u64::max_value(), WithdrawReasons::all());
|
||||
Balances::set_lock(ID_1, &1, 5, u64::max_value(), WithdrawReasons::all());
|
||||
assert_ok!(<Balances as TransferAsset<_>>::transfer(&1, &2, 1));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_locking_should_work() {
|
||||
with_externalities(&mut ExtBuilder::default().monied(true).build(), || {
|
||||
Balances::set_lock(ID_1, &1, 5, u64::max_value(), WithdrawReasons::all());
|
||||
Balances::set_lock(ID_2, &1, 5, u64::max_value(), WithdrawReasons::all());
|
||||
assert_ok!(<Balances as TransferAsset<_>>::transfer(&1, &2, 1));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combination_locking_should_work() {
|
||||
with_externalities(&mut ExtBuilder::default().monied(true).build(), || {
|
||||
Balances::set_lock(ID_1, &1, u64::max_value(), 0, WithdrawReasons::none());
|
||||
Balances::set_lock(ID_2, &1, 0, u64::max_value(), WithdrawReasons::none());
|
||||
Balances::set_lock(ID_3, &1, 0, 0, WithdrawReasons::all());
|
||||
assert_ok!(<Balances as TransferAsset<_>>::transfer(&1, &2, 1));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_value_extension_should_work() {
|
||||
with_externalities(&mut ExtBuilder::default().monied(true).build(), || {
|
||||
Balances::set_lock(ID_1, &1, 5, u64::max_value(), WithdrawReasons::all());
|
||||
assert_noop!(<Balances as TransferAsset<_>>::transfer(&1, &2, 6), "account liquidity restrictions prevent withdrawal");
|
||||
Balances::extend_lock(ID_1, &1, 2, u64::max_value(), WithdrawReasons::all());
|
||||
assert_noop!(<Balances as TransferAsset<_>>::transfer(&1, &2, 6), "account liquidity restrictions prevent withdrawal");
|
||||
Balances::extend_lock(ID_1, &1, 8, u64::max_value(), WithdrawReasons::all());
|
||||
assert_noop!(<Balances as TransferAsset<_>>::transfer(&1, &2, 3), "account liquidity restrictions prevent withdrawal");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_reasons_should_work() {
|
||||
with_externalities(&mut ExtBuilder::default().monied(true).build(), || {
|
||||
Balances::set_lock(ID_1, &1, 10, u64::max_value(), WithdrawReason::Transfer.into());
|
||||
assert_noop!(<Balances as TransferAsset<_>>::transfer(&1, &2, 1), "account liquidity restrictions prevent withdrawal");
|
||||
assert_ok!(<Balances as Currency<_>>::reserve(&1, 1));
|
||||
assert_ok!(<Balances as TransferAsset<_>>::withdraw(&1, 1, WithdrawReason::TransactionPayment));
|
||||
|
||||
Balances::set_lock(ID_1, &1, 10, u64::max_value(), WithdrawReason::Reserve.into());
|
||||
assert_ok!(<Balances as TransferAsset<_>>::transfer(&1, &2, 1));
|
||||
assert_noop!(<Balances as Currency<_>>::reserve(&1, 1), "account liquidity restrictions prevent withdrawal");
|
||||
assert_ok!(<Balances as TransferAsset<_>>::withdraw(&1, 1, WithdrawReason::TransactionPayment));
|
||||
|
||||
Balances::set_lock(ID_1, &1, 10, u64::max_value(), WithdrawReason::TransactionPayment.into());
|
||||
assert_ok!(<Balances as TransferAsset<_>>::transfer(&1, &2, 1));
|
||||
assert_ok!(<Balances as Currency<_>>::reserve(&1, 1));
|
||||
assert_noop!(<Balances as TransferAsset<_>>::withdraw(&1, 1, WithdrawReason::TransactionPayment), "account liquidity restrictions prevent withdrawal");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_block_number_should_work() {
|
||||
with_externalities(&mut ExtBuilder::default().monied(true).build(), || {
|
||||
Balances::set_lock(ID_1, &1, 10, 2, WithdrawReasons::all());
|
||||
assert_noop!(<Balances as TransferAsset<_>>::transfer(&1, &2, 1), "account liquidity restrictions prevent withdrawal");
|
||||
|
||||
System::set_block_number(2);
|
||||
assert_ok!(<Balances as TransferAsset<_>>::transfer(&1, &2, 1));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_block_number_extension_should_work() {
|
||||
with_externalities(&mut ExtBuilder::default().monied(true).build(), || {
|
||||
Balances::set_lock(ID_1, &1, 10, 2, WithdrawReasons::all());
|
||||
assert_noop!(<Balances as TransferAsset<_>>::transfer(&1, &2, 6), "account liquidity restrictions prevent withdrawal");
|
||||
Balances::extend_lock(ID_1, &1, 10, 1, WithdrawReasons::all());
|
||||
assert_noop!(<Balances as TransferAsset<_>>::transfer(&1, &2, 6), "account liquidity restrictions prevent withdrawal");
|
||||
System::set_block_number(2);
|
||||
Balances::extend_lock(ID_1, &1, 10, 8, WithdrawReasons::all());
|
||||
assert_noop!(<Balances as TransferAsset<_>>::transfer(&1, &2, 3), "account liquidity restrictions prevent withdrawal");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_reasons_extension_should_work() {
|
||||
with_externalities(&mut ExtBuilder::default().monied(true).build(), || {
|
||||
Balances::set_lock(ID_1, &1, 10, 10, WithdrawReason::Transfer.into());
|
||||
assert_noop!(<Balances as TransferAsset<_>>::transfer(&1, &2, 6), "account liquidity restrictions prevent withdrawal");
|
||||
Balances::extend_lock(ID_1, &1, 10, 10, WithdrawReasons::none());
|
||||
assert_noop!(<Balances as TransferAsset<_>>::transfer(&1, &2, 6), "account liquidity restrictions prevent withdrawal");
|
||||
Balances::extend_lock(ID_1, &1, 10, 10, WithdrawReason::Reserve.into());
|
||||
assert_noop!(<Balances as TransferAsset<_>>::transfer(&1, &2, 6), "account liquidity restrictions prevent withdrawal");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_indexing_on_new_accounts_should_not_work2() {
|
||||
@@ -464,4 +593,4 @@ fn extra_balance_should_transfer() {
|
||||
assert_ok!(Balances::transfer(Some(1).into(), 2, 256 * 5)); // Account 1 can send extra units gained
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
hex-literal = "0.1.0"
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
serde_derive = { version = "1.0", optional = true }
|
||||
parity-codec = { version = "3.1", default-features = false, features = ["derive"] }
|
||||
substrate-primitives = { path = "../../core/primitives", default-features = false }
|
||||
@@ -22,7 +22,7 @@ runtime_io = { package = "sr-io", path = "../../core/sr-io" }
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"parity-codec/std",
|
||||
"substrate-primitives/std",
|
||||
|
||||
@@ -5,7 +5,7 @@ authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
serde_derive = { version = "1.0", optional = true }
|
||||
pwasm-utils = { version = "0.6.1", default-features = false }
|
||||
parity-codec = { version = "3.1", default-features = false, features = ["derive"] }
|
||||
@@ -30,7 +30,7 @@ consensus = { package = "srml-consensus", path = "../consensus" }
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"parity-codec/std",
|
||||
"substrate-primitives/std",
|
||||
|
||||
@@ -20,8 +20,8 @@ use crate::gas::{GasMeter, Token, approx_gas_for_balance};
|
||||
|
||||
use rstd::prelude::*;
|
||||
use runtime_primitives::traits::{CheckedAdd, CheckedSub, Zero};
|
||||
use srml_support::traits::WithdrawReason;
|
||||
use timestamp;
|
||||
use srml_support::traits::EnsureAccountLiquid;
|
||||
|
||||
pub type BalanceOf<T> = <T as balances::Trait>::Balance;
|
||||
pub type AccountIdOf<T> = <T as system::Trait>::AccountId;
|
||||
@@ -520,7 +520,7 @@ fn transfer<'a, T: Trait, V: Vm<T>, L: Loader<T>>(
|
||||
if would_create && value < ctx.config.existential_deposit {
|
||||
return Err("value too low to create account");
|
||||
}
|
||||
<T as balances::Trait>::EnsureAccountLiquid::ensure_account_liquid(transactor)?;
|
||||
<balances::Module<T>>::ensure_account_can_withdraw(transactor, value, WithdrawReason::Transfer, new_from_balance)?;
|
||||
|
||||
let new_to_balance = match to_balance.checked_add(&value) {
|
||||
Some(b) => b,
|
||||
|
||||
@@ -77,7 +77,6 @@ impl balances::Trait for Test {
|
||||
type Balance = u64;
|
||||
type OnFreeBalanceZero = Contract;
|
||||
type OnNewAccount = ();
|
||||
type EnsureAccountLiquid = ();
|
||||
type Event = MetaEvent;
|
||||
}
|
||||
impl timestamp::Trait for Test {
|
||||
|
||||
@@ -5,7 +5,7 @@ authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
safe-mix = { version = "1.0", default-features = false}
|
||||
parity-codec = { version = "3.1", default-features = false }
|
||||
parity-codec-derive = { version = "3.1", default-features = false }
|
||||
@@ -29,6 +29,7 @@ std = [
|
||||
"parity-codec-derive/std",
|
||||
"substrate-primitives/std",
|
||||
"rstd/std",
|
||||
"serde",
|
||||
"runtime_io/std",
|
||||
"srml-support/std",
|
||||
"primitives/std",
|
||||
|
||||
@@ -76,7 +76,6 @@ mod tests {
|
||||
type Balance = u64;
|
||||
type OnFreeBalanceZero = ();
|
||||
type OnNewAccount = ();
|
||||
type EnsureAccountLiquid = ();
|
||||
type Event = Event;
|
||||
}
|
||||
impl democracy::Trait for Test {
|
||||
|
||||
@@ -6,7 +6,7 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
hex-literal = "0.1.0"
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
serde_derive = { version = "1.0", optional = true }
|
||||
safe-mix = { version = "1.0", default-features = false}
|
||||
parity-codec = { version = "3.1", default-features = false, features = ["derive"] }
|
||||
@@ -23,7 +23,7 @@ balances = { package = "srml-balances", path = "../balances" }
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"safe-mix/std",
|
||||
"parity-codec/std",
|
||||
|
||||
@@ -20,17 +20,19 @@
|
||||
|
||||
use rstd::prelude::*;
|
||||
use rstd::result;
|
||||
use primitives::traits::{Zero, As};
|
||||
use primitives::traits::{Zero, As, Bounded};
|
||||
use parity_codec::{Encode, Decode};
|
||||
use srml_support::{StorageValue, StorageMap, Parameter, Dispatchable, IsSubType};
|
||||
use srml_support::{decl_module, decl_storage, decl_event, ensure};
|
||||
use srml_support::traits::{Currency, OnFreeBalanceZero, EnsureAccountLiquid, WithdrawReason, ArithmeticType};
|
||||
use srml_support::traits::{Currency, LockableCurrency, WithdrawReason, ArithmeticType, LockIdentifier};
|
||||
use srml_support::dispatch::Result;
|
||||
use system::ensure_signed;
|
||||
|
||||
mod vote_threshold;
|
||||
pub use vote_threshold::{Approved, VoteThreshold};
|
||||
|
||||
const DEMOCRACY_ID: LockIdentifier = *b"democrac";
|
||||
|
||||
/// A proposal index.
|
||||
pub type PropIndex = u32;
|
||||
/// A referendum index.
|
||||
@@ -68,7 +70,7 @@ impl Vote {
|
||||
type BalanceOf<T> = <<T as Trait>::Currency as ArithmeticType>::Type;
|
||||
|
||||
pub trait Trait: system::Trait + Sized {
|
||||
type Currency: ArithmeticType + Currency<<Self as system::Trait>::AccountId, Balance=BalanceOf<Self>>;
|
||||
type Currency: ArithmeticType + LockableCurrency<<Self as system::Trait>::AccountId, Moment=Self::BlockNumber, Balance=BalanceOf<Self>>;
|
||||
|
||||
type Proposal: Parameter + Dispatchable<Origin=Self::Origin> + IsSubType<Module<Self>>;
|
||||
|
||||
@@ -208,9 +210,6 @@ decl_storage! {
|
||||
/// Queue of successful referenda to be dispatched.
|
||||
pub DispatchQueue get(dispatch_queue): map T::BlockNumber => Vec<Option<(T::Proposal, ReferendumIndex)>>;
|
||||
|
||||
/// The block at which the `who`'s funds become liquid.
|
||||
pub Bondage get(bondage): map T::AccountId => T::BlockNumber;
|
||||
|
||||
/// Get the voters for the current proposal.
|
||||
pub VotersFor get(voters_for): map ReferendumIndex => Vec<T::AccountId>;
|
||||
|
||||
@@ -371,7 +370,7 @@ impl<T: Trait> Module<T> {
|
||||
// lock should they win...
|
||||
let locked_until = now + lock_period * T::BlockNumber::sa((vote.multiplier()) as u64);
|
||||
// ...extend their bondage until at least then.
|
||||
<Bondage<T>>::mutate(a, |b| if *b < locked_until { *b = locked_until });
|
||||
T::Currency::extend_lock(DEMOCRACY_ID, &a, Bounded::max_value(), locked_until, WithdrawReason::Transfer.into());
|
||||
}
|
||||
|
||||
Self::clear_referendum(index);
|
||||
@@ -409,35 +408,6 @@ impl<T: Trait> Module<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Trait> OnFreeBalanceZero<T::AccountId> for Module<T> {
|
||||
fn on_free_balance_zero(who: &T::AccountId) {
|
||||
<Bondage<T>>::remove(who);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Trait> EnsureAccountLiquid<T::AccountId, BalanceOf<T>> for Module<T> {
|
||||
fn ensure_account_liquid(who: &T::AccountId) -> Result {
|
||||
if Self::bondage(who) > <system::Module<T>>::block_number() {
|
||||
Err("stash accounts are not liquid")
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn ensure_account_can_withdraw(
|
||||
who: &T::AccountId,
|
||||
_value: BalanceOf<T>,
|
||||
reason: WithdrawReason,
|
||||
) -> Result {
|
||||
if reason == WithdrawReason::TransactionPayment
|
||||
|| Self::bondage(who) <= <system::Module<T>>::block_number()
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err("cannot transfer voting funds")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -447,6 +417,7 @@ mod tests {
|
||||
use primitives::BuildStorage;
|
||||
use primitives::traits::{BlakeTwo256, IdentityLookup};
|
||||
use primitives::testing::{Digest, DigestItem, Header};
|
||||
use balances::BalanceLock;
|
||||
|
||||
const AYE: Vote = Vote(-1);
|
||||
const NAY: Vote = Vote(0);
|
||||
@@ -482,7 +453,6 @@ mod tests {
|
||||
type Balance = u64;
|
||||
type OnFreeBalanceZero = ();
|
||||
type OnNewAccount = ();
|
||||
type EnsureAccountLiquid = ();
|
||||
type Event = ();
|
||||
}
|
||||
impl Trait for Test {
|
||||
@@ -790,12 +760,12 @@ mod tests {
|
||||
|
||||
assert_eq!(Democracy::end_block(System::block_number()), Ok(()));
|
||||
|
||||
assert_eq!(Democracy::bondage(1), 0);
|
||||
assert_eq!(Democracy::bondage(2), 6);
|
||||
assert_eq!(Democracy::bondage(3), 5);
|
||||
assert_eq!(Democracy::bondage(4), 4);
|
||||
assert_eq!(Democracy::bondage(5), 3);
|
||||
assert_eq!(Democracy::bondage(6), 0);
|
||||
assert_eq!(Balances::locks(1), vec![]);
|
||||
assert_eq!(Balances::locks(2), vec![BalanceLock { id: DEMOCRACY_ID, amount: u64::max_value(), until: 6, reasons: WithdrawReason::Transfer.into() }]);
|
||||
assert_eq!(Balances::locks(3), vec![BalanceLock { id: DEMOCRACY_ID, amount: u64::max_value(), until: 5, reasons: WithdrawReason::Transfer.into() }]);
|
||||
assert_eq!(Balances::locks(4), vec![BalanceLock { id: DEMOCRACY_ID, amount: u64::max_value(), until: 4, reasons: WithdrawReason::Transfer.into() }]);
|
||||
assert_eq!(Balances::locks(5), vec![BalanceLock { id: DEMOCRACY_ID, amount: u64::max_value(), until: 3, reasons: WithdrawReason::Transfer.into() }]);
|
||||
assert_eq!(Balances::locks(6), vec![]);
|
||||
|
||||
System::set_block_number(2);
|
||||
assert_eq!(Democracy::end_block(System::block_number()), Ok(()));
|
||||
|
||||
@@ -6,7 +6,7 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
hex-literal = "0.1.0"
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
parity-codec = { version = "3.1", default-features = false }
|
||||
srml-support = { path = "../support", default-features = false }
|
||||
system = { package = "srml-system", path = "../system", default-features = false }
|
||||
@@ -20,7 +20,7 @@ sr-primitives = { path = "../../core/sr-primitives" }
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"parity-codec/std",
|
||||
"sr-primitives/std",
|
||||
"srml-support/std",
|
||||
|
||||
@@ -280,7 +280,6 @@ mod tests {
|
||||
type Balance = u64;
|
||||
type OnFreeBalanceZero = ();
|
||||
type OnNewAccount = ();
|
||||
type EnsureAccountLiquid = ();
|
||||
type Event = ();
|
||||
}
|
||||
impl Trait for Test {
|
||||
|
||||
@@ -5,7 +5,7 @@ authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
parity-codec = { version = "3.1", default-features = false }
|
||||
rstd = { package = "sr-std", path = "../../core/sr-std", default-features = false }
|
||||
runtime_io = { package = "sr-io", path = "../../core/sr-io", default-features = false }
|
||||
@@ -26,7 +26,7 @@ default = ["std"]
|
||||
std = [
|
||||
"rstd/std",
|
||||
"srml-support/std",
|
||||
"serde/std",
|
||||
"serde",
|
||||
"parity-codec/std",
|
||||
"primitives/std",
|
||||
"runtime_io/std",
|
||||
|
||||
@@ -319,7 +319,6 @@ mod tests {
|
||||
type Balance = u64;
|
||||
type OnFreeBalanceZero = ();
|
||||
type OnNewAccount = ();
|
||||
type EnsureAccountLiquid = ();
|
||||
type Event = MetaEvent;
|
||||
}
|
||||
impl fees::Trait for Runtime {
|
||||
|
||||
@@ -6,7 +6,7 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
hex-literal = "0.1.0"
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
parity-codec = { version = "3.1", default-features = false }
|
||||
parity-codec-derive = { version = "3.1", default-features = false }
|
||||
primitives = { package = "substrate-primitives", path = "../../core/primitives", default-features = false }
|
||||
@@ -19,7 +19,7 @@ system = { package = "srml-system", path = "../system", default-features = false
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"parity-codec/std",
|
||||
"parity-codec-derive/std",
|
||||
"primitives/std",
|
||||
|
||||
@@ -6,7 +6,7 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
#hex-literal = "0.1.0"
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
serde_derive = { version = "1.0", optional = true }
|
||||
parity-codec = { version = "3.1", default-features = false, features = ["derive"] }
|
||||
substrate-primitives = { path = "../../core/primitives", default-features = false }
|
||||
@@ -24,7 +24,7 @@ runtime_io = { package = "sr-io", path = "../../core/sr-io" }
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"parity-codec/std",
|
||||
"substrate-primitives/std",
|
||||
|
||||
@@ -6,7 +6,7 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
hex-literal = "0.1.0"
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
safe-mix = { version = "1.0", default-features = false}
|
||||
parity-codec = { version = "3.1", default-features = false }
|
||||
parity-codec-derive = { version = "3.1", default-features = false }
|
||||
@@ -24,7 +24,7 @@ ref_thread_local = "0.0"
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"safe-mix/std",
|
||||
"substrate-keyring",
|
||||
"parity-codec/std",
|
||||
|
||||
@@ -198,4 +198,7 @@ impl<T: Trait> StaticLookup for Module<T> {
|
||||
fn lookup(a: Self::Source) -> result::Result<Self::Target, &'static str> {
|
||||
Self::lookup_address(a).ok_or("invalid account index")
|
||||
}
|
||||
fn unlookup(a: Self::Target) -> Self::Source {
|
||||
address::Address::Id(a)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
hex-literal = "0.1.0"
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
safe-mix = { version = "1.0", default-features = false}
|
||||
parity-codec = { version = "3.1", default-features = false }
|
||||
parity-codec-derive = { version = "3.1", default-features = false }
|
||||
@@ -24,7 +24,7 @@ runtime_io = { package = "sr-io", path = "../../core/sr-io" }
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"safe-mix/std",
|
||||
"parity-codec/std",
|
||||
"parity-codec-derive/std",
|
||||
|
||||
@@ -50,7 +50,7 @@ macro_rules! impl_session_change {
|
||||
|
||||
for_each_tuple!(impl_session_change);
|
||||
|
||||
pub trait Trait: timestamp::Trait {
|
||||
pub trait Trait: timestamp::Trait + consensus::Trait {
|
||||
type ConvertAccountIdToSessionKey: Convert<Self::AccountId, Self::SessionKey>;
|
||||
type OnSessionChange: OnSessionChange<Self::Moment>;
|
||||
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
|
||||
|
||||
@@ -6,11 +6,12 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
hex-literal = "0.1.0"
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
safe-mix = { version = "1.0", default-features = false}
|
||||
parity-codec = { version = "3.1", default-features = false, features = ["derive"] }
|
||||
substrate-keyring = { path = "../../core/keyring", optional = true }
|
||||
rstd = { package = "sr-std", path = "../../core/sr-std", default-features = false }
|
||||
runtime_io = { package = "sr-io", path = "../../core/sr-io", default-features = false }
|
||||
primitives = { package = "sr-primitives", path = "../../core/sr-primitives", default-features = false }
|
||||
srml-support = { path = "../support", default-features = false }
|
||||
consensus = { package = "srml-consensus", path = "../consensus", default-features = false }
|
||||
@@ -19,18 +20,18 @@ session = { package = "srml-session", path = "../session", default-features = fa
|
||||
|
||||
[dev-dependencies]
|
||||
substrate-primitives = { path = "../../core/primitives" }
|
||||
runtime_io = { package = "sr-io", path = "../../core/sr-io" }
|
||||
timestamp = { package = "srml-timestamp", path = "../timestamp" }
|
||||
balances = { package = "srml-balances", path = "../balances" }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"safe-mix/std",
|
||||
"substrate-keyring",
|
||||
"parity-codec/std",
|
||||
"rstd/std",
|
||||
"runtime_io/std",
|
||||
"srml-support/std",
|
||||
"primitives/std",
|
||||
"session/std",
|
||||
|
||||
@@ -20,18 +20,20 @@
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
use runtime_io::with_storage;
|
||||
use rstd::{prelude::*, result};
|
||||
use parity_codec::{HasCompact, Encode, Decode};
|
||||
use srml_support::{StorageValue, StorageMap, EnumerableStorageMap, dispatch::Result};
|
||||
use srml_support::{decl_module, decl_event, decl_storage, ensure};
|
||||
use srml_support::traits::{
|
||||
Currency, OnDilution, EnsureAccountLiquid, OnFreeBalanceZero, WithdrawReason, ArithmeticType
|
||||
Currency, OnDilution, OnFreeBalanceZero, ArithmeticType,
|
||||
LockIdentifier, LockableCurrency, WithdrawReasons
|
||||
};
|
||||
use session::OnSessionChange;
|
||||
use primitives::Perbill;
|
||||
use primitives::traits::{Zero, One, As, StaticLookup, Saturating};
|
||||
use primitives::traits::{Zero, One, As, StaticLookup, Saturating, Bounded};
|
||||
use system::ensure_signed;
|
||||
|
||||
mod mock;
|
||||
|
||||
mod tests;
|
||||
@@ -111,7 +113,11 @@ pub struct StakingLedger<AccountId, Balance: HasCompact, BlockNumber: HasCompact
|
||||
pub unlocking: Vec<UnlockChunk<Balance, BlockNumber>>,
|
||||
}
|
||||
|
||||
impl<AccountId, Balance: HasCompact + Copy + Saturating, BlockNumber: HasCompact + PartialOrd> StakingLedger<AccountId, Balance, BlockNumber> {
|
||||
impl<
|
||||
AccountId,
|
||||
Balance: HasCompact + Copy + Saturating,
|
||||
BlockNumber: HasCompact + PartialOrd
|
||||
> StakingLedger<AccountId, Balance, BlockNumber> {
|
||||
/// Remove entries from `unlocking` that are sufficiently old and reduce the
|
||||
/// total by the sum of their balances.
|
||||
fn consolidate_unlocked(self, current_era: BlockNumber) -> Self {
|
||||
@@ -157,7 +163,10 @@ type BalanceOf<T> = <<T as Trait>::Currency as ArithmeticType>::Type;
|
||||
|
||||
pub trait Trait: system::Trait + session::Trait {
|
||||
/// The staking balance.
|
||||
type Currency: ArithmeticType + Currency<Self::AccountId, Balance=BalanceOf<Self>>;
|
||||
type Currency:
|
||||
ArithmeticType +
|
||||
Currency<Self::AccountId, Balance=BalanceOf<Self>> +
|
||||
LockableCurrency<Self::AccountId, Moment=Self::BlockNumber>;
|
||||
|
||||
/// Some tokens minted.
|
||||
type OnRewardMinted: OnDilution<BalanceOf<Self>>;
|
||||
@@ -166,6 +175,8 @@ pub trait Trait: system::Trait + session::Trait {
|
||||
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
|
||||
}
|
||||
|
||||
const STAKING_ID: LockIdentifier = *b"staking ";
|
||||
|
||||
decl_storage! {
|
||||
trait Store for Module<T: Trait> as Staking {
|
||||
|
||||
@@ -192,21 +203,9 @@ decl_storage! {
|
||||
pub Invulnerables get(invulnerables) config(): Vec<T::AccountId>;
|
||||
|
||||
/// Map from all locked "stash" accounts to the controller account.
|
||||
pub Bonded get(bonded) build(|config: &GenesisConfig<T>| {
|
||||
config.stakers.iter().map(|(stash, controller, _)| (stash.clone(), controller.clone())).collect::<Vec<_>>()
|
||||
}): map T::AccountId => Option<T::AccountId>;
|
||||
pub Bonded get(bonded): map T::AccountId => Option<T::AccountId>;
|
||||
/// Map from all (unlocked) "controller" accounts to the info regarding the staking.
|
||||
pub Ledger get(ledger) build(|config: &GenesisConfig<T>| {
|
||||
config.stakers.iter().map(|(stash, controller, value)| (
|
||||
controller.clone(),
|
||||
StakingLedger {
|
||||
stash: stash.clone(),
|
||||
total: *value,
|
||||
active: *value,
|
||||
unlocking: Vec::<UnlockChunk<BalanceOf<T>, T::BlockNumber>>::new(),
|
||||
},
|
||||
)).collect::<Vec<_>>()
|
||||
}): map T::AccountId => Option<StakingLedger<T::AccountId, BalanceOf<T>, T::BlockNumber>>;
|
||||
pub Ledger get(ledger): map T::AccountId => Option<StakingLedger<T::AccountId, BalanceOf<T>, T::BlockNumber>>;
|
||||
|
||||
/// Where the reward payment should be made.
|
||||
pub Payee get(payee): map T::AccountId => RewardDestination;
|
||||
@@ -214,12 +213,7 @@ decl_storage! {
|
||||
/// The set of keys are all controllers that want to validate.
|
||||
///
|
||||
/// The values are the preferences that a validator has.
|
||||
pub Validators get(validators) build(|config: &GenesisConfig<T>| {
|
||||
config.stakers.iter().map(|(_stash, controller, _value)| (
|
||||
controller.clone(),
|
||||
ValidatorPrefs::<BalanceOf<T>>::default(),
|
||||
)).collect::<Vec<_>>()
|
||||
}): linked_map T::AccountId => ValidatorPrefs<BalanceOf<T>>;
|
||||
pub Validators get(validators): linked_map T::AccountId => ValidatorPrefs<BalanceOf<T>>;
|
||||
|
||||
/// The set of keys are all controllers that want to nominate.
|
||||
///
|
||||
@@ -228,16 +222,7 @@ decl_storage! {
|
||||
|
||||
/// Nominators for a particular account that is in action right now. You can't iterate through validators here,
|
||||
/// but you can find them in the `sessions` module.
|
||||
pub Stakers get(stakers) build(|config: &GenesisConfig<T>| {
|
||||
config.stakers.iter().map(|(_stash, controller, value)| (
|
||||
controller.clone(),
|
||||
Exposure {
|
||||
total: *value,
|
||||
own: *value,
|
||||
others: Vec::<IndividualExposure<T::AccountId, _>>::new(),
|
||||
},
|
||||
)).collect::<Vec<_>>()
|
||||
}): map T::AccountId => Exposure<T::AccountId, BalanceOf<T>>;
|
||||
pub Stakers get(stakers): map T::AccountId => Exposure<T::AccountId, BalanceOf<T>>;
|
||||
|
||||
// The historical validators and their nominations for a given era. Stored as a trie root of the mapping
|
||||
// `T::AccountId` => `Exposure<T::AccountId, BalanceOf<T>>`, which is just the contents of `Stakers`,
|
||||
@@ -282,7 +267,16 @@ decl_storage! {
|
||||
}
|
||||
add_extra_genesis {
|
||||
config(stakers): Vec<(T::AccountId, T::AccountId, BalanceOf<T>)>;
|
||||
}
|
||||
build(|storage: &mut primitives::StorageOverlay, _: &mut primitives::ChildrenStorageOverlay, config: &GenesisConfig<T>| {
|
||||
with_storage(storage, || {
|
||||
for &(ref stash, ref controller, balance) in &config.stakers {
|
||||
let _ = <Module<T>>::bond(T::Origin::from(Some(stash.clone()).into()), T::Lookup::unlookup(controller.clone()), balance, RewardDestination::Staked);
|
||||
let _ = <Module<T>>::validate(T::Origin::from(Some(controller.clone()).into()), Default::default());
|
||||
}
|
||||
<Module<T>>::select_validators();
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
decl_module! {
|
||||
@@ -307,7 +301,7 @@ decl_module! {
|
||||
let stash_balance = T::Currency::free_balance(&stash);
|
||||
let value = value.min(stash_balance);
|
||||
|
||||
<Ledger<T>>::insert(&controller, StakingLedger { stash, total: value, active: value, unlocking: vec![] });
|
||||
Self::update_ledger(&controller, StakingLedger { stash, total: value, active: value, unlocking: vec![] });
|
||||
<Payee<T>>::insert(&controller, payee);
|
||||
}
|
||||
|
||||
@@ -326,7 +320,7 @@ decl_module! {
|
||||
let extra = (stash_balance - ledger.total).min(max_additional);
|
||||
ledger.total += extra;
|
||||
ledger.active += extra;
|
||||
<Ledger<T>>::insert(&controller, ledger);
|
||||
Self::update_ledger(&controller, ledger);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,7 +352,7 @@ decl_module! {
|
||||
|
||||
let era = Self::current_era() + Self::bonding_duration();
|
||||
ledger.unlocking.push(UnlockChunk { value, era });
|
||||
<Ledger<T>>::insert(&controller, ledger);
|
||||
Self::update_ledger(&controller, ledger);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -373,7 +367,8 @@ decl_module! {
|
||||
fn withdraw_unbonded(origin) {
|
||||
let controller = ensure_signed(origin)?;
|
||||
let ledger = Self::ledger(&controller).ok_or("not a controller")?;
|
||||
<Ledger<T>>::insert(&controller, ledger.consolidate_unlocked(Self::current_era()));
|
||||
let ledger = ledger.consolidate_unlocked(Self::current_era());
|
||||
Self::update_ledger(&controller, ledger);
|
||||
}
|
||||
|
||||
/// Declare the desire to validate for the origin controller.
|
||||
@@ -503,8 +498,14 @@ impl<T: Trait> Module<T> {
|
||||
Self::stakers(who).total
|
||||
}
|
||||
|
||||
// PUBLIC MUTABLES (DANGEROUS)
|
||||
|
||||
// MUTABLES (DANGEROUS)
|
||||
|
||||
/// Update the ledger for a controller. This will also update the stash lock.
|
||||
fn update_ledger(controller: &T::AccountId, ledger: StakingLedger<T::AccountId, BalanceOf<T>, T::BlockNumber>) {
|
||||
T::Currency::set_lock(STAKING_ID, &ledger.stash, ledger.total, T::BlockNumber::max_value(), WithdrawReasons::all());
|
||||
<Ledger<T>>::insert(controller, ledger);
|
||||
}
|
||||
|
||||
/// Slash a given validator by a specific amount. Removes the slash from their balance by preference,
|
||||
/// and reduces the nominators' balance if needed.
|
||||
fn slash_validator(v: &T::AccountId, slash: BalanceOf<T>) {
|
||||
@@ -540,13 +541,13 @@ impl<T: Trait> Module<T> {
|
||||
RewardDestination::Stash => {
|
||||
let _ = Self::ledger(who).map(|l| T::Currency::reward(&l.stash, amount));
|
||||
}
|
||||
RewardDestination::Staked => <Ledger<T>>::mutate(who, |ml| {
|
||||
if let Some(l) = ml.as_mut() {
|
||||
RewardDestination::Staked =>
|
||||
if let Some(mut l) = Self::ledger(who) {
|
||||
l.active += amount;
|
||||
l.total += amount;
|
||||
let _ = T::Currency::reward(&l.stash, amount);
|
||||
}
|
||||
}),
|
||||
Self::update_ledger(who, l);
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -626,7 +627,17 @@ impl<T: Trait> Module<T> {
|
||||
}
|
||||
|
||||
// Reassign all Stakers.
|
||||
let slot_stake = Self::select_validators();
|
||||
|
||||
// Update the balances for slashing/rewarding according to the stakes.
|
||||
<CurrentOfflineSlash<T>>::put(Self::offline_slash() * slot_stake);
|
||||
<CurrentSessionReward<T>>::put(Self::session_reward() * slot_stake);
|
||||
}
|
||||
|
||||
/// Select a new validator set from the assembled stakers and their role preferences.
|
||||
///
|
||||
/// @returns the new SlotStake value.
|
||||
fn select_validators() -> BalanceOf<T> {
|
||||
// Map of (would-be) validator account to amount of stake backing it.
|
||||
|
||||
// First, we pull all validators, together with their stash balance into a Vec (cpu=O(V), mem=O(V))
|
||||
@@ -658,6 +669,7 @@ impl<T: Trait> Module<T> {
|
||||
// cpu=O(V.log(s)) average, O(V.s) worst.
|
||||
let count = Self::validator_count() as usize;
|
||||
let candidates = if candidates.len() <= count {
|
||||
candidates.sort_unstable_by(|a, b| b.1.total.cmp(&a.1.total));
|
||||
candidates
|
||||
} else {
|
||||
candidates.into_iter().fold(vec![], |mut winners: Vec<(T::AccountId, Exposure<T::AccountId, BalanceOf<T>>)>, entry| {
|
||||
@@ -700,9 +712,7 @@ impl<T: Trait> Module<T> {
|
||||
&candidates.into_iter().map(|i| i.0).collect::<Vec<_>>()
|
||||
);
|
||||
|
||||
// Update the balances for slashing/rewarding according to the stakes.
|
||||
<CurrentOfflineSlash<T>>::put(Self::offline_slash() * slot_stake);
|
||||
<CurrentSessionReward<T>>::put(Self::session_reward() * slot_stake);
|
||||
slot_stake
|
||||
}
|
||||
|
||||
/// Call when a validator is determined to be offline. `count` is the
|
||||
@@ -769,29 +779,6 @@ impl<T: Trait> OnSessionChange<T::Moment> for Module<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Trait> EnsureAccountLiquid<T::AccountId, BalanceOf<T>> for Module<T> {
|
||||
fn ensure_account_liquid(who: &T::AccountId) -> Result {
|
||||
if <Bonded<T>>::exists(who) {
|
||||
Err("stash accounts are not liquid")
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn ensure_account_can_withdraw(
|
||||
who: &T::AccountId,
|
||||
amount: BalanceOf<T>,
|
||||
_reason: WithdrawReason,
|
||||
) -> Result {
|
||||
if let Some(controller) = Self::bonded(who) {
|
||||
let ledger = Self::ledger(&controller).ok_or("stash without controller")?;
|
||||
let free_balance = T::Currency::free_balance(&who);
|
||||
ensure!(free_balance.saturating_sub(ledger.total) > amount,
|
||||
"stash with too much under management");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Trait> OnFreeBalanceZero<T::AccountId> for Module<T> {
|
||||
fn on_free_balance_zero(who: &T::AccountId) {
|
||||
if let Some(controller) = <Bonded<T>>::take(who) {
|
||||
|
||||
@@ -54,7 +54,6 @@ impl balances::Trait for Test {
|
||||
type Balance = u64;
|
||||
type OnFreeBalanceZero = Staking;
|
||||
type OnNewAccount = ();
|
||||
type EnsureAccountLiquid = Staking;
|
||||
type Event = ();
|
||||
}
|
||||
impl session::Trait for Test {
|
||||
@@ -120,22 +119,22 @@ impl ExtBuilder {
|
||||
self
|
||||
}
|
||||
pub fn build(self) -> runtime_io::TestExternalities<Blake2Hasher> {
|
||||
let mut t = system::GenesisConfig::<Test>::default().build_storage().unwrap().0;
|
||||
let (mut t, mut c) = system::GenesisConfig::<Test>::default().build_storage().unwrap();
|
||||
let balance_factor = if self.existential_deposit > 0 {
|
||||
256
|
||||
} else {
|
||||
1
|
||||
};
|
||||
t.extend(consensus::GenesisConfig::<Test>{
|
||||
let _ = consensus::GenesisConfig::<Test>{
|
||||
code: vec![],
|
||||
authorities: vec![],
|
||||
}.build_storage().unwrap().0);
|
||||
t.extend(session::GenesisConfig::<Test>{
|
||||
}.assimilate_storage(&mut t, &mut c);
|
||||
let _ = session::GenesisConfig::<Test>{
|
||||
session_length: self.session_length,
|
||||
validators: vec![10, 20],
|
||||
keys: vec![],
|
||||
}.build_storage().unwrap().0);
|
||||
t.extend(balances::GenesisConfig::<Test>{
|
||||
}.assimilate_storage(&mut t, &mut c);
|
||||
let _ = balances::GenesisConfig::<Test>{
|
||||
balances: if self.monied {
|
||||
if self.reward > 0 {
|
||||
vec![(1, 10 * balance_factor), (2, 20 * balance_factor), (3, 300 * balance_factor), (4, 400 * balance_factor), (10, balance_factor), (11, balance_factor * 1000), (20, balance_factor), (21, balance_factor * 2000)]
|
||||
@@ -149,8 +148,8 @@ impl ExtBuilder {
|
||||
transfer_fee: 0,
|
||||
creation_fee: 0,
|
||||
vesting: vec![],
|
||||
}.build_storage().unwrap().0);
|
||||
t.extend(GenesisConfig::<Test>{
|
||||
}.assimilate_storage(&mut t, &mut c);
|
||||
let _ = GenesisConfig::<Test>{
|
||||
sessions_per_era: self.sessions_per_era,
|
||||
current_era: self.current_era,
|
||||
stakers: vec![(11, 10, balance_factor * 1000), (21, 20, balance_factor * 2000)],
|
||||
@@ -163,10 +162,10 @@ impl ExtBuilder {
|
||||
current_offline_slash: 20,
|
||||
offline_slash_grace: 0,
|
||||
invulnerables: vec![],
|
||||
}.build_storage().unwrap().0);
|
||||
t.extend(timestamp::GenesisConfig::<Test>{
|
||||
}.assimilate_storage(&mut t, &mut c);
|
||||
let _ = timestamp::GenesisConfig::<Test>{
|
||||
period: 5,
|
||||
}.build_storage().unwrap().0);
|
||||
}.assimilate_storage(&mut t, &mut c);
|
||||
t.into()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -332,7 +332,7 @@ fn staking_should_work() {
|
||||
assert_eq!(Staking::era_length(), 3);
|
||||
assert_eq!(Staking::validator_count(), 2);
|
||||
// remember + compare this along with the test.
|
||||
assert_eq!(Session::validators(), vec![10, 20]);
|
||||
assert_eq!(Session::validators(), vec![20, 10]);
|
||||
assert_ok!(Staking::set_bonding_duration(2));
|
||||
assert_eq!(Staking::bonding_duration(), 2);
|
||||
|
||||
@@ -347,7 +347,7 @@ fn staking_should_work() {
|
||||
Session::check_rotate_session(System::block_number());
|
||||
assert_eq!(Staking::current_era(), 0);
|
||||
// No effects will be seen so far.s
|
||||
assert_eq!(Session::validators(), vec![10, 20]);
|
||||
assert_eq!(Session::validators(), vec![20, 10]);
|
||||
|
||||
|
||||
// --- Block 2:
|
||||
@@ -359,7 +359,7 @@ fn staking_should_work() {
|
||||
Session::check_rotate_session(System::block_number());
|
||||
assert_eq!(Staking::current_era(), 0);
|
||||
// No effects will be seen so far. Era has not been yet triggered.
|
||||
assert_eq!(Session::validators(), vec![10, 20]);
|
||||
assert_eq!(Session::validators(), vec![20, 10]);
|
||||
|
||||
|
||||
// --- Block 3: the validators will now change.
|
||||
@@ -413,7 +413,7 @@ fn nominating_and_rewards_should_work() {
|
||||
assert_eq!(Staking::era_length(), 1);
|
||||
assert_eq!(Staking::validator_count(), 2);
|
||||
assert_eq!(Staking::bonding_duration(), 3);
|
||||
assert_eq!(Session::validators(), vec![10, 20]);
|
||||
assert_eq!(Session::validators(), vec![20, 10]);
|
||||
|
||||
// Set payee to controller
|
||||
assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller));
|
||||
@@ -447,7 +447,7 @@ fn nominating_and_rewards_should_work() {
|
||||
Session::check_rotate_session(System::block_number());
|
||||
assert_eq!(Staking::current_era(), 1);
|
||||
// validators will not change, since selection currently is actually not dependent on nomination and votes, only stake.
|
||||
assert_eq!(Session::validators(), vec![10, 20]);
|
||||
assert_eq!(Session::validators(), vec![20, 10]);
|
||||
// avalidators must have already received some rewards.
|
||||
assert_eq!(Balances::total_balance(&10), initial_balance + session_reward);
|
||||
assert_eq!(Balances::total_balance(&20), initial_balance + session_reward);
|
||||
@@ -487,7 +487,7 @@ fn nominators_also_get_slashed() {
|
||||
// Account 10 has not been reported offline
|
||||
assert_eq!(Staking::slash_count(&10), 0);
|
||||
// initial validators
|
||||
assert_eq!(Session::validators(), vec![10, 20]);
|
||||
assert_eq!(Session::validators(), vec![20, 10]);
|
||||
|
||||
// Set payee to controller
|
||||
assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller));
|
||||
@@ -500,7 +500,7 @@ fn nominators_also_get_slashed() {
|
||||
// 2 will nominate for 10
|
||||
let nominator_stake = 500;
|
||||
assert_ok!(Staking::bond(Origin::signed(1), 2, nominator_stake, RewardDestination::default()));
|
||||
assert_ok!(Staking::nominate(Origin::signed(2), vec![10, 20]));
|
||||
assert_ok!(Staking::nominate(Origin::signed(2), vec![20, 10]));
|
||||
|
||||
// new era, pay rewards,
|
||||
System::set_block_number(2);
|
||||
@@ -628,7 +628,7 @@ fn cannot_transfer_staked_balance() {
|
||||
// Confirm account 11 (via controller 10) is totally staked
|
||||
assert_eq!(Staking::stakers(&10).total, 1000);
|
||||
// Confirm account 11 cannot transfer as a result
|
||||
assert_noop!(Balances::transfer(Origin::signed(11), 20, 1), "stash with too much under management");
|
||||
assert_noop!(Balances::transfer(Origin::signed(11), 20, 1), "account liquidity restrictions prevent withdrawal");
|
||||
|
||||
// Give account 11 extra free balance
|
||||
Balances::set_free_balance(&11, 10000);
|
||||
@@ -637,8 +637,6 @@ fn cannot_transfer_staked_balance() {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
#[test]
|
||||
fn cannot_reserve_staked_balance() {
|
||||
// Checks that a bonded account cannot reserve balance from free balance
|
||||
@@ -650,7 +648,7 @@ fn cannot_reserve_staked_balance() {
|
||||
// Confirm account 11 (via controller 10) is totally staked
|
||||
assert_eq!(Staking::stakers(&10).total, 1000);
|
||||
// Confirm account 11 cannot transfer as a result
|
||||
assert_noop!(Balances::reserve(&11, 1), "stash with too much under management");
|
||||
assert_noop!(Balances::reserve(&11, 1), "account liquidity restrictions prevent withdrawal");
|
||||
|
||||
// Give account 11 extra free balance
|
||||
Balances::set_free_balance(&11, 10000);
|
||||
|
||||
@@ -6,7 +6,7 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
hex-literal = "0.1.0"
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
parity-codec = { version = "3.1", default-features = false }
|
||||
parity-codec-derive = { version = "3.1", default-features = false }
|
||||
sr-std = { path = "../../core/sr-std", default-features = false }
|
||||
@@ -22,7 +22,7 @@ substrate-primitives = { path = "../../core/primitives" }
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"parity-codec/std",
|
||||
"parity-codec-derive/std",
|
||||
"sr-std/std",
|
||||
|
||||
@@ -6,7 +6,7 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
hex-literal = { version = "0.1.0", optional = true }
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
serde_derive = { version = "1.0", optional = true }
|
||||
parity-codec = { version = "3.1", default-features = false, features = ["derive"] }
|
||||
srml-metadata = { path = "../metadata", default-features = false }
|
||||
@@ -17,6 +17,7 @@ inherents = { package = "substrate-inherents", path = "../../core/inherents", de
|
||||
srml-support-procedural = { path = "./procedural" }
|
||||
paste = "0.1"
|
||||
once_cell = { version = "0.1.6", default-features = false, optional = true }
|
||||
bitmask = { git = "https://github.com/paritytech/bitmask", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = "0.5.1"
|
||||
@@ -26,7 +27,8 @@ default = ["std"]
|
||||
std = [
|
||||
"hex-literal",
|
||||
"once_cell",
|
||||
"serde/std",
|
||||
"bitmask/std",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"runtime_io/std",
|
||||
"parity-codec/std",
|
||||
|
||||
@@ -232,9 +232,9 @@ fn decl_store_extra_genesis(
|
||||
use #scrate::rstd::{cell::RefCell, marker::PhantomData};
|
||||
use #scrate::codec::{Encode, Decode};
|
||||
|
||||
let storage = (RefCell::new(&mut r), PhantomData::<Self>::default());
|
||||
let v = (#builder)(&self);
|
||||
<#name<#traitinstance> as #scrate::storage::generator::StorageValue<#typ>>::put(&v, &storage);
|
||||
|
||||
}}
|
||||
},
|
||||
DeclStorageTypeInfosKind::Map { key_type, .. } => {
|
||||
@@ -242,7 +242,6 @@ fn decl_store_extra_genesis(
|
||||
use #scrate::rstd::{cell::RefCell, marker::PhantomData};
|
||||
use #scrate::codec::{Encode, Decode};
|
||||
|
||||
let storage = (RefCell::new(&mut r), PhantomData::<Self>::default());
|
||||
let data = (#builder)(&self);
|
||||
for (k, v) in data.into_iter() {
|
||||
<#name<#traitinstance> as #scrate::storage::generator::StorageMap<#key_type, #typ>>::insert(&k, &v, &storage);
|
||||
@@ -382,12 +381,28 @@ fn decl_store_extra_genesis(
|
||||
let mut r: #scrate::runtime_primitives::StorageOverlay = Default::default();
|
||||
let mut c: #scrate::runtime_primitives::ChildrenStorageOverlay = Default::default();
|
||||
|
||||
#builders
|
||||
{
|
||||
use #scrate::rstd::{cell::RefCell, marker::PhantomData};
|
||||
let storage = (RefCell::new(&mut r), PhantomData::<Self>::default());
|
||||
#builders
|
||||
}
|
||||
|
||||
#scall(&mut r, &mut c, &self);
|
||||
|
||||
Ok((r, c))
|
||||
}
|
||||
fn assimilate_storage(self, r: &mut #scrate::runtime_primitives::StorageOverlay, c: &mut #scrate::runtime_primitives::ChildrenStorageOverlay) -> ::std::result::Result<(), String> {
|
||||
use #scrate::rstd::{cell::RefCell, marker::PhantomData};
|
||||
let storage = (RefCell::new(r), PhantomData::<Self>::default());
|
||||
|
||||
#builders
|
||||
|
||||
let r = storage.0.into_inner();
|
||||
|
||||
#scall(r, c, &self);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -19,6 +19,9 @@
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
#![cfg_attr(not(feature = "std"), feature(alloc))]
|
||||
|
||||
#[macro_use]
|
||||
extern crate bitmask;
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
pub use serde;
|
||||
#[doc(hidden)]
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
//! Traits for SRML
|
||||
|
||||
use crate::rstd::result;
|
||||
use crate::codec::Codec;
|
||||
use crate::codec::{Codec, Encode, Decode};
|
||||
use crate::runtime_primitives::traits::{
|
||||
MaybeSerializeDebug, SimpleArithmetic, As
|
||||
};
|
||||
@@ -53,61 +53,6 @@ impl<Balance> OnDilution<Balance> for () {
|
||||
fn on_dilution(_minted: Balance, _portion: Balance) {}
|
||||
}
|
||||
|
||||
/// Determinator for whether a given account is able to use its **free** balance.
|
||||
///
|
||||
/// By convention, `ensure_account_liquid` overrules `ensure_account_can_withdraw`. If a
|
||||
/// caller gets `Ok` from the former, then they do not need to call the latter.
|
||||
///
|
||||
/// This implies that if you define the latter away from its default of replicating the
|
||||
/// former, then ensure you also redefine the former to return an `Err` in corresponding
|
||||
/// situations, otherwise you'll end up giving inconsistent information.
|
||||
// TODO: Remove in favour of explicit functionality in balances module: #1896
|
||||
pub trait EnsureAccountLiquid<AccountId, Balance> {
|
||||
/// Ensures that the account is completely unencumbered. If this is `Ok` then there's no need to
|
||||
/// check any other items. If it's an `Err`, then you must use one pair of the other items.
|
||||
fn ensure_account_liquid(who: &AccountId) -> result::Result<(), &'static str>;
|
||||
|
||||
/// Returns `Ok` iff the account is able to make a withdrawal of the given amount
|
||||
/// for the given reason.
|
||||
///
|
||||
/// `Err(...)` with the reason why not otherwise.
|
||||
///
|
||||
/// By default this just reflects the results of `ensure_account_liquid`.
|
||||
///
|
||||
/// @warning If you redefine this away from the default, ensure that you define
|
||||
/// `ensure_account_liquid` in accordance.
|
||||
fn ensure_account_can_withdraw(
|
||||
who: &AccountId,
|
||||
_amount: Balance,
|
||||
_reason: WithdrawReason
|
||||
) -> result::Result<(), &'static str> {
|
||||
Self::ensure_account_liquid(who)
|
||||
}
|
||||
}
|
||||
impl<
|
||||
AccountId,
|
||||
Balance: Copy,
|
||||
X: EnsureAccountLiquid<AccountId, Balance>,
|
||||
Y: EnsureAccountLiquid<AccountId, Balance>,
|
||||
> EnsureAccountLiquid<AccountId, Balance> for (X, Y) {
|
||||
fn ensure_account_liquid(who: &AccountId) -> result::Result<(), &'static str> {
|
||||
X::ensure_account_liquid(who)?;
|
||||
Y::ensure_account_liquid(who)
|
||||
}
|
||||
|
||||
fn ensure_account_can_withdraw(
|
||||
who: &AccountId,
|
||||
amount: Balance,
|
||||
reason: WithdrawReason
|
||||
) -> result::Result<(), &'static str> {
|
||||
X::ensure_account_can_withdraw(who, amount, reason)?;
|
||||
Y::ensure_account_can_withdraw(who, amount, reason)
|
||||
}
|
||||
}
|
||||
impl<AccountId, Balance> EnsureAccountLiquid<AccountId, Balance> for () {
|
||||
fn ensure_account_liquid(_who: &AccountId) -> result::Result<(), &'static str> { Ok(()) }
|
||||
}
|
||||
|
||||
/// Outcome of a balance update.
|
||||
pub enum UpdateBalanceOutcome {
|
||||
/// Account balance was simply updated.
|
||||
@@ -227,6 +172,41 @@ pub trait Currency<AccountId> {
|
||||
) -> result::Result<Option<Self::Balance>, &'static str>;
|
||||
}
|
||||
|
||||
/// An identifier for a lock. Used for disambiguating different locks so that
|
||||
/// they can be individually replaced or removed.
|
||||
pub type LockIdentifier = [u8; 8];
|
||||
|
||||
/// A currency whose accounts can have liquidity restructions.
|
||||
pub trait LockableCurrency<AccountId>: Currency<AccountId> {
|
||||
/// The quantity used to denote time; usually just a `BlockNumber`.
|
||||
type Moment;
|
||||
|
||||
/// Introduce a new lock or change an existing one.
|
||||
fn set_lock(
|
||||
id: LockIdentifier,
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
until: Self::Moment,
|
||||
reasons: WithdrawReasons,
|
||||
);
|
||||
|
||||
/// Change any existing lock so that it becomes strictly less liquid in all
|
||||
/// respects to the given parameters.
|
||||
fn extend_lock(
|
||||
id: LockIdentifier,
|
||||
who: &AccountId,
|
||||
amount: Self::Balance,
|
||||
until: Self::Moment,
|
||||
reasons: WithdrawReasons,
|
||||
);
|
||||
|
||||
/// Remove an existing lock.
|
||||
fn remove_lock(
|
||||
id: LockIdentifier,
|
||||
who: &AccountId,
|
||||
);
|
||||
}
|
||||
|
||||
/// Charge bytes fee trait
|
||||
pub trait ChargeBytesFee<AccountId> {
|
||||
/// Charge fees from `transactor` for an extrinsic (transaction) of encoded length
|
||||
@@ -246,16 +226,21 @@ pub trait ChargeFee<AccountId>: ChargeBytesFee<AccountId> {
|
||||
fn refund_fee(transactor: &AccountId, amount: Self::Amount) -> Result<(), &'static str>;
|
||||
}
|
||||
|
||||
/// Reason for moving funds out of an account.
|
||||
#[derive(Copy, Clone, Eq, PartialEq)]
|
||||
#[cfg_attr(feature = "std", derive(Debug))]
|
||||
pub enum WithdrawReason {
|
||||
/// In order to pay for (system) transaction costs.
|
||||
TransactionPayment,
|
||||
/// In order to transfer ownership.
|
||||
Transfer,
|
||||
/// In order to reserve some funds for a later return or repatriation
|
||||
Reserve,
|
||||
bitmask! {
|
||||
/// 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 {
|
||||
/// In order to pay for (system) transaction costs.
|
||||
TransactionPayment = 0b00000001,
|
||||
/// In order to transfer ownership.
|
||||
Transfer = 0b00000010,
|
||||
/// In order to reserve some funds for a later return or repatriation
|
||||
Reserve = 0b00000100,
|
||||
}
|
||||
}
|
||||
|
||||
/// Transfer fungible asset trait
|
||||
|
||||
@@ -6,7 +6,7 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
hex-literal = "0.1.0"
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
serde_derive = { version = "1.0", optional = true }
|
||||
safe-mix = { version = "1.0", default-features = false}
|
||||
parity-codec = { version = "3.1", default-features = false, features = ["derive"] }
|
||||
@@ -19,7 +19,7 @@ srml-support = { path = "../support", default-features = false }
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"safe-mix/std",
|
||||
"parity-codec/std",
|
||||
|
||||
@@ -6,14 +6,13 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
hex-literal = "0.1.0"
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
parity-codec = { version = "3.1", default-features = false, features = ["derive"] }
|
||||
rstd = { package = "sr-std", path = "../../core/sr-std", default-features = false }
|
||||
runtime_primitives = { package = "sr-primitives", path = "../../core/sr-primitives", default-features = false }
|
||||
inherents = { package = "substrate-inherents", path = "../../core/inherents", default-features = false }
|
||||
srml-support = { path = "../support", default-features = false }
|
||||
system = { package = "srml-system", path = "../system", default-features = false }
|
||||
consensus = { package = "srml-consensus", path = "../consensus", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
runtime_io = { package = "sr-io", path = "../../core/sr-io" }
|
||||
@@ -25,8 +24,7 @@ std = [
|
||||
"rstd/std",
|
||||
"srml-support/std",
|
||||
"runtime_primitives/std",
|
||||
"consensus/std",
|
||||
"serde/std",
|
||||
"serde",
|
||||
"parity-codec/std",
|
||||
"system/std",
|
||||
"inherents/std",
|
||||
|
||||
@@ -32,17 +32,17 @@
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use parity_codec::Encode;
|
||||
#[cfg(feature = "std")]
|
||||
use parity_codec::Decode;
|
||||
use parity_codec::Encode;
|
||||
#[cfg(feature = "std")]
|
||||
use inherents::ProvideInherentData;
|
||||
use srml_support::{StorageValue, Parameter, decl_storage, decl_module};
|
||||
use srml_support::for_each_tuple;
|
||||
use runtime_primitives::traits::{As, SimpleArithmetic, Zero};
|
||||
use system::ensure_inherent;
|
||||
use rstd::{result, ops::{Mul, Div}, cmp};
|
||||
use inherents::{RuntimeString, InherentIdentifier, ProvideInherent, IsFatalError, InherentData};
|
||||
#[cfg(feature = "std")]
|
||||
use inherents::ProvideInherentData;
|
||||
|
||||
/// The identifier for the `timestamp` inherent.
|
||||
pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"timstap0";
|
||||
@@ -144,7 +144,7 @@ macro_rules! impl_timestamp_set {
|
||||
|
||||
for_each_tuple!(impl_timestamp_set);
|
||||
|
||||
pub trait Trait: consensus::Trait + system::Trait {
|
||||
pub trait Trait: system::Trait {
|
||||
/// Type used for expressing timestamp.
|
||||
type Moment: Parameter + Default + SimpleArithmetic
|
||||
+ Mul<Self::BlockNumber, Output = Self::Moment>
|
||||
@@ -259,7 +259,7 @@ mod tests {
|
||||
use substrate_primitives::H256;
|
||||
use runtime_primitives::BuildStorage;
|
||||
use runtime_primitives::traits::{BlakeTwo256, IdentityLookup};
|
||||
use runtime_primitives::testing::{Digest, DigestItem, Header, UintAuthorityId};
|
||||
use runtime_primitives::testing::{Digest, DigestItem, Header};
|
||||
|
||||
impl_outer_origin! {
|
||||
pub enum Origin for Test {}
|
||||
@@ -280,11 +280,6 @@ mod tests {
|
||||
type Event = ();
|
||||
type Log = DigestItem;
|
||||
}
|
||||
impl consensus::Trait for Test {
|
||||
type Log = DigestItem;
|
||||
type SessionKey = UintAuthorityId;
|
||||
type InherentOfflineReport = ();
|
||||
}
|
||||
impl Trait for Test {
|
||||
type Moment = u64;
|
||||
type OnTimestampSet = ();
|
||||
|
||||
@@ -6,7 +6,7 @@ edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
hex-literal = "0.1.0"
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
serde_derive = { version = "1.0", optional = true }
|
||||
parity-codec = { version = "3.1", default-features = false, features = ["derive"] }
|
||||
rstd = { package = "sr-std", path = "../../core/sr-std", default-features = false }
|
||||
@@ -22,7 +22,7 @@ substrate-primitives = { path = "../../core/primitives" }
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"parity-codec/std",
|
||||
"rstd/std",
|
||||
|
||||
@@ -287,7 +287,6 @@ mod tests {
|
||||
type Balance = u64;
|
||||
type OnNewAccount = ();
|
||||
type OnFreeBalanceZero = ();
|
||||
type EnsureAccountLiquid = ();
|
||||
type Event = ();
|
||||
}
|
||||
impl Trait for Test {
|
||||
|
||||
@@ -5,7 +5,7 @@ authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", default-features = false }
|
||||
serde = { version = "1.0", optional = true }
|
||||
parity-codec = { version = "3.1", default-features = false }
|
||||
sr-std = { path = "../../core/sr-std", default-features = false }
|
||||
sr-primitives = { path = "../../core/sr-primitives", default-features = false }
|
||||
@@ -16,7 +16,7 @@ consensus = { package = "srml-consensus", path = "../consensus", default-feature
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde/std",
|
||||
"serde",
|
||||
"parity-codec/std",
|
||||
"sr-std/std",
|
||||
"sr-primitives/std",
|
||||
|
||||
Reference in New Issue
Block a user