1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// This file is part of Substrate.

// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Storage value type. Implements StorageValue trait and its method directly.

use crate::{
	metadata::{StorageEntryMetadata, StorageEntryType},
	storage::{
		generator::StorageValue as StorageValueT,
		types::{OptionQuery, QueryKindTrait, StorageEntryMetadataBuilder},
		StorageAppend, StorageDecodeLength, StorageTryAppend,
	},
	traits::{GetDefault, StorageInfo, StorageInstance},
};
use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen};
use sp_arithmetic::traits::SaturatedConversion;
use sp_std::prelude::*;

/// A type that allow to store a value.
///
/// Each value is stored at:
/// ```nocompile
/// Twox128(Prefix::pallet_prefix()) ++ Twox128(Prefix::STORAGE_PREFIX)
/// ```
pub struct StorageValue<Prefix, Value, QueryKind = OptionQuery, OnEmpty = GetDefault>(
	core::marker::PhantomData<(Prefix, Value, QueryKind, OnEmpty)>,
);

impl<Prefix, Value, QueryKind, OnEmpty> crate::storage::generator::StorageValue<Value>
	for StorageValue<Prefix, Value, QueryKind, OnEmpty>
where
	Prefix: StorageInstance,
	Value: FullCodec,
	QueryKind: QueryKindTrait<Value, OnEmpty>,
	OnEmpty: crate::traits::Get<QueryKind::Query> + 'static,
{
	type Query = QueryKind::Query;
	fn module_prefix() -> &'static [u8] {
		Prefix::pallet_prefix().as_bytes()
	}
	fn storage_prefix() -> &'static [u8] {
		Prefix::STORAGE_PREFIX.as_bytes()
	}
	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, Value, QueryKind, OnEmpty> StorageValue<Prefix, Value, QueryKind, OnEmpty>
where
	Prefix: StorageInstance,
	Value: FullCodec,
	QueryKind: QueryKindTrait<Value, OnEmpty>,
	OnEmpty: crate::traits::Get<QueryKind::Query> + 'static,
{
	/// Get the storage key.
	pub fn hashed_key() -> [u8; 32] {
		<Self as crate::storage::StorageValue<Value>>::hashed_key()
	}

	/// Does the value (explicitly) exist in storage?
	pub fn exists() -> bool {
		<Self as crate::storage::StorageValue<Value>>::exists()
	}

	/// Load the value from the provided storage instance.
	pub fn get() -> QueryKind::Query {
		<Self as crate::storage::StorageValue<Value>>::get()
	}

	/// Try to get the underlying value from the provided storage instance; `Ok` if it exists,
	/// `Err` if not.
	pub fn try_get() -> Result<Value, ()> {
		<Self as crate::storage::StorageValue<Value>>::try_get()
	}

	/// Translate a value from some previous type (`O`) to the current type.
	///
	/// `f: F` is the translation function.
	///
	/// Returns `Err` if the storage item could not be interpreted as the old type, and Ok, along
	/// with the new value if it could.
	///
	/// NOTE: This operates from and to `Option<_>` types; no effort is made to respect the default
	/// value of the original type.
	///
	/// # Warning
	///
	/// This function must be used with care, before being updated the storage still contains the
	/// old type, thus other calls (such as `get`) will fail at decoding it.
	///
	/// # Usage
	///
	/// This would typically be called inside the module implementation of on_runtime_upgrade,
	/// while ensuring **no usage of this storage are made before the call to
	/// `on_runtime_upgrade`**. (More precisely prior initialized modules doesn't make use of this
	/// storage).
	pub fn translate<O: Decode, F: FnOnce(Option<O>) -> Option<Value>>(
		f: F,
	) -> Result<Option<Value>, ()> {
		<Self as crate::storage::StorageValue<Value>>::translate(f)
	}

	/// Store a value under this key into the provided storage instance.
	pub fn put<Arg: EncodeLike<Value>>(val: Arg) {
		<Self as crate::storage::StorageValue<Value>>::put(val)
	}

	/// Store a value under this key into the provided storage instance.
	///
	/// this uses the query type rather than the underlying value.
	pub fn set(val: QueryKind::Query) {
		<Self as crate::storage::StorageValue<Value>>::set(val)
	}

	/// Mutate the value
	pub fn mutate<R, F: FnOnce(&mut QueryKind::Query) -> R>(f: F) -> R {
		<Self as crate::storage::StorageValue<Value>>::mutate(f)
	}

	/// Mutate the value if closure returns `Ok`
	pub fn try_mutate<R, E, F: FnOnce(&mut QueryKind::Query) -> Result<R, E>>(
		f: F,
	) -> Result<R, E> {
		<Self as crate::storage::StorageValue<Value>>::try_mutate(f)
	}

	/// Clear the storage value.
	pub fn kill() {
		<Self as crate::storage::StorageValue<Value>>::kill()
	}

	/// Take a value from storage, removing it afterwards.
	pub fn take() -> QueryKind::Query {
		<Self as crate::storage::StorageValue<Value>>::take()
	}

	/// Append the given item to the value in the storage.
	///
	/// `Value` is required to implement [`StorageAppend`].
	///
	/// # Warning
	///
	/// If the storage item is not encoded properly, the storage item will be overwritten
	/// and set to `[item]`. Any default value set for the storage item will be ignored
	/// on overwrite.
	pub fn append<Item, EncodeLikeItem>(item: EncodeLikeItem)
	where
		Item: Encode,
		EncodeLikeItem: EncodeLike<Item>,
		Value: StorageAppend<Item>,
	{
		<Self as crate::storage::StorageValue<Value>>::append(item)
	}

	/// Read the length of the storage value without decoding the entire value.
	///
	/// `Value` is required to implement [`StorageDecodeLength`].
	///
	/// If the value does not exists or it fails to decode the length, `None` is returned.
	/// Otherwise `Some(len)` is returned.
	///
	/// # Warning
	///
	/// `None` does not mean that `get()` does not return a value. The default value is completly
	/// ignored by this function.
	pub fn decode_len() -> Option<usize>
	where
		Value: StorageDecodeLength,
	{
		<Self as crate::storage::StorageValue<Value>>::decode_len()
	}

	/// Try and append the given item to the value in the storage.
	///
	/// Is only available if `Value` of the storage implements [`StorageTryAppend`].
	pub fn try_append<Item, EncodeLikeItem>(item: EncodeLikeItem) -> Result<(), ()>
	where
		Item: Encode,
		EncodeLikeItem: EncodeLike<Item>,
		Value: StorageTryAppend<Item>,
	{
		<Self as crate::storage::TryAppendValue<Value, Item>>::try_append(item)
	}
}

impl<Prefix, Value, QueryKind, OnEmpty> StorageEntryMetadataBuilder
	for StorageValue<Prefix, Value, QueryKind, OnEmpty>
where
	Prefix: StorageInstance,
	Value: FullCodec + scale_info::StaticTypeInfo,
	QueryKind: QueryKindTrait<Value, OnEmpty>,
	OnEmpty: crate::traits::Get<QueryKind::Query> + 'static,
{
	fn build_metadata(docs: Vec<&'static str>, entries: &mut Vec<StorageEntryMetadata>) {
		let entry = StorageEntryMetadata {
			name: Prefix::STORAGE_PREFIX,
			modifier: QueryKind::METADATA,
			ty: StorageEntryType::Plain(scale_info::meta_type::<Value>()),
			default: OnEmpty::get().encode(),
			docs,
		};

		entries.push(entry);
	}
}

impl<Prefix, Value, QueryKind, OnEmpty> crate::traits::StorageInfoTrait
	for StorageValue<Prefix, Value, QueryKind, OnEmpty>
where
	Prefix: StorageInstance,
	Value: FullCodec + MaxEncodedLen,
	QueryKind: QueryKindTrait<Value, OnEmpty>,
	OnEmpty: crate::traits::Get<QueryKind::Query> + 'static,
{
	fn storage_info() -> Vec<StorageInfo> {
		vec![StorageInfo {
			pallet_name: Self::module_prefix().to_vec(),
			storage_name: Self::storage_prefix().to_vec(),
			prefix: Self::hashed_key().to_vec(),
			max_values: Some(1),
			max_size: Some(Value::max_encoded_len().saturated_into()),
		}]
	}
}

/// It doesn't require to implement `MaxEncodedLen` and give no information for `max_size`.
impl<Prefix, Value, QueryKind, OnEmpty> crate::traits::PartialStorageInfoTrait
	for StorageValue<Prefix, Value, QueryKind, OnEmpty>
where
	Prefix: StorageInstance,
	Value: FullCodec,
	QueryKind: QueryKindTrait<Value, OnEmpty>,
	OnEmpty: crate::traits::Get<QueryKind::Query> + 'static,
{
	fn partial_storage_info() -> Vec<StorageInfo> {
		vec![StorageInfo {
			pallet_name: Self::module_prefix().to_vec(),
			storage_name: Self::storage_prefix().to_vec(),
			prefix: Self::hashed_key().to_vec(),
			max_values: Some(1),
			max_size: None,
		}]
	}
}

#[cfg(test)]
mod test {
	use super::*;
	use crate::{metadata::StorageEntryModifier, storage::types::ValueQuery};
	use sp_io::{hashing::twox_128, TestExternalities};

	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 test() {
		type A = StorageValue<Prefix, u32, OptionQuery>;
		type AValueQueryWithAnOnEmpty = StorageValue<Prefix, u32, ValueQuery, ADefault>;
		type B = StorageValue<Prefix, u16, ValueQuery>;
		type WithLen = StorageValue<Prefix, Vec<u32>>;

		TestExternalities::default().execute_with(|| {
			assert_eq!(A::hashed_key().to_vec(), [twox_128(b"test"), twox_128(b"foo")].concat());
			assert_eq!(A::exists(), false);
			assert_eq!(A::get(), None);
			assert_eq!(AValueQueryWithAnOnEmpty::get(), 97);
			assert_eq!(A::try_get(), Err(()));

			A::put(2);
			assert_eq!(A::exists(), true);
			assert_eq!(A::get(), Some(2));
			assert_eq!(AValueQueryWithAnOnEmpty::get(), 2);
			assert_eq!(A::try_get(), Ok(2));
			assert_eq!(A::try_get(), Ok(2));

			B::put(4);
			A::translate::<u16, _>(|v| v.map(Into::into)).unwrap();
			assert_eq!(A::try_get(), Ok(4));

			A::set(None);
			assert_eq!(A::try_get(), Err(()));

			A::set(Some(2));
			assert_eq!(A::try_get(), Ok(2));

			A::mutate(|v| *v = Some(v.unwrap() * 2));
			assert_eq!(A::try_get(), Ok(4));

			A::set(Some(4));
			let _: Result<(), ()> = A::try_mutate(|v| {
				*v = Some(v.unwrap() * 2);
				Ok(())
			});
			assert_eq!(A::try_get(), Ok(8));

			let _: Result<(), ()> = A::try_mutate(|v| {
				*v = Some(v.unwrap() * 2);
				Err(())
			});
			assert_eq!(A::try_get(), Ok(8));

			A::kill();
			AValueQueryWithAnOnEmpty::mutate(|v| *v = *v * 2);
			assert_eq!(AValueQueryWithAnOnEmpty::try_get(), Ok(97 * 2));

			AValueQueryWithAnOnEmpty::kill();
			let _: Result<(), ()> = AValueQueryWithAnOnEmpty::try_mutate(|v| {
				*v = *v * 2;
				Ok(())
			});
			assert_eq!(AValueQueryWithAnOnEmpty::try_get(), Ok(97 * 2));

			A::kill();
			assert_eq!(A::try_get(), Err(()));

			let mut entries = vec![];
			A::build_metadata(vec![], &mut entries);
			AValueQueryWithAnOnEmpty::build_metadata(vec![], &mut entries);
			assert_eq!(
				entries,
				vec![
					StorageEntryMetadata {
						name: "foo",
						modifier: StorageEntryModifier::Optional,
						ty: StorageEntryType::Plain(scale_info::meta_type::<u32>()),
						default: Option::<u32>::None.encode(),
						docs: vec![],
					},
					StorageEntryMetadata {
						name: "foo",
						modifier: StorageEntryModifier::Default,
						ty: StorageEntryType::Plain(scale_info::meta_type::<u32>()),
						default: 97u32.encode(),
						docs: vec![],
					}
				]
			);

			WithLen::kill();
			assert_eq!(WithLen::decode_len(), None);
			WithLen::append(3);
			assert_eq!(WithLen::decode_len(), Some(1));
		});
	}
}