Skip to content

Commit

Permalink
Migrate pallet-assets-freezer to umbrella crate (#6599)
Browse files Browse the repository at this point in the history
Part of #6504

### Added modules

- `utility`: Traits not tied to any direct operation in the runtime.

polkadot address: 14SRqZTC1d8rfxL8W1tBTnfUBPU23ACFVPzp61FyGf4ftUFg

---------

Co-authored-by: Giuseppe Re <[email protected]>
  • Loading branch information
runcomet and re-gius authored Jan 20, 2025
1 parent 569ce71 commit 711e6ff
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 89 deletions.
7 changes: 1 addition & 6 deletions Cargo.lock

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

23 changes: 4 additions & 19 deletions substrate/frame/assets-freezer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,46 +16,31 @@ targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
codec = { workspace = true }
frame-benchmarking = { optional = true, workspace = true }
frame-support = { workspace = true }
frame-system = { workspace = true }
frame = { workspace = true, features = ["runtime"] }
log = { workspace = true }
pallet-assets = { workspace = true }
scale-info = { features = ["derive"], workspace = true }
sp-runtime = { workspace = true }

[dev-dependencies]
pallet-balances = { workspace = true }
sp-core = { workspace = true }
sp-io = { workspace = true }

[features]
default = ["std"]
std = [
"codec/std",
"frame-benchmarking?/std",
"frame-support/std",
"frame-system/std",
"frame/std",
"log/std",
"pallet-assets/std",
"pallet-balances/std",
"scale-info/std",
"sp-core/std",
"sp-io/std",
"sp-runtime/std",
]
runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"frame/runtime-benchmarks",
"pallet-assets/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
]
try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
"frame/try-runtime",
"pallet-assets/try-runtime",
"pallet-balances/try-runtime",
"sp-runtime/try-runtime",
]
12 changes: 3 additions & 9 deletions substrate/frame/assets-freezer/src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,7 @@
// limitations under the License.

use super::*;

use frame_support::traits::{
fungibles::{Inspect, InspectFreeze, MutateFreeze},
tokens::{DepositConsequence, Fortitude, Preservation, Provenance, WithdrawConsequence},
};
use pallet_assets::FrozenBalance;
use sp_runtime::traits::Zero;

// Implements [`FrozenBalance`] from [`pallet-assets`], so it can understand how much of an
// account balance is frozen, and is able to signal to this pallet when to clear the state of an
Expand Down Expand Up @@ -115,7 +109,7 @@ impl<T: Config<I>, I: 'static> MutateFreeze<T::AccountId> for Pallet<T, I> {
id: &Self::Id,
who: &T::AccountId,
amount: Self::Balance,
) -> sp_runtime::DispatchResult {
) -> DispatchResult {
if amount.is_zero() {
return Self::thaw(asset, id, who);
}
Expand All @@ -135,7 +129,7 @@ impl<T: Config<I>, I: 'static> MutateFreeze<T::AccountId> for Pallet<T, I> {
id: &Self::Id,
who: &T::AccountId,
amount: Self::Balance,
) -> sp_runtime::DispatchResult {
) -> DispatchResult {
if amount.is_zero() {
return Ok(());
}
Expand All @@ -150,7 +144,7 @@ impl<T: Config<I>, I: 'static> MutateFreeze<T::AccountId> for Pallet<T, I> {
Self::update_freezes(asset, who, freezes.as_bounded_slice())
}

fn thaw(asset: Self::AssetId, id: &Self::Id, who: &T::AccountId) -> sp_runtime::DispatchResult {
fn thaw(asset: Self::AssetId, id: &Self::Id, who: &T::AccountId) -> DispatchResult {
let mut freezes = Freezes::<T, I>::get(asset.clone(), who);
freezes.retain(|f| &f.id != id);
Self::update_freezes(asset, who, freezes.as_bounded_slice())
Expand Down
43 changes: 22 additions & 21 deletions substrate/frame/assets-freezer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@
//! # Assets Freezer Pallet
//!
//! A pallet capable of freezing fungibles from `pallet-assets`. This is an extension of
//! `pallet-assets`, wrapping [`fungibles::Inspect`](`frame_support::traits::fungibles::Inspect`).
//! `pallet-assets`, wrapping [`fungibles::Inspect`](`Inspect`).
//! It implements both
//! [`fungibles::freeze::Inspect`](frame_support::traits::fungibles::freeze::Inspect) and
//! [`fungibles::freeze::Mutate`](frame_support::traits::fungibles::freeze::Mutate). The complexity
//! [`fungibles::freeze::Inspect`](InspectFreeze) and
//! [`fungibles::freeze::Mutate`](MutateFreeze). The complexity
//! of the operations is `O(n)`. where `n` is the variant count of `RuntimeFreezeReason`.
//!
//! ## Pallet API
Expand All @@ -35,34 +35,35 @@
//!
//! - Pallet hooks allowing [`pallet-assets`] to know the frozen balance for an account on a given
//! asset (see [`pallet_assets::FrozenBalance`]).
//! - An implementation of
//! [`fungibles::freeze::Inspect`](frame_support::traits::fungibles::freeze::Inspect) and
//! [`fungibles::freeze::Mutate`](frame_support::traits::fungibles::freeze::Mutate), allowing
//! other pallets to manage freezes for the `pallet-assets` assets.
//! - An implementation of [`fungibles::freeze::Inspect`](InspectFreeze) and
//! [`fungibles::freeze::Mutate`](MutateFreeze), allowing other pallets to manage freezes for the
//! `pallet-assets` assets.
#![cfg_attr(not(feature = "std"), no_std)]

use frame_support::{
pallet_prelude::*,
traits::{tokens::IdAmount, VariantCount, VariantCountOf},
BoundedVec,
};
use frame_system::pallet_prelude::BlockNumberFor;
use sp_runtime::{
traits::{Saturating, Zero},
BoundedSlice,
use frame::{
prelude::*,
traits::{
fungibles::{Inspect, InspectFreeze, MutateFreeze},
tokens::{
DepositConsequence, Fortitude, IdAmount, Preservation, Provenance, WithdrawConsequence,
},
},
};

pub use pallet::*;

#[cfg(feature = "try-runtime")]
use frame::try_runtime::TryRuntimeError;

#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;

mod impls;

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

Expand Down Expand Up @@ -125,7 +126,7 @@ pub mod pallet {
#[pallet::hooks]
impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
#[cfg(feature = "try-runtime")]
fn try_state(_: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
fn try_state(_: BlockNumberFor<T>) -> Result<(), TryRuntimeError> {
Self::do_try_state()
}
}
Expand Down Expand Up @@ -159,13 +160,13 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
Ok(())
}

#[cfg(any(test, feature = "try-runtime"))]
fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
#[cfg(feature = "try-runtime")]
fn do_try_state() -> Result<(), TryRuntimeError> {
for (asset, who, _) in FrozenBalances::<T, I>::iter() {
let max_frozen_amount =
Freezes::<T, I>::get(asset.clone(), who.clone()).iter().map(|l| l.amount).max();

frame_support::ensure!(
ensure!(
FrozenBalances::<T, I>::get(asset, who) == max_frozen_amount,
"The `FrozenAmount` is not equal to the maximum amount in `Freezes` for (`asset`, `who`)"
);
Expand Down
23 changes: 8 additions & 15 deletions substrate/frame/assets-freezer/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,15 @@
use crate as pallet_assets_freezer;
pub use crate::*;
use codec::{Compact, Decode, Encode, MaxEncodedLen};
use frame_support::{
derive_impl,
traits::{AsEnsureOriginWithArg, ConstU64},
};
use frame::testing_prelude::*;
use scale_info::TypeInfo;
use sp_core::{ConstU32, H256};
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
BuildStorage,
};

pub type AccountId = u64;
pub type Balance = u64;
pub type AssetId = u32;
type Block = frame_system::mocking::MockBlock<Test>;

frame_support::construct_runtime!(
construct_runtime!(
pub enum Test
{
System: frame_system,
Expand All @@ -48,7 +40,7 @@ frame_support::construct_runtime!(

#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for Test {
type BaseCallFilter = frame_support::traits::Everything;
type BaseCallFilter = Everything;
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
Expand All @@ -70,7 +62,7 @@ impl frame_system::Config for Test {
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = frame_support::traits::ConstU32<16>;
type MaxConsumers = ConstU32<16>;
}

impl pallet_balances::Config for Test {
Expand Down Expand Up @@ -132,7 +124,7 @@ impl Config for Test {
type RuntimeEvent = RuntimeEvent;
}

pub fn new_test_ext(execute: impl FnOnce()) -> sp_io::TestExternalities {
pub fn new_test_ext(execute: impl FnOnce()) -> TestExternalities {
let t = RuntimeGenesisConfig {
assets: pallet_assets::GenesisConfig {
assets: vec![(1, 0, true, 1)],
Expand All @@ -145,11 +137,12 @@ pub fn new_test_ext(execute: impl FnOnce()) -> sp_io::TestExternalities {
}
.build_storage()
.unwrap();
let mut ext: sp_io::TestExternalities = t.into();
let mut ext: TestExternalities = t.into();
ext.execute_with(|| {
System::set_block_number(1);
execute();
frame_support::assert_ok!(AssetsFreezer::do_try_state());
#[cfg(feature = "try-runtime")]
assert_ok!(AssetsFreezer::do_try_state());
});

ext
Expand Down
16 changes: 4 additions & 12 deletions substrate/frame/assets-freezer/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,16 @@

//! Tests for pallet-assets-freezer.
use crate::mock::*;
use crate::mock::{self, *};

use codec::Compact;
use frame_support::{
assert_ok, assert_storage_noop,
traits::{
fungibles::{Inspect, InspectFreeze, MutateFreeze},
tokens::{Fortitude, Preservation},
},
};
use frame::testing_prelude::*;
use pallet_assets::FrozenBalance;

const WHO: AccountId = 1;
const ASSET_ID: AssetId = 1;
const ASSET_ID: mock::AssetId = 1;

fn test_set_freeze(id: DummyFreezeReason, amount: Balance) {
fn test_set_freeze(id: DummyFreezeReason, amount: mock::Balance) {
let mut freezes = Freezes::<Test>::get(ASSET_ID, WHO);

if let Some(i) = freezes.iter_mut().find(|l| l.id == id) {
Expand Down Expand Up @@ -281,8 +275,6 @@ mod impl_mutate_freeze {
}

mod with_pallet_assets {
use frame_support::assert_noop;

use super::*;

#[test]
Expand Down
29 changes: 22 additions & 7 deletions substrate/frame/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,12 +202,10 @@ pub mod prelude {
/// Dispatch types from `frame-support`, other fundamental traits
#[doc(no_inline)]
pub use frame_support::dispatch::{GetDispatchInfo, PostDispatchInfo};
pub use frame_support::{
defensive, defensive_assert,
traits::{
Contains, EitherOf, EstimateNextSessionRotation, IsSubType, MapSuccess, NoOpPoll,
OnRuntimeUpgrade, OneSessionHandler, RankedMembers, RankedMembersSwapHandler,
},
pub use frame_support::traits::{
Contains, EitherOf, EstimateNextSessionRotation, Everything, IsSubType, MapSuccess,
NoOpPoll, OnRuntimeUpgrade, OneSessionHandler, RankedMembers, RankedMembersSwapHandler,
VariantCount, VariantCountOf,
};

/// Pallet prelude of `frame-system`.
Expand All @@ -225,6 +223,9 @@ pub mod prelude {
/// All hashing related things
pub use super::hashing::*;

/// All account related things.
pub use super::account::*;

/// All arithmetic types and traits used for safe math.
pub use super::arithmetic::*;

Expand All @@ -234,6 +235,10 @@ pub mod prelude {
BlockNumberProvider, Bounded, Convert, DispatchInfoOf, Dispatchable, ReduceBy,
ReplaceWithDefault, SaturatedConversion, Saturating, StaticLookup, TrailingZeroInput,
};

/// Bounded storage related types.
pub use sp_runtime::{BoundedSlice, BoundedVec};

/// Other error/result types for runtime
#[doc(no_inline)]
pub use sp_runtime::{
Expand Down Expand Up @@ -321,7 +326,7 @@ pub mod testing_prelude {
/// Other helper macros from `frame_support` that help with asserting in tests.
pub use frame_support::{
assert_err, assert_err_ignore_postinfo, assert_error_encoded_size, assert_noop, assert_ok,
assert_storage_noop, hypothetically, storage_alias,
assert_storage_noop, ensure, hypothetically, storage_alias,
};

pub use frame_system::{self, mocking::*, RunToBlockHooks};
Expand Down Expand Up @@ -551,6 +556,16 @@ pub mod hashing {
pub use sp_runtime::traits::{BlakeTwo256, Hash, Keccak256};
}

/// All account management related traits.
///
/// This is already part of the [`prelude`].
pub mod account {
pub use frame_support::traits::{
AsEnsureOriginWithArg, ChangeMembers, EitherOfDiverse, InitializeMembers,
};
pub use sp_runtime::traits::{IdentifyAccount, IdentityLookup};
}

/// Access to all of the dependencies of this crate. In case the prelude re-exports are not enough,
/// this module can be used.
///
Expand Down

0 comments on commit 711e6ff

Please sign in to comment.