use crate::{
storage::{
types::{OptionQuery, QueryKindTrait, StorageEntryMetadataBuilder},
KeyLenOf, StorageAppend, StorageDecodeLength, StoragePrefixedMap, StorageTryAppend,
},
traits::{Get, GetDefault, StorageInfo, StorageInstance},
StorageHasher, Twox128,
};
use alloc::{vec, vec::Vec};
use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen};
use frame_support::storage::StorageDecodeNonDedupLength;
use sp_arithmetic::traits::SaturatedConversion;
use sp_metadata_ir::{StorageEntryMetadataIR, StorageEntryTypeIR};
pub struct StorageMap<
Prefix,
Hasher,
Key,
Value,
QueryKind = OptionQuery,
OnEmpty = GetDefault,
MaxValues = GetDefault,
>(core::marker::PhantomData<(Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues)>);
impl<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues> Get<u32>
for KeyLenOf<StorageMap<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues>>
where
Prefix: StorageInstance,
Hasher: crate::hash::StorageHasher,
Key: FullCodec + MaxEncodedLen,
{
fn get() -> u32 {
let z = Hasher::max_len::<Key>() + Twox128::max_len::<()>() * 2;
z as u32
}
}
impl<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues>
crate::storage::generator::StorageMap<Key, Value>
for StorageMap<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues>
where
Prefix: StorageInstance,
Hasher: crate::hash::StorageHasher,
Key: FullCodec,
Value: FullCodec,
QueryKind: QueryKindTrait<Value, OnEmpty>,
OnEmpty: Get<QueryKind::Query> + 'static,
MaxValues: Get<Option<u32>>,
{
type Query = QueryKind::Query;
type Hasher = Hasher;
fn pallet_prefix() -> &'static [u8] {
Prefix::pallet_prefix().as_bytes()
}
fn storage_prefix() -> &'static [u8] {
Prefix::STORAGE_PREFIX.as_bytes()
}
fn prefix_hash() -> [u8; 32] {
Prefix::prefix_hash()
}
fn from_optional_value_to_query(v: Option<Value>) -> Self::Query {
QueryKind::from_optional_value_to_query(v)
}
fn from_query_to_optional_value(v: Self::Query) -> Option<Value> {
QueryKind::from_query_to_optional_value(v)
}
}
impl<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues> StoragePrefixedMap<Value>
for StorageMap<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues>
where
Prefix: StorageInstance,
Hasher: crate::hash::StorageHasher,
Key: FullCodec,
Value: FullCodec,
QueryKind: QueryKindTrait<Value, OnEmpty>,
OnEmpty: Get<QueryKind::Query> + 'static,
MaxValues: Get<Option<u32>>,
{
fn pallet_prefix() -> &'static [u8] {
<Self as crate::storage::generator::StorageMap<Key, Value>>::pallet_prefix()
}
fn storage_prefix() -> &'static [u8] {
<Self as crate::storage::generator::StorageMap<Key, Value>>::storage_prefix()
}
}
impl<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues>
StorageMap<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues>
where
Prefix: StorageInstance,
Hasher: crate::hash::StorageHasher,
Key: FullCodec,
Value: FullCodec,
QueryKind: QueryKindTrait<Value, OnEmpty>,
OnEmpty: Get<QueryKind::Query> + 'static,
MaxValues: Get<Option<u32>>,
{
pub fn hashed_key_for<KeyArg: EncodeLike<Key>>(key: KeyArg) -> Vec<u8> {
<Self as crate::storage::StorageMap<Key, Value>>::hashed_key_for(key)
}
pub fn contains_key<KeyArg: EncodeLike<Key>>(key: KeyArg) -> bool {
<Self as crate::storage::StorageMap<Key, Value>>::contains_key(key)
}
pub fn get<KeyArg: EncodeLike<Key>>(key: KeyArg) -> QueryKind::Query {
<Self as crate::storage::StorageMap<Key, Value>>::get(key)
}
pub fn try_get<KeyArg: EncodeLike<Key>>(key: KeyArg) -> Result<Value, ()> {
<Self as crate::storage::StorageMap<Key, Value>>::try_get(key)
}
pub fn swap<KeyArg1: EncodeLike<Key>, KeyArg2: EncodeLike<Key>>(key1: KeyArg1, key2: KeyArg2) {
<Self as crate::storage::StorageMap<Key, Value>>::swap(key1, key2)
}
pub fn set<KeyArg: EncodeLike<Key>>(key: KeyArg, q: QueryKind::Query) {
<Self as crate::storage::StorageMap<Key, Value>>::set(key, q)
}
pub fn insert<KeyArg: EncodeLike<Key>, ValArg: EncodeLike<Value>>(key: KeyArg, val: ValArg) {
<Self as crate::storage::StorageMap<Key, Value>>::insert(key, val)
}
pub fn remove<KeyArg: EncodeLike<Key>>(key: KeyArg) {
<Self as crate::storage::StorageMap<Key, Value>>::remove(key)
}
pub fn mutate<KeyArg: EncodeLike<Key>, R, F: FnOnce(&mut QueryKind::Query) -> R>(
key: KeyArg,
f: F,
) -> R {
<Self as crate::storage::StorageMap<Key, Value>>::mutate(key, f)
}
pub fn try_mutate<KeyArg, R, E, F>(key: KeyArg, f: F) -> Result<R, E>
where
KeyArg: EncodeLike<Key>,
F: FnOnce(&mut QueryKind::Query) -> Result<R, E>,
{
<Self as crate::storage::StorageMap<Key, Value>>::try_mutate(key, f)
}
pub fn mutate_extant<KeyArg: EncodeLike<Key>, R: Default, F: FnOnce(&mut Value) -> R>(
key: KeyArg,
f: F,
) -> R {
<Self as crate::storage::StorageMap<Key, Value>>::mutate_extant(key, f)
}
pub fn mutate_exists<KeyArg: EncodeLike<Key>, R, F: FnOnce(&mut Option<Value>) -> R>(
key: KeyArg,
f: F,
) -> R {
<Self as crate::storage::StorageMap<Key, Value>>::mutate_exists(key, f)
}
pub fn try_mutate_exists<KeyArg, R, E, F>(key: KeyArg, f: F) -> Result<R, E>
where
KeyArg: EncodeLike<Key>,
F: FnOnce(&mut Option<Value>) -> Result<R, E>,
{
<Self as crate::storage::StorageMap<Key, Value>>::try_mutate_exists(key, f)
}
pub fn take<KeyArg: EncodeLike<Key>>(key: KeyArg) -> QueryKind::Query {
<Self as crate::storage::StorageMap<Key, Value>>::take(key)
}
pub fn append<Item, EncodeLikeItem, EncodeLikeKey>(key: EncodeLikeKey, item: EncodeLikeItem)
where
EncodeLikeKey: EncodeLike<Key>,
Item: Encode,
EncodeLikeItem: EncodeLike<Item>,
Value: StorageAppend<Item>,
{
<Self as crate::storage::StorageMap<Key, Value>>::append(key, item)
}
pub fn decode_len<KeyArg: EncodeLike<Key>>(key: KeyArg) -> Option<usize>
where
Value: StorageDecodeLength,
{
<Self as crate::storage::StorageMap<Key, Value>>::decode_len(key)
}
pub fn decode_non_dedup_len<KeyArg: EncodeLike<Key>>(key: KeyArg) -> Option<usize>
where
Value: StorageDecodeNonDedupLength,
{
<Self as crate::storage::StorageMap<Key, Value>>::decode_non_dedup_len(key)
}
pub fn migrate_key<OldHasher: crate::hash::StorageHasher, KeyArg: EncodeLike<Key>>(
key: KeyArg,
) -> Option<Value> {
<Self as crate::storage::StorageMap<Key, Value>>::migrate_key::<OldHasher, _>(key)
}
#[deprecated = "Use `clear` instead"]
pub fn remove_all(limit: Option<u32>) -> sp_io::KillStorageResult {
#[allow(deprecated)]
<Self as crate::storage::StoragePrefixedMap<Value>>::remove_all(limit)
}
pub fn clear(limit: u32, maybe_cursor: Option<&[u8]>) -> sp_io::MultiRemovalResults {
<Self as crate::storage::StoragePrefixedMap<Value>>::clear(limit, maybe_cursor)
}
pub fn iter_values() -> crate::storage::PrefixIterator<Value> {
<Self as crate::storage::StoragePrefixedMap<Value>>::iter_values()
}
pub fn translate_values<OldValue: Decode, F: FnMut(OldValue) -> Option<Value>>(f: F) {
<Self as crate::storage::StoragePrefixedMap<Value>>::translate_values(f)
}
pub fn try_append<KArg, Item, EncodeLikeItem>(key: KArg, item: EncodeLikeItem) -> Result<(), ()>
where
KArg: EncodeLike<Key> + Clone,
Item: Encode,
EncodeLikeItem: EncodeLike<Item>,
Value: StorageTryAppend<Item>,
{
<Self as crate::storage::TryAppendMap<Key, Value, Item>>::try_append(key, item)
}
}
impl<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues>
StorageMap<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues>
where
Prefix: StorageInstance,
Hasher: crate::hash::StorageHasher + crate::ReversibleStorageHasher,
Key: FullCodec,
Value: FullCodec,
QueryKind: QueryKindTrait<Value, OnEmpty>,
OnEmpty: Get<QueryKind::Query> + 'static,
MaxValues: Get<Option<u32>>,
{
pub fn iter() -> crate::storage::PrefixIterator<(Key, Value)> {
<Self as crate::storage::IterableStorageMap<Key, Value>>::iter()
}
pub fn iter_from(starting_raw_key: Vec<u8>) -> crate::storage::PrefixIterator<(Key, Value)> {
<Self as crate::storage::IterableStorageMap<Key, Value>>::iter_from(starting_raw_key)
}
pub fn iter_from_key(
starting_key: impl EncodeLike<Key>,
) -> crate::storage::PrefixIterator<(Key, Value)> {
Self::iter_from(Self::hashed_key_for(starting_key))
}
pub fn iter_keys() -> crate::storage::KeyPrefixIterator<Key> {
<Self as crate::storage::IterableStorageMap<Key, Value>>::iter_keys()
}
pub fn iter_keys_from(starting_raw_key: Vec<u8>) -> crate::storage::KeyPrefixIterator<Key> {
<Self as crate::storage::IterableStorageMap<Key, Value>>::iter_keys_from(starting_raw_key)
}
pub fn iter_keys_from_key(
starting_key: impl EncodeLike<Key>,
) -> crate::storage::KeyPrefixIterator<Key> {
Self::iter_keys_from(Self::hashed_key_for(starting_key))
}
pub fn drain() -> crate::storage::PrefixIterator<(Key, Value)> {
<Self as crate::storage::IterableStorageMap<Key, Value>>::drain()
}
pub fn translate<O: Decode, F: FnMut(Key, O) -> Option<Value>>(f: F) {
<Self as crate::storage::IterableStorageMap<Key, Value>>::translate(f)
}
}
impl<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues> StorageEntryMetadataBuilder
for StorageMap<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues>
where
Prefix: StorageInstance,
Hasher: crate::hash::StorageHasher,
Key: FullCodec + scale_info::StaticTypeInfo,
Value: FullCodec + scale_info::StaticTypeInfo,
QueryKind: QueryKindTrait<Value, OnEmpty>,
OnEmpty: Get<QueryKind::Query> + 'static,
MaxValues: Get<Option<u32>>,
{
fn build_metadata(
deprecation_status: sp_metadata_ir::DeprecationStatusIR,
docs: Vec<&'static str>,
entries: &mut Vec<StorageEntryMetadataIR>,
) {
let docs = if cfg!(feature = "no-metadata-docs") { vec![] } else { docs };
let entry = StorageEntryMetadataIR {
name: Prefix::STORAGE_PREFIX,
modifier: QueryKind::METADATA,
ty: StorageEntryTypeIR::Map {
hashers: vec![Hasher::METADATA],
key: scale_info::meta_type::<Key>(),
value: scale_info::meta_type::<Value>(),
},
default: OnEmpty::get().encode(),
docs,
deprecation_info: deprecation_status,
};
entries.push(entry);
}
}
impl<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues> crate::traits::StorageInfoTrait
for StorageMap<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues>
where
Prefix: StorageInstance,
Hasher: crate::hash::StorageHasher,
Key: FullCodec + MaxEncodedLen,
Value: FullCodec + MaxEncodedLen,
QueryKind: QueryKindTrait<Value, OnEmpty>,
OnEmpty: Get<QueryKind::Query> + 'static,
MaxValues: Get<Option<u32>>,
{
fn storage_info() -> Vec<StorageInfo> {
vec![StorageInfo {
pallet_name: Self::pallet_prefix().to_vec(),
storage_name: Self::storage_prefix().to_vec(),
prefix: Self::final_prefix().to_vec(),
max_values: MaxValues::get(),
max_size: Some(
Hasher::max_len::<Key>()
.saturating_add(Value::max_encoded_len())
.saturated_into(),
),
}]
}
}
impl<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues>
crate::traits::PartialStorageInfoTrait
for StorageMap<Prefix, Hasher, Key, Value, QueryKind, OnEmpty, MaxValues>
where
Prefix: StorageInstance,
Hasher: crate::hash::StorageHasher,
Key: FullCodec,
Value: FullCodec,
QueryKind: QueryKindTrait<Value, OnEmpty>,
OnEmpty: Get<QueryKind::Query> + 'static,
MaxValues: Get<Option<u32>>,
{
fn partial_storage_info() -> Vec<StorageInfo> {
vec![StorageInfo {
pallet_name: Self::pallet_prefix().to_vec(),
storage_name: Self::storage_prefix().to_vec(),
prefix: Self::final_prefix().to_vec(),
max_values: MaxValues::get(),
max_size: None,
}]
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{
hash::*,
storage::{types::ValueQuery, IterableStorageMap},
};
use sp_io::{hashing::twox_128, TestExternalities};
use sp_metadata_ir::{StorageEntryModifierIR, StorageEntryTypeIR, StorageHasherIR};
struct Prefix;
impl StorageInstance for Prefix {
fn pallet_prefix() -> &'static str {
"test"
}
const STORAGE_PREFIX: &'static str = "foo";
}
struct ADefault;
impl crate::traits::Get<u32> for ADefault {
fn get() -> u32 {
97
}
}
#[test]
fn keylenof_works() {
type A = StorageMap<Prefix, Blake2_128Concat, u32, u32>;
let size = 16 * 2 + 16 + 4; assert_eq!(KeyLenOf::<A>::get(), size);
type B = StorageMap<Prefix, Blake2_256, u32, u32>;
let size = 16 * 2 + 32; assert_eq!(KeyLenOf::<B>::get(), size);
type C = StorageMap<Prefix, Twox64Concat, u32, u32>;
let size = 16 * 2 + 8 + 4; assert_eq!(KeyLenOf::<C>::get(), size);
}
#[test]
fn test() {
type A = StorageMap<Prefix, Blake2_128Concat, u16, u32, OptionQuery>;
type AValueQueryWithAnOnEmpty =
StorageMap<Prefix, Blake2_128Concat, u16, u32, ValueQuery, ADefault>;
type B = StorageMap<Prefix, Blake2_256, u16, u32, ValueQuery>;
type C = StorageMap<Prefix, Blake2_128Concat, u16, u8, ValueQuery>;
type WithLen = StorageMap<Prefix, Blake2_128Concat, u16, Vec<u32>>;
TestExternalities::default().execute_with(|| {
let mut k: Vec<u8> = vec![];
k.extend(&twox_128(b"test"));
k.extend(&twox_128(b"foo"));
k.extend(&3u16.blake2_128_concat());
assert_eq!(A::hashed_key_for(3).to_vec(), k);
assert_eq!(A::contains_key(3), false);
assert_eq!(A::get(3), None);
assert_eq!(AValueQueryWithAnOnEmpty::get(3), 97);
A::insert(3, 10);
assert_eq!(A::contains_key(3), true);
assert_eq!(A::get(3), Some(10));
assert_eq!(A::try_get(3), Ok(10));
assert_eq!(AValueQueryWithAnOnEmpty::get(3), 10);
A::swap(3, 2);
assert_eq!(A::contains_key(3), false);
assert_eq!(A::contains_key(2), true);
assert_eq!(A::get(3), None);
assert_eq!(A::try_get(3), Err(()));
assert_eq!(AValueQueryWithAnOnEmpty::get(3), 97);
assert_eq!(A::get(2), Some(10));
assert_eq!(AValueQueryWithAnOnEmpty::get(2), 10);
A::remove(2);
assert_eq!(A::contains_key(2), false);
assert_eq!(A::get(2), None);
AValueQueryWithAnOnEmpty::mutate(2, |v| *v = *v * 2);
AValueQueryWithAnOnEmpty::mutate(2, |v| *v = *v * 2);
assert_eq!(AValueQueryWithAnOnEmpty::contains_key(2), true);
assert_eq!(AValueQueryWithAnOnEmpty::get(2), 97 * 4);
A::remove(2);
let _: Result<(), ()> = AValueQueryWithAnOnEmpty::try_mutate(2, |v| {
*v = *v * 2;
Ok(())
});
let _: Result<(), ()> = AValueQueryWithAnOnEmpty::try_mutate(2, |v| {
*v = *v * 2;
Ok(())
});
assert_eq!(A::contains_key(2), true);
assert_eq!(A::get(2), Some(97 * 4));
A::remove(2);
let _: Result<(), ()> = AValueQueryWithAnOnEmpty::try_mutate(2, |v| {
*v = *v * 2;
Err(())
});
assert_eq!(A::contains_key(2), false);
A::remove(2);
AValueQueryWithAnOnEmpty::mutate_exists(2, |v| {
assert!(v.is_none());
*v = Some(10);
});
assert_eq!(A::contains_key(2), true);
assert_eq!(A::get(2), Some(10));
AValueQueryWithAnOnEmpty::mutate_exists(2, |v| {
*v = Some(v.unwrap() * 10);
});
assert_eq!(A::contains_key(2), true);
assert_eq!(A::get(2), Some(100));
A::remove(2);
let _: Result<(), ()> = AValueQueryWithAnOnEmpty::try_mutate_exists(2, |v| {
assert!(v.is_none());
*v = Some(10);
Ok(())
});
assert_eq!(A::contains_key(2), true);
assert_eq!(A::get(2), Some(10));
let _: Result<(), ()> = AValueQueryWithAnOnEmpty::try_mutate_exists(2, |v| {
*v = Some(v.unwrap() * 10);
Ok(())
});
assert_eq!(A::contains_key(2), true);
assert_eq!(A::get(2), Some(100));
let _: Result<(), ()> = AValueQueryWithAnOnEmpty::try_mutate_exists(2, |v| {
*v = Some(v.unwrap() * 10);
Err(())
});
assert_eq!(A::contains_key(2), true);
assert_eq!(A::get(2), Some(100));
A::insert(2, 10);
assert_eq!(A::take(2), Some(10));
assert_eq!(A::contains_key(2), false);
assert_eq!(AValueQueryWithAnOnEmpty::take(2), 97);
assert_eq!(A::contains_key(2), false);
B::set(30, 100);
assert_eq!(B::contains_key(30), true);
assert_eq!(B::get(30), 100);
assert_eq!(B::try_get(30), Ok(100));
B::set(30, 101);
assert_eq!(B::contains_key(30), true);
assert_eq!(B::get(30), 101);
assert_eq!(B::try_get(30), Ok(101));
A::set(30, Some(100));
assert_eq!(A::contains_key(30), true);
assert_eq!(A::get(30), Some(100));
assert_eq!(A::try_get(30), Ok(100));
A::set(30, Some(101));
assert_eq!(A::contains_key(30), true);
assert_eq!(A::get(30), Some(101));
assert_eq!(A::try_get(30), Ok(101));
A::set(30, None);
assert_eq!(A::contains_key(30), false);
assert_eq!(A::get(30), None);
assert_eq!(A::try_get(30), Err(()));
A::set(31, None);
assert_eq!(A::contains_key(31), false);
assert_eq!(A::get(31), None);
assert_eq!(A::try_get(31), Err(()));
B::insert(2, 10);
assert_eq!(A::migrate_key::<Blake2_256, _>(2), Some(10));
assert_eq!(A::contains_key(2), true);
assert_eq!(A::get(2), Some(10));
A::insert(3, 10);
A::insert(4, 10);
let _ = A::clear(u32::max_value(), None);
assert_eq!(A::contains_key(3), false);
assert_eq!(A::contains_key(4), false);
A::insert(3, 10);
A::insert(4, 10);
assert_eq!(A::iter_values().collect::<Vec<_>>(), vec![10, 10]);
C::insert(3, 10);
C::insert(4, 10);
A::translate_values::<u8, _>(|v| Some((v * 2).into()));
assert_eq!(A::iter().collect::<Vec<_>>(), vec![(4, 20), (3, 20)]);
A::insert(3, 10);
A::insert(4, 10);
assert_eq!(A::iter().collect::<Vec<_>>(), vec![(4, 10), (3, 10)]);
assert_eq!(A::drain().collect::<Vec<_>>(), vec![(4, 10), (3, 10)]);
assert_eq!(A::iter().collect::<Vec<_>>(), vec![]);
C::insert(3, 10);
C::insert(4, 10);
A::translate::<u8, _>(|k, v| Some((k * v as u16).into()));
assert_eq!(A::iter().collect::<Vec<_>>(), vec![(4, 40), (3, 30)]);
let translate_next = |k: u16, v: u8| Some((v as u16 / k).into());
let k = A::translate_next::<u8, _>(None, translate_next);
let k = A::translate_next::<u8, _>(k, translate_next);
assert_eq!(None, A::translate_next::<u8, _>(k, translate_next));
assert_eq!(A::iter().collect::<Vec<_>>(), vec![(4, 10), (3, 10)]);
let _ = A::translate_next::<u8, _>(None, |_, _| None);
assert_eq!(A::iter().collect::<Vec<_>>(), vec![(3, 10)]);
let mut entries = vec![];
A::build_metadata(
sp_metadata_ir::DeprecationStatusIR::NotDeprecated,
vec![],
&mut entries,
);
AValueQueryWithAnOnEmpty::build_metadata(
sp_metadata_ir::DeprecationStatusIR::NotDeprecated,
vec![],
&mut entries,
);
assert_eq!(
entries,
vec![
StorageEntryMetadataIR {
name: "foo",
modifier: StorageEntryModifierIR::Optional,
ty: StorageEntryTypeIR::Map {
hashers: vec![StorageHasherIR::Blake2_128Concat],
key: scale_info::meta_type::<u16>(),
value: scale_info::meta_type::<u32>(),
},
default: Option::<u32>::None.encode(),
docs: vec![],
deprecation_info: sp_metadata_ir::DeprecationStatusIR::NotDeprecated
},
StorageEntryMetadataIR {
name: "foo",
modifier: StorageEntryModifierIR::Default,
ty: StorageEntryTypeIR::Map {
hashers: vec![StorageHasherIR::Blake2_128Concat],
key: scale_info::meta_type::<u16>(),
value: scale_info::meta_type::<u32>(),
},
default: 97u32.encode(),
docs: vec![],
deprecation_info: sp_metadata_ir::DeprecationStatusIR::NotDeprecated
}
]
);
let _ = WithLen::clear(u32::max_value(), None);
assert_eq!(WithLen::decode_len(3), None);
WithLen::append(0, 10);
assert_eq!(WithLen::decode_len(0), Some(1));
})
}
}