1use alloc::{collections::btree_set::BTreeSet, vec, vec::Vec};
21use codec::{Decode, DecodeWithMemTracking, Encode, FullCodec, MaxEncodedLen};
22use core::{marker::PhantomData, mem, ops::Drop};
23use frame_support::CloneNoBound;
24use impl_trait_for_tuples::impl_for_tuples;
25use scale_info::TypeInfo;
26pub use sp_core::storage::TrackedStorageKey;
27use sp_core::Get;
28use sp_runtime::{
29 traits::{Convert, Member},
30 Debug, DispatchError,
31};
32
33pub trait Instance: 'static {
41 const PREFIX: &'static str;
43 const INDEX: u8;
45}
46
47impl Instance for () {
49 const PREFIX: &'static str = "";
50 const INDEX: u8 = 0;
51}
52
53pub trait StorageInstance {
62 fn pallet_prefix() -> &'static str;
64
65 fn pallet_prefix_hash() -> [u8; 16] {
70 sp_io::hashing::twox_128(Self::pallet_prefix().as_bytes())
71 }
72
73 const STORAGE_PREFIX: &'static str;
75
76 fn storage_prefix_hash() -> [u8; 16] {
80 sp_io::hashing::twox_128(Self::STORAGE_PREFIX.as_bytes())
81 }
82
83 fn prefix_hash() -> [u8; 32] {
88 let mut final_key = [0u8; 32];
89 final_key[..16].copy_from_slice(&Self::pallet_prefix_hash());
90 final_key[16..].copy_from_slice(&Self::storage_prefix_hash());
91
92 final_key
93 }
94}
95
96#[derive(Debug, codec::Encode, codec::Decode, Eq, PartialEq, Clone, scale_info::TypeInfo)]
98pub struct StorageInfo {
99 pub pallet_name: Vec<u8>,
101 pub storage_name: Vec<u8>,
103 pub prefix: Vec<u8>,
105 pub max_values: Option<u32>,
107 pub max_size: Option<u32>,
109}
110
111pub trait StorageInfoTrait {
115 fn storage_info() -> Vec<StorageInfo>;
116}
117
118#[cfg_attr(all(not(feature = "tuples-96"), not(feature = "tuples-128")), impl_for_tuples(64))]
119#[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))]
120#[cfg_attr(feature = "tuples-128", impl_for_tuples(128))]
121impl StorageInfoTrait for Tuple {
122 fn storage_info() -> Vec<StorageInfo> {
123 let mut res = vec![];
124 for_tuples!( #( res.extend_from_slice(&Tuple::storage_info()); )* );
125 res
126 }
127}
128
129pub trait PartialStorageInfoTrait {
134 fn partial_storage_info() -> Vec<StorageInfo>;
135}
136
137pub trait WhitelistedStorageKeys {
141 fn whitelisted_storage_keys() -> Vec<TrackedStorageKey>;
145}
146
147#[cfg_attr(all(not(feature = "tuples-96"), not(feature = "tuples-128")), impl_for_tuples(64))]
148#[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))]
149#[cfg_attr(feature = "tuples-128", impl_for_tuples(128))]
150impl WhitelistedStorageKeys for Tuple {
151 fn whitelisted_storage_keys() -> Vec<TrackedStorageKey> {
152 let mut combined_keys: BTreeSet<TrackedStorageKey> = BTreeSet::new();
154 for_tuples!( #(
155 for storage_key in Tuple::whitelisted_storage_keys() {
156 combined_keys.insert(storage_key);
157 }
158 )* );
159 combined_keys.into_iter().collect::<Vec<_>>()
160 }
161}
162
163#[derive(
166 Default,
167 Copy,
168 Clone,
169 Eq,
170 PartialEq,
171 Debug,
172 TypeInfo,
173 MaxEncodedLen,
174 Decode,
175 Encode,
176 DecodeWithMemTracking,
177)]
178pub struct Footprint {
179 pub count: u64,
181 pub size: u64,
183}
184
185impl Footprint {
186 pub fn from_parts(items: usize, len: usize) -> Self {
188 Self { count: items as u64, size: len as u64 }
189 }
190
191 pub fn from_encodable(e: impl Encode) -> Self {
193 Self::from_parts(1, e.encoded_size())
194 }
195
196 pub fn from_mel<E: MaxEncodedLen>() -> Self {
198 Self::from_parts(1, E::max_encoded_len())
199 }
200}
201
202pub struct LinearStoragePrice<Base, Slope, Balance>(PhantomData<(Base, Slope, Balance)>);
204impl<Base, Slope, Balance> Convert<Footprint, Balance> for LinearStoragePrice<Base, Slope, Balance>
205where
206 Base: Get<Balance>,
207 Slope: Get<Balance>,
208 Balance: From<u64> + sp_runtime::Saturating,
209{
210 fn convert(a: Footprint) -> Balance {
211 let s: Balance = (a.count.saturating_mul(a.size)).into();
212 s.saturating_mul(Slope::get()).saturating_add(Base::get())
213 }
214}
215
216pub struct ConstantStoragePrice<Price, Balance>(PhantomData<(Price, Balance)>);
218impl<Price, Balance> Convert<Footprint, Balance> for ConstantStoragePrice<Price, Balance>
219where
220 Price: Get<Balance>,
221 Balance: From<u64> + sp_runtime::Saturating,
222{
223 fn convert(_: Footprint) -> Balance {
224 Price::get()
225 }
226}
227
228#[derive(CloneNoBound, Debug, Encode, Eq, Decode, TypeInfo, MaxEncodedLen, PartialEq)]
230pub struct Disabled;
231impl<A, F> Consideration<A, F> for Disabled {
232 fn new(_: &A, _: F) -> Result<Self, DispatchError> {
233 Err(DispatchError::Other("Disabled"))
234 }
235 fn update(self, _: &A, _: F) -> Result<Self, DispatchError> {
236 Err(DispatchError::Other("Disabled"))
237 }
238 fn drop(self, _: &A) -> Result<(), DispatchError> {
239 Ok(())
240 }
241 #[cfg(feature = "runtime-benchmarks")]
242 fn ensure_successful(_: &A, _: F) {}
243}
244
245#[must_use]
262pub trait Consideration<AccountId, Footprint>:
263 Member + FullCodec + TypeInfo + MaxEncodedLen
264{
265 fn new(who: &AccountId, new: Footprint) -> Result<Self, DispatchError>;
268
269 fn update(self, who: &AccountId, new: Footprint) -> Result<Self, DispatchError>;
274
275 fn drop(self, who: &AccountId) -> Result<(), DispatchError>;
277
278 fn burn(self, _: &AccountId) {
284 let _ = self;
285 }
286 #[cfg(feature = "runtime-benchmarks")]
289 fn ensure_successful(who: &AccountId, new: Footprint);
290}
291
292impl<A, F> Consideration<A, F> for () {
293 fn new(_: &A, _: F) -> Result<Self, DispatchError> {
294 Ok(())
295 }
296 fn update(self, _: &A, _: F) -> Result<(), DispatchError> {
297 Ok(())
298 }
299 fn drop(self, _: &A) -> Result<(), DispatchError> {
300 Ok(())
301 }
302 #[cfg(feature = "runtime-benchmarks")]
303 fn ensure_successful(_: &A, _: F) {}
304}
305
306pub trait MaybeConsideration<AccountId, Footprint>: Consideration<AccountId, Footprint> {
311 fn is_none(&self) -> bool;
314}
315
316impl<A, F> MaybeConsideration<A, F> for () {
317 fn is_none(&self) -> bool {
318 true
319 }
320}
321
322macro_rules! impl_incrementable {
323 ($($type:ty),+) => {
324 $(
325 impl Incrementable for $type {
326 fn increment(&self) -> Option<Self> {
327 self.checked_add(1)
328 }
329
330 fn initial_value() -> Option<Self> {
331 Some(0)
332 }
333 }
334 )+
335 };
336}
337
338pub trait Incrementable
343where
344 Self: Sized,
345{
346 fn increment(&self) -> Option<Self>;
350
351 fn initial_value() -> Option<Self>;
355}
356
357impl_incrementable!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128);
358
359#[derive(Default, Encode, Decode, DecodeWithMemTracking, MaxEncodedLen, TypeInfo)]
365pub struct NoDrop<T: Default>(T);
366
367impl<T: Default> Drop for NoDrop<T> {
368 fn drop(&mut self) {
369 mem::forget(mem::take(&mut self.0))
370 }
371}
372
373pub trait SuppressedDrop: sealed::Sealed {
378 type Inner;
380
381 fn new(inner: Self::Inner) -> Self;
382 fn as_ref(&self) -> &Self::Inner;
383 fn as_mut(&mut self) -> &mut Self::Inner;
384 fn into_inner(self) -> Self::Inner;
385}
386
387impl SuppressedDrop for () {
388 type Inner = ();
389
390 fn new(inner: Self::Inner) -> Self {
391 inner
392 }
393
394 fn as_ref(&self) -> &Self::Inner {
395 self
396 }
397
398 fn as_mut(&mut self) -> &mut Self::Inner {
399 self
400 }
401
402 fn into_inner(self) -> Self::Inner {
403 self
404 }
405}
406
407impl<T: Default> SuppressedDrop for NoDrop<T> {
408 type Inner = T;
409
410 fn as_ref(&self) -> &Self::Inner {
411 &self.0
412 }
413
414 fn as_mut(&mut self) -> &mut Self::Inner {
415 &mut self.0
416 }
417
418 fn into_inner(mut self) -> Self::Inner {
419 mem::take(&mut self.0)
420 }
421
422 fn new(inner: Self::Inner) -> Self {
423 Self(inner)
424 }
425}
426
427mod sealed {
428 pub trait Sealed {}
429 impl Sealed for () {}
430 impl<T: Default> Sealed for super::NoDrop<T> {}
431}
432
433#[cfg(test)]
434mod tests {
435 use super::*;
436 use crate::BoundedVec;
437 use sp_core::{ConstU32, ConstU64};
438
439 #[test]
440 fn incrementable_works() {
441 assert_eq!(0u8.increment(), Some(1));
442 assert_eq!(1u8.increment(), Some(2));
443
444 assert_eq!(u8::MAX.increment(), None);
445 }
446
447 #[test]
448 fn linear_storage_price_works() {
449 type Linear = LinearStoragePrice<ConstU64<7>, ConstU64<3>, u64>;
450 let p = |count, size| Linear::convert(Footprint { count, size });
451
452 assert_eq!(p(0, 0), 7);
453 assert_eq!(p(0, 1), 7);
454 assert_eq!(p(1, 0), 7);
455
456 assert_eq!(p(1, 1), 10);
457 assert_eq!(p(8, 1), 31);
458 assert_eq!(p(1, 8), 31);
459
460 assert_eq!(p(u64::MAX, u64::MAX), u64::MAX);
461 }
462
463 #[test]
464 fn footprint_from_mel_works() {
465 let footprint = Footprint::from_mel::<(u8, BoundedVec<u8, ConstU32<9>>)>();
466 let expected_size = BoundedVec::<u8, ConstU32<9>>::max_encoded_len() as u64;
467 assert_eq!(expected_size, 10);
468 assert_eq!(footprint, Footprint { count: 1, size: expected_size + 1 });
469
470 let footprint = Footprint::from_mel::<(u8, BoundedVec<u8, ConstU32<999>>)>();
471 let expected_size = BoundedVec::<u8, ConstU32<999>>::max_encoded_len() as u64;
472 assert_eq!(expected_size, 1001);
473 assert_eq!(footprint, Footprint { count: 1, size: expected_size + 1 });
474 }
475}