referrerpolicy=no-referrer-when-downgrade

pallet_assets/
impl_fungibles.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//! Implementations for fungibles trait.
19
20use alloc::vec::Vec;
21use frame_support::{
22	defensive,
23	traits::tokens::{
24		Fortitude,
25		Precision::{self, BestEffort},
26		Preservation::{self, Expendable},
27		Provenance::{self, Minted},
28	},
29};
30
31use super::*;
32
33impl<T: Config<I>, I: 'static> fungibles::Inspect<<T as SystemConfig>::AccountId> for Pallet<T, I> {
34	type AssetId = T::AssetId;
35	type Balance = T::Balance;
36
37	fn total_issuance(asset: Self::AssetId) -> Self::Balance {
38		Asset::<T, I>::get(asset).map(|x| x.supply).unwrap_or_else(Zero::zero)
39	}
40
41	fn minimum_balance(asset: Self::AssetId) -> Self::Balance {
42		Asset::<T, I>::get(asset).map(|x| x.min_balance).unwrap_or_else(Zero::zero)
43	}
44
45	fn balance(asset: Self::AssetId, who: &<T as SystemConfig>::AccountId) -> Self::Balance {
46		Pallet::<T, I>::balance(asset, who)
47	}
48
49	fn total_balance(asset: Self::AssetId, who: &<T as SystemConfig>::AccountId) -> Self::Balance {
50		Pallet::<T, I>::balance(asset.clone(), who)
51			.saturating_add(T::Holder::balance_on_hold(asset, who).unwrap_or_default())
52	}
53
54	fn reducible_balance(
55		asset: Self::AssetId,
56		who: &<T as SystemConfig>::AccountId,
57		preservation: Preservation,
58		_: Fortitude,
59	) -> Self::Balance {
60		Pallet::<T, I>::reducible_balance(asset, who, !matches!(preservation, Expendable))
61			.unwrap_or(Zero::zero())
62	}
63
64	fn can_deposit(
65		asset: Self::AssetId,
66		who: &<T as SystemConfig>::AccountId,
67		amount: Self::Balance,
68		provenance: Provenance,
69	) -> DepositConsequence {
70		Pallet::<T, I>::can_increase(asset, who, amount, provenance == Minted)
71	}
72
73	fn can_withdraw(
74		asset: Self::AssetId,
75		who: &<T as SystemConfig>::AccountId,
76		amount: Self::Balance,
77	) -> WithdrawConsequence<Self::Balance> {
78		Pallet::<T, I>::can_decrease(asset, who, amount, false)
79	}
80
81	fn asset_exists(asset: Self::AssetId) -> bool {
82		Asset::<T, I>::contains_key(asset)
83	}
84
85	fn is_sufficient(asset: Self::AssetId) -> bool {
86		Asset::<T, I>::get(asset).map(|x| x.is_sufficient).unwrap_or(false)
87	}
88}
89
90impl<T: Config<I>, I: 'static> fungibles::Mutate<<T as SystemConfig>::AccountId> for Pallet<T, I> {
91	fn done_mint_into(
92		asset_id: Self::AssetId,
93		beneficiary: &<T as SystemConfig>::AccountId,
94		amount: Self::Balance,
95	) {
96		Self::deposit_event(Event::Issued {
97			asset_id: asset_id.clone(),
98			owner: beneficiary.clone(),
99			amount,
100		});
101		T::CallbackHandle::issued(&asset_id, beneficiary, amount);
102	}
103
104	fn done_burn_from(
105		asset_id: Self::AssetId,
106		target: &<T as SystemConfig>::AccountId,
107		balance: Self::Balance,
108	) {
109		Self::deposit_event(Event::Burned {
110			asset_id: asset_id.clone(),
111			owner: target.clone(),
112			balance,
113		});
114		T::CallbackHandle::burned(&asset_id, target, balance);
115	}
116
117	fn done_shelve(
118		asset_id: Self::AssetId,
119		who: &<T as SystemConfig>::AccountId,
120		amount: Self::Balance,
121	) {
122		T::CallbackHandle::burned(&asset_id, who, amount);
123	}
124
125	fn done_restore(
126		asset_id: Self::AssetId,
127		who: &<T as SystemConfig>::AccountId,
128		amount: Self::Balance,
129	) {
130		T::CallbackHandle::issued(&asset_id, who, amount);
131	}
132
133	fn done_transfer(
134		asset_id: Self::AssetId,
135		source: &<T as SystemConfig>::AccountId,
136		dest: &<T as SystemConfig>::AccountId,
137		amount: Self::Balance,
138	) {
139		Self::deposit_event(Event::Transferred {
140			asset_id: asset_id.clone(),
141			from: source.clone(),
142			to: dest.clone(),
143			amount,
144		});
145		T::CallbackHandle::transferred(&asset_id, source, dest, amount);
146	}
147}
148
149/// Simple handler for an imbalance drop which increases the total issuance of the system by the
150/// imbalance amount. Used for leftover debt. Emits event.
151pub struct IncreaseIssuanceWithEvent<T, I>(PhantomData<(T, I)>);
152impl<T: Config<I>, I: 'static>
153	fungibles::HandleImbalanceDrop<<T as Config<I>>::AssetId, <T as Config<I>>::Balance>
154	for IncreaseIssuanceWithEvent<T, I>
155{
156	fn handle(asset_id: <T as Config<I>>::AssetId, amount: <T as Config<I>>::Balance) {
157		fungibles::IncreaseIssuance::<T::AccountId, Pallet<T, I>>::handle(asset_id.clone(), amount);
158		Pallet::<T, I>::deposit_event(Event::BurnedDebt { asset_id, amount });
159	}
160}
161
162/// Simple handler for an imbalance drop which decreases the total issuance of the system by the
163/// imbalance amount. Used for leftover credit. Emits event.
164pub struct DecreaseIssuanceWithEvent<T, I>(PhantomData<(T, I)>);
165impl<T: Config<I>, I: 'static>
166	fungibles::HandleImbalanceDrop<<T as Config<I>>::AssetId, <T as Config<I>>::Balance>
167	for DecreaseIssuanceWithEvent<T, I>
168{
169	fn handle(asset_id: <T as Config<I>>::AssetId, amount: <T as Config<I>>::Balance) {
170		fungibles::DecreaseIssuance::<T::AccountId, Pallet<T, I>>::handle(asset_id.clone(), amount);
171		Pallet::<T, I>::deposit_event(Event::BurnedCredit { asset_id, amount });
172	}
173}
174
175impl<T: Config<I>, I: 'static> fungibles::Balanced<<T as SystemConfig>::AccountId>
176	for Pallet<T, I>
177{
178	type OnDropCredit = DecreaseIssuanceWithEvent<T, I>;
179	type OnDropDebt = IncreaseIssuanceWithEvent<T, I>;
180
181	fn done_deposit(
182		asset_id: Self::AssetId,
183		who: &<T as SystemConfig>::AccountId,
184		amount: Self::Balance,
185	) {
186		Self::deposit_event(Event::Deposited {
187			asset_id: asset_id.clone(),
188			who: who.clone(),
189			amount,
190		});
191		T::CallbackHandle::deposited(&asset_id, who, amount);
192	}
193
194	fn done_withdraw(
195		asset_id: Self::AssetId,
196		who: &<T as SystemConfig>::AccountId,
197		amount: Self::Balance,
198	) {
199		Self::deposit_event(Event::Withdrawn {
200			asset_id: asset_id.clone(),
201			who: who.clone(),
202			amount,
203		});
204		T::CallbackHandle::withdrawn(&asset_id, who, amount);
205	}
206
207	fn done_rescind(asset_id: Self::AssetId, amount: Self::Balance) {
208		Self::deposit_event(Event::IssuedDebt { asset_id, amount })
209	}
210
211	fn done_issue(asset_id: Self::AssetId, amount: Self::Balance) {
212		Self::deposit_event(Event::IssuedCredit { asset_id, amount })
213	}
214}
215
216impl<T: Config<I>, I: 'static> fungibles::Unbalanced<T::AccountId> for Pallet<T, I> {
217	fn handle_raw_dust(_: Self::AssetId, _: Self::Balance) {}
218	fn handle_dust(_: fungibles::Dust<T::AccountId, Self>) {
219		defensive!("`decrease_balance` and `increase_balance` have non-default impls; nothing else calls this; qed");
220	}
221	fn write_balance(
222		_: Self::AssetId,
223		_: &T::AccountId,
224		_: Self::Balance,
225	) -> Result<Option<Self::Balance>, DispatchError> {
226		defensive!("write_balance is not used if other functions are impl'd");
227		Err(DispatchError::Unavailable)
228	}
229	fn set_total_issuance(id: T::AssetId, amount: Self::Balance) {
230		Asset::<T, I>::mutate_exists(id, |maybe_asset| {
231			if let Some(ref mut asset) = maybe_asset {
232				asset.supply = amount
233			}
234		});
235	}
236	fn decrease_balance(
237		asset: T::AssetId,
238		who: &T::AccountId,
239		amount: Self::Balance,
240		precision: Precision,
241		preservation: Preservation,
242		_: Fortitude,
243	) -> Result<Self::Balance, DispatchError> {
244		let f = DebitFlags {
245			keep_alive: preservation != Expendable,
246			best_effort: precision == BestEffort,
247		};
248		Self::decrease_balance(asset, who, amount, f, |_, _| Ok(()))
249	}
250	fn increase_balance(
251		asset: T::AssetId,
252		who: &T::AccountId,
253		amount: Self::Balance,
254		_: Precision,
255	) -> Result<Self::Balance, DispatchError> {
256		Self::increase_balance(asset, who, amount, |_| Ok(()))?;
257		Ok(amount)
258	}
259
260	// TODO: #13196 implement deactivate/reactivate once we have inactive balance tracking.
261}
262
263impl<T: Config<I>, I: 'static> fungibles::Create<T::AccountId> for Pallet<T, I> {
264	fn create(
265		id: T::AssetId,
266		admin: T::AccountId,
267		is_sufficient: bool,
268		min_balance: Self::Balance,
269	) -> DispatchResult {
270		// Not gated on `ForceOrigin`, so the id must follow `AssetIdAllocator`.
271		Self::do_force_create(id, admin, is_sufficient, min_balance, true)
272	}
273}
274
275impl<T: Config<I>, I: 'static> fungibles::Destroy<T::AccountId> for Pallet<T, I> {
276	fn start_destroy(id: T::AssetId, maybe_check_owner: Option<T::AccountId>) -> DispatchResult {
277		Self::do_start_destroy(id, maybe_check_owner)
278	}
279
280	fn destroy_accounts(id: T::AssetId, max_items: u32) -> Result<u32, DispatchError> {
281		Self::do_destroy_accounts(id, max_items)
282	}
283
284	fn destroy_approvals(id: T::AssetId, max_items: u32) -> Result<u32, DispatchError> {
285		Self::do_destroy_approvals(id, max_items)
286	}
287
288	fn finish_destroy(id: T::AssetId) -> DispatchResult {
289		Self::do_finish_destroy(id)
290	}
291}
292
293impl<T: Config<I>, I: 'static> fungibles::metadata::Inspect<<T as SystemConfig>::AccountId>
294	for Pallet<T, I>
295{
296	fn name(asset: T::AssetId) -> Vec<u8> {
297		Metadata::<T, I>::get(asset).name.to_vec()
298	}
299
300	fn symbol(asset: T::AssetId) -> Vec<u8> {
301		Metadata::<T, I>::get(asset).symbol.to_vec()
302	}
303
304	fn decimals(asset: T::AssetId) -> u8 {
305		Metadata::<T, I>::get(asset).decimals
306	}
307}
308
309impl<T: Config<I>, I: 'static> fungibles::metadata::Mutate<<T as SystemConfig>::AccountId>
310	for Pallet<T, I>
311{
312	fn set(
313		asset: T::AssetId,
314		from: &<T as SystemConfig>::AccountId,
315		name: Vec<u8>,
316		symbol: Vec<u8>,
317		decimals: u8,
318	) -> DispatchResult {
319		Self::do_set_metadata(asset, from, name, symbol, decimals)
320	}
321}
322
323impl<T: Config<I>, I: 'static>
324	fungibles::metadata::MetadataDeposit<
325		<T::Currency as Currency<<T as SystemConfig>::AccountId>>::Balance,
326	> for Pallet<T, I>
327{
328	fn calc_metadata_deposit(
329		name: &[u8],
330		symbol: &[u8],
331	) -> <T::Currency as Currency<<T as SystemConfig>::AccountId>>::Balance {
332		Self::calc_metadata_deposit(&name, &symbol)
333	}
334}
335
336impl<T: Config<I>, I: 'static> fungibles::approvals::Inspect<<T as SystemConfig>::AccountId>
337	for Pallet<T, I>
338{
339	// Check the amount approved to be spent by an owner to a delegate
340	fn allowance(
341		asset: T::AssetId,
342		owner: &<T as SystemConfig>::AccountId,
343		delegate: &<T as SystemConfig>::AccountId,
344	) -> T::Balance {
345		Approvals::<T, I>::get((asset, &owner, &delegate))
346			.map(|x| x.amount)
347			.unwrap_or_else(Zero::zero)
348	}
349}
350
351impl<T: Config<I>, I: 'static> fungibles::approvals::Mutate<<T as SystemConfig>::AccountId>
352	for Pallet<T, I>
353{
354	// Approve spending tokens from a given account
355	fn approve(
356		asset: T::AssetId,
357		owner: &<T as SystemConfig>::AccountId,
358		delegate: &<T as SystemConfig>::AccountId,
359		amount: T::Balance,
360	) -> DispatchResult {
361		Self::do_approve_transfer(asset, owner, delegate, amount)
362	}
363
364	fn transfer_from(
365		asset: T::AssetId,
366		owner: &<T as SystemConfig>::AccountId,
367		delegate: &<T as SystemConfig>::AccountId,
368		dest: &<T as SystemConfig>::AccountId,
369		amount: T::Balance,
370	) -> DispatchResult {
371		Self::do_transfer_approved(asset, owner, delegate, dest, amount)
372	}
373}
374
375impl<T: Config<I>, I: 'static> fungibles::roles::Inspect<<T as SystemConfig>::AccountId>
376	for Pallet<T, I>
377{
378	fn owner(asset: T::AssetId) -> Option<<T as SystemConfig>::AccountId> {
379		Asset::<T, I>::get(asset).map(|x| x.owner)
380	}
381
382	fn issuer(asset: T::AssetId) -> Option<<T as SystemConfig>::AccountId> {
383		Asset::<T, I>::get(asset).map(|x| x.issuer)
384	}
385
386	fn admin(asset: T::AssetId) -> Option<<T as SystemConfig>::AccountId> {
387		Asset::<T, I>::get(asset).map(|x| x.admin)
388	}
389
390	fn freezer(asset: T::AssetId) -> Option<<T as SystemConfig>::AccountId> {
391		Asset::<T, I>::get(asset).map(|x| x.freezer)
392	}
393}
394
395impl<T: Config<I>, I: 'static> fungibles::InspectEnumerable<T::AccountId> for Pallet<T, I> {
396	type AssetsIterator = KeyPrefixIterator<<T as Config<I>>::AssetId>;
397
398	/// Returns an iterator of the assets in existence.
399	///
400	/// NOTE: iterating this list invokes a storage read per item.
401	fn asset_ids() -> Self::AssetsIterator {
402		Asset::<T, I>::iter_keys()
403	}
404}
405
406impl<T: Config<I>, I: 'static> fungibles::roles::ResetTeam<T::AccountId> for Pallet<T, I> {
407	fn reset_team(
408		id: T::AssetId,
409		owner: T::AccountId,
410		admin: T::AccountId,
411		issuer: T::AccountId,
412		freezer: T::AccountId,
413	) -> DispatchResult {
414		Self::do_reset_team(id, owner, admin, issuer, freezer)
415	}
416}
417
418impl<T: Config<I>, I: 'static> fungibles::Refund<T::AccountId> for Pallet<T, I> {
419	type AssetId = T::AssetId;
420	type Balance = DepositBalanceOf<T, I>;
421	fn deposit_held(id: Self::AssetId, who: T::AccountId) -> Option<(T::AccountId, Self::Balance)> {
422		use ExistenceReason::*;
423		match Account::<T, I>::get(&id, &who).ok_or(Error::<T, I>::NoDeposit).ok()?.reason {
424			DepositHeld(b) => Some((who, b)),
425			DepositFrom(d, b) => Some((d, b)),
426			_ => None,
427		}
428	}
429	fn refund(id: Self::AssetId, who: T::AccountId) -> DispatchResult {
430		match Self::deposit_held(id.clone(), who.clone()) {
431			Some((d, _)) if d == who => Self::do_refund(id, who, false),
432			Some(..) => Self::do_refund_other(id, &who, None),
433			None => Err(Error::<T, I>::NoDeposit.into()),
434		}
435	}
436}