Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all 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())]
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())]
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>,
Comment thread
ggwpez marked this conversation as resolved.
>;

#[pallet::error]
Expand Down
4 changes: 2 additions & 2 deletions frame/bags-list/src/list/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -545,7 +545,7 @@ impl<T: Config> List<T> {
/// iteration so that there's no incentive to churn ids positioning to improve the chances of
/// appearing within the ids set.
#[derive(DefaultNoBound, Encode, Decode, MaxEncodedLen, TypeInfo)]
#[codec(mel_bound(T: Config))]
#[codec(mel_bound())]
#[scale_info(skip_type_params(T))]
#[cfg_attr(feature = "std", derive(frame_support::DebugNoBound, Clone, PartialEq))]
pub struct Bag<T: Config> {
Expand Down Expand Up @@ -748,7 +748,7 @@ impl<T: Config> Bag<T> {

/// A Node is the fundamental element comprising the doubly-linked list described by `Bag`.
#[derive(Encode, Decode, MaxEncodedLen, TypeInfo)]
#[codec(mel_bound(T: Config))]
#[codec(mel_bound())]
#[scale_info(skip_type_params(T))]
#[cfg_attr(feature = "std", derive(frame_support::DebugNoBound, Clone, PartialEq))]
pub struct Node<T: Config> {
Expand Down
1 change: 0 additions & 1 deletion frame/beefy-mmr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@ pub mod pallet {
/// BEEFY-MMR pallet.
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);

/// The module's configuration trait.
Expand Down
26 changes: 14 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 @@ -249,6 +248,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 +289,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::MaxApprovals>, ValueQuery>;

#[pallet::call]
impl<T: Config> Pallet<T> {
Expand Down Expand Up @@ -341,7 +344,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 +784,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
Copy Markdown
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
Copy Markdown
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 +808,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
2 changes: 1 addition & 1 deletion frame/contracts/src/wasm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ pub struct PrefabWasmModule<T: Config> {
///
/// It is stored in a separate storage entry to avoid loading the code when not necessary.
#[derive(Clone, Encode, Decode, scale_info::TypeInfo, MaxEncodedLen)]
#[codec(mel_bound(T: Config))]
#[codec(mel_bound())]
#[scale_info(skip_type_params(T))]
pub struct OwnerInfo<T: Config> {
/// The account that has deployed the contract and hence is allowed to remove it.
Expand Down
2 changes: 1 addition & 1 deletion frame/election-provider-multi-phase/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ pub struct ReadySolution<A> {
///
/// These are stored together because they are often accessed together.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, Default, TypeInfo)]
#[codec(mel_bound(T: Config))]
#[codec(mel_bound())]
#[scale_info(skip_type_params(T))]
pub struct RoundSnapshot<T: Config> {
/// All of the voters.
Expand Down
15 changes: 7 additions & 8 deletions frame/examples/offchain-worker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,11 +154,14 @@ pub mod pallet {
/// multiple pallets send unsigned transactions.
#[pallet::constant]
type UnsignedPriority: Get<TransactionPriority>;

/// Maximum number of prices.
#[pallet::constant]
type MaxPrices: Get<u32>;
}

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

#[pallet::hooks]
Expand Down Expand Up @@ -330,7 +333,7 @@ pub mod pallet {
/// This is used to calculate average price, should have bounded size.
#[pallet::storage]
#[pallet::getter(fn prices)]
pub(super) type Prices<T: Config> = StorageValue<_, Vec<u32>, ValueQuery>;
pub(super) type Prices<T: Config> = StorageValue<_, BoundedVec<u32, T::MaxPrices>, ValueQuery>;

/// Defines the block when next unsigned transaction will be accepted.
///
Expand Down Expand Up @@ -645,12 +648,8 @@ impl<T: Config> Pallet<T> {
fn add_price(maybe_who: Option<T::AccountId>, price: u32) {
log::info!("Adding to the average: {}", price);
<Prices<T>>::mutate(|prices| {
const MAX_LEN: usize = 64;

if prices.len() < MAX_LEN {
prices.push(price);
} else {
prices[price as usize % MAX_LEN] = price;
if prices.try_push(price).is_err() {
prices[(price % T::MaxPrices::get()) as usize] = price;
}
});

Expand Down
1 change: 1 addition & 0 deletions frame/examples/offchain-worker/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ impl Config for Test {
type GracePeriod = ConstU64<5>;
type UnsignedInterval = ConstU64<128>;
type UnsignedPriority = UnsignedPriority;
type MaxPrices = ConstU32<64>;
}

fn test_pub() -> sp_core::sr25519::Public {
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::MaxQueueLen>,
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.");
Comment thread
shawntabrizi marked this conversation as 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
8 changes: 2 additions & 6 deletions frame/grandpa/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,13 +364,9 @@ pub type BoundedAuthorityList<Limit> = WeakBoundedVec<(AuthorityId, AuthorityWei
/// A stored pending change.
/// `Limit` is the bound for `next_authorities`
#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]
#[codec(mel_bound(Limit: Get<u32>))]
#[codec(mel_bound(N: MaxEncodedLen, Limit: Get<u32>))]
#[scale_info(skip_type_params(Limit))]
pub struct StoredPendingChange<N, Limit>
where
Limit: Get<u32>,
N: MaxEncodedLen,
{
pub struct StoredPendingChange<N, Limit> {
/// The block number this was scheduled at.
pub scheduled_at: N,
/// The delay in blocks until it will be applied.
Expand Down
8 changes: 2 additions & 6 deletions frame/identity/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ impl TypeInfo for IdentityFields {
#[derive(
CloneNoBound, Encode, Decode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo,
)]
#[codec(mel_bound(FieldLimit: Get<u32>))]
#[codec(mel_bound())]
#[cfg_attr(test, derive(frame_support::DefaultNoBound))]
#[scale_info(skip_type_params(FieldLimit))]
pub struct IdentityInfo<FieldLimit: Get<u32>> {
Expand Down Expand Up @@ -339,11 +339,7 @@ pub struct IdentityInfo<FieldLimit: Get<u32>> {
#[derive(
CloneNoBound, Encode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo,
)]
#[codec(mel_bound(
Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq + Zero + Add,
MaxJudgements: Get<u32>,
MaxAdditionalFields: Get<u32>,
))]
#[codec(mel_bound())]
#[scale_info(skip_type_params(MaxJudgements, MaxAdditionalFields))]
pub struct Registration<
Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq,
Expand Down
Loading