#![cfg_attr(not(feature = "std"), no_std)]
use sp_std::prelude::*;
use sp_std::fmt::Debug;
use codec::{Encode, Decode};
use sp_runtime::{DispatchResult, RuntimeDebug, traits::{
StaticLookup, Zero, AtLeast32Bit, MaybeSerializeDeserialize, Convert
}};
use frame_support::{decl_module, decl_event, decl_storage, decl_error, ensure};
use frame_support::traits::{
Currency, LockableCurrency, VestingSchedule, WithdrawReason, LockIdentifier,
ExistenceRequirement, Get
};
use frame_support::weights::SimpleDispatchInfo;
use frame_system::{self as system, ensure_signed};
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
type BalanceOf<T> = <<T as Trait>::Currency as Currency<<T as frame_system::Trait>::AccountId>>::Balance;
pub trait Trait: frame_system::Trait {
type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>;
type Currency: LockableCurrency<Self::AccountId>;
type BlockNumberToBalance: Convert<Self::BlockNumber, BalanceOf<Self>>;
type MinVestedTransfer: Get<BalanceOf<Self>>;
}
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: AtLeast32Bit + Copy,
BlockNumber: AtLeast32Bit + 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: Trait> 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 sp_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(sp_runtime::traits::One::one());
Vesting::<T>::insert(who, VestingInfo {
locked: locked,
per_block: per_block,
starting_block: begin
});
let reasons = WithdrawReason::Transfer | WithdrawReason::Reserve;
T::Currency::set_lock(VESTING_ID, who, locked, reasons);
}
})
}
}
decl_event!(
pub enum Event<T> where AccountId = <T as frame_system::Trait>::AccountId, Balance = BalanceOf<T> {
VestingUpdated(AccountId, Balance),
VestingCompleted(AccountId),
}
);
decl_error! {
pub enum Error for Module<T: Trait> {
NotVesting,
ExistingVestingSchedule,
AmountLow,
}
}
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
type Error = Error<T>;
const MinVestedTransfer: BalanceOf<T> = T::MinVestedTransfer::get();
fn deposit_event() = default;
fn vest(origin) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::update_lock(who)
}
fn vest_other(origin, target: <T::Lookup as StaticLookup>::Source) -> DispatchResult {
ensure_signed(origin)?;
Self::update_lock(T::Lookup::lookup(target)?)
}
#[weight = SimpleDispatchInfo::FixedNormal(1_000_000)]
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(())
}
}
}
impl<T: Trait> Module<T> {
fn update_lock(who: T::AccountId) -> DispatchResult {
let vesting = Self::vesting(&who).ok_or(Error::<T>::NotVesting)?;
let now = <frame_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 = WithdrawReason::Transfer | WithdrawReason::Reserve;
T::Currency::set_lock(VESTING_ID, &who, locked_now, reasons);
Self::deposit_event(RawEvent::VestingUpdated(who, locked_now));
}
Ok(())
}
}
impl<T: Trait> 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 = <frame_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 std::cell::RefCell;
use frame_support::{
assert_ok, assert_noop, impl_outer_origin, parameter_types, weights::Weight,
traits::Get
};
use sp_core::H256;
use sp_runtime::{
Perbill,
testing::Header,
traits::{BlakeTwo256, IdentityLookup, Identity},
};
impl_outer_origin! {
pub enum Origin for Test where system = frame_system {}
}
#[derive(Clone, Eq, PartialEq)]
pub struct Test;
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: Weight = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl frame_system::Trait for Test {
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Call = ();
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = ();
type BlockHashCount = BlockHashCount;
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
type ModuleToIndex = ();
type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
}
impl pallet_balances::Trait for Test {
type Balance = u64;
type DustRemoval = ();
type Event = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
}
parameter_types! {
pub const MinVestedTransfer: u64 = 256 * 2;
}
impl Trait for Test {
type Event = ();
type Currency = Balances;
type BlockNumberToBalance = Identity;
type MinVestedTransfer = MinVestedTransfer;
}
type System = frame_system::Module<Test>;
type Balances = pallet_balances::Module<Test>;
type Vesting = Module<Test>;
thread_local! {
static EXISTENTIAL_DEPOSIT: RefCell<u64> = RefCell::new(0);
}
pub struct ExistentialDeposit;
impl Get<u64> for ExistentialDeposit {
fn get() -> u64 { EXISTENTIAL_DEPOSIT.with(|v| *v.borrow()) }
}
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) -> sp_io::TestExternalities {
EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit);
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
pallet_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();
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();
t.into()
}
}
#[test]
fn check_vesting_status() {
ExtBuilder::default()
.existential_deposit(256)
.build()
.execute_with(|| {
assert_eq!(System::block_number(), 1);
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(|| {
assert_eq!(System::block_number(), 1);
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),
pallet_balances::Error::<Test, _>::LiquidityRestrictions,
);
});
}
#[test]
fn vested_balance_should_transfer() {
ExtBuilder::default()
.existential_deposit(10)
.build()
.execute_with(|| {
assert_eq!(System::block_number(), 1);
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(|| {
assert_eq!(System::block_number(), 1);
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_eq!(System::block_number(), 1);
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(|| {
assert_eq!(System::block_number(), 1);
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(|| {
assert_eq!(System::block_number(), 1);
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(|| {
assert_eq!(System::block_number(), 1);
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);
});
}
}