Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace Currency->fungible trait migration for time-release pallet #1818

Merged
merged 14 commits into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from 11 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
237 changes: 114 additions & 123 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion e2e/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion pallets/time-release/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,12 @@ sp-io = { workspace = true }
sp-runtime = { workspace = true }
sp-std = { workspace = true }
frame-benchmarking = { workspace = true, optional = true }
sp-core = { workspace = true }
log = { workspace = true, default-features = false }

[dev-dependencies]
chrono = { workspace = true }
pallet-balances = { workspace = true }
sp-core = { workspace = true }
common-primitives = { default-features = false, path = "../../common/primitives" }

[features]
Expand Down
10 changes: 4 additions & 6 deletions pallets/time-release/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use super::*;
use crate::Pallet as TimeReleasePallet;

use frame_benchmarking::{account, benchmarks, whitelist_account, whitelisted_caller};
use frame_support::traits::{Currency, Imbalance};
use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin};
use sp_runtime::{traits::TrailingZeroInput, SaturatedConversion};
use sp_std::prelude::*;
Expand All @@ -17,9 +16,8 @@ pub type Schedule<T> = ReleaseSchedule<BlockNumberFor<T>, BalanceOf<T>>;
const SEED: u32 = 0;

fn set_balance<T: Config>(who: &T::AccountId, balance: BalanceOf<T>) {
let deposit_result = T::Currency::deposit_creating(who, balance.saturated_into());
let actual_deposit = deposit_result.peek();
assert_eq!(balance, actual_deposit);
let actual_deposit = T::Currency::mint_into(&who, balance.saturated_into());
assert_eq!(balance, actual_deposit.unwrap());
}

fn lookup_of_account<T: Config>(
Expand Down Expand Up @@ -76,7 +74,7 @@ benchmarks! {
}: _(RawOrigin::Signed(to.clone()))
verify {
assert_eq!(
T::Currency::free_balance(&to),
T::Currency::balance(&to),
schedule.total_amount().unwrap() * BalanceOf::<T>::from(i) ,
);
}
Expand All @@ -103,7 +101,7 @@ benchmarks! {
}: _(RawOrigin::Root, to_lookup, schedules)
verify {
assert_eq!(
T::Currency::free_balance(&to),
T::Currency::balance(&to),
schedule.total_amount().unwrap() * BalanceOf::<T>::from(i)
);
}
Expand Down
95 changes: 60 additions & 35 deletions pallets/time-release/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,22 @@
)]

use frame_support::{
dispatch::DispatchResult,
ensure,
pallet_prelude::*,
traits::{
BuildGenesisConfig, Currency, EnsureOrigin, ExistenceRequirement, Get, LockIdentifier,
LockableCurrency, WithdrawReasons,
tokens::{
fungible::{Inspect as InspectFungible, Mutate, MutateFreeze},
Balance, Preservation,
},
BuildGenesisConfig, EnsureOrigin, Get,
},
BoundedVec,
};
use frame_system::{ensure_root, ensure_signed, pallet_prelude::*};
use sp_runtime::{
traits::{BlockNumberProvider, CheckedAdd, StaticLookup, Zero},
ArithmeticError, DispatchResult,
ArithmeticError,
};
use sp_std::vec::Vec;

Expand All @@ -57,6 +61,9 @@
#[cfg(test)]
mod tests;

/// storage migrations
pub mod migration;

mod types;
pub use types::*;

Expand All @@ -68,15 +75,13 @@

pub use module::*;

/// The lock identifier for timed released transfers.
pub const RELEASE_LOCK_ID: LockIdentifier = *b"timeRels";

#[frame_support::pallet]
pub mod module {
use super::*;

pub(crate) type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
pub(crate) type BalanceOf<T> = <<T as Config>::Currency as InspectFungible<
<T as frame_system::Config>::AccountId,
>>::Balance;
pub(crate) type ReleaseScheduleOf<T> = ReleaseSchedule<BlockNumberFor<T>, BalanceOf<T>>;

/// Scheduled item used for configuring genesis.
Expand All @@ -88,13 +93,32 @@
BalanceOf<T>,
);

/// A reason for freezing funds.
/// Creates a freeze reason for this pallet that is aggregated by `construct_runtime`.
#[pallet::composite_enum]
pub enum FreezeReason {
/// Funds are currently locked and are not yet liquid.
TimeReleaseVesting,
}

/// the storage version for this pallet
pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);

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

/// The overarching freeze reason.
type RuntimeFreezeReason: From<FreezeReason>;

/// We need MaybeSerializeDeserialize because of the genesis config.
type Balance: Balance + MaybeSerializeDeserialize;

/// The currency trait used to set a lock on a balance.
type Currency: LockableCurrency<Self::AccountId, Moment = BlockNumberFor<Self>>;
type Currency: MutateFreeze<Self::AccountId, Id = Self::RuntimeFreezeReason>
+ InspectFungible<Self::AccountId, Balance = Self::Balance>
+ Mutate<Self::AccountId>;

#[pallet::constant]
/// The minimum amount transferred to call `transfer`.
Expand Down Expand Up @@ -207,22 +231,23 @@
.expect("Invalid release schedule");

assert!(
T::Currency::free_balance(who) >= total_amount,
T::Currency::balance(who) >= total_amount,
"Account do not have enough balance"
mattheworris marked this conversation as resolved.
Show resolved Hide resolved
);

T::Currency::set_lock(
RELEASE_LOCK_ID,
T::Currency::set_freeze(
&FreezeReason::TimeReleaseVesting.into(),
who,
total_amount,
WithdrawReasons::all(),
);
)
.expect("Failed to set freeze");
ReleaseSchedules::<T>::insert(who, bounded_schedules);
});
}
}

#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]

Check warning on line 250 in pallets/time-release/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

pallets/time-release/src/lib.rs#L250

Added line #L250 was not covered by tests
pub struct Pallet<T>(_);

#[pallet::hooks]
Expand All @@ -239,7 +264,7 @@
#[pallet::weight(T::WeightInfo::claim(<T as Config>::MaxReleaseSchedules::get() / 2))]
pub fn claim(origin: OriginFor<T>) -> DispatchResult {
let who = ensure_signed(origin)?;
let locked_amount = Self::do_claim(&who);
let locked_amount = Self::do_claim(&who)?;

Self::deposit_event(Event::Claimed { who, amount: locked_amount });
Ok(())
Expand Down Expand Up @@ -268,7 +293,7 @@

if to == from {
ensure!(
T::Currency::free_balance(&from) >=
T::Currency::balance(&from) >=
schedule.total_amount().ok_or(ArithmeticError::Overflow)?,
Error::<T>::InsufficientBalanceToLock,
);
Expand Down Expand Up @@ -324,7 +349,7 @@
) -> DispatchResult {
ensure_signed(origin)?;
let who = T::Lookup::lookup(dest)?;
let locked_amount = Self::do_claim(&who);
let locked_amount = Self::do_claim(&who)?;

Self::deposit_event(Event::Claimed { who, amount: locked_amount });
Ok(())
Expand All @@ -333,15 +358,15 @@
}

impl<T: Config> Pallet<T> {
fn do_claim(who: &T::AccountId) -> BalanceOf<T> {
fn do_claim(who: &T::AccountId) -> Result<BalanceOf<T>, DispatchError> {
let locked = Self::prune_and_get_locked_balance(who);
if locked.is_zero() {
Self::delete_lock(who);
Self::delete_lock(who)?;
mattheworris marked this conversation as resolved.
Show resolved Hide resolved
} else {
Self::update_lock(who, locked);
Self::update_lock(who, locked)?;
}

locked
Ok(locked)
}

/// Deletes schedules that have released all funds up to a block-number.
Expand Down Expand Up @@ -385,9 +410,9 @@
.checked_add(&schedule_amount)
.ok_or(ArithmeticError::Overflow)?;

T::Currency::transfer(from, to, schedule_amount, ExistenceRequirement::AllowDeath)?;
T::Currency::transfer(from, to, schedule_amount, Preservation::Expendable)?;

Self::update_lock(&to, total_amount);
Self::update_lock(&to, total_amount)?;

<ReleaseSchedules<T>>::try_append(to, schedule)
.map_err(|_| Error::<T>::MaxReleaseSchedulesExceeded)?;
Expand All @@ -405,7 +430,7 @@

// empty release schedules cleanup the storage and unlock the fund
if bounded_schedules.is_empty() {
Self::delete_release_schedules(who);
Self::delete_release_schedules(who)?;
return Ok(())
}

Expand All @@ -418,23 +443,22 @@
},
)?;

ensure!(
T::Currency::free_balance(who) >= total_amount,
Error::<T>::InsufficientBalanceToLock,
);
ensure!(T::Currency::balance(who) >= total_amount, Error::<T>::InsufficientBalanceToLock,);

Self::update_lock(&who, total_amount);
Self::update_lock(&who, total_amount)?;
Self::set_schedules_for(who, bounded_schedules);

Ok(())
}

fn update_lock(who: &T::AccountId, locked: BalanceOf<T>) {
T::Currency::set_lock(RELEASE_LOCK_ID, who, locked, WithdrawReasons::all());
fn update_lock(who: &T::AccountId, locked: BalanceOf<T>) -> DispatchResult {
T::Currency::set_freeze(&FreezeReason::TimeReleaseVesting.into(), who, locked)?;
Ok(())
}

fn delete_lock(who: &T::AccountId) {
T::Currency::remove_lock(RELEASE_LOCK_ID, who);
fn delete_lock(who: &T::AccountId) -> DispatchResult {
T::Currency::thaw(&FreezeReason::TimeReleaseVesting.into(), who)?;
Ok(())
}

fn set_schedules_for(
Expand All @@ -444,9 +468,10 @@
ReleaseSchedules::<T>::insert(who, schedules);
}

fn delete_release_schedules(who: &T::AccountId) {
fn delete_release_schedules(who: &T::AccountId) -> DispatchResult {
<ReleaseSchedules<T>>::remove(who);
Self::delete_lock(who);
Self::delete_lock(who)?;
Ok(())
}
}

Expand Down
2 changes: 2 additions & 0 deletions pallets/time-release/src/migration/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/// migrations to v2
pub mod v2;
Loading
Loading