This repository was archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
feat: pallet asset-rate #13608
Merged
paritytech-processbot
merged 21 commits into
paritytech:master
from
wischli:feat/treasury-oracle
Apr 19, 2023
Merged
feat: pallet asset-rate #13608
Changes from 4 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
8996e05
poc
wischli 8a07bc0
fix: remove AssetIdParameter
wischli 47443ec
tests: add
wischli 8d3ddee
docs: add pallet description
wischli 109a321
feat: add benches
wischli 4a0fca4
refactor: UnknownAssetId
wischli d78f6cb
Merge remote-tracking branch 'origin/master' into feat/treasury-oracle
wischli 719364f
fix: normalize mock cfg
wischli 0adf951
fix: benchmarks
wischli ffb6d95
chore: add weights
wischli 301ddb2
refactor: remove storage getter
wischli 7153a2c
chore: apply suggestions from code review
wischli fdeefbd
docs: add native balance to calls
wischli 65df23e
chore: apply suggestions from code review
wischli acf046b
Merge remote-tracking branch 'origin/master' into feat/treasury-oracle
58cc428
chore: apply ConversionFromAssetBalance
wischli 44a9f6a
tests: update balance mock
wischli 03acddb
chore: apply suggestions from code review
wischli 1f14c39
ci: set publish to false
wischli 329b846
docs: fix missing rustdoc
wischli 57c5c6f
Merge remote-tracking branch 'origin/master' into feat/treasury-oracle
wischli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| [package] | ||
| name = "pallet-treasury-oracle" | ||
| version = "4.0.0-dev" | ||
| description = "Convert whitelisted assets to native balance" | ||
| authors = ["Centrifuge <[email protected]>"] | ||
| homepage = "https://substrate.io" | ||
| edition = "2021" | ||
| license = "Unlicense" | ||
| publish = false | ||
| repository = "https://github.com/paritytech/substrate/" | ||
|
|
||
| [package.metadata.docs.rs] | ||
| targets = ["x86_64-unknown-linux-gnu"] | ||
|
|
||
| [dependencies] | ||
| codec = { package = "parity-scale-codec", version = "3.2.2", default-features = false, features = [ | ||
| "derive", | ||
| ] } | ||
| scale-info = { version = "2.1.1", default-features = false, features = ["derive"] } | ||
| frame-benchmarking = { version = "4.0.0-dev", default-features = false, optional = true, path = "../benchmarking" } | ||
| frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } | ||
| frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } | ||
| sp-runtime = { version = "7.0.0", path = "../../primitives/runtime" } | ||
|
|
||
| [dev-dependencies] | ||
| pallet-balances = { version = "4.0.0-dev", default-features = false, path = "../balances" } | ||
| sp-core = { version = "7.0.0", path = "../../primitives/core" } | ||
| sp-io = { version = "7.0.0", path = "../../primitives/io" } | ||
|
|
||
| [features] | ||
| default = ["std"] | ||
| std = [ | ||
| "codec/std", | ||
| "frame-benchmarking?/std", | ||
| "frame-support/std", | ||
| "frame-system/std", | ||
| "pallet-balances/std", | ||
| "scale-info/std", | ||
| "sp-runtime/std", | ||
| ] | ||
| runtime-benchmarks = ["frame-benchmarking/runtime-benchmarks"] | ||
| try-runtime = ["frame-support/try-runtime"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,226 @@ | ||
| // 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. | ||
|
|
||
| //! A simple oracle pallet for the treasury. | ||
| //! | ||
| //! ## Overview | ||
| //! | ||
| //! The TreasuryOracle 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 | ||
| //! identifier of the asset and nothing more. | ||
| //! * **Native balance**: The balance type of the network's native currency. | ||
| //! * **Treasury spend**: A payment from the treasury after the corresponding proposal has been | ||
| //! approved. | ||
| //! | ||
| //! ### Goals | ||
| //! | ||
| //! The treasury-oracle system in Substrate is designed to make the following possible: | ||
| //! | ||
| //! * Whitelisting assets other than the native currency which can be accepted for Treasury spends. | ||
| //! * Providing a soft conversion for the balance of whitelisted assets to native. | ||
| //! * 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 will not be used to determine the payment amount in another asset. | ||
| //! * Conversion rates will be used to determine the tier of the spender status, e.g. | ||
| //! `SmallSpender`, `MediumSpender` or `BigSpender`. | ||
| //! * Conversion rates are only required from some asset to native. | ||
| //! | ||
| //! ## Related Modules | ||
| //! * [`Treasury`](../treasury/index.html) | ||
|
|
||
| #![cfg_attr(not(feature = "std"), no_std)] | ||
|
|
||
| use frame_support::traits::{ | ||
| fungible::Inspect, | ||
| tokens::{Balance, BalanceConversion}, | ||
| }; | ||
| use frame_system::WeightInfo; | ||
| use sp_runtime::{traits::Zero, FixedPointNumber, FixedPointOperand, FixedU128}; | ||
|
|
||
| pub use pallet::*; | ||
|
|
||
| #[cfg(test)] | ||
| mod mock; | ||
|
|
||
| #[cfg(test)] | ||
| mod tests; | ||
|
|
||
| // #[cfg(feature = "runtime-benchmarks")] | ||
| // mod benchmarking; | ||
|
|
||
| // Type alias for `frame_system`'s account id. | ||
| type AccountIdOf<T> = <T as frame_system::Config>::AccountId; | ||
| // This pallet's asset id and balance type. | ||
| type AssetIdOf<T> = <T as Config>::AssetId; | ||
| // Generic fungible balance type. | ||
| type BalanceOf<T> = <<T as Config>::Currency as Inspect<AccountIdOf<T>>>::Balance; | ||
|
|
||
| // #[frame_support::pallet] | ||
| // TODO: Remove | ||
| #[frame_support::pallet(dev_mode)] | ||
| 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 existiing conversion rate for an asset. | ||
| type UpdateOrigin: EnsureOrigin<Self::RuntimeOrigin>; | ||
|
|
||
| /// The units in which we record balances. | ||
| type Balance: Balance + FixedPointOperand; | ||
|
|
||
| /// The currency mechanism for this pallet. | ||
| type Currency: Inspect<Self::AccountId, Balance = Self::Balance>; | ||
|
|
||
| /// The identifier for the class of asset. | ||
| type AssetId: Member + Parameter + Copy + MaybeSerializeDeserialize + MaxEncodedLen; | ||
| } | ||
|
|
||
| #[pallet::storage] | ||
| #[pallet::getter(fn conversion_rate_to_native)] | ||
| /// Maps an asset to its fixed point representation in the native balance. | ||
| pub(super) type ConversionRateToNative<T: Config> = | ||
| StorageMap<_, Blake2_128Concat, T::AssetId, FixedU128, OptionQuery>; | ||
|
|
||
| #[pallet::event] | ||
| #[pallet::generate_deposit(pub(super) fn deposit_event)] | ||
| pub enum Event<T: Config> { | ||
| // Some `asset_id` conversion rate was created. | ||
| Created { asset_id: T::AssetId, rate: FixedU128 }, | ||
| // Some `asset_id` conversion rate was removed. | ||
| Removed { asset_id: T::AssetId }, | ||
| // Some existing `asset_id` conversion rate was updated from `old` to `new`. | ||
| Updated { asset_id: T::AssetId, old: FixedU128, new: FixedU128 }, | ||
wischli marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| #[pallet::error] | ||
| pub enum Error<T> { | ||
| /// The given asset ID is unknown. | ||
| Unknown, | ||
wischli marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| /// The given asset ID already has an assigned conversion rate and cannot be re-created. | ||
| AlreadyExists, | ||
| } | ||
|
|
||
| #[pallet::call] | ||
| impl<T: Config> Pallet<T> { | ||
| #[pallet::call_index(0)] | ||
| pub fn create( | ||
| origin: OriginFor<T>, | ||
| asset_id: T::AssetId, | ||
| rate: FixedU128, | ||
| ) -> DispatchResult { | ||
| T::CreateOrigin::ensure_origin(origin)?; | ||
|
|
||
| ensure!( | ||
| !ConversionRateToNative::<T>::contains_key(asset_id), | ||
| Error::<T>::AlreadyExists | ||
| ); | ||
| ConversionRateToNative::<T>::set(asset_id, Some(rate)); | ||
|
|
||
| Self::deposit_event(Event::Created { asset_id, rate }); | ||
| Ok(()) | ||
| } | ||
|
|
||
| #[pallet::call_index(1)] | ||
| pub fn update( | ||
| origin: OriginFor<T>, | ||
| asset_id: T::AssetId, | ||
| rate: FixedU128, | ||
| ) -> DispatchResult { | ||
| T::UpdateOrigin::ensure_origin(origin)?; | ||
|
|
||
| let mut old = FixedU128::zero(); | ||
| ConversionRateToNative::<T>::mutate(asset_id, |maybe_rate| { | ||
| if let Some(r) = maybe_rate { | ||
| old = *r; | ||
| *r = rate; | ||
|
|
||
| Ok(()) | ||
| } else { | ||
| Err(Error::<T>::Unknown) | ||
| } | ||
| })?; | ||
|
|
||
| Self::deposit_event(Event::Updated { asset_id, old, new: rate }); | ||
| Ok(()) | ||
| } | ||
|
|
||
| #[pallet::call_index(2)] | ||
| pub fn remove(origin: OriginFor<T>, asset_id: T::AssetId) -> DispatchResult { | ||
| T::RemoveOrigin::ensure_origin(origin)?; | ||
|
|
||
| ensure!(ConversionRateToNative::<T>::contains_key(asset_id), Error::<T>::Unknown); | ||
| ConversionRateToNative::<T>::remove(asset_id); | ||
|
|
||
| Self::deposit_event(Event::Removed { asset_id }); | ||
| Ok(()) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<T> BalanceConversion<BalanceOf<T>, AssetIdOf<T>, BalanceOf<T>> for Pallet<T> | ||
| where | ||
| T: Config, | ||
| BalanceOf<T>: FixedPointOperand + Zero, | ||
| { | ||
| type Error = pallet::Error<T>; | ||
|
|
||
| fn to_asset_balance( | ||
| balance: BalanceOf<T>, | ||
| asset_id: AssetIdOf<T>, | ||
| ) -> Result<BalanceOf<T>, pallet::Error<T>> { | ||
| let rate = Pallet::<T>::conversion_rate_to_native(asset_id) | ||
| .ok_or(pallet::Error::<T>::Unknown.into())?; | ||
| Ok(rate.saturating_mul_int(balance)) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| // 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. | ||
|
|
||
| //! The crate's mock. | ||
|
|
||
| use crate as pallet_treasury_oracle; | ||
| use frame_support::traits::{ConstU16, ConstU64}; | ||
| use sp_core::H256; | ||
| use sp_runtime::{ | ||
| testing::Header, | ||
| traits::{BlakeTwo256, IdentityLookup}, | ||
| }; | ||
|
|
||
| type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; | ||
| type Block = frame_system::mocking::MockBlock<Test>; | ||
|
|
||
| frame_support::construct_runtime!( | ||
| pub enum Test where | ||
| Block = Block, | ||
| NodeBlock = Block, | ||
| UncheckedExtrinsic = UncheckedExtrinsic, | ||
| { | ||
| System: frame_system, | ||
| TreasuryOracle: pallet_treasury_oracle, | ||
| Balances: pallet_balances, | ||
| } | ||
| ); | ||
|
|
||
| impl frame_system::Config for Test { | ||
| type BaseCallFilter = frame_support::traits::Everything; | ||
| type BlockWeights = (); | ||
| type BlockLength = (); | ||
| type DbWeight = (); | ||
| type RuntimeOrigin = RuntimeOrigin; | ||
| type RuntimeCall = RuntimeCall; | ||
| type Index = u64; | ||
| type BlockNumber = u64; | ||
| type Hash = H256; | ||
| type Hashing = BlakeTwo256; | ||
| type AccountId = u64; | ||
| type Lookup = IdentityLookup<Self::AccountId>; | ||
| type Header = Header; | ||
| type RuntimeEvent = RuntimeEvent; | ||
| type BlockHashCount = ConstU64<250>; | ||
| type Version = (); | ||
| type PalletInfo = PalletInfo; | ||
| type AccountData = pallet_balances::AccountData<u64>; | ||
| type OnNewAccount = (); | ||
| type OnKilledAccount = (); | ||
| type SystemWeightInfo = (); | ||
| type SS58Prefix = ConstU16<42>; | ||
| type OnSetCode = (); | ||
| type MaxConsumers = frame_support::traits::ConstU32<16>; | ||
| } | ||
|
|
||
| impl pallet_balances::Config for Test { | ||
| type Balance = u64; | ||
| type DustRemoval = (); | ||
| type RuntimeEvent = RuntimeEvent; | ||
| type ExistentialDeposit = ConstU64<1>; | ||
| type AccountStore = System; | ||
| type WeightInfo = (); | ||
| type MaxLocks = (); | ||
| type MaxReserves = (); | ||
| type ReserveIdentifier = [u8; 8]; | ||
| } | ||
|
|
||
| impl pallet_treasury_oracle::Config for Test { | ||
| type WeightInfo = (); | ||
| type RuntimeEvent = RuntimeEvent; | ||
| type CreateOrigin = frame_system::EnsureRoot<u64>; | ||
| type RemoveOrigin = frame_system::EnsureSigned<u64>; | ||
| type UpdateOrigin = frame_system::EnsureSigned<u64>; | ||
| type Balance = u64; | ||
| type Currency = Balances; | ||
| type AssetId = u32; | ||
| } | ||
|
|
||
| // Build genesis storage according to the mock runtime. | ||
| pub fn new_test_ext() -> sp_io::TestExternalities { | ||
| frame_system::GenesisConfig::default().build_storage::<Test>().unwrap().into() | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.