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 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
// Copyright (C) Use Ink (UK) Ltd.
//
// 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.
//! A simple mapping to contract storage.
//!
//! # Note
//!
//! This mapping doesn't actually "own" any data.
//! Instead it is just a simple wrapper around the contract storage facilities.
use crate::traits::{
AutoKey,
Packed,
StorableHint,
StorageKey,
};
use core::marker::PhantomData;
use ink_primitives::Key;
use ink_storage_traits::Storable;
use scale::{
Encode,
Error,
Input,
Output,
};
/// A mapping of key-value pairs directly into contract storage.
///
/// # Important
///
/// The mapping requires its own pre-defined storage key where to store values. By
/// default, the is automatically calculated using [`AutoKey`](crate::traits::AutoKey)
/// during compilation. However, anyone can specify a storage key using
/// [`ManualKey`](crate::traits::ManualKey). Specifying the storage key can be helpful for
/// upgradeable contracts or you want to be resistant to future changes of storage key
/// calculation strategy.
///
/// This is an example of how you can do this:
/// ```rust
/// # use ink::env::{
/// # Environment,
/// # DefaultEnvironment,
/// # };
/// # type AccountId = <DefaultEnvironment as Environment>::AccountId;
///
/// # #[ink::contract]
/// # mod my_module {
/// use ink::storage::{
/// traits::ManualKey,
/// Mapping,
/// };
///
/// #[ink(storage)]
/// #[derive(Default)]
/// pub struct MyContract {
/// balances: Mapping<AccountId, Balance, ManualKey<123>>,
/// }
///
/// impl MyContract {
/// #[ink(constructor)]
/// pub fn new() -> Self {
/// let mut instance = Self::default();
/// let caller = Self::env().caller();
/// let value: Balance = Default::default();
/// instance.balances.insert(&caller, &value);
/// instance
/// }
///
/// # #[ink(message)]
/// # pub fn my_message(&self) { }
/// }
/// # }
/// ```
///
/// More usage examples can be found [in the ink! examples](https://github.com/use-ink/ink-examples).
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct Mapping<K, V: Packed, KeyType: StorageKey = AutoKey> {
#[allow(clippy::type_complexity)]
_marker: PhantomData<fn() -> (K, V, KeyType)>,
}
/// We implement this manually because the derived implementation adds trait bounds.
impl<K, V, KeyType> Default for Mapping<K, V, KeyType>
where
V: Packed,
KeyType: StorageKey,
{
fn default() -> Self {
Self::new()
}
}
impl<K, V, KeyType> Mapping<K, V, KeyType>
where
V: Packed,
KeyType: StorageKey,
{
/// Creates a new empty `Mapping`.
pub const fn new() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl<K, V, KeyType> ::core::fmt::Debug for Mapping<K, V, KeyType>
where
V: Packed,
KeyType: StorageKey,
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("Mapping")
.field("key", &KeyType::KEY)
.finish()
}
}
impl<K, V, KeyType> Mapping<K, V, KeyType>
where
K: Encode,
V: Packed,
KeyType: StorageKey,
{
/// Insert the given `value` to the contract storage.
///
/// Returns the size in bytes of the pre-existing value at the specified key if any.
///
/// # Panics
///
/// Traps if encoding the `key` together with the `value` doesn't fit into the static
/// buffer.
#[inline]
pub fn insert<Q, R>(&mut self, key: Q, value: &R) -> Option<u32>
where
Q: scale::EncodeLike<K>,
R: Storable + scale::EncodeLike<V>,
{
ink_env::set_contract_storage(&(&KeyType::KEY, key), value)
}
/// Try to insert the given `value` into the mapping under given `key`.
///
/// Fails if `key` or `value` exceeds the static buffer size.
///
/// Returns:
/// - `Ok(Some(_))` if the value was inserted successfully, containing the size in
/// bytes of the pre-existing value at the specified key if any.
/// - `Ok(None)` if the insert was successful but there was no pre-existing value.
/// - `Err(_)` if encoding the `key` together with the `value` exceeds the static
/// buffer size.
#[inline]
pub fn try_insert<Q, R>(&mut self, key: Q, value: &R) -> ink_env::Result<Option<u32>>
where
Q: scale::EncodeLike<K>,
R: Storable + scale::EncodeLike<V>,
{
let key_size = <Q as Encode>::encoded_size(&key);
if key_size > ink_env::BUFFER_SIZE {
return Err(ink_env::Error::BufferTooSmall)
}
let value_size = <R as Storable>::encoded_size(value);
if key_size.saturating_add(value_size) > ink_env::BUFFER_SIZE {
return Err(ink_env::Error::BufferTooSmall)
}
Ok(self.insert(key, value))
}
/// Get the `value` at `key` from the contract storage.
///
/// Returns `None` if no `value` exists at the given `key`.
///
/// # Panics
///
/// Traps if the the encoded `key` or `value` doesn't fit into the static buffer.
#[inline]
pub fn get<Q>(&self, key: Q) -> Option<V>
where
Q: scale::EncodeLike<K>,
{
ink_env::get_contract_storage(&(&KeyType::KEY, key))
.unwrap_or_else(|error| panic!("Failed to get value in Mapping: {error:?}"))
}
/// Try to get the `value` at the given `key`.
///
/// Returns:
/// - `Some(Ok(_))` containing the value if it existed and was decoded successfully.
/// - `Some(Err(_))` if either (a) the encoded key doesn't fit into the static buffer
/// or (b) the value existed but its length exceeds the static buffer size.
/// - `None` if there was no value under this mapping key.
#[inline]
pub fn try_get<Q>(&self, key: Q) -> Option<ink_env::Result<V>>
where
Q: scale::EncodeLike<K>,
{
let key_size = <Q as Encode>::encoded_size(&key);
if key_size > ink_env::BUFFER_SIZE {
return Some(Err(ink_env::Error::BufferTooSmall))
}
let value_size: usize =
ink_env::contains_contract_storage(&(&KeyType::KEY, &key))?
.try_into()
.expect("targets of less than 32bit pointer size are not supported; qed");
if key_size.saturating_add(value_size) > ink_env::BUFFER_SIZE {
return Some(Err(ink_env::Error::BufferTooSmall))
}
self.get(key).map(Ok)
}
/// Removes the `value` at `key`, returning the previous `value` at `key` from
/// storage.
///
/// Returns `None` if no `value` exists at the given `key`.
///
/// # Panics
///
/// Traps if the encoded `key` or `value` doesn't fit into the static buffer.
///
/// # Warning
///
/// This method uses the
/// [unstable interface](https://github.com/paritytech/substrate/tree/master/frame/contracts#unstable-interfaces),
/// which is unsafe and normally is not available on production chains.
#[inline]
pub fn take<Q>(&self, key: Q) -> Option<V>
where
Q: scale::EncodeLike<K>,
{
ink_env::take_contract_storage(&(&KeyType::KEY, key))
.unwrap_or_else(|error| panic!("Failed to take value in Mapping: {error:?}"))
}
/// Try to take the `value` at the given `key`.
/// On success, this operation will remove the value from the mapping
///
/// Returns:
/// - `Some(Ok(_))` containing the value if it existed and was decoded successfully.
/// - `Some(Err(_))` if either (a) the encoded key doesn't fit into the static buffer
/// or (b) the value existed but its length exceeds the static buffer size.
/// - `None` if there was no value under this mapping key.
////
/// # Warning
///
/// This method uses the
/// [unstable interface](https://github.com/paritytech/substrate/tree/master/frame/contracts#unstable-interfaces),
/// which is unsafe and normally is not available on production chains.
#[inline]
pub fn try_take<Q>(&self, key: Q) -> Option<ink_env::Result<V>>
where
Q: scale::EncodeLike<K>,
{
let key_size = <Q as Encode>::encoded_size(&key);
if key_size > ink_env::BUFFER_SIZE {
return Some(Err(ink_env::Error::BufferTooSmall))
}
let value_size: usize =
ink_env::contains_contract_storage(&(&KeyType::KEY, &key))?
.try_into()
.expect("targets of less than 32bit pointer size are not supported; qed");
if key_size.saturating_add(value_size) > ink_env::BUFFER_SIZE {
return Some(Err(ink_env::Error::BufferTooSmall))
}
self.take(key).map(Ok)
}
/// Get the size in bytes of a value stored at `key` in the contract storage.
///
/// Returns `None` if no `value` exists at the given `key`.
#[inline]
pub fn size<Q>(&self, key: Q) -> Option<u32>
where
Q: scale::EncodeLike<K>,
{
ink_env::contains_contract_storage(&(&KeyType::KEY, key))
}
/// Checks if a value is stored at the given `key` in the contract storage.
///
/// Returns `false` if no `value` exists at the given `key`.
#[inline]
pub fn contains<Q>(&self, key: Q) -> bool
where
Q: scale::EncodeLike<K>,
{
ink_env::contains_contract_storage(&(&KeyType::KEY, key)).is_some()
}
/// Clears the value at `key` from storage.
#[inline]
pub fn remove<Q>(&self, key: Q)
where
Q: scale::EncodeLike<K>,
{
ink_env::clear_contract_storage(&(&KeyType::KEY, key));
}
}
impl<K, V, KeyType> Storable for Mapping<K, V, KeyType>
where
V: Packed,
KeyType: StorageKey,
{
#[inline]
fn encode<T: Output + ?Sized>(&self, _dest: &mut T) {}
#[inline]
fn decode<I: Input>(_input: &mut I) -> Result<Self, Error> {
Ok(Default::default())
}
#[inline]
fn encoded_size(&self) -> usize {
0
}
}
impl<K, V, Key, InnerKey> StorableHint<Key> for Mapping<K, V, InnerKey>
where
V: Packed,
Key: StorageKey,
InnerKey: StorageKey,
{
type Type = Mapping<K, V, Key>;
type PreferredKey = InnerKey;
}
impl<K, V, KeyType> StorageKey for Mapping<K, V, KeyType>
where
V: Packed,
KeyType: StorageKey,
{
const KEY: Key = KeyType::KEY;
}
#[cfg(feature = "std")]
const _: () = {
use crate::traits::StorageLayout;
use ink_metadata::layout::{
Layout,
LayoutKey,
RootLayout,
};
impl<K, V, KeyType> StorageLayout for Mapping<K, V, KeyType>
where
K: scale_info::TypeInfo + 'static,
V: Packed + StorageLayout + scale_info::TypeInfo + 'static,
KeyType: StorageKey + scale_info::TypeInfo + 'static,
{
fn layout(_: &Key) -> Layout {
Layout::Root(RootLayout::new(
LayoutKey::from(&KeyType::KEY),
<V as StorageLayout>::layout(&KeyType::KEY),
scale_info::meta_type::<Self>(),
))
}
}
};
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::ManualKey;
#[test]
fn insert_and_get_work() {
ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
let mut mapping: Mapping<u8, _> = Mapping::new();
mapping.insert(1, &2);
assert_eq!(mapping.get(1), Some(2));
Ok(())
})
.unwrap()
}
#[test]
fn insert_and_get_work_for_two_mapping_with_same_manual_key() {
ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
let mut mapping: Mapping<u8, u8, ManualKey<123>> = Mapping::new();
mapping.insert(1, &2);
let mapping2: Mapping<u8, u8, ManualKey<123>> = Mapping::new();
assert_eq!(mapping2.get(1), Some(2));
Ok(())
})
.unwrap()
}
#[test]
fn gets_default_if_no_key_set() {
ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
let mapping: Mapping<u8, u8> = Mapping::new();
assert_eq!(mapping.get(1), None);
Ok(())
})
.unwrap()
}
#[test]
fn insert_and_take_work() {
ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
let mut mapping: Mapping<u8, _> = Mapping::new();
mapping.insert(1, &2);
assert_eq!(mapping.take(1), Some(2));
assert!(mapping.get(1).is_none());
Ok(())
})
.unwrap()
}
#[test]
fn take_empty_value_work() {
ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
let mapping: Mapping<u8, u8> = Mapping::new();
assert_eq!(mapping.take(1), None);
Ok(())
})
.unwrap()
}
#[test]
fn can_clear_entries() {
ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
// Given
let mut mapping: Mapping<u8, u8> = Mapping::new();
mapping.insert(1, &2);
assert_eq!(mapping.get(1), Some(2));
// When
mapping.remove(1);
// Then
assert_eq!(mapping.get(1), None);
Ok(())
})
.unwrap()
}
#[test]
fn can_clear_unexistent_entries() {
ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
// Given
let mapping: Mapping<u8, u8> = Mapping::new();
// When
mapping.remove(1);
// Then
assert_eq!(mapping.get(1), None);
Ok(())
})
.unwrap()
}
#[test]
fn fallible_storage_works_for_fitting_data() {
ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
let mut mapping: Mapping<u8, [u8; ink_env::BUFFER_SIZE - 1]> = Mapping::new();
let key = 0;
let value = [0u8; ink_env::BUFFER_SIZE - 1];
assert_eq!(mapping.try_insert(key, &value), Ok(None));
assert_eq!(mapping.try_get(key), Some(Ok(value)));
assert_eq!(mapping.try_take(key), Some(Ok(value)));
assert_eq!(mapping.try_get(key), None);
Ok(())
})
.unwrap()
}
#[test]
fn fallible_storage_fails_gracefully_for_overgrown_data() {
ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
let mut mapping: Mapping<u8, [u8; ink_env::BUFFER_SIZE]> = Mapping::new();
let key = 0;
let value = [0u8; ink_env::BUFFER_SIZE];
assert_eq!(mapping.try_get(0), None);
assert_eq!(
mapping.try_insert(key, &value),
Err(ink_env::Error::BufferTooSmall)
);
// The off-chain impl conveniently uses a Vec for encoding,
// allowing writing values exceeding the static buffer size.
ink_env::set_contract_storage(&(&mapping.key(), key), &value);
assert_eq!(
mapping.try_get(key),
Some(Err(ink_env::Error::BufferTooSmall))
);
assert_eq!(
mapping.try_take(key),
Some(Err(ink_env::Error::BufferTooSmall))
);
Ok(())
})
.unwrap()
}
#[test]
fn fallible_storage_considers_key_size() {
ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
let mut mapping: Mapping<[u8; ink_env::BUFFER_SIZE + 1], u8> = Mapping::new();
let key = [0u8; ink_env::BUFFER_SIZE + 1];
let value = 0;
// Key is already too large, so this should fail anyways.
assert_eq!(
mapping.try_insert(key, &value),
Err(ink_env::Error::BufferTooSmall)
);
// The off-chain impl conveniently uses a Vec for encoding,
// allowing writing values exceeding the static buffer size.
ink_env::set_contract_storage(&(&mapping.key(), key), &value);
assert_eq!(
mapping.try_get(key),
Some(Err(ink_env::Error::BufferTooSmall))
);
assert_eq!(
mapping.try_take(key),
Some(Err(ink_env::Error::BufferTooSmall))
);
Ok(())
})
.unwrap()
}
}