use alloc::{collections::btree_set::BTreeSet, vec, vec::Vec};
use codec::{Decode, DecodeWithMemTracking, Encode, FullCodec, MaxEncodedLen};
use core::{marker::PhantomData, mem, ops::Drop};
use impl_trait_for_tuples::impl_for_tuples;
use scale_info::TypeInfo;
pub use subsoil::core::storage::TrackedStorageKey;
use subsoil::core::Get;
use subsoil::runtime::{
traits::{Convert, Member},
Debug, DispatchError,
};
use topsoil_core::CloneNoBound;
pub trait Instance: 'static {
const PREFIX: &'static str;
const INDEX: u8;
}
impl Instance for () {
const PREFIX: &'static str = "";
const INDEX: u8 = 0;
}
pub trait StorageInstance {
fn pallet_prefix() -> &'static str;
fn pallet_prefix_hash() -> [u8; 16] {
subsoil::io::hashing::twox_128(Self::pallet_prefix().as_bytes())
}
const STORAGE_PREFIX: &'static str;
fn storage_prefix_hash() -> [u8; 16] {
subsoil::io::hashing::twox_128(Self::STORAGE_PREFIX.as_bytes())
}
fn prefix_hash() -> [u8; 32] {
let mut final_key = [0u8; 32];
final_key[..16].copy_from_slice(&Self::pallet_prefix_hash());
final_key[16..].copy_from_slice(&Self::storage_prefix_hash());
final_key
}
}
#[derive(Debug, codec::Encode, codec::Decode, Eq, PartialEq, Clone, scale_info::TypeInfo)]
pub struct StorageInfo {
pub pallet_name: Vec<u8>,
pub storage_name: Vec<u8>,
pub prefix: Vec<u8>,
pub max_values: Option<u32>,
pub max_size: Option<u32>,
}
pub trait StorageInfoTrait {
fn storage_info() -> Vec<StorageInfo>;
}
#[cfg_attr(all(not(feature = "tuples-96"), not(feature = "tuples-128")), impl_for_tuples(64))]
#[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))]
#[cfg_attr(feature = "tuples-128", impl_for_tuples(128))]
impl StorageInfoTrait for Tuple {
fn storage_info() -> Vec<StorageInfo> {
let mut res = vec![];
for_tuples!( #( res.extend_from_slice(&Tuple::storage_info()); )* );
res
}
}
pub trait PartialStorageInfoTrait {
fn partial_storage_info() -> Vec<StorageInfo>;
}
pub trait WhitelistedStorageKeys {
fn whitelisted_storage_keys() -> Vec<TrackedStorageKey>;
}
#[cfg_attr(all(not(feature = "tuples-96"), not(feature = "tuples-128")), impl_for_tuples(64))]
#[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))]
#[cfg_attr(feature = "tuples-128", impl_for_tuples(128))]
impl WhitelistedStorageKeys for Tuple {
fn whitelisted_storage_keys() -> Vec<TrackedStorageKey> {
let mut combined_keys: BTreeSet<TrackedStorageKey> = BTreeSet::new();
for_tuples!( #(
for storage_key in Tuple::whitelisted_storage_keys() {
combined_keys.insert(storage_key);
}
)* );
combined_keys.into_iter().collect::<Vec<_>>()
}
}
#[derive(Default, Copy, Clone, Eq, PartialEq, Debug)]
pub struct Footprint {
pub count: u64,
pub size: u64,
}
impl Footprint {
pub fn from_parts(items: usize, len: usize) -> Self {
Self { count: items as u64, size: len as u64 }
}
pub fn from_encodable(e: impl Encode) -> Self {
Self::from_parts(1, e.encoded_size())
}
pub fn from_mel<E: MaxEncodedLen>() -> Self {
Self::from_parts(1, E::max_encoded_len())
}
}
pub struct LinearStoragePrice<Base, Slope, Balance>(PhantomData<(Base, Slope, Balance)>);
impl<Base, Slope, Balance> Convert<Footprint, Balance> for LinearStoragePrice<Base, Slope, Balance>
where
Base: Get<Balance>,
Slope: Get<Balance>,
Balance: From<u64> + subsoil::runtime::Saturating,
{
fn convert(a: Footprint) -> Balance {
let s: Balance = (a.count.saturating_mul(a.size)).into();
s.saturating_mul(Slope::get()).saturating_add(Base::get())
}
}
pub struct ConstantStoragePrice<Price, Balance>(PhantomData<(Price, Balance)>);
impl<Price, Balance> Convert<Footprint, Balance> for ConstantStoragePrice<Price, Balance>
where
Price: Get<Balance>,
Balance: From<u64> + subsoil::runtime::Saturating,
{
fn convert(_: Footprint) -> Balance {
Price::get()
}
}
#[derive(CloneNoBound, Debug, Encode, Eq, Decode, TypeInfo, MaxEncodedLen, PartialEq)]
pub struct Disabled;
impl<A, F> Consideration<A, F> for Disabled {
fn new(_: &A, _: F) -> Result<Self, DispatchError> {
Err(DispatchError::Other("Disabled"))
}
fn update(self, _: &A, _: F) -> Result<Self, DispatchError> {
Err(DispatchError::Other("Disabled"))
}
fn drop(self, _: &A) -> Result<(), DispatchError> {
Ok(())
}
#[cfg(feature = "runtime-benchmarks")]
fn ensure_successful(_: &A, _: F) {}
}
#[must_use]
pub trait Consideration<AccountId, Footprint>:
Member + FullCodec + TypeInfo + MaxEncodedLen
{
fn new(who: &AccountId, new: Footprint) -> Result<Self, DispatchError>;
fn update(self, who: &AccountId, new: Footprint) -> Result<Self, DispatchError>;
fn drop(self, who: &AccountId) -> Result<(), DispatchError>;
fn burn(self, _: &AccountId) {
let _ = self;
}
#[cfg(feature = "runtime-benchmarks")]
fn ensure_successful(who: &AccountId, new: Footprint);
}
impl<A, F> Consideration<A, F> for () {
fn new(_: &A, _: F) -> Result<Self, DispatchError> {
Ok(())
}
fn update(self, _: &A, _: F) -> Result<(), DispatchError> {
Ok(())
}
fn drop(self, _: &A) -> Result<(), DispatchError> {
Ok(())
}
#[cfg(feature = "runtime-benchmarks")]
fn ensure_successful(_: &A, _: F) {}
}
#[cfg(feature = "experimental")]
pub trait MaybeConsideration<AccountId, Footprint>: Consideration<AccountId, Footprint> {
fn is_none(&self) -> bool;
}
#[cfg(feature = "experimental")]
impl<A, F> MaybeConsideration<A, F> for () {
fn is_none(&self) -> bool {
true
}
}
macro_rules! impl_incrementable {
($($type:ty),+) => {
$(
impl Incrementable for $type {
fn increment(&self) -> Option<Self> {
self.checked_add(1)
}
fn initial_value() -> Option<Self> {
Some(0)
}
}
)+
};
}
pub trait Incrementable
where
Self: Sized,
{
fn increment(&self) -> Option<Self>;
fn initial_value() -> Option<Self>;
}
impl_incrementable!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128);
#[derive(Default, Encode, Decode, DecodeWithMemTracking, MaxEncodedLen, TypeInfo)]
pub struct NoDrop<T: Default>(T);
impl<T: Default> Drop for NoDrop<T> {
fn drop(&mut self) {
mem::forget(mem::take(&mut self.0))
}
}
pub trait SuppressedDrop: sealed::Sealed {
type Inner;
fn new(inner: Self::Inner) -> Self;
fn as_ref(&self) -> &Self::Inner;
fn as_mut(&mut self) -> &mut Self::Inner;
fn into_inner(self) -> Self::Inner;
}
impl SuppressedDrop for () {
type Inner = ();
fn new(inner: Self::Inner) -> Self {
inner
}
fn as_ref(&self) -> &Self::Inner {
self
}
fn as_mut(&mut self) -> &mut Self::Inner {
self
}
fn into_inner(self) -> Self::Inner {
self
}
}
impl<T: Default> SuppressedDrop for NoDrop<T> {
type Inner = T;
fn as_ref(&self) -> &Self::Inner {
&self.0
}
fn as_mut(&mut self) -> &mut Self::Inner {
&mut self.0
}
fn into_inner(mut self) -> Self::Inner {
mem::take(&mut self.0)
}
fn new(inner: Self::Inner) -> Self {
Self(inner)
}
}
mod sealed {
pub trait Sealed {}
impl Sealed for () {}
impl<T: Default> Sealed for super::NoDrop<T> {}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::BoundedVec;
use subsoil::core::{ConstU32, ConstU64};
#[test]
fn incrementable_works() {
assert_eq!(0u8.increment(), Some(1));
assert_eq!(1u8.increment(), Some(2));
assert_eq!(u8::MAX.increment(), None);
}
#[test]
fn linear_storage_price_works() {
type Linear = LinearStoragePrice<ConstU64<7>, ConstU64<3>, u64>;
let p = |count, size| Linear::convert(Footprint { count, size });
assert_eq!(p(0, 0), 7);
assert_eq!(p(0, 1), 7);
assert_eq!(p(1, 0), 7);
assert_eq!(p(1, 1), 10);
assert_eq!(p(8, 1), 31);
assert_eq!(p(1, 8), 31);
assert_eq!(p(u64::MAX, u64::MAX), u64::MAX);
}
#[test]
fn footprint_from_mel_works() {
let footprint = Footprint::from_mel::<(u8, BoundedVec<u8, ConstU32<9>>)>();
let expected_size = BoundedVec::<u8, ConstU32<9>>::max_encoded_len() as u64;
assert_eq!(expected_size, 10);
assert_eq!(footprint, Footprint { count: 1, size: expected_size + 1 });
let footprint = Footprint::from_mel::<(u8, BoundedVec<u8, ConstU32<999>>)>();
let expected_size = BoundedVec::<u8, ConstU32<999>>::max_encoded_len() as u64;
assert_eq!(expected_size, 1001);
assert_eq!(footprint, Footprint { count: 1, size: expected_size + 1 });
}
}