Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Migrate pallet-vesting to pallet attribute macro. #8440

Merged
4 commits merged into from
Mar 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion frame/vesting/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use frame_system::{RawOrigin, Pallet as System};
use frame_benchmarking::{benchmarks, account, whitelisted_caller, impl_benchmark_test_suite};
use sp_runtime::traits::Bounded;

use crate::Module as Vesting;
use crate::Pallet as Vesting;

const SEED: u32 = 0;

Expand Down
165 changes: 94 additions & 71 deletions frame/vesting/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@
// See the License for the specific language governing permissions and
// limitations under the License.

//! # Vesting Module
//! # Vesting Pallet
//!
//! - [`Config`]
//! - [`Call`]
//!
//! ## Overview
//!
//! A simple module providing a means of placing a linear curve on an account's locked balance. This
//! module ensures that there is a lock in place preventing the balance to drop below the *unvested*
//! A simple pallet providing a means of placing a linear curve on an account's locked balance. This
//! pallet ensures that there is a lock in place preventing the balance to drop below the *unvested*
//! amount for any reason other than transaction fee payment.
//!
//! As the amount vested increases over time, the amount unvested reduces. However, locks remain in
Expand All @@ -34,7 +34,7 @@
//!
//! ## Interface
//!
//! This module implements the `VestingSchedule` trait.
//! This pallet implements the `VestingSchedule` trait.
//!
//! ### Dispatchable Functions
//!
Expand All @@ -50,37 +50,21 @@ pub mod weights;
use sp_std::prelude::*;
use sp_std::fmt::Debug;
use codec::{Encode, Decode};
use sp_runtime::{DispatchResult, RuntimeDebug, traits::{
use sp_runtime::{RuntimeDebug, traits::{
StaticLookup, Zero, AtLeast32BitUnsigned, MaybeSerializeDeserialize, Convert
}};
use frame_support::{decl_module, decl_event, decl_storage, decl_error, ensure};
use frame_support::{ensure, pallet_prelude::*};
use frame_support::traits::{
Currency, LockableCurrency, VestingSchedule, WithdrawReasons, LockIdentifier,
ExistenceRequirement, Get,
};
use frame_system::{ensure_signed, ensure_root};
use frame_system::{ensure_signed, ensure_root, pallet_prelude::*};
pub use weights::WeightInfo;
pub use pallet::*;

type BalanceOf<T> = <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
type MaxLocksOf<T> = <<T as Config>::Currency as LockableCurrency<<T as frame_system::Config>::AccountId>>::MaxLocks;

pub trait Config: frame_system::Config {
/// The overarching event type.
type Event: From<Event<Self>> + Into<<Self as frame_system::Config>::Event>;

/// The currency trait.
type Currency: LockableCurrency<Self::AccountId>;

/// Convert the block number into a balance.
type BlockNumberToBalance: Convert<Self::BlockNumber, BalanceOf<Self>>;

/// The minimum amount transferred to call `vested_transfer`.
type MinVestedTransfer: Get<BalanceOf<Self>>;

/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
}

const VESTING_ID: LockIdentifier = *b"vesting ";

/// Struct to encode the vesting schedule of an individual account.
Expand Down Expand Up @@ -116,23 +100,68 @@ impl<
}
}

decl_storage! {
trait Store for Module<T: Config> as Vesting {
/// Information regarding the vesting of a given account.
pub Vesting get(fn vesting):
map hasher(blake2_128_concat) T::AccountId
=> Option<VestingInfo<BalanceOf<T>, T::BlockNumber>>;
#[frame_support::pallet]
pub mod pallet {
use super::*;

#[pallet::config]
pub trait Config: frame_system::Config {
/// The overarching event type.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;

/// The currency trait.
type Currency: LockableCurrency<Self::AccountId>;

/// Convert the block number into a balance.
type BlockNumberToBalance: Convert<Self::BlockNumber, BalanceOf<Self>>;

/// The minimum amount transferred to call `vested_transfer`.
#[pallet::constant]
type MinVestedTransfer: Get<BalanceOf<Self>>;

/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
}

/// Information regarding the vesting of a given account.
#[pallet::storage]
#[pallet::getter(fn vesting)]
pub type Vesting<T: Config> = StorageMap<
_,
Blake2_128Concat,
T::AccountId,
VestingInfo<BalanceOf<T>, T::BlockNumber>,
>;

#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);

#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub vesting: Vec<(T::AccountId, T::BlockNumber, T::BlockNumber, BalanceOf<T>)>,
}
add_extra_genesis {
config(vesting): Vec<(T::AccountId, T::BlockNumber, T::BlockNumber, BalanceOf<T>)>;
build(|config: &GenesisConfig<T>| {

#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
GenesisConfig {
vesting: Default::default(),
}
}
}

#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
fn build(&self) {
use sp_runtime::traits::Saturating;

// Generate initial vesting configuration
// * who - Account which we are generating vesting configuration for
// * begin - Block when the account will start to vest
// * length - Number of blocks from `begin` until fully vested
// * liquid - Number of units which can be spent before vesting begins
for &(ref who, begin, length, liquid) in config.vesting.iter() {
for &(ref who, begin, length, liquid) in self.vesting.iter() {
let balance = T::Currency::free_balance(who);
assert!(!balance.is_zero(), "Currencies must be init'd before vesting");
// Total genesis `balance` minus `liquid` equals funds locked for vesting
Expand All @@ -148,47 +177,41 @@ decl_storage! {
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 frame_system::Config>::AccountId, Balance = BalanceOf<T> {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
#[pallet::metadata(T::AccountId = "AccountId", BalanceOf<T> = "Balance")]
pub enum Event<T: Config> {
/// The amount vested has been updated. This could indicate more funds are available. The
/// balance given is the amount which is left unvested (and thus locked).
/// \[account, unvested\]
VestingUpdated(AccountId, Balance),
VestingUpdated(T::AccountId, BalanceOf<T>),
/// An \[account\] has become fully vested. No further vesting can happen.
VestingCompleted(AccountId),
VestingCompleted(T::AccountId),
}
);

decl_error! {
/// Error for the vesting module.
pub enum Error for Module<T: Config> {
/// Error for the vesting pallet.
#[pallet::error]
pub enum Error<T> {
/// The account given is not vesting.
NotVesting,
/// An existing vesting schedule already exists for this account that cannot be clobbered.
ExistingVestingSchedule,
/// Amount being transferred is too low to create a vesting schedule.
AmountLow,
}
}

decl_module! {
/// Vesting module declaration.
pub struct Module<T: Config> for enum Call where origin: T::Origin {
type Error = Error<T>;

/// The minimum amount to be transferred to create a new vesting schedule.
const MinVestedTransfer: BalanceOf<T> = T::MinVestedTransfer::get();

fn deposit_event() = default;
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}

#[pallet::call]
impl<T: Config> Pallet<T> {
/// Unlock any vested funds of the sender account.
///
/// The dispatch origin for this call must be _Signed_ and the sender must have funds still
/// locked under this module.
/// locked under this pallet.
///
/// Emits either `VestingCompleted` or `VestingUpdated`.
///
Expand All @@ -198,10 +221,10 @@ decl_module! {
/// - Reads: Vesting Storage, Balances Locks, [Sender Account]
/// - Writes: Vesting Storage, Balances Locks, [Sender Account]
/// # </weight>
#[weight = T::WeightInfo::vest_locked(MaxLocksOf::<T>::get())
#[pallet::weight(T::WeightInfo::vest_locked(MaxLocksOf::<T>::get())
.max(T::WeightInfo::vest_unlocked(MaxLocksOf::<T>::get()))
]
fn vest(origin) -> DispatchResult {
)]
pub fn vest(origin: OriginFor<T>) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::update_lock(who)
}
Expand All @@ -211,7 +234,7 @@ decl_module! {
/// The dispatch origin for this call must be _Signed_.
///
/// - `target`: The account whose vested funds should be unlocked. Must have funds still
/// locked under this module.
/// locked under this pallet.
///
/// Emits either `VestingCompleted` or `VestingUpdated`.
///
Expand All @@ -221,10 +244,10 @@ decl_module! {
/// - Reads: Vesting Storage, Balances Locks, Target Account
/// - Writes: Vesting Storage, Balances Locks, Target Account
/// # </weight>
#[weight = T::WeightInfo::vest_other_locked(MaxLocksOf::<T>::get())
#[pallet::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 {
)]
pub fn vest_other(origin: OriginFor<T>, target: <T::Lookup as StaticLookup>::Source) -> DispatchResult {
ensure_signed(origin)?;
Self::update_lock(T::Lookup::lookup(target)?)
}
Expand All @@ -245,9 +268,9 @@ decl_module! {
/// - Reads: Vesting Storage, Balances Locks, Target Account, [Sender Account]
/// - Writes: Vesting Storage, Balances Locks, Target Account, [Sender Account]
/// # </weight>
#[weight = T::WeightInfo::vested_transfer(MaxLocksOf::<T>::get())]
#[pallet::weight(T::WeightInfo::vested_transfer(MaxLocksOf::<T>::get()))]
pub fn vested_transfer(
origin,
origin: OriginFor<T>,
target: <T::Lookup as StaticLookup>::Source,
schedule: VestingInfo<BalanceOf<T>, T::BlockNumber>,
) -> DispatchResult {
Expand Down Expand Up @@ -282,9 +305,9 @@ decl_module! {
/// - Reads: Vesting Storage, Balances Locks, Target Account, Source Account
/// - Writes: Vesting Storage, Balances Locks, Target Account, Source Account
/// # </weight>
#[weight = T::WeightInfo::force_vested_transfer(MaxLocksOf::<T>::get())]
#[pallet::weight(T::WeightInfo::force_vested_transfer(MaxLocksOf::<T>::get()))]
pub fn force_vested_transfer(
origin,
origin: OriginFor<T>,
source: <T::Lookup as StaticLookup>::Source,
target: <T::Lookup as StaticLookup>::Source,
schedule: VestingInfo<BalanceOf<T>, T::BlockNumber>,
Expand All @@ -306,8 +329,8 @@ decl_module! {
}
}

impl<T: Config> Module<T> {
/// (Re)set or remove the module's currency lock on `who`'s account in accordance with their
impl<T: Config> Pallet<T> {
/// (Re)set or remove the pallet's currency lock on `who`'s account in accordance with their
/// current unvested amount.
fn update_lock(who: T::AccountId) -> DispatchResult {
let vesting = Self::vesting(&who).ok_or(Error::<T>::NotVesting)?;
Expand All @@ -317,17 +340,17 @@ impl<T: Config> Module<T> {
if locked_now.is_zero() {
T::Currency::remove_lock(VESTING_ID, &who);
Vesting::<T>::remove(&who);
Self::deposit_event(RawEvent::VestingCompleted(who));
Self::deposit_event(Event::<T>::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));
Self::deposit_event(Event::<T>::VestingUpdated(who, locked_now));
}
Ok(())
}
}

impl<T: Config> VestingSchedule<T::AccountId> for Module<T> where
impl<T: Config> VestingSchedule<T::AccountId> for Pallet<T> where
BalanceOf<T>: MaybeSerializeDeserialize + Debug
{
type Moment = T::BlockNumber;
Expand Down