1use alloc::{collections::btree_set::BTreeSet, vec, vec::Vec};
10use codec::{Decode, DecodeWithMemTracking, Encode, FullCodec, MaxEncodedLen};
11use core::{marker::PhantomData, mem, ops::Drop};
12use impl_trait_for_tuples::impl_for_tuples;
13use scale_info::TypeInfo;
14pub use subsoil::core::storage::TrackedStorageKey;
15use subsoil::core::Get;
16use subsoil::runtime::{
17 traits::{Convert, Member},
18 Debug, DispatchError,
19};
20use topsoil_core::CloneNoBound;
21
22pub trait Instance: 'static {
30 const PREFIX: &'static str;
32 const INDEX: u8;
34}
35
36impl Instance for () {
38 const PREFIX: &'static str = "";
39 const INDEX: u8 = 0;
40}
41
42pub trait StorageInstance {
51 fn pallet_prefix() -> &'static str;
53
54 fn pallet_prefix_hash() -> [u8; 16] {
59 subsoil::io::hashing::twox_128(Self::pallet_prefix().as_bytes())
60 }
61
62 const STORAGE_PREFIX: &'static str;
64
65 fn storage_prefix_hash() -> [u8; 16] {
69 subsoil::io::hashing::twox_128(Self::STORAGE_PREFIX.as_bytes())
70 }
71
72 fn prefix_hash() -> [u8; 32] {
77 let mut final_key = [0u8; 32];
78 final_key[..16].copy_from_slice(&Self::pallet_prefix_hash());
79 final_key[16..].copy_from_slice(&Self::storage_prefix_hash());
80
81 final_key
82 }
83}
84
85#[derive(Debug, codec::Encode, codec::Decode, Eq, PartialEq, Clone, scale_info::TypeInfo)]
87pub struct StorageInfo {
88 pub pallet_name: Vec<u8>,
90 pub storage_name: Vec<u8>,
92 pub prefix: Vec<u8>,
94 pub max_values: Option<u32>,
96 pub max_size: Option<u32>,
98}
99
100pub trait StorageInfoTrait {
104 fn storage_info() -> Vec<StorageInfo>;
105}
106
107#[cfg_attr(all(not(feature = "tuples-96"), not(feature = "tuples-128")), impl_for_tuples(64))]
108#[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))]
109#[cfg_attr(feature = "tuples-128", impl_for_tuples(128))]
110impl StorageInfoTrait for Tuple {
111 fn storage_info() -> Vec<StorageInfo> {
112 let mut res = vec![];
113 for_tuples!( #( res.extend_from_slice(&Tuple::storage_info()); )* );
114 res
115 }
116}
117
118pub trait PartialStorageInfoTrait {
123 fn partial_storage_info() -> Vec<StorageInfo>;
124}
125
126pub trait WhitelistedStorageKeys {
130 fn whitelisted_storage_keys() -> Vec<TrackedStorageKey>;
134}
135
136#[cfg_attr(all(not(feature = "tuples-96"), not(feature = "tuples-128")), impl_for_tuples(64))]
137#[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))]
138#[cfg_attr(feature = "tuples-128", impl_for_tuples(128))]
139impl WhitelistedStorageKeys for Tuple {
140 fn whitelisted_storage_keys() -> Vec<TrackedStorageKey> {
141 let mut combined_keys: BTreeSet<TrackedStorageKey> = BTreeSet::new();
143 for_tuples!( #(
144 for storage_key in Tuple::whitelisted_storage_keys() {
145 combined_keys.insert(storage_key);
146 }
147 )* );
148 combined_keys.into_iter().collect::<Vec<_>>()
149 }
150}
151
152#[derive(Default, Copy, Clone, Eq, PartialEq, Debug)]
155pub struct Footprint {
156 pub count: u64,
158 pub size: u64,
160}
161
162impl Footprint {
163 pub fn from_parts(items: usize, len: usize) -> Self {
165 Self { count: items as u64, size: len as u64 }
166 }
167
168 pub fn from_encodable(e: impl Encode) -> Self {
170 Self::from_parts(1, e.encoded_size())
171 }
172
173 pub fn from_mel<E: MaxEncodedLen>() -> Self {
175 Self::from_parts(1, E::max_encoded_len())
176 }
177}
178
179pub struct LinearStoragePrice<Base, Slope, Balance>(PhantomData<(Base, Slope, Balance)>);
181impl<Base, Slope, Balance> Convert<Footprint, Balance> for LinearStoragePrice<Base, Slope, Balance>
182where
183 Base: Get<Balance>,
184 Slope: Get<Balance>,
185 Balance: From<u64> + subsoil::runtime::Saturating,
186{
187 fn convert(a: Footprint) -> Balance {
188 let s: Balance = (a.count.saturating_mul(a.size)).into();
189 s.saturating_mul(Slope::get()).saturating_add(Base::get())
190 }
191}
192
193pub struct ConstantStoragePrice<Price, Balance>(PhantomData<(Price, Balance)>);
195impl<Price, Balance> Convert<Footprint, Balance> for ConstantStoragePrice<Price, Balance>
196where
197 Price: Get<Balance>,
198 Balance: From<u64> + subsoil::runtime::Saturating,
199{
200 fn convert(_: Footprint) -> Balance {
201 Price::get()
202 }
203}
204
205#[derive(CloneNoBound, Debug, Encode, Eq, Decode, TypeInfo, MaxEncodedLen, PartialEq)]
207pub struct Disabled;
208impl<A, F> Consideration<A, F> for Disabled {
209 fn new(_: &A, _: F) -> Result<Self, DispatchError> {
210 Err(DispatchError::Other("Disabled"))
211 }
212 fn update(self, _: &A, _: F) -> Result<Self, DispatchError> {
213 Err(DispatchError::Other("Disabled"))
214 }
215 fn drop(self, _: &A) -> Result<(), DispatchError> {
216 Ok(())
217 }
218 #[cfg(feature = "runtime-benchmarks")]
219 fn ensure_successful(_: &A, _: F) {}
220}
221
222#[must_use]
235pub trait Consideration<AccountId, Footprint>:
236 Member + FullCodec + TypeInfo + MaxEncodedLen
237{
238 fn new(who: &AccountId, new: Footprint) -> Result<Self, DispatchError>;
241
242 fn update(self, who: &AccountId, new: Footprint) -> Result<Self, DispatchError>;
247
248 fn drop(self, who: &AccountId) -> Result<(), DispatchError>;
250
251 fn burn(self, _: &AccountId) {
257 let _ = self;
258 }
259 #[cfg(feature = "runtime-benchmarks")]
262 fn ensure_successful(who: &AccountId, new: Footprint);
263}
264
265impl<A, F> Consideration<A, F> for () {
266 fn new(_: &A, _: F) -> Result<Self, DispatchError> {
267 Ok(())
268 }
269 fn update(self, _: &A, _: F) -> Result<(), DispatchError> {
270 Ok(())
271 }
272 fn drop(self, _: &A) -> Result<(), DispatchError> {
273 Ok(())
274 }
275 #[cfg(feature = "runtime-benchmarks")]
276 fn ensure_successful(_: &A, _: F) {}
277}
278
279#[cfg(feature = "experimental")]
280pub trait MaybeConsideration<AccountId, Footprint>: Consideration<AccountId, Footprint> {
285 fn is_none(&self) -> bool;
288}
289
290#[cfg(feature = "experimental")]
291impl<A, F> MaybeConsideration<A, F> for () {
292 fn is_none(&self) -> bool {
293 true
294 }
295}
296
297macro_rules! impl_incrementable {
298 ($($type:ty),+) => {
299 $(
300 impl Incrementable for $type {
301 fn increment(&self) -> Option<Self> {
302 self.checked_add(1)
303 }
304
305 fn initial_value() -> Option<Self> {
306 Some(0)
307 }
308 }
309 )+
310 };
311}
312
313pub trait Incrementable
318where
319 Self: Sized,
320{
321 fn increment(&self) -> Option<Self>;
325
326 fn initial_value() -> Option<Self>;
330}
331
332impl_incrementable!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128);
333
334#[derive(Default, Encode, Decode, DecodeWithMemTracking, MaxEncodedLen, TypeInfo)]
340pub struct NoDrop<T: Default>(T);
341
342impl<T: Default> Drop for NoDrop<T> {
343 fn drop(&mut self) {
344 mem::forget(mem::take(&mut self.0))
345 }
346}
347
348pub trait SuppressedDrop: sealed::Sealed {
353 type Inner;
355
356 fn new(inner: Self::Inner) -> Self;
357 fn as_ref(&self) -> &Self::Inner;
358 fn as_mut(&mut self) -> &mut Self::Inner;
359 fn into_inner(self) -> Self::Inner;
360}
361
362impl SuppressedDrop for () {
363 type Inner = ();
364
365 fn new(inner: Self::Inner) -> Self {
366 inner
367 }
368
369 fn as_ref(&self) -> &Self::Inner {
370 self
371 }
372
373 fn as_mut(&mut self) -> &mut Self::Inner {
374 self
375 }
376
377 fn into_inner(self) -> Self::Inner {
378 self
379 }
380}
381
382impl<T: Default> SuppressedDrop for NoDrop<T> {
383 type Inner = T;
384
385 fn as_ref(&self) -> &Self::Inner {
386 &self.0
387 }
388
389 fn as_mut(&mut self) -> &mut Self::Inner {
390 &mut self.0
391 }
392
393 fn into_inner(mut self) -> Self::Inner {
394 mem::take(&mut self.0)
395 }
396
397 fn new(inner: Self::Inner) -> Self {
398 Self(inner)
399 }
400}
401
402mod sealed {
403 pub trait Sealed {}
404 impl Sealed for () {}
405 impl<T: Default> Sealed for super::NoDrop<T> {}
406}
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411 use crate::BoundedVec;
412 use subsoil::core::{ConstU32, ConstU64};
413
414 #[test]
415 fn incrementable_works() {
416 assert_eq!(0u8.increment(), Some(1));
417 assert_eq!(1u8.increment(), Some(2));
418
419 assert_eq!(u8::MAX.increment(), None);
420 }
421
422 #[test]
423 fn linear_storage_price_works() {
424 type Linear = LinearStoragePrice<ConstU64<7>, ConstU64<3>, u64>;
425 let p = |count, size| Linear::convert(Footprint { count, size });
426
427 assert_eq!(p(0, 0), 7);
428 assert_eq!(p(0, 1), 7);
429 assert_eq!(p(1, 0), 7);
430
431 assert_eq!(p(1, 1), 10);
432 assert_eq!(p(8, 1), 31);
433 assert_eq!(p(1, 8), 31);
434
435 assert_eq!(p(u64::MAX, u64::MAX), u64::MAX);
436 }
437
438 #[test]
439 fn footprint_from_mel_works() {
440 let footprint = Footprint::from_mel::<(u8, BoundedVec<u8, ConstU32<9>>)>();
441 let expected_size = BoundedVec::<u8, ConstU32<9>>::max_encoded_len() as u64;
442 assert_eq!(expected_size, 10);
443 assert_eq!(footprint, Footprint { count: 1, size: expected_size + 1 });
444
445 let footprint = Footprint::from_mel::<(u8, BoundedVec<u8, ConstU32<999>>)>();
446 let expected_size = BoundedVec::<u8, ConstU32<999>>::max_encoded_len() as u64;
447 assert_eq!(expected_size, 1001);
448 assert_eq!(footprint, Footprint { count: 1, size: expected_size + 1 });
449 }
450}