pallet_assets/impl_stored_map.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Assets pallet's `StoredMap` implementation.
19
20use super::*;
21
22impl<T: Config<I>, I: 'static> StoredMap<(T::AssetId, T::AccountId), T::Extra> for Pallet<T, I> {
23 fn get(id_who: &(T::AssetId, T::AccountId)) -> T::Extra {
24 let (id, who) = id_who;
25 Account::<T, I>::get(id, who).map(|a| a.extra).unwrap_or_default()
26 }
27
28 fn try_mutate_exists<R, E: From<DispatchError>>(
29 id_who: &(T::AssetId, T::AccountId),
30 f: impl FnOnce(&mut Option<T::Extra>) -> Result<R, E>,
31 ) -> Result<R, E> {
32 let (id, who) = id_who;
33 let mut maybe_extra = Account::<T, I>::get(id, who).map(|a| a.extra);
34 let r = f(&mut maybe_extra)?;
35 // They want to write some value or delete it.
36 // If the account existed and they want to write a value, then we write.
37 // If the account didn't exist and they want to delete it, then we let it pass.
38 // Otherwise, we fail.
39 Account::<T, I>::try_mutate(id, who, |maybe_account| {
40 if let Some(extra) = maybe_extra {
41 // They want to write a value. Let this happen only if the account actually exists.
42 if let Some(ref mut account) = maybe_account {
43 account.extra = extra;
44 } else {
45 return Err(DispatchError::NoProviders.into())
46 }
47 } else {
48 // They want to delete it. Let this pass if the item never existed anyway.
49 ensure!(maybe_account.is_none(), DispatchError::ConsumerRemaining);
50 }
51 Ok(r)
52 })
53 }
54}