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
//! # Asset Rate Pallet
19
//!
20
//! - [`Config`]
21
//! - [`Call`]
22
//!
23
//! ## Overview
24
//!
25
//! The AssetRate pallet provides means of setting conversion rates for some asset to native
26
//! balance.
27
//!
28
//! The supported dispatchable functions are documented in the [`Call`] enum.
29
//!
30
//! ### Terminology
31
//!
32
//! * **Asset balance**: The balance type of an arbitrary asset. The network might only know about
33
//!   the identifier of the asset and nothing more.
34
//! * **Native balance**: The balance type of the network's native currency.
35
//!
36
//! ### Goals
37
//!
38
//! The asset-rate system in Substrate is designed to make the following possible:
39
//!
40
//! * Providing a soft conversion for the balance of supported assets to a default asset class.
41
//! * Updating existing conversion rates.
42
//!
43
//! ## Interface
44
//!
45
//! ### Permissioned Functions
46
//!
47
//! * `create`: Creates a new asset conversion rate.
48
//! * `remove`: Removes an existing asset conversion rate.
49
//! * `update`: Overwrites an existing assert conversion rate.
50
//!
51
//! Please refer to the [`Call`] enum and its associated variants for documentation on each
52
//! function.
53
//!
54
//! ### Assumptions
55
//!
56
//! * Conversion rates are only used as estimates, and are not designed to be precise or closely
57
//!   tracking real world values.
58
//! * All conversion rates reflect the ration of some asset to native, e.g. native = asset * rate.
59

            
60
#![cfg_attr(not(feature = "std"), no_std)]
61

            
62
extern crate alloc;
63

            
64
use alloc::boxed::Box;
65
use frame_support::traits::{
66
	fungible::Inspect,
67
	tokens::{ConversionFromAssetBalance, ConversionToAssetBalance},
68
};
69
use sp_runtime::{
70
	traits::{CheckedDiv, Zero},
71
	FixedPointNumber, FixedU128,
72
};
73

            
74
pub use pallet::*;
75
pub use weights::WeightInfo;
76

            
77
#[cfg(feature = "runtime-benchmarks")]
78
mod benchmarking;
79
#[cfg(test)]
80
mod mock;
81
#[cfg(test)]
82
mod tests;
83
pub mod weights;
84
#[cfg(feature = "runtime-benchmarks")]
85
pub use benchmarking::AssetKindFactory;
86

            
87
// Type alias for `frame_system`'s account id.
88
type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
89
// This pallet's asset kind and balance type.
90
type AssetKindOf<T> = <T as Config>::AssetKind;
91
// Generic fungible balance type.
92
type BalanceOf<T> = <<T as Config>::Currency as Inspect<AccountIdOf<T>>>::Balance;
93

            
94
2340
#[frame_support::pallet]
95
pub mod pallet {
96
	use super::*;
97
	use frame_support::pallet_prelude::*;
98
	use frame_system::pallet_prelude::*;
99

            
100
554790
	#[pallet::pallet]
101
	pub struct Pallet<T>(_);
102

            
103
	#[pallet::config]
104
	pub trait Config: frame_system::Config {
105
		/// The Weight information for extrinsics in this pallet.
106
		type WeightInfo: WeightInfo;
107

            
108
		/// The runtime event type.
109
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
110

            
111
		/// The origin permissioned to create a conversion rate for an asset.
112
		type CreateOrigin: EnsureOrigin<Self::RuntimeOrigin>;
113

            
114
		/// The origin permissioned to remove an existing conversion rate for an asset.
115
		type RemoveOrigin: EnsureOrigin<Self::RuntimeOrigin>;
116

            
117
		/// The origin permissioned to update an existing conversion rate for an asset.
118
		type UpdateOrigin: EnsureOrigin<Self::RuntimeOrigin>;
119

            
120
		/// The currency mechanism for this pallet.
121
		type Currency: Inspect<Self::AccountId>;
122

            
123
		/// The type for asset kinds for which the conversion rate to native balance is set.
124
		type AssetKind: Parameter + MaxEncodedLen;
125

            
126
		/// Helper type for benchmarks.
127
		#[cfg(feature = "runtime-benchmarks")]
128
		type BenchmarkHelper: crate::AssetKindFactory<Self::AssetKind>;
129
	}
130

            
131
	/// Maps an asset to its fixed point representation in the native balance.
132
	///
133
	/// E.g. `native_amount = asset_amount * ConversionRateToNative::<T>::get(asset_kind)`
134
	#[pallet::storage]
135
	pub type ConversionRateToNative<T: Config> =
136
		StorageMap<_, Blake2_128Concat, T::AssetKind, FixedU128, OptionQuery>;
137

            
138
	#[pallet::event]
139
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
140
	pub enum Event<T: Config> {
141
		// Some `asset_kind` conversion rate was created.
142
		AssetRateCreated { asset_kind: T::AssetKind, rate: FixedU128 },
143
		// Some `asset_kind` conversion rate was removed.
144
		AssetRateRemoved { asset_kind: T::AssetKind },
145
		// Some existing `asset_kind` conversion rate was updated from `old` to `new`.
146
		AssetRateUpdated { asset_kind: T::AssetKind, old: FixedU128, new: FixedU128 },
147
	}
148

            
149
	#[pallet::error]
150
	pub enum Error<T> {
151
		/// The given asset ID is unknown.
152
		UnknownAssetKind,
153
		/// The given asset ID already has an assigned conversion rate and cannot be re-created.
154
		AlreadyExists,
155
		/// Overflow ocurred when calculating the inverse rate.
156
		Overflow,
157
	}
158

            
159
9789
	#[pallet::call]
160
	impl<T: Config> Pallet<T> {
161
		/// Initialize a conversion rate to native balance for the given asset.
162
		///
163
		/// ## Complexity
164
		/// - O(1)
165
		#[pallet::call_index(0)]
166
		#[pallet::weight(T::WeightInfo::create())]
167
		pub fn create(
168
			origin: OriginFor<T>,
169
			asset_kind: Box<T::AssetKind>,
170
			rate: FixedU128,
171
2223
		) -> DispatchResult {
172
2223
			T::CreateOrigin::ensure_origin(origin)?;
173

            
174
			ensure!(
175
				!ConversionRateToNative::<T>::contains_key(asset_kind.as_ref()),
176
				Error::<T>::AlreadyExists
177
			);
178
			ConversionRateToNative::<T>::set(asset_kind.as_ref(), Some(rate));
179

            
180
			Self::deposit_event(Event::AssetRateCreated { asset_kind: *asset_kind, rate });
181
			Ok(())
182
		}
183

            
184
		/// Update the conversion rate to native balance for the given asset.
185
		///
186
		/// ## Complexity
187
		/// - O(1)
188
		#[pallet::call_index(1)]
189
		#[pallet::weight(T::WeightInfo::update())]
190
		pub fn update(
191
			origin: OriginFor<T>,
192
			asset_kind: Box<T::AssetKind>,
193
			rate: FixedU128,
194
96
		) -> DispatchResult {
195
96
			T::UpdateOrigin::ensure_origin(origin)?;
196

            
197
			let mut old = FixedU128::zero();
198
			ConversionRateToNative::<T>::mutate(asset_kind.as_ref(), |maybe_rate| {
199
				if let Some(r) = maybe_rate {
200
					old = *r;
201
					*r = rate;
202

            
203
					Ok(())
204
				} else {
205
					Err(Error::<T>::UnknownAssetKind)
206
				}
207
			})?;
208

            
209
			Self::deposit_event(Event::AssetRateUpdated {
210
				asset_kind: *asset_kind,
211
				old,
212
				new: rate,
213
			});
214
			Ok(())
215
		}
216

            
217
		/// Remove an existing conversion rate to native balance for the given asset.
218
		///
219
		/// ## Complexity
220
		/// - O(1)
221
		#[pallet::call_index(2)]
222
		#[pallet::weight(T::WeightInfo::remove())]
223
6
		pub fn remove(origin: OriginFor<T>, asset_kind: Box<T::AssetKind>) -> DispatchResult {
224
6
			T::RemoveOrigin::ensure_origin(origin)?;
225

            
226
			ensure!(
227
				ConversionRateToNative::<T>::contains_key(asset_kind.as_ref()),
228
				Error::<T>::UnknownAssetKind
229
			);
230
			ConversionRateToNative::<T>::remove(asset_kind.as_ref());
231

            
232
			Self::deposit_event(Event::AssetRateRemoved { asset_kind: *asset_kind });
233
			Ok(())
234
		}
235
	}
236
}
237

            
238
/// Exposes conversion of an arbitrary balance of an asset to native balance.
239
impl<T> ConversionFromAssetBalance<BalanceOf<T>, AssetKindOf<T>, BalanceOf<T>> for Pallet<T>
240
where
241
	T: Config,
242
{
243
	type Error = pallet::Error<T>;
244

            
245
	fn from_asset_balance(
246
		balance: BalanceOf<T>,
247
		asset_kind: AssetKindOf<T>,
248
	) -> Result<BalanceOf<T>, pallet::Error<T>> {
249
		let rate = pallet::ConversionRateToNative::<T>::get(asset_kind)
250
			.ok_or(pallet::Error::<T>::UnknownAssetKind.into())?;
251
		Ok(rate.saturating_mul_int(balance))
252
	}
253
	/// Set a conversion rate to `1` for the `asset_id`.
254
	#[cfg(feature = "runtime-benchmarks")]
255
	fn ensure_successful(asset_id: AssetKindOf<T>) {
256
		pallet::ConversionRateToNative::<T>::set(asset_id.clone(), Some(1.into()));
257
	}
258
}
259

            
260
/// Exposes conversion of a native balance to an asset balance.
261
impl<T> ConversionToAssetBalance<BalanceOf<T>, AssetKindOf<T>, BalanceOf<T>> for Pallet<T>
262
where
263
	T: Config,
264
{
265
	type Error = pallet::Error<T>;
266

            
267
	fn to_asset_balance(
268
		balance: BalanceOf<T>,
269
		asset_kind: AssetKindOf<T>,
270
	) -> Result<BalanceOf<T>, pallet::Error<T>> {
271
		let rate = pallet::ConversionRateToNative::<T>::get(asset_kind)
272
			.ok_or(pallet::Error::<T>::UnknownAssetKind.into())?;
273

            
274
		// We cannot use `saturating_div` here so we use `checked_div`.
275
		Ok(FixedU128::from_u32(1)
276
			.checked_div(&rate)
277
			.ok_or(pallet::Error::<T>::Overflow.into())?
278
			.saturating_mul_int(balance))
279
	}
280
}