Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ members = [
"frame/transaction-payment/rpc/runtime-api",
"frame/transaction-storage",
"frame/treasury",
"frame/treasury-oracle",
"frame/tips",
"frame/uniques",
"frame/utility",
Expand Down
42 changes: 42 additions & 0 deletions frame/treasury-oracle/Cargo.toml
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"]
226 changes: 226 additions & 0 deletions frame/treasury-oracle/src/lib.rs
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 },
}

#[pallet::error]
pub enum Error<T> {
/// The given asset ID is unknown.
Unknown,
/// 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))
}
}
96 changes: 96 additions & 0 deletions frame/treasury-oracle/src/mock.rs
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()
}
Loading