#![cfg_attr(not(feature = "std"), no_std)]
mod benchmarking;
pub mod weights;
use tetcore_std::prelude::*;
use tetcore_std::fmt::Debug;
use codec::{Encode, Decode};
use tp_runtime::{DispatchResult, RuntimeDebug, traits::{
StaticLookup, Zero, AtLeast32BitUnsigned, MaybeSerializeDeserialize, Convert
}};
use fabric_support::{decl_module, decl_event, decl_storage, decl_error, ensure};
use fabric_support::traits::{
Currency, LockableCurrency, VestingSchedule, WithdrawReasons, LockIdentifier,
ExistenceRequirement, Get,
};
use fabric_system::{ensure_signed, ensure_root};
pub use weights::WeightInfo;
type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as fabric_system::Config>::AccountId>>::Balance;
type MaxLocksOf<T> = <<T as Config>::Currency as LockableCurrency<<T as fabric_system::Config>::AccountId>>::MaxLocks;
pub trait Config: fabric_system::Config {
type Event: From<Event<Self>> + Into<<Self as fabric_system::Config>::Event>;
type Currency: LockableCurrency<Self::AccountId>;
type BlockNumberToBalance: Convert<Self::BlockNumber, BalanceOf<Self>>;
type MinVestedTransfer: Get<BalanceOf<Self>>;
type WeightInfo: WeightInfo;
}
const VESTING_ID: LockIdentifier = *b"vesting ";
#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug)]
pub struct VestingInfo<Balance, BlockNumber> {
pub locked: Balance,
pub per_block: Balance,
pub starting_block: BlockNumber,
}
impl<
Balance: AtLeast32BitUnsigned + Copy,
BlockNumber: AtLeast32BitUnsigned + Copy,
> VestingInfo<Balance, BlockNumber> {
pub fn locked_at<
BlockNumberToBalance: Convert<BlockNumber, Balance>
>(&self, n: BlockNumber) -> Balance {
let vested_block_count = n.saturating_sub(self.starting_block);
let vested_block_count = BlockNumberToBalance::convert(vested_block_count);
let maybe_balance = vested_block_count.checked_mul(&self.per_block);
if let Some(balance) = maybe_balance {
self.locked.saturating_sub(balance)
} else {
Zero::zero()
}
}
}
decl_storage! {
trait Store for Module<T: Config> as Vesting {
pub Vesting get(fn vesting):
map hasher(blake2_128_concat) T::AccountId
=> Option<VestingInfo<BalanceOf<T>, T::BlockNumber>>;
}
add_extra_genesis {
config(vesting): Vec<(T::AccountId, T::BlockNumber, T::BlockNumber, BalanceOf<T>)>;
build(|config: &GenesisConfig<T>| {
use tp_runtime::traits::Saturating;
for &(ref who, begin, length, liquid) in config.vesting.iter() {
let balance = T::Currency::free_balance(who);
assert!(!balance.is_zero(), "Currencies must be init'd before vesting");
let locked = balance.saturating_sub(liquid);
let length_as_balance = T::BlockNumberToBalance::convert(length);
let per_block = locked / length_as_balance.max(tp_runtime::traits::One::one());
Vesting::<T>::insert(who, VestingInfo {
locked: locked,
per_block: per_block,
starting_block: begin
});
let reasons = WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE;
T::Currency::set_lock(VESTING_ID, who, locked, reasons);
}
})
}
}
decl_event!(
pub enum Event<T> where AccountId = <T as fabric_system::Config>::AccountId, Balance = BalanceOf<T> {
VestingUpdated(AccountId, Balance),
VestingCompleted(AccountId),
}
);
decl_error! {
pub enum Error for Module<T: Config> {
NotVesting,
ExistingVestingSchedule,
AmountLow,
}
}
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin {
type Error = Error<T>;
const MinVestedTransfer: BalanceOf<T> = T::MinVestedTransfer::get();
fn deposit_event() = default;
#[weight = T::WeightInfo::vest_locked(MaxLocksOf::<T>::get())
.max(T::WeightInfo::vest_unlocked(MaxLocksOf::<T>::get()))
]
fn vest(origin) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::update_lock(who)
}
#[weight = T::WeightInfo::vest_other_locked(MaxLocksOf::<T>::get())
.max(T::WeightInfo::vest_other_unlocked(MaxLocksOf::<T>::get()))
]
fn vest_other(origin, target: <T::Lookup as StaticLookup>::Source) -> DispatchResult {
ensure_signed(origin)?;
Self::update_lock(T::Lookup::lookup(target)?)
}
#[weight = T::WeightInfo::vested_transfer(MaxLocksOf::<T>::get())]
pub fn vested_transfer(
origin,
target: <T::Lookup as StaticLookup>::Source,
schedule: VestingInfo<BalanceOf<T>, T::BlockNumber>,
) -> DispatchResult {
let transactor = ensure_signed(origin)?;
ensure!(schedule.locked >= T::MinVestedTransfer::get(), Error::<T>::AmountLow);
let who = T::Lookup::lookup(target)?;
ensure!(!Vesting::<T>::contains_key(&who), Error::<T>::ExistingVestingSchedule);
T::Currency::transfer(&transactor, &who, schedule.locked, ExistenceRequirement::AllowDeath)?;
Self::add_vesting_schedule(&who, schedule.locked, schedule.per_block, schedule.starting_block)
.expect("user does not have an existing vesting schedule; q.e.d.");
Ok(())
}
#[weight = T::WeightInfo::force_vested_transfer(MaxLocksOf::<T>::get())]
pub fn force_vested_transfer(
origin,
source: <T::Lookup as StaticLookup>::Source,
target: <T::Lookup as StaticLookup>::Source,
schedule: VestingInfo<BalanceOf<T>, T::BlockNumber>,
) -> DispatchResult {
ensure_root(origin)?;
ensure!(schedule.locked >= T::MinVestedTransfer::get(), Error::<T>::AmountLow);
let target = T::Lookup::lookup(target)?;
let source = T::Lookup::lookup(source)?;
ensure!(!Vesting::<T>::contains_key(&target), Error::<T>::ExistingVestingSchedule);
T::Currency::transfer(&source, &target, schedule.locked, ExistenceRequirement::AllowDeath)?;
Self::add_vesting_schedule(&target, schedule.locked, schedule.per_block, schedule.starting_block)
.expect("user does not have an existing vesting schedule; q.e.d.");
Ok(())
}
}
}
impl<T: Config> Module<T> {
fn update_lock(who: T::AccountId) -> DispatchResult {
let vesting = Self::vesting(&who).ok_or(Error::<T>::NotVesting)?;
let now = <fabric_system::Module<T>>::block_number();
let locked_now = vesting.locked_at::<T::BlockNumberToBalance>(now);
if locked_now.is_zero() {
T::Currency::remove_lock(VESTING_ID, &who);
Vesting::<T>::remove(&who);
Self::deposit_event(RawEvent::VestingCompleted(who));
} else {
let reasons = WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE;
T::Currency::set_lock(VESTING_ID, &who, locked_now, reasons);
Self::deposit_event(RawEvent::VestingUpdated(who, locked_now));
}
Ok(())
}
}
impl<T: Config> VestingSchedule<T::AccountId> for Module<T> where
BalanceOf<T>: MaybeSerializeDeserialize + Debug
{
type Moment = T::BlockNumber;
type Currency = T::Currency;
fn vesting_balance(who: &T::AccountId) -> Option<BalanceOf<T>> {
if let Some(v) = Self::vesting(who) {
let now = <fabric_system::Module<T>>::block_number();
let locked_now = v.locked_at::<T::BlockNumberToBalance>(now);
Some(T::Currency::free_balance(who).min(locked_now))
} else {
None
}
}
fn add_vesting_schedule(
who: &T::AccountId,
locked: BalanceOf<T>,
per_block: BalanceOf<T>,
starting_block: T::BlockNumber
) -> DispatchResult {
if locked.is_zero() { return Ok(()) }
if Vesting::<T>::contains_key(who) {
Err(Error::<T>::ExistingVestingSchedule)?
}
let vesting_schedule = VestingInfo {
locked,
per_block,
starting_block
};
Vesting::<T>::insert(who, vesting_schedule);
let _ = Self::update_lock(who.clone());
Ok(())
}
fn remove_vesting_schedule(who: &T::AccountId) {
Vesting::<T>::remove(who);
let _ = Self::update_lock(who.clone());
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate as noble_vesting;
use fabric_support::{assert_ok, assert_noop, parameter_types};
use tet_core::H256;
use tp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup, Identity, BadOrigin},
};
use fabric_system::RawOrigin;
type UncheckedExtrinsic = fabric_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = fabric_system::mocking::MockBlock<Test>;
fabric_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: fabric_system::{Module, Call, Config, Storage, Event<T>},
Balances: noble_balances::{Module, Call, Storage, Config<T>, Event<T>},
Vesting: noble_vesting::{Module, Call, Storage, Event<T>, Config<T>},
}
);
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub BlockWeights: fabric_system::limits::BlockWeights =
fabric_system::limits::BlockWeights::simple_max(1024);
}
impl fabric_system::Config for Test {
type BaseCallFilter = ();
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Call = Call;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type BlockHashCount = BlockHashCount;
type Version = ();
type NobleInfo = NobleInfo;
type AccountData = noble_balances::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
}
parameter_types! {
pub const MaxLocks: u32 = 10;
}
impl noble_balances::Config for Test {
type Balance = u64;
type DustRemoval = ();
type Event = Event;
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type MaxLocks = MaxLocks;
type WeightInfo = ();
}
parameter_types! {
pub const MinVestedTransfer: u64 = 256 * 2;
pub static ExistentialDeposit: u64 = 0;
}
impl Config for Test {
type Event = Event;
type Currency = Balances;
type BlockNumberToBalance = Identity;
type MinVestedTransfer = MinVestedTransfer;
type WeightInfo = ();
}
pub struct ExtBuilder {
existential_deposit: u64,
}
impl Default for ExtBuilder {
fn default() -> Self {
Self {
existential_deposit: 1,
}
}
}
impl ExtBuilder {
pub fn existential_deposit(mut self, existential_deposit: u64) -> Self {
self.existential_deposit = existential_deposit;
self
}
pub fn build(self) -> tet_io::TestExternalities {
EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit);
let mut t = fabric_system::GenesisConfig::default().build_storage::<Test>().unwrap();
noble_balances::GenesisConfig::<Test> {
balances: vec![
(1, 10 * self.existential_deposit),
(2, 20 * self.existential_deposit),
(3, 30 * self.existential_deposit),
(4, 40 * self.existential_deposit),
(12, 10 * self.existential_deposit)
],
}.assimilate_storage(&mut t).unwrap();
noble_vesting::GenesisConfig::<Test> {
vesting: vec![
(1, 0, 10, 5 * self.existential_deposit),
(2, 10, 20, 0),
(12, 10, 20, 5 * self.existential_deposit)
],
}.assimilate_storage(&mut t).unwrap();
let mut ext = tet_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
}
#[test]
fn check_vesting_status() {
ExtBuilder::default()
.existential_deposit(256)
.build()
.execute_with(|| {
let user1_free_balance = Balances::free_balance(&1);
let user2_free_balance = Balances::free_balance(&2);
let user12_free_balance = Balances::free_balance(&12);
assert_eq!(user1_free_balance, 256 * 10);
assert_eq!(user2_free_balance, 256 * 20);
assert_eq!(user12_free_balance, 256 * 10);
let user1_vesting_schedule = VestingInfo {
locked: 256 * 5,
per_block: 128,
starting_block: 0,
};
let user2_vesting_schedule = VestingInfo {
locked: 256 * 20,
per_block: 256,
starting_block: 10,
};
let user12_vesting_schedule = VestingInfo {
locked: 256 * 5,
per_block: 64,
starting_block: 10,
};
assert_eq!(Vesting::vesting(&1), Some(user1_vesting_schedule));
assert_eq!(Vesting::vesting(&2), Some(user2_vesting_schedule));
assert_eq!(Vesting::vesting(&12), Some(user12_vesting_schedule));
assert_eq!(Vesting::vesting_balance(&1), Some(128 * 9));
assert_eq!(Vesting::vesting_balance(&2), Some(user2_free_balance));
assert_eq!(Vesting::vesting_balance(&12), Some(user12_free_balance - 256 * 5));
System::set_block_number(10);
assert_eq!(System::block_number(), 10);
assert_eq!(Vesting::vesting_balance(&1), Some(0));
assert_eq!(Vesting::vesting_balance(&2), Some(user2_free_balance));
assert_eq!(Vesting::vesting_balance(&12), Some(user12_free_balance - 256 * 5));
System::set_block_number(30);
assert_eq!(System::block_number(), 30);
assert_eq!(Vesting::vesting_balance(&1), Some(0));
assert_eq!(Vesting::vesting_balance(&2), Some(0));
assert_eq!(Vesting::vesting_balance(&12), Some(0));
});
}
#[test]
fn unvested_balance_should_not_transfer() {
ExtBuilder::default()
.existential_deposit(10)
.build()
.execute_with(|| {
let user1_free_balance = Balances::free_balance(&1);
assert_eq!(user1_free_balance, 100);
assert_eq!(Vesting::vesting_balance(&1), Some(45));
assert_noop!(
Balances::transfer(Some(1).into(), 2, 56),
noble_balances::Error::<Test, _>::LiquidityRestrictions,
);
});
}
#[test]
fn vested_balance_should_transfer() {
ExtBuilder::default()
.existential_deposit(10)
.build()
.execute_with(|| {
let user1_free_balance = Balances::free_balance(&1);
assert_eq!(user1_free_balance, 100);
assert_eq!(Vesting::vesting_balance(&1), Some(45));
assert_ok!(Vesting::vest(Some(1).into()));
assert_ok!(Balances::transfer(Some(1).into(), 2, 55));
});
}
#[test]
fn vested_balance_should_transfer_using_vest_other() {
ExtBuilder::default()
.existential_deposit(10)
.build()
.execute_with(|| {
let user1_free_balance = Balances::free_balance(&1);
assert_eq!(user1_free_balance, 100);
assert_eq!(Vesting::vesting_balance(&1), Some(45));
assert_ok!(Vesting::vest_other(Some(2).into(), 1));
assert_ok!(Balances::transfer(Some(1).into(), 2, 55));
});
}
#[test]
fn extra_balance_should_transfer() {
ExtBuilder::default()
.existential_deposit(10)
.build()
.execute_with(|| {
assert_ok!(Balances::transfer(Some(3).into(), 1, 100));
assert_ok!(Balances::transfer(Some(3).into(), 2, 100));
let user1_free_balance = Balances::free_balance(&1);
assert_eq!(user1_free_balance, 200);
let user2_free_balance = Balances::free_balance(&2);
assert_eq!(user2_free_balance, 300);
assert_eq!(Vesting::vesting_balance(&1), Some(45));
assert_ok!(Vesting::vest(Some(1).into()));
assert_ok!(Balances::transfer(Some(1).into(), 3, 155));
assert_eq!(Vesting::vesting_balance(&2), Some(200));
assert_ok!(Vesting::vest(Some(2).into()));
assert_ok!(Balances::transfer(Some(2).into(), 3, 100));
});
}
#[test]
fn liquid_funds_should_transfer_with_delayed_vesting() {
ExtBuilder::default()
.existential_deposit(256)
.build()
.execute_with(|| {
let user12_free_balance = Balances::free_balance(&12);
assert_eq!(user12_free_balance, 2560);
assert_eq!(Vesting::vesting_balance(&12), Some(user12_free_balance - 256 * 5));
let user12_vesting_schedule = VestingInfo {
locked: 256 * 5,
per_block: 64,
starting_block: 10,
};
assert_eq!(Vesting::vesting(&12), Some(user12_vesting_schedule));
assert_ok!(Balances::transfer(Some(12).into(), 3, 256 * 5));
});
}
#[test]
fn vested_transfer_works() {
ExtBuilder::default()
.existential_deposit(256)
.build()
.execute_with(|| {
let user3_free_balance = Balances::free_balance(&3);
let user4_free_balance = Balances::free_balance(&4);
assert_eq!(user3_free_balance, 256 * 30);
assert_eq!(user4_free_balance, 256 * 40);
assert_eq!(Vesting::vesting(&4), None);
let new_vesting_schedule = VestingInfo {
locked: 256 * 5,
per_block: 64,
starting_block: 10,
};
assert_ok!(Vesting::vested_transfer(Some(3).into(), 4, new_vesting_schedule));
assert_eq!(Vesting::vesting(&4), Some(new_vesting_schedule));
let user3_free_balance_updated = Balances::free_balance(&3);
assert_eq!(user3_free_balance_updated, 256 * 25);
let user4_free_balance_updated = Balances::free_balance(&4);
assert_eq!(user4_free_balance_updated, 256 * 45);
assert_eq!(Vesting::vesting_balance(&4), Some(256 * 5));
System::set_block_number(20);
assert_eq!(System::block_number(), 20);
assert_eq!(Vesting::vesting_balance(&4), Some(10 * 64));
System::set_block_number(30);
assert_eq!(System::block_number(), 30);
assert_eq!(Vesting::vesting_balance(&4), Some(0));
});
}
#[test]
fn vested_transfer_correctly_fails() {
ExtBuilder::default()
.existential_deposit(256)
.build()
.execute_with(|| {
let user2_free_balance = Balances::free_balance(&2);
let user4_free_balance = Balances::free_balance(&4);
assert_eq!(user2_free_balance, 256 * 20);
assert_eq!(user4_free_balance, 256 * 40);
let user2_vesting_schedule = VestingInfo {
locked: 256 * 20,
per_block: 256,
starting_block: 10,
};
assert_eq!(Vesting::vesting(&2), Some(user2_vesting_schedule));
let new_vesting_schedule = VestingInfo {
locked: 256 * 5,
per_block: 64,
starting_block: 10,
};
assert_noop!(
Vesting::vested_transfer(Some(4).into(), 2, new_vesting_schedule),
Error::<Test>::ExistingVestingSchedule,
);
let new_vesting_schedule_too_low = VestingInfo {
locked: 256 * 1,
per_block: 64,
starting_block: 10,
};
assert_noop!(
Vesting::vested_transfer(Some(3).into(), 4, new_vesting_schedule_too_low),
Error::<Test>::AmountLow,
);
assert_eq!(user2_free_balance, 256 * 20);
assert_eq!(user4_free_balance, 256 * 40);
});
}
#[test]
fn force_vested_transfer_works() {
ExtBuilder::default()
.existential_deposit(256)
.build()
.execute_with(|| {
let user3_free_balance = Balances::free_balance(&3);
let user4_free_balance = Balances::free_balance(&4);
assert_eq!(user3_free_balance, 256 * 30);
assert_eq!(user4_free_balance, 256 * 40);
assert_eq!(Vesting::vesting(&4), None);
let new_vesting_schedule = VestingInfo {
locked: 256 * 5,
per_block: 64,
starting_block: 10,
};
assert_noop!(Vesting::force_vested_transfer(Some(4).into(), 3, 4, new_vesting_schedule), BadOrigin);
assert_ok!(Vesting::force_vested_transfer(RawOrigin::Root.into(), 3, 4, new_vesting_schedule));
assert_eq!(Vesting::vesting(&4), Some(new_vesting_schedule));
let user3_free_balance_updated = Balances::free_balance(&3);
assert_eq!(user3_free_balance_updated, 256 * 25);
let user4_free_balance_updated = Balances::free_balance(&4);
assert_eq!(user4_free_balance_updated, 256 * 45);
assert_eq!(Vesting::vesting_balance(&4), Some(256 * 5));
System::set_block_number(20);
assert_eq!(System::block_number(), 20);
assert_eq!(Vesting::vesting_balance(&4), Some(10 * 64));
System::set_block_number(30);
assert_eq!(System::block_number(), 30);
assert_eq!(Vesting::vesting_balance(&4), Some(0));
});
}
#[test]
fn force_vested_transfer_correctly_fails() {
ExtBuilder::default()
.existential_deposit(256)
.build()
.execute_with(|| {
let user2_free_balance = Balances::free_balance(&2);
let user4_free_balance = Balances::free_balance(&4);
assert_eq!(user2_free_balance, 256 * 20);
assert_eq!(user4_free_balance, 256 * 40);
let user2_vesting_schedule = VestingInfo {
locked: 256 * 20,
per_block: 256,
starting_block: 10,
};
assert_eq!(Vesting::vesting(&2), Some(user2_vesting_schedule));
let new_vesting_schedule = VestingInfo {
locked: 256 * 5,
per_block: 64,
starting_block: 10,
};
assert_noop!(
Vesting::force_vested_transfer(RawOrigin::Root.into(), 4, 2, new_vesting_schedule),
Error::<Test>::ExistingVestingSchedule,
);
let new_vesting_schedule_too_low = VestingInfo {
locked: 256 * 1,
per_block: 64,
starting_block: 10,
};
assert_noop!(
Vesting::force_vested_transfer(RawOrigin::Root.into(), 3, 4, new_vesting_schedule_too_low),
Error::<Test>::AmountLow,
);
assert_eq!(user2_free_balance, 256 * 20);
assert_eq!(user4_free_balance, 256 * 40);
});
}
}