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

Add Storage Info to Various Pallets #10810

Merged
merged 28 commits into from
Feb 8, 2022
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
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
13 changes: 9 additions & 4 deletions frame/atomic-swap/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ mod tests;
use codec::{Decode, Encode};
use frame_support::{
dispatch::DispatchResult,
pallet_prelude::MaxEncodedLen,
traits::{BalanceStatus, Currency, Get, ReservableCurrency},
weights::Weight,
RuntimeDebugNoBound,
Expand All @@ -59,8 +60,9 @@ use sp_std::{
};

/// Pending atomic swap operation.
#[derive(Clone, Eq, PartialEq, RuntimeDebugNoBound, Encode, Decode, TypeInfo)]
#[derive(Clone, Eq, PartialEq, RuntimeDebugNoBound, Encode, Decode, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(T))]
#[codec(mel_bound(T: Config))]
pub struct PendingSwap<T: Config> {
/// Source of the swap.
pub source: T::AccountId,
Expand Down Expand Up @@ -93,8 +95,9 @@ pub trait SwapAction<AccountId, T: Config> {
}

/// A swap action that only allows transferring balances.
#[derive(Clone, RuntimeDebug, Eq, PartialEq, Encode, Decode, TypeInfo)]
#[derive(Clone, RuntimeDebug, Eq, PartialEq, Encode, Decode, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(C))]
#[codec(mel_bound(C: ReservableCurrency<AccountId>))]
KiChjang marked this conversation as resolved.
Show resolved Hide resolved
pub struct BalanceSwapAction<AccountId, C: ReservableCurrency<AccountId>> {
value: <C as Currency<AccountId>>::Balance,
_marker: PhantomData<C>,
Expand Down Expand Up @@ -165,7 +168,7 @@ pub mod pallet {
/// The overarching event type.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
/// Swap action.
type SwapAction: SwapAction<Self::AccountId, Self> + Parameter;
type SwapAction: SwapAction<Self::AccountId, Self> + Parameter + MaxEncodedLen;
/// Limit of proof size.
///
/// Atomic swap is only atomic if once the proof is revealed, both parties can submit the
Expand All @@ -182,7 +185,6 @@ pub mod pallet {

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

#[pallet::storage]
Expand All @@ -193,6 +195,9 @@ pub mod pallet {
Blake2_128Concat,
HashedProof,
PendingSwap<T>,
OptionQuery,
GetDefault,
ConstU32<300_000>,
ggwpez marked this conversation as resolved.
Show resolved Hide resolved
>;

#[pallet::error]
Expand Down
30 changes: 18 additions & 12 deletions frame/bounties/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ type PositiveImbalanceOf<T> = pallet_treasury::PositiveImbalanceOf<T>;
pub type BountyIndex = u32;

/// A bounty proposal.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
pub struct Bounty<AccountId, Balance, BlockNumber> {
/// The account proposing it.
proposer: AccountId,
Expand All @@ -133,7 +133,7 @@ impl<AccountId: PartialEq + Clone + Ord, Balance, BlockNumber: Clone>
}

/// The status of a bounty proposal.
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
pub enum BountyStatus<AccountId, BlockNumber> {
/// The bounty is proposed and waiting for approval.
Proposed,
Expand Down Expand Up @@ -180,7 +180,6 @@ pub mod pallet {

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

#[pallet::config]
Expand Down Expand Up @@ -224,6 +223,10 @@ pub mod pallet {

/// The child-bounty manager.
type ChildBountyManager: ChildBountyManager<BalanceOf<Self>>;

/// Maximum number of approved bounties queued.
#[pallet::constant]
type MaxBountiesQueued: Get<u32>;
}

#[pallet::error]
Expand All @@ -249,6 +252,8 @@ pub mod pallet {
Premature,
/// The bounty cannot be closed because it has active child-bounties.
HasActiveChildBounty,
/// Too many approvals are already queued.
TooManyQueued,
}

#[pallet::event]
Expand Down Expand Up @@ -288,12 +293,14 @@ pub mod pallet {
/// The description of each bounty.
#[pallet::storage]
#[pallet::getter(fn bounty_descriptions)]
pub type BountyDescriptions<T: Config> = StorageMap<_, Twox64Concat, BountyIndex, Vec<u8>>;
pub type BountyDescriptions<T: Config> =
StorageMap<_, Twox64Concat, BountyIndex, BoundedVec<u8, T::MaximumReasonLength>>;

/// Bounty indices that have been approved but not yet funded.
#[pallet::storage]
#[pallet::getter(fn bounty_approvals)]
pub type BountyApprovals<T: Config> = StorageValue<_, Vec<BountyIndex>, ValueQuery>;
pub type BountyApprovals<T: Config> =
StorageValue<_, BoundedVec<BountyIndex, T::MaxBountiesQueued>, ValueQuery>;

#[pallet::call]
impl<T: Config> Pallet<T> {
Expand Down Expand Up @@ -341,7 +348,8 @@ pub mod pallet {

bounty.status = BountyStatus::Approved;

BountyApprovals::<T>::append(bounty_id);
BountyApprovals::<T>::try_append(bounty_id)
.map_err(|()| Error::<T>::TooManyQueued)?;

Ok(())
})?;
Expand Down Expand Up @@ -780,17 +788,15 @@ impl<T: Config> Pallet<T> {
description: Vec<u8>,
value: BalanceOf<T>,
) -> DispatchResult {
ensure!(
description.len() <= T::MaximumReasonLength::get() as usize,
Error::<T>::ReasonTooBig
);
let bounded_description: BoundedVec<_, _> =
description.try_into().map_err(|()| Error::<T>::ReasonTooBig)?;
ensure!(value >= T::BountyValueMinimum::get(), Error::<T>::InvalidValue);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seeing how the BoundedVec improved the type safety for the descriptions; we could also add a AtLeast or AtMost and then only use try_into (or even as SCALE types). AtLeast<T::BountyValueMinimum> in this case.
Then we could sooner or later maybe get rid of all explicit ensure! calls and have our assumptions enforced by the typing.

Copy link
Member Author

@shawntabrizi shawntabrizi Feb 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Honestly, I find that BoundedVec is not ergonomic to use still, and most of it is because of typing. I would rather than have it in places where it is not needed, and where a simple line like above is sufficient.


let index = Self::bounty_count();

// reserve deposit for new bounty
let bond = T::BountyDepositBase::get() +
T::DataDepositPerByte::get() * (description.len() as u32).into();
T::DataDepositPerByte::get() * (bounded_description.len() as u32).into();
T::Currency::reserve(&proposer, bond)
.map_err(|_| Error::<T>::InsufficientProposersBalance)?;

Expand All @@ -806,7 +812,7 @@ impl<T: Config> Pallet<T> {
};

Bounties::<T>::insert(index, &bounty);
BountyDescriptions::<T>::insert(index, description);
BountyDescriptions::<T>::insert(index, bounded_description);

Self::deposit_event(Event::<T>::BountyProposed { index });

Expand Down
1 change: 1 addition & 0 deletions frame/bounties/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ impl Config for Test {
type MaximumReasonLength = ConstU32<16384>;
type WeightInfo = ();
type ChildBountyManager = ();
type MaxBountiesQueued = ConstU32<100>;
}

type TreasuryError = pallet_treasury::Error<Test>;
Expand Down
43 changes: 30 additions & 13 deletions frame/gilt/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ pub mod pallet {
+ sp_std::fmt::Debug
+ Default
+ From<u64>
+ TypeInfo;
+ TypeInfo
+ MaxEncodedLen;

/// Origin required for setting the target proportion to be under gilt.
type AdminOrigin: EnsureOrigin<Self::Origin>;
Expand Down Expand Up @@ -178,11 +179,12 @@ pub mod pallet {

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

/// A single bid on a gilt, an item of a *queue* in `Queues`.
#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo)]
#[derive(
Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen,
)]
pub struct GiltBid<Balance, AccountId> {
/// The amount bid.
pub amount: Balance,
Expand All @@ -191,7 +193,9 @@ pub mod pallet {
}

/// Information representing an active gilt.
#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo)]
#[derive(
Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen,
)]
pub struct ActiveGilt<Balance, AccountId, BlockNumber> {
/// The proportion of the effective total issuance (i.e. accounting for any eventual gilt
/// expansion or contraction that may eventually be claimed).
Expand All @@ -215,7 +219,9 @@ pub mod pallet {
/// `issuance - frozen + proportion * issuance`
///
/// where `issuance = total_issuance - IgnoredIssuance`
#[derive(Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo)]
#[derive(
Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen,
)]
pub struct ActiveGiltsTotal<Balance> {
/// The total amount of funds held in reserve for all active gilts.
pub frozen: Balance,
Expand All @@ -233,12 +239,18 @@ pub mod pallet {
/// The vector is indexed by duration in `Period`s, offset by one, so information on the queue
/// whose duration is one `Period` would be storage `0`.
#[pallet::storage]
pub type QueueTotals<T> = StorageValue<_, Vec<(u32, BalanceOf<T>)>, ValueQuery>;
pub type QueueTotals<T: Config> =
StorageValue<_, BoundedVec<(u32, BalanceOf<T>), T::QueueCount>, ValueQuery>;

/// The queues of bids ready to become gilts. Indexed by duration (in `Period`s).
#[pallet::storage]
pub type Queues<T: Config> =
StorageMap<_, Blake2_128Concat, u32, Vec<GiltBid<BalanceOf<T>, T::AccountId>>, ValueQuery>;
pub type Queues<T: Config> = StorageMap<
_,
Blake2_128Concat,
u32,
BoundedVec<GiltBid<BalanceOf<T>, T::AccountId>, T::QueueCount>,
ValueQuery,
>;

/// Information relating to the gilts currently active.
#[pallet::storage]
Expand All @@ -265,7 +277,11 @@ pub mod pallet {
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
QueueTotals::<T>::put(vec![(0, BalanceOf::<T>::zero()); T::QueueCount::get() as usize]);
let unbounded = vec![(0, BalanceOf::<T>::zero()); T::QueueCount::get() as usize];
let bounded: BoundedVec<_, _> = unbounded
.try_into()
.expect("QueueTotals should support up to QueueCount items. qed");
QueueTotals::<T>::put(bounded);
}
}

Expand Down Expand Up @@ -366,7 +382,7 @@ pub mod pallet {
T::Currency::unreserve(&bid.who, bid.amount);
(0, amount - bid.amount)
} else {
q.insert(0, bid);
q.try_insert(0, bid).expect("verified queue was not full above. qed.");
shawntabrizi marked this conversation as resolved.
Show resolved Hide resolved
(1, amount)
};

Expand All @@ -379,7 +395,7 @@ pub mod pallet {
},
)?;
QueueTotals::<T>::mutate(|qs| {
qs.resize(queue_count, (0, Zero::zero()));
qs.bounded_resize(queue_count, (0, Zero::zero()));
qs[queue_index].0 += net.0;
qs[queue_index].1 = qs[queue_index].1.saturating_add(net.1);
});
Expand Down Expand Up @@ -415,7 +431,7 @@ pub mod pallet {
})?;

QueueTotals::<T>::mutate(|qs| {
qs.resize(queue_count, (0, Zero::zero()));
qs.bounded_resize(queue_count, (0, Zero::zero()));
qs[queue_index].0 = new_len;
qs[queue_index].1 = qs[queue_index].1.saturating_sub(bid.amount);
});
Expand Down Expand Up @@ -592,7 +608,8 @@ pub mod pallet {
if remaining < bid.amount {
let overflow = bid.amount - remaining;
bid.amount = remaining;
q.push(GiltBid { amount: overflow, who: bid.who.clone() });
q.try_push(GiltBid { amount: overflow, who: bid.who.clone() })
.expect("just popped, so there must be space. qed");
}
let amount = bid.amount;
// Can never overflow due to block above.
Expand Down
4 changes: 2 additions & 2 deletions frame/indices/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ pub mod pallet {
+ Codec
+ Default
+ AtLeast32Bit
+ Copy;
+ Copy
+ MaxEncodedLen;

/// The currency trait.
type Currency: ReservableCurrency<Self::AccountId>;
Expand All @@ -74,7 +75,6 @@ pub mod pallet {

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

#[pallet::call]
Expand Down
24 changes: 16 additions & 8 deletions frame/nicks/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,10 @@ pub mod pallet {
/// The lookup table for names.
#[pallet::storage]
pub(super) type NameOf<T: Config> =
StorageMap<_, Twox64Concat, T::AccountId, (Vec<u8>, BalanceOf<T>)>;
StorageMap<_, Twox64Concat, T::AccountId, (BoundedVec<u8, T::MaxLength>, BalanceOf<T>)>;

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

#[pallet::call]
Expand All @@ -139,8 +138,9 @@ pub mod pallet {
pub fn set_name(origin: OriginFor<T>, name: Vec<u8>) -> DispatchResult {
let sender = ensure_signed(origin)?;

ensure!(name.len() >= T::MinLength::get() as usize, Error::<T>::TooShort);
ensure!(name.len() <= T::MaxLength::get() as usize, Error::<T>::TooLong);
let bounded_name: BoundedVec<_, _> =
name.try_into().map_err(|()| Error::<T>::TooLong)?;
ensure!(bounded_name.len() >= T::MinLength::get() as usize, Error::<T>::TooShort);

let deposit = if let Some((_, deposit)) = <NameOf<T>>::get(&sender) {
Self::deposit_event(Event::<T>::NameChanged { who: sender.clone() });
Expand All @@ -152,7 +152,7 @@ pub mod pallet {
deposit
};

<NameOf<T>>::insert(&sender, (name, deposit));
<NameOf<T>>::insert(&sender, (bounded_name, deposit));
Ok(())
}

Expand Down Expand Up @@ -230,9 +230,11 @@ pub mod pallet {
) -> DispatchResult {
T::ForceOrigin::ensure_origin(origin)?;

let bounded_name: BoundedVec<_, _> =
name.try_into().map_err(|()| Error::<T>::TooLong)?;
let target = T::Lookup::lookup(target)?;
let deposit = <NameOf<T>>::get(&target).map(|x| x.1).unwrap_or_else(Zero::zero);
<NameOf<T>>::insert(&target, (name, deposit));
<NameOf<T>>::insert(&target, (bounded_name, deposit));

Self::deposit_event(Event::<T>::NameForced { target });
Ok(())
Expand Down Expand Up @@ -356,9 +358,15 @@ mod tests {

assert_ok!(Nicks::set_name(Origin::signed(2), b"Dave".to_vec()));
assert_eq!(Balances::reserved_balance(2), 2);
assert_ok!(Nicks::force_name(Origin::signed(1), 2, b"Dr. David Brubeck, III".to_vec()));
assert_noop!(
Nicks::force_name(Origin::signed(1), 2, b"Dr. David Brubeck, III".to_vec()),
Error::<Test>::TooLong,
);
assert_ok!(Nicks::force_name(Origin::signed(1), 2, b"Dr. Brubeck, III".to_vec()));
assert_eq!(Balances::reserved_balance(2), 2);
assert_eq!(<NameOf<Test>>::get(2).unwrap(), (b"Dr. David Brubeck, III".to_vec(), 2));
let (name, amount) = <NameOf<Test>>::get(2).unwrap();
assert_eq!(name, b"Dr. Brubeck, III".to_vec());
assert_eq!(amount, 2);
});
}

Expand Down
9 changes: 4 additions & 5 deletions frame/randomness-collective-flip/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ pub mod pallet {

#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::without_storage_info]
//#[pallet::without_storage_info]
shawntabrizi marked this conversation as resolved.
Show resolved Hide resolved
pub struct Pallet<T>(_);

#[pallet::config]
Expand All @@ -103,9 +103,7 @@ pub mod pallet {
let parent_hash = <frame_system::Pallet<T>>::parent_hash();

<RandomMaterial<T>>::mutate(|ref mut values| {
if values.len() < RANDOM_MATERIAL_LEN as usize {
values.push(parent_hash)
} else {
if values.try_push(parent_hash).is_err() {
let index = block_number_to_index::<T>(block_number);
values[index] = parent_hash;
}
Expand All @@ -120,7 +118,8 @@ pub mod pallet {
/// the oldest hash.
#[pallet::storage]
#[pallet::getter(fn random_material)]
pub(super) type RandomMaterial<T: Config> = StorageValue<_, Vec<T::Hash>, ValueQuery>;
pub(super) type RandomMaterial<T: Config> =
StorageValue<_, BoundedVec<T::Hash, ConstU32<RANDOM_MATERIAL_LEN>>, ValueQuery>;
}

impl<T: Config> Randomness<T::Hash, T::BlockNumber> for Pallet<T> {
Expand Down
Loading