Files
pezkuwi-subxt/substrate/frame/asset-rate/src/lib.rs
T
Dcompoze 002d9260f9 Fix spelling mistakes across the whole repository (#3808)
**Update:** Pushed additional changes based on the review comments.

**This pull request fixes various spelling mistakes in this
repository.**

Most of the changes are contained in the first **3** commits:

- `Fix spelling mistakes in comments and docs`

- `Fix spelling mistakes in test names`

- `Fix spelling mistakes in error messages, panic messages, logs and
tracing`

Other source code spelling mistakes are separated into individual
commits for easier reviewing:

- `Fix the spelling of 'authority'`

- `Fix the spelling of 'REASONABLE_HEADERS_IN_JUSTIFICATION_ANCESTRY'`

- `Fix the spelling of 'prev_enqueud_messages'`

- `Fix the spelling of 'endpoint'`

- `Fix the spelling of 'children'`

- `Fix the spelling of 'PenpalSiblingSovereignAccount'`

- `Fix the spelling of 'PenpalSudoAccount'`

- `Fix the spelling of 'insufficient'`

- `Fix the spelling of 'PalletXcmExtrinsicsBenchmark'`

- `Fix the spelling of 'subtracted'`

- `Fix the spelling of 'CandidatePendingAvailability'`

- `Fix the spelling of 'exclusive'`

- `Fix the spelling of 'until'`

- `Fix the spelling of 'discriminator'`

- `Fix the spelling of 'nonexistent'`

- `Fix the spelling of 'subsystem'`

- `Fix the spelling of 'indices'`

- `Fix the spelling of 'committed'`

- `Fix the spelling of 'topology'`

- `Fix the spelling of 'response'`

- `Fix the spelling of 'beneficiary'`

- `Fix the spelling of 'formatted'`

- `Fix the spelling of 'UNKNOWN_PROOF_REQUEST'`

- `Fix the spelling of 'succeeded'`

- `Fix the spelling of 'reopened'`

- `Fix the spelling of 'proposer'`

- `Fix the spelling of 'InstantiationNonce'`

- `Fix the spelling of 'depositor'`

- `Fix the spelling of 'expiration'`

- `Fix the spelling of 'phantom'`

- `Fix the spelling of 'AggregatedKeyValue'`

- `Fix the spelling of 'randomness'`

- `Fix the spelling of 'defendant'`

- `Fix the spelling of 'AquaticMammal'`

- `Fix the spelling of 'transactions'`

- `Fix the spelling of 'PassingTracingSubscriber'`

- `Fix the spelling of 'TxSignaturePayload'`

- `Fix the spelling of 'versioning'`

- `Fix the spelling of 'descendant'`

- `Fix the spelling of 'overridden'`

- `Fix the spelling of 'network'`

Let me know if this structure is adequate.

**Note:** The usage of the words `Merkle`, `Merkelize`, `Merklization`,
`Merkelization`, `Merkleization`, is somewhat inconsistent but I left it
as it is.

~~**Note:** In some places the term `Receival` is used to refer to
message reception, IMO `Reception` is the correct word here, but I left
it as it is.~~

~~**Note:** In some places the term `Overlayed` is used instead of the
more acceptable version `Overlaid` but I also left it as it is.~~

~~**Note:** In some places the term `Applyable` is used instead of the
correct version `Applicable` but I also left it as it is.~~

**Note:** Some usage of British vs American english e.g. `judgement` vs
`judgment`, `initialise` vs `initialize`, `optimise` vs `optimize` etc.
are both present in different places, but I suppose that's
understandable given the number of contributors.

~~**Note:** There is a spelling mistake in `.github/CODEOWNERS` but it
triggers errors in CI when I make changes to it, so I left it as it
is.~~
2024-03-26 13:57:57 +00:00

279 lines
8.4 KiB
Rust

// This file is part of Substrate.
// Copyright (C) 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.
//! # Asset Rate Pallet
//!
//! - [`Config`]
//! - [`Call`]
//!
//! ## Overview
//!
//! The AssetRate pallet provides means of setting conversion rates for some asset to native
//! balance.
//!
//! The supported dispatchable functions are documented in the [`Call`] enum.
//!
//! ### Terminology
//!
//! * **Asset balance**: The balance type of an arbitrary asset. The network might only know about
//! the identifier of the asset and nothing more.
//! * **Native balance**: The balance type of the network's native currency.
//!
//! ### Goals
//!
//! The asset-rate system in Substrate is designed to make the following possible:
//!
//! * Providing a soft conversion for the balance of supported assets to a default asset class.
//! * Updating existing conversion rates.
//!
//! ## Interface
//!
//! ### Permissioned Functions
//!
//! * `create`: Creates a new asset conversion rate.
//! * `remove`: Removes an existing asset conversion rate.
//! * `update`: Overwrites an existing assert conversion rate.
//!
//! Please refer to the [`Call`] enum and its associated variants for documentation on each
//! function.
//!
//! ### Assumptions
//!
//! * Conversion rates are only used as estimates, and are not designed to be precise or closely
//! tracking real world values.
//! * All conversion rates reflect the ration of some asset to native, e.g. native = asset * rate.
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::traits::{
fungible::Inspect,
tokens::{ConversionFromAssetBalance, ConversionToAssetBalance},
};
use sp_runtime::{
traits::{CheckedDiv, Zero},
FixedPointNumber, FixedU128,
};
use sp_std::boxed::Box;
pub use pallet::*;
pub use weights::WeightInfo;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
pub mod weights;
#[cfg(feature = "runtime-benchmarks")]
pub use benchmarking::AssetKindFactory;
// Type alias for `frame_system`'s account id.
type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
// This pallet's asset kind and balance type.
type AssetKindOf<T> = <T as Config>::AssetKind;
// Generic fungible balance type.
type BalanceOf<T> = <<T as Config>::Currency as Inspect<AccountIdOf<T>>>::Balance;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config {
/// The Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
/// The runtime event type.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// The origin permissioned to create a conversion rate for an asset.
type CreateOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// The origin permissioned to remove an existing conversion rate for an asset.
type RemoveOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// The origin permissioned to update an existing conversion rate for an asset.
type UpdateOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// The currency mechanism for this pallet.
type Currency: Inspect<Self::AccountId>;
/// The type for asset kinds for which the conversion rate to native balance is set.
type AssetKind: Parameter + MaxEncodedLen;
/// Helper type for benchmarks.
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper: crate::AssetKindFactory<Self::AssetKind>;
}
/// Maps an asset to its fixed point representation in the native balance.
///
/// E.g. `native_amount = asset_amount * ConversionRateToNative::<T>::get(asset_kind)`
#[pallet::storage]
pub type ConversionRateToNative<T: Config> =
StorageMap<_, Blake2_128Concat, T::AssetKind, FixedU128, OptionQuery>;
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
// Some `asset_kind` conversion rate was created.
AssetRateCreated { asset_kind: T::AssetKind, rate: FixedU128 },
// Some `asset_kind` conversion rate was removed.
AssetRateRemoved { asset_kind: T::AssetKind },
// Some existing `asset_kind` conversion rate was updated from `old` to `new`.
AssetRateUpdated { asset_kind: T::AssetKind, old: FixedU128, new: FixedU128 },
}
#[pallet::error]
pub enum Error<T> {
/// The given asset ID is unknown.
UnknownAssetKind,
/// The given asset ID already has an assigned conversion rate and cannot be re-created.
AlreadyExists,
/// Overflow ocurred when calculating the inverse rate.
Overflow,
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Initialize a conversion rate to native balance for the given asset.
///
/// ## Complexity
/// - O(1)
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::create())]
pub fn create(
origin: OriginFor<T>,
asset_kind: Box<T::AssetKind>,
rate: FixedU128,
) -> DispatchResult {
T::CreateOrigin::ensure_origin(origin)?;
ensure!(
!ConversionRateToNative::<T>::contains_key(asset_kind.as_ref()),
Error::<T>::AlreadyExists
);
ConversionRateToNative::<T>::set(asset_kind.as_ref(), Some(rate));
Self::deposit_event(Event::AssetRateCreated { asset_kind: *asset_kind, rate });
Ok(())
}
/// Update the conversion rate to native balance for the given asset.
///
/// ## Complexity
/// - O(1)
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::update())]
pub fn update(
origin: OriginFor<T>,
asset_kind: Box<T::AssetKind>,
rate: FixedU128,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin(origin)?;
let mut old = FixedU128::zero();
ConversionRateToNative::<T>::mutate(asset_kind.as_ref(), |maybe_rate| {
if let Some(r) = maybe_rate {
old = *r;
*r = rate;
Ok(())
} else {
Err(Error::<T>::UnknownAssetKind)
}
})?;
Self::deposit_event(Event::AssetRateUpdated {
asset_kind: *asset_kind,
old,
new: rate,
});
Ok(())
}
/// Remove an existing conversion rate to native balance for the given asset.
///
/// ## Complexity
/// - O(1)
#[pallet::call_index(2)]
#[pallet::weight(T::WeightInfo::remove())]
pub fn remove(origin: OriginFor<T>, asset_kind: Box<T::AssetKind>) -> DispatchResult {
T::RemoveOrigin::ensure_origin(origin)?;
ensure!(
ConversionRateToNative::<T>::contains_key(asset_kind.as_ref()),
Error::<T>::UnknownAssetKind
);
ConversionRateToNative::<T>::remove(asset_kind.as_ref());
Self::deposit_event(Event::AssetRateRemoved { asset_kind: *asset_kind });
Ok(())
}
}
}
/// Exposes conversion of an arbitrary balance of an asset to native balance.
impl<T> ConversionFromAssetBalance<BalanceOf<T>, AssetKindOf<T>, BalanceOf<T>> for Pallet<T>
where
T: Config,
{
type Error = pallet::Error<T>;
fn from_asset_balance(
balance: BalanceOf<T>,
asset_kind: AssetKindOf<T>,
) -> Result<BalanceOf<T>, pallet::Error<T>> {
let rate = pallet::ConversionRateToNative::<T>::get(asset_kind)
.ok_or(pallet::Error::<T>::UnknownAssetKind.into())?;
Ok(rate.saturating_mul_int(balance))
}
/// Set a conversion rate to `1` for the `asset_id`.
#[cfg(feature = "runtime-benchmarks")]
fn ensure_successful(asset_id: AssetKindOf<T>) {
pallet::ConversionRateToNative::<T>::set(asset_id.clone(), Some(1.into()));
}
}
/// Exposes conversion of a native balance to an asset balance.
impl<T> ConversionToAssetBalance<BalanceOf<T>, AssetKindOf<T>, BalanceOf<T>> for Pallet<T>
where
T: Config,
{
type Error = pallet::Error<T>;
fn to_asset_balance(
balance: BalanceOf<T>,
asset_kind: AssetKindOf<T>,
) -> Result<BalanceOf<T>, pallet::Error<T>> {
let rate = pallet::ConversionRateToNative::<T>::get(asset_kind)
.ok_or(pallet::Error::<T>::UnknownAssetKind.into())?;
// We cannot use `saturating_div` here so we use `checked_div`.
Ok(FixedU128::from_u32(1)
.checked_div(&rate)
.ok_or(pallet::Error::<T>::Overflow.into())?
.saturating_mul_int(balance))
}
}