diff --git a/Cargo.lock b/Cargo.lock index 35271b2768..9328f69f90 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8052,7 +8052,7 @@ dependencies = [ [[package]] name = "pallet-society" version = "4.0.0-dev" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.43#5e49f6e44820affccaf517fd22af564f4b495d40" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.43#5e49f6e44820affccaf517fd22af564f4b495d40" dependencies = [ "frame-support", "frame-system", @@ -8089,7 +8089,7 @@ dependencies = [ [[package]] name = "pallet-staking-reward-curve" version = "4.0.0-dev" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.43#5e49f6e44820affccaf517fd22af564f4b495d40" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.43#5e49f6e44820affccaf517fd22af564f4b495d40" dependencies = [ "proc-macro-crate 1.3.1", "proc-macro2", @@ -8100,7 +8100,7 @@ dependencies = [ [[package]] name = "pallet-staking-reward-fn" version = "4.0.0-dev" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.43#5e49f6e44820affccaf517fd22af564f4b495d40" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.43#5e49f6e44820affccaf517fd22af564f4b495d40" dependencies = [ "log", "sp-arithmetic", @@ -10937,6 +10937,7 @@ dependencies = [ "sp-runtime", "sp-std", "xcm", + "xcm-builder", "xcm-executor", "xcm-primitives", ] diff --git a/Cargo.toml b/Cargo.toml index 61bf0afca7..f610ac938c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -357,10 +357,7 @@ pallet-recovery = { git = "https://github.com/paritytech//substrate", branch = " pallet-scheduler = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } pallet-session = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } pallet-session-benchmarking = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } -pallet-society = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } pallet-staking = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } -pallet-staking-reward-curve = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } -pallet-staking-reward-fn = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } pallet-sudo = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } pallet-timestamp = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } pallet-tips = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } @@ -567,10 +564,7 @@ pallet-recovery = { git = "https://github.com/paritytech//substrate", branch = " pallet-scheduler = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } pallet-session = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } pallet-session-benchmarking = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } -pallet-society = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } pallet-staking = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } -pallet-staking-reward-curve = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } -pallet-staking-reward-fn = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } pallet-sudo = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } pallet-timestamp = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } pallet-tips = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.43" } diff --git a/libs/mocks/src/token_swaps.rs b/libs/mocks/src/token_swaps.rs index 6d82500a0e..230e7c9ce7 100644 --- a/libs/mocks/src/token_swaps.rs +++ b/libs/mocks/src/token_swaps.rs @@ -1,6 +1,6 @@ #[frame_support::pallet] pub mod pallet { - use cfg_traits::{OrderInfo, OrderRatio, TokenSwaps}; + use cfg_traits::swaps::{OrderInfo, OrderRatio, TokenSwaps}; use frame_support::pallet_prelude::*; use mock_builder::{execute_call, register_call}; diff --git a/libs/primitives/src/lib.rs b/libs/primitives/src/lib.rs index a0185a4294..b0a82a2ce8 100644 --- a/libs/primitives/src/lib.rs +++ b/libs/primitives/src/lib.rs @@ -75,10 +75,6 @@ pub mod types { /// it equivalent to the public key of our transaction signing scheme. pub type AccountId = <::Signer as IdentifyAccount>::AccountId; - /// The type for looking up accounts. We don't expect more than 4 billion of - /// them, but you never know... - pub type AccountIndex = u32; - /// The address format for describing accounts. pub type Address = sp_runtime::MultiAddress; @@ -102,6 +98,7 @@ pub mod types { /// A generic block for the node to use, as we can not commit to /// a specific Extrinsic format at this point. Runtimes will ensure /// Extrinsic are correctly decoded. + /// Used by the node. pub type Block = sp_runtime::generic::Block; /// Block header type as expected by this runtime. diff --git a/libs/traits/src/fees.rs b/libs/traits/src/fees.rs new file mode 100644 index 0000000000..b0d52267b2 --- /dev/null +++ b/libs/traits/src/fees.rs @@ -0,0 +1,90 @@ +use frame_support::{dispatch::DispatchResult, traits::tokens::Balance}; +use parity_scale_codec::FullCodec; +use scale_info::TypeInfo; +use sp_runtime::traits::MaybeSerializeDeserialize; + +/// Type used for identity the key used to retrieve the fees. +pub trait FeeKey: + FullCodec + TypeInfo + MaybeSerializeDeserialize + sp_std::fmt::Debug + Clone + PartialEq +{ +} + +impl< + T: FullCodec + TypeInfo + MaybeSerializeDeserialize + sp_std::fmt::Debug + Clone + PartialEq, + > FeeKey for T +{ +} + +/// A way to identify a fee value. +pub enum Fee { + /// The fee value itself. + Balance(Balance), + + /// The fee value is already stored and identified by a key. + Key(FeeKey), +} + +impl Fee { + pub fn value>(&self) -> Balance { + match self { + Fee::Balance(value) => *value, + Fee::Key(key) => F::fee_value(key.clone()), + } + } +} + +/// A trait that used to deal with fees +pub trait Fees { + type AccountId; + type Balance: Balance; + type FeeKey: FeeKey; + + /// Get the fee balance for a fee key + fn fee_value(key: Self::FeeKey) -> Self::Balance; + + /// Pay an amount of fee to the block author + /// If the `from` account has not enough balance or the author is + /// invalid the fees are not paid. + fn fee_to_author( + from: &Self::AccountId, + fee: Fee, + ) -> DispatchResult; + + /// Burn an amount of fee + /// If the `from` account has not enough balance the fees are not paid. + fn fee_to_burn(from: &Self::AccountId, fee: Fee) + -> DispatchResult; + + /// Send an amount of fee to the treasury + /// If the `from` account has not enough balance the fees are not paid. + fn fee_to_treasury( + from: &Self::AccountId, + fee: Fee, + ) -> DispatchResult; + + /// Allows to initialize an initial state required for a pallet that + /// calls pay a fee + #[cfg(feature = "runtime-benchmarks")] + fn add_fee_requirements(_from: &Self::AccountId, _fee: Fee) {} +} + +/// Trait to pay fees +/// This trait can be used by a pallet to just pay fees without worring +/// about the value or where the fee goes. +pub trait PayFee { + /// Pay the fee using a payer + fn pay(payer: &AccountId) -> DispatchResult; + + /// Allows to initialize an initial state required for a pallet that + /// calls `pay()`. + #[cfg(feature = "runtime-benchmarks")] + fn add_pay_requirements(_payer: &AccountId) {} +} + +/// Type to avoid paying fees +pub struct NoPayFee; +impl PayFee for NoPayFee { + fn pay(_: &AccountId) -> DispatchResult { + Ok(()) + } +} diff --git a/libs/traits/src/lib.rs b/libs/traits/src/lib.rs index d2a22cae87..54dcb25022 100644 --- a/libs/traits/src/lib.rs +++ b/libs/traits/src/lib.rs @@ -41,6 +41,10 @@ pub mod changes; pub mod data; /// Traits related to Ethereum/EVM. pub mod ethereum; +/// Traits related to pool fees. +pub mod fee; +/// Traits related to fees payment. +pub mod fees; /// Traits related to interest rates. pub mod interest; /// Traits related to investments. @@ -49,11 +53,12 @@ pub mod investments; pub mod liquidity_pools; /// Traits related to rewards. pub mod rewards; +/// Traits related to swaps. +pub mod swaps; #[cfg(feature = "runtime-benchmarks")] /// Traits related to benchmarking tooling. pub mod benchmarking; -pub mod fee; /// A trait used for loosely coupling the claim pallet with a reward mechanism. /// @@ -380,106 +385,6 @@ impl PreConditions for Never { } } -pub mod fees { - use frame_support::{dispatch::DispatchResult, traits::tokens::Balance}; - use parity_scale_codec::FullCodec; - use scale_info::TypeInfo; - use sp_runtime::traits::MaybeSerializeDeserialize; - - /// Type used for identity the key used to retrieve the fees. - pub trait FeeKey: - FullCodec + TypeInfo + MaybeSerializeDeserialize + sp_std::fmt::Debug + Clone + PartialEq - { - } - - impl< - T: FullCodec - + TypeInfo - + MaybeSerializeDeserialize - + sp_std::fmt::Debug - + Clone - + PartialEq, - > FeeKey for T - { - } - - /// A way to identify a fee value. - pub enum Fee { - /// The fee value itself. - Balance(Balance), - - /// The fee value is already stored and identified by a key. - Key(FeeKey), - } - - impl Fee { - pub fn value>(&self) -> Balance { - match self { - Fee::Balance(value) => *value, - Fee::Key(key) => F::fee_value(key.clone()), - } - } - } - - /// A trait that used to deal with fees - pub trait Fees { - type AccountId; - type Balance: Balance; - type FeeKey: FeeKey; - - /// Get the fee balance for a fee key - fn fee_value(key: Self::FeeKey) -> Self::Balance; - - /// Pay an amount of fee to the block author - /// If the `from` account has not enough balance or the author is - /// invalid the fees are not paid. - fn fee_to_author( - from: &Self::AccountId, - fee: Fee, - ) -> DispatchResult; - - /// Burn an amount of fee - /// If the `from` account has not enough balance the fees are not paid. - fn fee_to_burn( - from: &Self::AccountId, - fee: Fee, - ) -> DispatchResult; - - /// Send an amount of fee to the treasury - /// If the `from` account has not enough balance the fees are not paid. - fn fee_to_treasury( - from: &Self::AccountId, - fee: Fee, - ) -> DispatchResult; - - /// Allows to initialize an initial state required for a pallet that - /// calls pay a fee - #[cfg(feature = "runtime-benchmarks")] - fn add_fee_requirements(_from: &Self::AccountId, _fee: Fee) {} - } - - /// Trait to pay fees - /// This trait can be used by a pallet to just pay fees without worring - /// about the value or where the fee goes. - pub trait PayFee { - /// Pay the fee using a payer - fn pay(payer: &AccountId) -> DispatchResult; - - /// Allows to initialize an initial state required for a pallet that - /// calls `pay()`. - #[cfg(feature = "runtime-benchmarks")] - fn add_pay_requirements(_payer: &AccountId) {} - } - - /// Type to avoid paying fees - pub struct NoPayFee; - impl PayFee for NoPayFee { - fn pay(_: &AccountId) -> DispatchResult { - Ok(()) - } - } -} - /// Trait to determine whether a sending account and currency have a /// restriction, and if so is there an allowance for the receiver location. pub trait TransferAllowance { @@ -503,188 +408,6 @@ pub trait CurrencyInspect { fn is_tranche_token(currency: Self::CurrencyId) -> bool; } -/// Determines an order price -#[derive(Clone, Copy, Debug, Encode, Decode, Eq, PartialEq, MaxEncodedLen, TypeInfo)] -pub enum OrderRatio { - Market, - Custom(Ratio), -} - -/// A simple representation of a currency swap. -#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct Swap { - /// The incoming currency, i.e. the desired one. - pub currency_in: Currency, - - /// The outgoing currency, i.e. the one which should be replaced. - pub currency_out: Currency, - - /// The amount of outcoming currency that will be swapped. - pub amount_out: Amount, -} - -impl Swap { - pub fn has_same_currencies(&self) -> bool { - self.currency_in == self.currency_out - } - - pub fn is_same_direction(&self, other: &Self) -> Result { - if self.currency_in == other.currency_in && self.currency_out == other.currency_out { - Ok(true) - } else if self.currency_in == other.currency_out && self.currency_out == other.currency_in { - Ok(false) - } else { - Err(DispatchError::Other("Swap contains different currencies")) - } - } -} - -/// The information of a swap order -#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] -pub struct OrderInfo { - /// The underlying currency swap - pub swap: Swap, - /// The ratio at which the swap should happen - pub ratio: OrderRatio, -} - -pub trait TokenSwaps { - type CurrencyId; - type BalanceOut; - type BalanceIn; - type Ratio; - type OrderId; - - /// Swap tokens selling `amount_out` of `currency_out` and buying - /// `currency_in` given an order ratio. - fn place_order( - account: Account, - currency_in: Self::CurrencyId, - currency_out: Self::CurrencyId, - amount_out: Self::BalanceOut, - ratio: OrderRatio, - ) -> Result; - - /// Update an existing active order. - fn update_order( - order_id: Self::OrderId, - amount_out: Self::BalanceOut, - ratio: OrderRatio, - ) -> DispatchResult; - - /// Fill an existing order up to the provided amount. - /// * If `amount` equals the `order.amount_out`, the order is completely - /// fulfilled. - /// * Else, the order is partially fulfilled for `amount / - /// order.amount_out`%. - fn fill_order( - account: Account, - order_id: Self::OrderId, - amount: Self::BalanceOut, - ) -> DispatchResult; - - /// A sanity check that can be used for validating that a trading pair - /// is supported. Will also be checked when placing an order but might be - /// cheaper. - fn valid_pair(currency_in: Self::CurrencyId, currency_out: Self::CurrencyId) -> bool; - - /// Cancel an already active order. - fn cancel_order(order: Self::OrderId) -> DispatchResult; - - /// Retrieve the details of the order if it exists. - fn get_order_details( - order: Self::OrderId, - ) -> Option>; - - /// Makes a conversion between 2 currencies using the market ratio between - /// them. - fn convert_by_market( - currency_in: Self::CurrencyId, - currency_out: Self::CurrencyId, - amount_out: Self::BalanceOut, - ) -> Result; - - #[cfg(feature = "runtime-benchmarks")] - /// Adds a valid trading pair. - fn add_trading_pair( - currency_in: Self::CurrencyId, - currency_out: Self::CurrencyId, - min_order: Self::BalanceOut, - ) -> DispatchResult; -} - -/// A representation of a currency swap in process. -#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct SwapState { - /// Swap not yet processed with the pending outcomming amount - pub remaining: Swap, - - /// Amount of incoming currency already swapped - pub swapped_in: AmountIn, - - /// Amount of incoming currency already swapped denominated in outgoing - /// currency - pub swapped_out: AmountOut, -} - -/// Used as result of `Pallet::apply_swap()` -/// Amounts are donominated referenced by the `new_swap` paramenter given to -/// `apply_swap()` -#[derive(Clone, PartialEq, Eq, Debug)] -pub struct SwapStatus { - /// The incoming amount already swapped and available to use. - pub swapped: Amount, - - /// The outgoing amount pending to be swapped - pub pending: Amount, -} - -/// Trait to perform swaps without handling directly an order book -pub trait Swaps { - type Amount; - type CurrencyId; - type SwapId; - - /// Apply a swap over a current possible swap state. - /// - If there was no previous swap, it adds it. - /// - If there was a swap in the same direction, it increments it. - /// - If there was a swap in the opposite direction: - /// - If the amount is smaller, it decrements it. - /// - If the amount is the same, it removes the inverse swap. - /// - If the amount is greater, it removes the inverse swap and create - /// another with the excess - /// - /// The returned status contains the swapped amount after this call - /// (denominated in the incoming currency) and the pending amounts to be - /// swapped. - fn apply_swap( - who: &AccountId, - swap_id: Self::SwapId, - swap: Swap, - ) -> Result, DispatchError>; - - /// Returns the pending amount for a pending swap. The direction of the swap - /// is determined by the `from_currency` parameter. The amount returned is - /// denominated in the same currency as the given `from_currency`. - fn pending_amount( - who: &AccountId, - swap_id: Self::SwapId, - from_currency: Self::CurrencyId, - ) -> Result; - - /// Check that validates that if swapping pair is supported. - fn valid_pair(currency_in: Self::CurrencyId, currency_out: Self::CurrencyId) -> bool; - - /// Makes a conversion between 2 currencies using the market ratio between - /// them - // TODO: Should be removed after #1723 - fn convert_by_market( - currency_in: Self::CurrencyId, - currency_out: Self::CurrencyId, - amount_out: Self::Amount, - ) -> Result; -} - /// Trait to transmit a change of status for anything uniquely identifiable. /// /// NOTE: The main use case to handle asynchronous operations. diff --git a/libs/traits/src/swaps.rs b/libs/traits/src/swaps.rs new file mode 100644 index 0000000000..1ec7906d34 --- /dev/null +++ b/libs/traits/src/swaps.rs @@ -0,0 +1,186 @@ +use frame_support::{scale_info::TypeInfo, RuntimeDebug}; +use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; +use sp_runtime::{DispatchError, DispatchResult}; +use sp_std::fmt::Debug; + +/// Determines an order price +#[derive(Clone, Copy, Debug, Encode, Decode, Eq, PartialEq, MaxEncodedLen, TypeInfo)] +pub enum OrderRatio { + Market, + Custom(Ratio), +} + +/// A simple representation of a currency swap. +#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] +pub struct Swap { + /// The incoming currency, i.e. the desired one. + pub currency_in: Currency, + + /// The outgoing currency, i.e. the one which should be replaced. + pub currency_out: Currency, + + /// The amount of outcoming currency that will be swapped. + pub amount_out: Amount, +} + +impl Swap { + pub fn has_same_currencies(&self) -> bool { + self.currency_in == self.currency_out + } + + pub fn is_same_direction(&self, other: &Self) -> Result { + if self.currency_in == other.currency_in && self.currency_out == other.currency_out { + Ok(true) + } else if self.currency_in == other.currency_out && self.currency_out == other.currency_in { + Ok(false) + } else { + Err(DispatchError::Other("Swap contains different currencies")) + } + } +} + +/// The information of a swap order +#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct OrderInfo { + /// The underlying currency swap + pub swap: Swap, + /// The ratio at which the swap should happen + pub ratio: OrderRatio, +} + +pub trait TokenSwaps { + type CurrencyId; + type BalanceOut; + type BalanceIn; + type Ratio; + type OrderId; + + /// Swap tokens selling `amount_out` of `currency_out` and buying + /// `currency_in` given an order ratio. + fn place_order( + account: Account, + currency_in: Self::CurrencyId, + currency_out: Self::CurrencyId, + amount_out: Self::BalanceOut, + ratio: OrderRatio, + ) -> Result; + + /// Update an existing active order. + fn update_order( + order_id: Self::OrderId, + amount_out: Self::BalanceOut, + ratio: OrderRatio, + ) -> DispatchResult; + + /// Fill an existing order up to the provided amount. + /// * If `amount` equals the `order.amount_out`, the order is completely + /// fulfilled. + /// * Else, the order is partially fulfilled for `amount / + /// order.amount_out`%. + fn fill_order( + account: Account, + order_id: Self::OrderId, + amount: Self::BalanceOut, + ) -> DispatchResult; + + /// A sanity check that can be used for validating that a trading pair + /// is supported. Will also be checked when placing an order but might be + /// cheaper. + fn valid_pair(currency_in: Self::CurrencyId, currency_out: Self::CurrencyId) -> bool; + + /// Cancel an already active order. + fn cancel_order(order: Self::OrderId) -> DispatchResult; + + /// Retrieve the details of the order if it exists. + fn get_order_details( + order: Self::OrderId, + ) -> Option>; + + /// Makes a conversion between 2 currencies using the market ratio between + /// them. + fn convert_by_market( + currency_in: Self::CurrencyId, + currency_out: Self::CurrencyId, + amount_out: Self::BalanceOut, + ) -> Result; + + #[cfg(feature = "runtime-benchmarks")] + /// Adds a valid trading pair. + fn add_trading_pair( + currency_in: Self::CurrencyId, + currency_out: Self::CurrencyId, + min_order: Self::BalanceOut, + ) -> DispatchResult; +} + +/// A representation of a currency swap in process. +#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] +pub struct SwapState { + /// Swap not yet processed with the pending outcomming amount + pub remaining: Swap, + + /// Amount of incoming currency already swapped + pub swapped_in: AmountIn, + + /// Amount of incoming currency already swapped denominated in outgoing + /// currency + pub swapped_out: AmountOut, +} + +/// Used as result of `Pallet::apply_swap()` +/// Amounts are donominated referenced by the `new_swap` paramenter given to +/// `apply_swap()` +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct SwapStatus { + /// The incoming amount already swapped and available to use. + pub swapped: Amount, + + /// The outgoing amount pending to be swapped + pub pending: Amount, +} + +/// Trait to perform swaps without handling directly an order book +pub trait Swaps { + type Amount; + type CurrencyId; + type SwapId; + + /// Apply a swap over a current possible swap state. + /// - If there was no previous swap, it adds it. + /// - If there was a swap in the same direction, it increments it. + /// - If there was a swap in the opposite direction: + /// - If the amount is smaller, it decrements it. + /// - If the amount is the same, it removes the inverse swap. + /// - If the amount is greater, it removes the inverse swap and create + /// another with the excess + /// + /// The returned status contains the swapped amount after this call + /// (denominated in the incoming currency) and the pending amounts to be + /// swapped. + fn apply_swap( + who: &AccountId, + swap_id: Self::SwapId, + swap: Swap, + ) -> Result, DispatchError>; + + /// Returns the pending amount for a pending swap. The direction of the swap + /// is determined by the `from_currency` parameter. The amount returned is + /// denominated in the same currency as the given `from_currency`. + fn pending_amount( + who: &AccountId, + swap_id: Self::SwapId, + from_currency: Self::CurrencyId, + ) -> Result; + + /// Check that validates that if swapping pair is supported. + fn valid_pair(currency_in: Self::CurrencyId, currency_out: Self::CurrencyId) -> bool; + + /// Makes a conversion between 2 currencies using the market ratio between + /// them + // TODO: Should be removed after #1723 + fn convert_by_market( + currency_in: Self::CurrencyId, + currency_out: Self::CurrencyId, + amount_out: Self::Amount, + ) -> Result; +} diff --git a/node/src/chain_spec.rs b/node/src/chain_spec.rs index ec9f122bc4..36384f994f 100644 --- a/node/src/chain_spec.rs +++ b/node/src/chain_spec.rs @@ -26,7 +26,8 @@ use std::collections::BTreeMap; use altair_runtime::constants::currency::{AIR, MILLI_AIR}; use cfg_primitives::{ - currency_decimals, parachains, Balance, BlockNumber, CFG, MILLI_CFG, SAFE_XCM_VERSION, + currency_decimals, parachains, AccountId, AuraId, Balance, BlockNumber, CFG, MILLI_CFG, + SAFE_XCM_VERSION, }; use cfg_types::{ fee_keys::FeeKey, @@ -59,9 +60,9 @@ pub type CentrifugeChainSpec = pub type DevelopmentChainSpec = sc_service::GenericChainSpec; -use altair_runtime::evm::AltairPrecompiles; -use centrifuge_runtime::evm::CentrifugePrecompiles; -use development_runtime::evm::DevelopmentPrecompiles; +use altair_runtime::AltairPrecompiles; +use centrifuge_runtime::CentrifugePrecompiles; +use development_runtime::DevelopmentPrecompiles; /// Helper function to generate a crypto pair from seed pub fn get_from_seed(seed: &str) -> ::Public { @@ -101,25 +102,21 @@ fn development_extensions(para_id: u32) -> Extensions { } } -pub fn get_altair_session_keys(keys: altair_runtime::AuraId) -> altair_runtime::SessionKeys { +pub fn get_altair_session_keys(keys: AuraId) -> altair_runtime::SessionKeys { altair_runtime::SessionKeys { aura: keys.clone(), block_rewards: keys, } } -pub fn get_centrifuge_session_keys( - keys: centrifuge_runtime::AuraId, -) -> centrifuge_runtime::SessionKeys { +pub fn get_centrifuge_session_keys(keys: AuraId) -> centrifuge_runtime::SessionKeys { centrifuge_runtime::SessionKeys { aura: keys.clone(), block_rewards: keys, } } -pub fn get_development_session_keys( - keys: development_runtime::AuraId, -) -> development_runtime::SessionKeys { +pub fn get_development_session_keys(keys: AuraId) -> development_runtime::SessionKeys { development_runtime::SessionKeys { aura: keys.clone(), block_rewards: keys, @@ -129,7 +126,7 @@ pub fn get_development_session_keys( type AccountPublic = ::Signer; /// Helper function to generate an account ID from seed -pub fn get_account_id_from_seed(seed: &str) -> cfg_primitives::AccountId +pub fn get_account_id_from_seed(seed: &str) -> AccountId where AccountPublic: From<::Public>, { @@ -157,15 +154,15 @@ pub fn centrifuge_dev(para_id: ParaId) -> CentrifugeChainSpec { vec![ ( get_account_id_from_seed::("Alice"), - get_from_seed::("Alice"), + get_from_seed::("Alice"), ), ( get_account_id_from_seed::("Bob"), - get_from_seed::("Bob"), + get_from_seed::("Bob"), ), ( get_account_id_from_seed::("Charlie"), - get_from_seed::("Charlie"), + get_from_seed::("Charlie"), ), ], endowed_accounts(), @@ -197,7 +194,7 @@ pub fn centrifuge_local(para_id: ParaId) -> CentrifugeChainSpec { centrifuge_genesis( vec![( get_account_id_from_seed::("Alice"), - get_from_seed::("Alice"), + get_from_seed::("Alice"), )], endowed_accounts(), endowed_evm_accounts(), @@ -233,7 +230,7 @@ pub fn catalyst_local(para_id: ParaId) -> CentrifugeChainSpec { centrifuge_genesis( vec![( get_account_id_from_seed::("Alice"), - get_from_seed::("Alice"), + get_from_seed::("Alice"), )], endowed_accounts(), endowed_evm_accounts(), @@ -272,15 +269,15 @@ pub fn altair_dev(para_id: ParaId) -> AltairChainSpec { vec![ ( get_account_id_from_seed::("Alice"), - get_from_seed::("Alice"), + get_from_seed::("Alice"), ), ( get_account_id_from_seed::("Bob"), - get_from_seed::("Bob"), + get_from_seed::("Bob"), ), ( get_account_id_from_seed::("Charlie"), - get_from_seed::("Charlie"), + get_from_seed::("Charlie"), ), ], endowed_accounts(), @@ -312,7 +309,7 @@ pub fn altair_local(para_id: ParaId) -> AltairChainSpec { altair_genesis( vec![( get_account_id_from_seed::("Alice"), - get_from_seed::("Alice"), + get_from_seed::("Alice"), )], endowed_accounts(), endowed_evm_accounts(), @@ -347,7 +344,7 @@ pub fn antares_local(para_id: ParaId) -> AltairChainSpec { altair_genesis( vec![( get_account_id_from_seed::("Alice"), - get_from_seed::("Alice"), + get_from_seed::("Alice"), )], endowed_accounts(), endowed_evm_accounts(), @@ -382,7 +379,7 @@ pub fn charcoal_local(para_id: ParaId) -> AltairChainSpec { altair_genesis( vec![( get_account_id_from_seed::("Alice"), - get_from_seed::("Alice"), + get_from_seed::("Alice"), )], endowed_accounts(), endowed_evm_accounts(), @@ -449,7 +446,7 @@ pub fn development(para_id: ParaId) -> DevelopmentChainSpec { get_account_id_from_seed::("Alice"), vec![( get_account_id_from_seed::("Alice"), - get_from_seed::("Alice"), + get_from_seed::("Alice"), )], endowed_accounts(), endowed_evm_accounts(), @@ -480,7 +477,7 @@ pub fn development_local(para_id: ParaId) -> DevelopmentChainSpec { get_account_id_from_seed::("Alice"), vec![( get_account_id_from_seed::("Alice"), - get_from_seed::("Alice"), + get_from_seed::("Alice"), )], endowed_accounts(), endowed_evm_accounts(), @@ -497,7 +494,7 @@ pub fn development_local(para_id: ParaId) -> DevelopmentChainSpec { ) } -fn demo_endowed_accounts() -> Vec { +fn demo_endowed_accounts() -> Vec { vec![ //kANEUrMbi9xC16AfL5vSGwfvBVRoRdfWoQ8abPiXi5etFxpdP hex!["e0c426785313bb7e712d66dce43ccb81a7eaef373784511fb508fff4b5df3305"].into(), @@ -518,7 +515,7 @@ fn demo_endowed_accounts() -> Vec { ] } -fn endowed_accounts() -> Vec { +fn endowed_accounts() -> Vec { vec![ get_account_id_from_seed::("Alice"), get_account_id_from_seed::("Bob"), @@ -543,31 +540,34 @@ fn endowed_evm_accounts() -> Vec<([u8; 20], Option)> { )] } -fn council_members_bootstrap() -> Vec { +fn council_members_bootstrap() -> Vec { endowed_accounts().into_iter().take(4).collect() } fn centrifuge_genesis( - initial_authorities: Vec<(centrifuge_runtime::AccountId, centrifuge_runtime::AuraId)>, - mut endowed_accounts: Vec, + initial_authorities: Vec<(AccountId, AuraId)>, + mut endowed_accounts: Vec, endowed_evm_accounts: Vec<([u8; 20], Option)>, - total_issuance: Option, + total_issuance: Option, id: ParaId, - council_members: Vec, + council_members: Vec, ) -> centrifuge_runtime::GenesisConfig { let chain_id: u32 = id.into(); endowed_accounts.extend(endowed_evm_accounts.into_iter().map(|(addr, id)| { let chain_id = id.unwrap_or_else(|| chain_id.into()); - AccountConverter::::convert_evm_address(chain_id, addr) + AccountConverter::< + centrifuge_runtime::Runtime, + centrifuge_runtime::xcm::LocationToAccountId, + >::convert_evm_address(chain_id, addr) })); let num_endowed_accounts = endowed_accounts.len(); let balances = match total_issuance { Some(total_issuance) => { let balance_per_endowed = total_issuance - .checked_div(num_endowed_accounts as centrifuge_runtime::Balance) - .unwrap_or(0 as centrifuge_runtime::Balance); + .checked_div(num_endowed_accounts as Balance) + .unwrap_or(0 as Balance); endowed_accounts .iter() .cloned() @@ -680,26 +680,29 @@ fn centrifuge_genesis( } fn altair_genesis( - initial_authorities: Vec<(altair_runtime::AccountId, altair_runtime::AuraId)>, - mut endowed_accounts: Vec, + initial_authorities: Vec<(AccountId, AuraId)>, + mut endowed_accounts: Vec, endowed_evm_accounts: Vec<([u8; 20], Option)>, - total_issuance: Option, + total_issuance: Option, id: ParaId, - council_members: Vec, + council_members: Vec, ) -> altair_runtime::GenesisConfig { let chain_id: u32 = id.into(); endowed_accounts.extend(endowed_evm_accounts.into_iter().map(|(addr, id)| { let chain_id = id.unwrap_or_else(|| chain_id.into()); - AccountConverter::::convert_evm_address(chain_id, addr) + AccountConverter::< + altair_runtime::Runtime, + altair_runtime::xcm::LocationToAccountId, + >::convert_evm_address(chain_id, addr) })); let num_endowed_accounts = endowed_accounts.len(); let balances = match total_issuance { Some(total_issuance) => { let balance_per_endowed = total_issuance - .checked_div(num_endowed_accounts as altair_runtime::Balance) - .unwrap_or(0 as altair_runtime::Balance); + .checked_div(num_endowed_accounts as Balance) + .unwrap_or(0 as Balance); endowed_accounts .iter() .cloned() @@ -798,26 +801,29 @@ const DEV_USDT_CURRENCY_ID: CurrencyId = CurrencyId::ForeignAsset(1); const DEV_AUSD_CURRENCY_ID: CurrencyId = CurrencyId::ForeignAsset(2); fn development_genesis( - root_key: development_runtime::AccountId, - initial_authorities: Vec<(development_runtime::AccountId, development_runtime::AuraId)>, - mut endowed_accounts: Vec, + root_key: AccountId, + initial_authorities: Vec<(AccountId, AuraId)>, + mut endowed_accounts: Vec, endowed_evm_accounts: Vec<([u8; 20], Option)>, - total_issuance: Option, + total_issuance: Option, id: ParaId, ) -> development_runtime::GenesisConfig { let chain_id: u32 = id.into(); endowed_accounts.extend(endowed_evm_accounts.into_iter().map(|(addr, id)| { let chain_id = id.unwrap_or_else(|| chain_id.into()); - AccountConverter::::convert_evm_address(chain_id, addr) + AccountConverter::< + development_runtime::Runtime, + development_runtime::xcm::LocationToAccountId, + >::convert_evm_address(chain_id, addr) })); let num_endowed_accounts = endowed_accounts.len(); let (balances, token_balances) = match total_issuance { Some(total_issuance) => { let balance_per_endowed = total_issuance - .checked_div(num_endowed_accounts as development_runtime::Balance) - .unwrap_or(0 as development_runtime::Balance); + .checked_div(num_endowed_accounts as Balance) + .unwrap_or(0 as Balance); ( // pallet_balances balances @@ -1034,7 +1040,7 @@ fn asset_registry_assets() -> Vec<(CurrencyId, Vec)> { lp_wrapped_usdc_metadata( "LP Ethereum Wrapped USDC".as_bytes().to_vec(), "LpEthUSDC".as_bytes().to_vec(), - development_runtime::liquidity_pools::LiquidityPoolsPalletIndex::get(), + development_runtime::LiquidityPoolsPalletIndex::get(), CHAIN_ID_ETH_GOERLI_TESTNET, CONTRACT_ETH_GOERLI, true, diff --git a/pallets/foreign-investments/src/entities.rs b/pallets/foreign-investments/src/entities.rs index 5b313623f8..eed4c104ea 100644 --- a/pallets/foreign-investments/src/entities.rs +++ b/pallets/foreign-investments/src/entities.rs @@ -1,6 +1,9 @@ //! Types with Config access. This module does not mutate FI storage -use cfg_traits::{investments::Investment, Swap, Swaps}; +use cfg_traits::{ + investments::Investment, + swaps::{Swap, Swaps}, +}; use cfg_types::investments::{ CollectedAmount, ExecutedForeignCollect, ExecutedForeignDecreaseInvest, }; diff --git a/pallets/foreign-investments/src/impls.rs b/pallets/foreign-investments/src/impls.rs index 125f77523e..bf24ede27a 100644 --- a/pallets/foreign-investments/src/impls.rs +++ b/pallets/foreign-investments/src/impls.rs @@ -2,7 +2,8 @@ use cfg_traits::{ investments::{ForeignInvestment, Investment, InvestmentCollector, TrancheCurrency}, - PoolInspect, StatusNotificationHook, SwapState, Swaps, + swaps::{SwapState, Swaps}, + PoolInspect, StatusNotificationHook, }; use cfg_types::investments::CollectedAmount; use frame_support::pallet_prelude::*; diff --git a/pallets/foreign-investments/src/lib.rs b/pallets/foreign-investments/src/lib.rs index 542b7b1256..867322476e 100644 --- a/pallets/foreign-investments/src/lib.rs +++ b/pallets/foreign-investments/src/lib.rs @@ -35,7 +35,7 @@ #![cfg_attr(not(feature = "std"), no_std)] -use cfg_traits::Swap; +use cfg_traits::swaps::Swap; pub use impls::{CollectedInvestmentHook, CollectedRedemptionHook, FulfilledSwapHook}; pub use pallet::*; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; @@ -96,7 +96,8 @@ pub fn pool_currency_of( pub mod pallet { use cfg_traits::{ investments::{Investment, InvestmentCollector, TrancheCurrency}, - PoolInspect, StatusNotificationHook, Swaps, + swaps::Swaps, + PoolInspect, StatusNotificationHook, }; use cfg_types::investments::{ExecutedForeignCollect, ExecutedForeignDecreaseInvest}; use frame_support::pallet_prelude::*; diff --git a/pallets/foreign-investments/src/tests.rs b/pallets/foreign-investments/src/tests.rs index ca740b958e..71c568fd04 100644 --- a/pallets/foreign-investments/src/tests.rs +++ b/pallets/foreign-investments/src/tests.rs @@ -1,6 +1,7 @@ use cfg_traits::{ investments::{ForeignInvestment as _, Investment, TrancheCurrency}, - OrderInfo, OrderRatio, StatusNotificationHook, Swap, SwapState, TokenSwaps, + swaps::{OrderInfo, OrderRatio, Swap, SwapState, TokenSwaps}, + StatusNotificationHook, }; use cfg_types::investments::{ CollectedAmount, ExecutedForeignCollect, ExecutedForeignDecreaseInvest, diff --git a/pallets/order-book/src/benchmarking.rs b/pallets/order-book/src/benchmarking.rs index daa184acce..c37983756c 100644 --- a/pallets/order-book/src/benchmarking.rs +++ b/pallets/order-book/src/benchmarking.rs @@ -10,7 +10,10 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -use cfg_traits::{ConversionToAssetBalance, OrderRatio, TokenSwaps, ValueProvider}; +use cfg_traits::{ + swaps::{OrderRatio, TokenSwaps}, + ConversionToAssetBalance, ValueProvider, +}; use cfg_types::tokens::{AssetMetadata, CustomMetadata}; use frame_benchmarking::{account, v2::*}; use frame_support::traits::{fungibles::Mutate as _, Get}; diff --git a/pallets/order-book/src/lib.rs b/pallets/order-book/src/lib.rs index 27d5982c51..87d091cb1c 100644 --- a/pallets/order-book/src/lib.rs +++ b/pallets/order-book/src/lib.rs @@ -37,8 +37,8 @@ pub use weights::WeightInfo; pub mod pallet { use cfg_primitives::conversion::convert_balance_decimals; use cfg_traits::{ - ConversionToAssetBalance, OrderInfo, OrderRatio, StatusNotificationHook, Swap, SwapState, - TokenSwaps, ValueProvider, + swaps::{OrderInfo, OrderRatio, Swap, SwapState, TokenSwaps}, + ConversionToAssetBalance, StatusNotificationHook, ValueProvider, }; use cfg_types::{self, tokens::CustomMetadata}; use frame_support::{ diff --git a/pallets/order-book/src/mock.rs b/pallets/order-book/src/mock.rs index 13c6affadc..3bf1b22182 100644 --- a/pallets/order-book/src/mock.rs +++ b/pallets/order-book/src/mock.rs @@ -11,7 +11,7 @@ // GNU General Public License for more details. use cfg_mocks::pallet_mock_fees; -use cfg_traits::{ConversionToAssetBalance, SwapState}; +use cfg_traits::{swaps::SwapState, ConversionToAssetBalance}; use cfg_types::tokens::{CurrencyId, CustomMetadata}; use frame_support::{ parameter_types, diff --git a/pallets/order-book/src/tests.rs b/pallets/order-book/src/tests.rs index 268ead3284..d71890f73a 100644 --- a/pallets/order-book/src/tests.rs +++ b/pallets/order-book/src/tests.rs @@ -10,7 +10,7 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -use cfg_traits::{OrderInfo, OrderRatio, Swap, SwapState, TokenSwaps}; +use cfg_traits::swaps::{OrderInfo, OrderRatio, Swap, SwapState, TokenSwaps}; use frame_support::{ assert_err, assert_noop, assert_ok, traits::fungibles::{Inspect, InspectHold}, diff --git a/pallets/pool-registry/src/mock.rs b/pallets/pool-registry/src/mock.rs index 202758e281..fae60dce5f 100644 --- a/pallets/pool-registry/src/mock.rs +++ b/pallets/pool-registry/src/mock.rs @@ -385,7 +385,6 @@ frame_support::construct_runtime!( Balances: pallet_balances::{Pallet, Storage, Event}, FakeNav: cfg_test_utils::mocks::nav::{Pallet, Storage}, OrmlTokens: orml_tokens::{Pallet, Storage, Event, Config}, - ParachainInfo: parachain_info::{Pallet, Storage}, PoolRegistry: pallet_pool_registry::{Pallet, Call, Storage, Event}, PoolSystem: pallet_pool_system::{Pallet, Call, Storage, Event}, System: frame_system::{Pallet, Call, Config, Storage, Event}, @@ -408,8 +407,6 @@ impl Contains for PoolCurrency { } } -impl parachain_info::Config for Test {} - pub struct UpdateGuard; impl PoolUpdateGuard for UpdateGuard { type Moment = Seconds; diff --git a/pallets/pool-system/src/mock.rs b/pallets/pool-system/src/mock.rs index a86decc88a..3727096b59 100644 --- a/pallets/pool-system/src/mock.rs +++ b/pallets/pool-system/src/mock.rs @@ -142,7 +142,6 @@ frame_support::construct_runtime!( FakeNav: cfg_test_utils::mocks::nav::{Pallet, Storage}, Permissions: pallet_permissions::{Pallet, Call, Storage, Event}, Balances: pallet_balances::{Pallet, Storage, Event}, - ParachainInfo: parachain_info::{Pallet, Storage}, Investments: pallet_investments::{Pallet, Call, Storage, Event}, MockChangeGuard: pallet_mock_change_guard, MockIsAdmin: cfg_mocks::pre_conditions::pallet, diff --git a/pallets/swaps/src/lib.rs b/pallets/swaps/src/lib.rs index 6c9ea06add..5dca9c9e81 100644 --- a/pallets/swaps/src/lib.rs +++ b/pallets/swaps/src/lib.rs @@ -27,7 +27,8 @@ pub use pallet::*; #[frame_support::pallet] pub mod pallet { use cfg_traits::{ - OrderRatio, StatusNotificationHook, Swap, SwapState, SwapStatus, Swaps, TokenSwaps, + swaps::{OrderRatio, Swap, SwapState, SwapStatus, Swaps, TokenSwaps}, + StatusNotificationHook, }; use frame_support::pallet_prelude::*; use sp_runtime::traits::{AtLeast32BitUnsigned, EnsureAdd, EnsureSub, Zero}; diff --git a/pallets/swaps/src/mock.rs b/pallets/swaps/src/mock.rs index a70e8df1d6..14b6a5c225 100644 --- a/pallets/swaps/src/mock.rs +++ b/pallets/swaps/src/mock.rs @@ -1,4 +1,4 @@ -use cfg_traits::SwapState; +use cfg_traits::swaps::SwapState; use frame_support::traits::{ConstU16, ConstU32, ConstU64}; use sp_runtime::{ testing::{Header, H256}, diff --git a/pallets/swaps/src/tests.rs b/pallets/swaps/src/tests.rs index d092d276ac..047cd5e23e 100644 --- a/pallets/swaps/src/tests.rs +++ b/pallets/swaps/src/tests.rs @@ -1,5 +1,6 @@ use cfg_traits::{ - OrderInfo, OrderRatio, StatusNotificationHook, Swap, SwapState, SwapStatus, Swaps as TSwaps, + swaps::{OrderInfo, OrderRatio, Swap, SwapState, SwapStatus, Swaps as TSwaps}, + StatusNotificationHook, }; use frame_support::assert_ok; diff --git a/pallets/token-mux/src/benchmarking.rs b/pallets/token-mux/src/benchmarking.rs index 48941b7e93..893abb2845 100644 --- a/pallets/token-mux/src/benchmarking.rs +++ b/pallets/token-mux/src/benchmarking.rs @@ -10,7 +10,7 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -use cfg_traits::OrderRatio; +use cfg_traits::swaps::OrderRatio; use cfg_types::tokens::{ CurrencyId, CurrencyId::{ForeignAsset, LocalAsset}, @@ -46,7 +46,7 @@ fn mock_match_swap(who: T::AccountId) where AccountId32: From, { - use cfg_traits::{OrderInfo, Swap}; + use cfg_traits::swaps::{OrderInfo, Swap}; use tests::swaps::utils::mock_swap; use crate::mock::MockTokenSwaps; diff --git a/pallets/token-mux/src/lib.rs b/pallets/token-mux/src/lib.rs index 3dac5fc59a..86f86c5f7e 100644 --- a/pallets/token-mux/src/lib.rs +++ b/pallets/token-mux/src/lib.rs @@ -36,14 +36,14 @@ mod benchmarking; pub mod weights; -pub use cfg_traits::TokenSwaps; +pub use cfg_traits::swaps::TokenSwaps; pub use pallet::*; pub use weights::WeightInfo; #[frame_support::pallet] pub mod pallet { - use cfg_traits::{OrderRatio, TokenSwaps}; + use cfg_traits::swaps::{OrderRatio, TokenSwaps}; use cfg_types::tokens::CustomMetadata; use frame_support::{ pallet_prelude::{DispatchResult, *}, diff --git a/pallets/token-mux/src/tests.rs b/pallets/token-mux/src/tests.rs index f262937934..c9cc348336 100644 --- a/pallets/token-mux/src/tests.rs +++ b/pallets/token-mux/src/tests.rs @@ -291,7 +291,7 @@ pub(crate) mod swaps { }; pub(crate) mod utils { - use cfg_traits::{OrderInfo, OrderRatio, Swap}; + use cfg_traits::swaps::{OrderInfo, OrderRatio, Swap}; use frame_support::traits::tokens::{fungibles::Mutate, Preservation}; use sp_arithmetic::traits::One; diff --git a/runtime/altair/src/evm.rs b/runtime/altair/src/evm.rs deleted file mode 100644 index 5ab831dcff..0000000000 --- a/runtime/altair/src/evm.rs +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2023 Centrifuge Foundation (centrifuge.io). -// -// This file is part of the Centrifuge chain project. -// Centrifuge is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version (see http://www.gnu.org/licenses). -// Centrifuge is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -use cfg_primitives::{EnsureRootOr, HalfOfCouncil, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO}; -use frame_support::{parameter_types, traits::FindAuthor, weights::Weight, ConsensusEngineId}; -use pallet_ethereum::PostLogContent; -use pallet_evm::{EnsureAddressRoot, EnsureAddressTruncated}; -use runtime_common::{ - account_conversion::AccountConverter, - evm::{precompile::Precompiles, BaseFeeThreshold, WEIGHT_PER_GAS}, -}; -use sp_core::{crypto::ByteArray, H160, U256}; -use sp_runtime::Permill; -use sp_std::marker::PhantomData; - -use crate::{Aura, LocationToAccountId, Runtime, RuntimeEvent}; - -/// To create valid Ethereum-compatible blocks, we need a 20-byte -/// "author" for the block. Since that author is purely informational, -/// we do a simple truncation of the 32-byte Substrate author -pub struct FindAuthorTruncated(PhantomData); -impl> FindAuthor for FindAuthorTruncated { - fn find_author<'a, I>(digests: I) -> Option - where - I: 'a + IntoIterator, - { - if let Some(author_index) = F::find_author(digests) { - let authority_id = Aura::authorities()[author_index as usize].clone(); - return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24])); - } - None - } -} - -pub type AltairPrecompiles = Precompiles; - -parameter_types! { - pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS); - pub PrecompilesValue: AltairPrecompiles = Precompiles::<_, _>::new(); - pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0); - // - // pub GasLimitPovSizeRatio: u64 = { - // let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64(); - // block_gas_limit.saturating_div(MAX_POV_SIZE) - // }; - // - // NOTE: The above results in a value of 2. AS this factor is a divisor generating a - // a storage limit we are conservative and use the value that moonbeam is using - // in their staging environment - // (https://github.com/moonbeam-foundation/moonbeam/blob/973015c376e8741073013094be88e7c58c716a70/runtime/moonriver/src/lib.rs#L408) - pub const GasLimitPovSizeRatio: u64 = 4; - - // - // pub const GasLimitStorageGrowthRatio: u64 = - // BlockGasLimit::get().min(u64::MAX.into()).low_u64().saturating_div(BLOCK_STORAGE_LIMIT); - // - // NOTE: The above results in a value of 366 which is the same value that moonbeam is using - // in their staging environment. As we can not constantly assert this value we hardcode - // it for now. - pub const GasLimitStorageGrowthRatio: u64 = 366; - pub const TokenSymbol: &'static str = "AIR"; -} - -impl pallet_evm::Config for Runtime { - type AddressMapping = AccountConverter; - type BlockGasLimit = BlockGasLimit; - type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping; - type CallOrigin = EnsureAddressRoot; - type ChainId = crate::EVMChainId; - type Currency = crate::Balances; - type FeeCalculator = crate::BaseFee; - type FindAuthor = FindAuthorTruncated; - type GasLimitPovSizeRatio = GasLimitPovSizeRatio; - type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio; - type GasWeightMapping = pallet_evm::FixedGasWeightMapping; - type OnChargeTransaction = (); - type OnCreate = (); - type PrecompilesType = AltairPrecompiles; - type PrecompilesValue = PrecompilesValue; - type Runner = pallet_evm::runner::stack::Runner; - type RuntimeEvent = RuntimeEvent; - type Timestamp = crate::Timestamp; - type WeightInfo = (); - type WeightPerGas = WeightPerGas; - type WithdrawOrigin = EnsureAddressTruncated; -} - -impl pallet_evm_chain_id::Config for Runtime {} - -parameter_types! { - pub DefaultBaseFeePerGas: U256 = U256::from(1_000_000_000); - pub DefaultElasticity: Permill = Permill::from_parts(125_000); -} - -impl pallet_base_fee::Config for Runtime { - type DefaultBaseFeePerGas = DefaultBaseFeePerGas; - type DefaultElasticity = DefaultElasticity; - type RuntimeEvent = RuntimeEvent; - type Threshold = BaseFeeThreshold; -} - -parameter_types! { - pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes; - pub const ExtraDataLength: u32 = 30; -} - -impl pallet_ethereum::Config for Runtime { - type ExtraDataLength = ExtraDataLength; - type PostLogContent = PostBlockAndTxnHashes; - type RuntimeEvent = RuntimeEvent; - type StateRoot = pallet_ethereum::IntermediateStateRoot; -} - -impl pallet_ethereum_transaction::Config for Runtime {} - -impl axelar_gateway_precompile::Config for Runtime { - type AdminOrigin = EnsureRootOr; - type RuntimeEvent = RuntimeEvent; - type WeightInfo = (); -} diff --git a/runtime/altair/src/lib.rs b/runtime/altair/src/lib.rs index 3b4c12979c..030437e4df 100644 --- a/runtime/altair/src/lib.rs +++ b/runtime/altair/src/lib.rs @@ -19,36 +19,46 @@ // Allow things like `1 * CFG` #![allow(clippy::identity_op)] -pub use cfg_primitives::{constants::*, types::*}; +use cfg_primitives::{ + constants::*, + liquidity_pools::GeneralCurrencyPrefix, + types::{ + AccountId, Address, AllOfCouncil, AuraId, Balance, BlockNumber, CollectionId, + CouncilCollective, EnsureRootOr, HalfOfCouncil, Hash, Hashing, Header, IBalance, Index, + ItemId, LoanId, OrderId, OutboundMessageNonce, PalletIndex, PoolEpochId, PoolFeeId, PoolId, + Signature, ThreeFourthOfCouncil, TrancheId, TrancheWeight, TwoThirdOfCouncil, + }, +}; use cfg_traits::{ investments::{OrderManager, TrancheCurrency as _}, Millis, Permissions as PermissionsT, PoolNAV, PoolUpdateGuard, PreConditions, Seconds, TryConvert, }; -pub use cfg_types::tokens::CurrencyId; use cfg_types::{ - consts::pools::*, + consts::pools::{MaxTrancheNameLengthBytes, MaxTrancheSymbolLengthBytes}, fee_keys::{Fee, FeeKey}, fixed_point::{Quantity, Rate, Ratio}, investments::InvestmentPortfolio, oracles::OracleKey, permissions::{PermissionRoles, PermissionScope, PermissionedCurrencyRole, PoolRole, Role}, time::TimeProvider, - tokens::{CustomMetadata, StakingCurrency, TrancheCurrency}, + tokens::{CurrencyId, CustomMetadata, StakingCurrency, TrancheCurrency}, }; use constants::currency::*; +use cumulus_primitives_core::{MultiAsset, MultiLocation}; use fp_rpc::TransactionStatus; use frame_support::{ construct_runtime, dispatch::DispatchClass, + parameter_types, traits::{ - AsEnsureOriginWithArg, ConstU32, EitherOfDiverse, EqualPrivilegeOnly, InstanceFilter, - LockIdentifier, OnFinalize, PalletInfoAccess, U128CurrencyToVote, UnixTime, - WithdrawReasons, + AsEnsureOriginWithArg, ConstU32, ConstU64, Contains, EitherOfDiverse, EqualPrivilegeOnly, + Get, InstanceFilter, LockIdentifier, OnFinalize, PalletInfoAccess, U128CurrencyToVote, + UnixTime, WithdrawReasons, }, weights::{ constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}, - ConstantMultiplier, + ConstantMultiplier, Weight, }, PalletId, RuntimeDebug, }; @@ -58,31 +68,42 @@ use frame_system::{ }; use orml_traits::currency::MutationHooks; use pallet_anchors::AnchorData; -pub use pallet_balances::Call as BalancesCall; use pallet_collective::{EnsureMember, EnsureProportionMoreThan}; -use pallet_ethereum::Call::transact; -use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, Runner}; +use pallet_ethereum::{Call::transact, PostLogContent}; +use pallet_evm::{ + Account as EVMAccount, EnsureAddressRoot, EnsureAddressTruncated, FeeCalculator, + GasWeightMapping, Runner, +}; use pallet_investments::OrderType; +use pallet_liquidity_pools::hooks::{ + CollectedForeignInvestmentHook, CollectedForeignRedemptionHook, DecreasedForeignInvestOrderHook, +}; use pallet_pool_system::{ pool_types::{PoolDetails, ScheduledUpdateDetails}, tranches::{TrancheIndex, TrancheLoc, TrancheSolution}, EpochSolution, }; use pallet_restricted_tokens::{FungibleInspectPassthrough, FungiblesInspectPassthrough}; -pub use pallet_timestamp::Call as TimestampCall; -pub use pallet_transaction_payment::{CurrencyAdapter, Multiplier, TargetedFeeAdjustment}; +use pallet_transaction_payment::CurrencyAdapter; use pallet_transaction_payment_rpc_runtime_api::{FeeDetails, RuntimeDispatchInfo}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use polkadot_runtime_common::{prod_or_fast, BlockHashCount, SlowAdjustingFeeUpdate}; use runtime_common::{ account_conversion::AccountConverter, asset_registry, + evm::{ + precompile::Precompiles, BaseFeeThreshold, FindAuthorTruncated, GAS_LIMIT_POV_SIZE_RATIO, + GAS_LIMIT_STORAGE_GROWTH_RATIO, WEIGHT_PER_GAS, + }, fees::{DealWithFees, FeeToTreasury, WeightToFee}, + gateway::GatewayAccountProvider, + liquidity_pools::LiquidityPoolsMessage, oracle::{ Feeder, OracleConverterBridge, OracleRatioProvider, OracleRatioProviderLocalAssetExtension, }, permissions::PoolAdminCheck, remarks::Remark, + transfer_filter::PreLpTransfer, xcm::AccountIdToMultiLocation, xcm_transactor, AllowanceDeposit, CurrencyED, HoldId, }; @@ -90,8 +111,6 @@ use scale_info::TypeInfo; use sp_api::impl_runtime_apis; use sp_core::{OpaqueMetadata, H160, H256, U256}; use sp_inherents::{CheckInherentsResult, InherentData}; -#[cfg(any(feature = "std", test))] -pub use sp_runtime::BuildStorage; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{ @@ -102,21 +121,17 @@ use sp_runtime::{ ApplyExtrinsicResult, DispatchError, DispatchResult, FixedI128, Perbill, Permill, Perquintill, }; use sp_std::{marker::PhantomData, prelude::*}; -#[cfg(any(feature = "std", test))] -use sp_version::NativeVersion; use sp_version::RuntimeVersion; use static_assertions::const_assert; use xcm_executor::XcmExecutor; +use crate::xcm::*; + pub mod constants; -pub mod evm; -pub mod liquidity_pools; mod migrations; mod weights; pub mod xcm; -pub use crate::xcm::*; - // Make the WASM binary available. #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); @@ -146,8 +161,8 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { /// Native version. #[cfg(any(feature = "std", test))] -pub fn native_version() -> NativeVersion { - NativeVersion { +pub fn native_version() -> sp_version::NativeVersion { + sp_version::NativeVersion { runtime_version: VERSION, can_author_with: Default::default(), } @@ -1722,6 +1737,70 @@ impl pallet_swaps::Config for Runtime { type SwapId = pallet_foreign_investments::SwapId; } +impl pallet_foreign_investments::Config for Runtime { + type CollectedForeignInvestmentHook = CollectedForeignInvestmentHook; + type CollectedForeignRedemptionHook = CollectedForeignRedemptionHook; + type CurrencyId = CurrencyId; + type DecreasedForeignInvestOrderHook = DecreasedForeignInvestOrderHook; + type ForeignBalance = Balance; + type Investment = Investments; + type InvestmentId = TrancheCurrency; + type PoolBalance = Balance; + type PoolInspect = PoolSystem; + type SwapBalance = Balance; + type Swaps = Swaps; + type TrancheBalance = Balance; +} + +parameter_types! { + pub LiquidityPoolsPalletIndex: PalletIndex = ::index() as u8; +} + +impl pallet_liquidity_pools::Config for Runtime { + type AdminOrigin = EnsureRoot; + type AssetRegistry = OrmlAssetRegistry; + type Balance = Balance; + type BalanceRatio = Ratio; + type CurrencyId = CurrencyId; + type DomainAccountToAccountId = AccountConverter; + type DomainAddressToAccountId = AccountConverter; + type ForeignInvestment = ForeignInvestments; + type GeneralCurrencyPrefix = GeneralCurrencyPrefix; + type OutboundQueue = LiquidityPoolsGateway; + type Permission = Permissions; + type PoolId = PoolId; + type PoolInspect = PoolSystem; + type PreTransferFilter = PreLpTransfer; + type RuntimeEvent = RuntimeEvent; + type Time = Timestamp; + type Tokens = Tokens; + type TrancheCurrency = TrancheCurrency; + type TrancheId = TrancheId; + type TrancheTokenPrice = PoolSystem; + type TreasuryAccount = TreasuryAccount; + type WeightInfo = (); +} + +parameter_types! { + pub const MaxIncomingMessageSize: u32 = 1024; + pub Sender: AccountId = GatewayAccountProvider::::get_gateway_account(); +} + +impl pallet_liquidity_pools_gateway::Config for Runtime { + type AdminOrigin = EnsureRoot; + type InboundQueue = LiquidityPools; + type LocalEVMOrigin = pallet_liquidity_pools_gateway::EnsureLocal; + type MaxIncomingMessageSize = MaxIncomingMessageSize; + type Message = LiquidityPoolsMessage; + type OriginRecovery = LiquidityPoolsAxelarGateway; + type OutboundMessageNonce = OutboundMessageNonce; + type Router = liquidity_pools_gateway_routers::DomainRouter; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; + type Sender = Sender; + type WeightInfo = (); +} + parameter_types! { pub const TokenMuxPalletId: PalletId = cfg_types::ids::TOKEN_MUX_PALLET_ID; } @@ -1765,6 +1844,109 @@ impl pallet_transfer_allowlist::Config for Runtime { type WeightInfo = weights::pallet_transfer_allowlist::WeightInfo; } +pub type AltairPrecompiles = Precompiles; + +parameter_types! { + pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS); + pub PrecompilesValue: AltairPrecompiles = Precompiles::<_, _>::new(); + pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0); + pub const TokenSymbol: &'static str = "AIR"; +} + +impl pallet_evm::Config for Runtime { + type AddressMapping = AccountConverter; + type BlockGasLimit = BlockGasLimit; + type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping; + type CallOrigin = EnsureAddressRoot; + type ChainId = EVMChainId; + type Currency = Balances; + type FeeCalculator = BaseFee; + type FindAuthor = FindAuthorTruncated; + type GasLimitPovSizeRatio = ConstU64; + type GasLimitStorageGrowthRatio = ConstU64; + type GasWeightMapping = pallet_evm::FixedGasWeightMapping; + type OnChargeTransaction = (); + type OnCreate = (); + type PrecompilesType = AltairPrecompiles; + type PrecompilesValue = PrecompilesValue; + type Runner = pallet_evm::runner::stack::Runner; + type RuntimeEvent = RuntimeEvent; + type Timestamp = Timestamp; + type WeightInfo = (); + type WeightPerGas = WeightPerGas; + type WithdrawOrigin = EnsureAddressTruncated; +} + +impl pallet_evm_chain_id::Config for Runtime {} + +parameter_types! { + pub DefaultBaseFeePerGas: U256 = U256::from(1_000_000_000); + pub DefaultElasticity: Permill = Permill::from_parts(125_000); +} + +impl pallet_base_fee::Config for Runtime { + type DefaultBaseFeePerGas = DefaultBaseFeePerGas; + type DefaultElasticity = DefaultElasticity; + type RuntimeEvent = RuntimeEvent; + type Threshold = BaseFeeThreshold; +} + +parameter_types! { + pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes; + pub const ExtraDataLength: u32 = 30; +} + +impl pallet_ethereum::Config for Runtime { + type ExtraDataLength = ExtraDataLength; + type PostLogContent = PostBlockAndTxnHashes; + type RuntimeEvent = RuntimeEvent; + type StateRoot = pallet_ethereum::IntermediateStateRoot; +} + +impl pallet_ethereum_transaction::Config for Runtime {} + +impl axelar_gateway_precompile::Config for Runtime { + type AdminOrigin = EnsureRootOr; + type RuntimeEvent = RuntimeEvent; + type WeightInfo = (); +} + +/// Block type as expected by this runtime. +pub type Block = generic::Block; +/// A Block signed with a Justification +pub type SignedBlock = generic::SignedBlock; +/// BlockId type as expected by this runtime. +pub type BlockId = generic::BlockId; +/// The SignedExtension to the basic transaction logic. +pub type SignedExtra = ( + frame_system::CheckNonZeroSender, + frame_system::CheckSpecVersion, + frame_system::CheckTxVersion, + frame_system::CheckGenesis, + frame_system::CheckEra, + frame_system::CheckNonce, + frame_system::CheckWeight, + pallet_transaction_payment::ChargeTransactionPayment, + runtime_common::transfer_filter::PreBalanceTransferExtension, +); + +/// Unchecked extrinsic type as expected by this runtime. +pub type UncheckedExtrinsic = + fp_self_contained::UncheckedExtrinsic; +/// Extrinsic type that has already been checked. +pub type CheckedExtrinsic = + fp_self_contained::CheckedExtrinsic; + +/// Executive: handles dispatch to the various modules. +pub type Executive = frame_executive::Executive< + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, + migrations::UpgradeAltair1034, +>; + // Frame Order in this block dictates the index of each one in the metadata // Any addition should be done at the bottom // Any deletion affects the following frames during runtime upgrades @@ -1866,42 +2048,6 @@ construct_runtime!( } ); -/// Block type as expected by this runtime. -pub type Block = generic::Block; -/// A Block signed with a Justification -pub type SignedBlock = generic::SignedBlock; -/// BlockId type as expected by this runtime. -pub type BlockId = generic::BlockId; -/// The SignedExtension to the basic transaction logic. -pub type SignedExtra = ( - frame_system::CheckNonZeroSender, - frame_system::CheckSpecVersion, - frame_system::CheckTxVersion, - frame_system::CheckGenesis, - frame_system::CheckEra, - frame_system::CheckNonce, - frame_system::CheckWeight, - pallet_transaction_payment::ChargeTransactionPayment, - runtime_common::transfer_filter::PreBalanceTransferExtension, -); - -/// Unchecked extrinsic type as expected by this runtime. -pub type UncheckedExtrinsic = - fp_self_contained::UncheckedExtrinsic; -/// Extrinsic type that has already been checked. -pub type CheckedExtrinsic = - fp_self_contained::CheckedExtrinsic; - -/// Executive: handles dispatch to the various modules. -pub type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext, - Runtime, - AllPalletsWithSystem, - migrations::UpgradeAltair1034, ->; - impl fp_self_contained::SelfContainedCall for RuntimeCall { type SignedInfo = H160; diff --git a/runtime/altair/src/xcm.rs b/runtime/altair/src/xcm.rs index 746475aad0..2ef2c9accd 100644 --- a/runtime/altair/src/xcm.rs +++ b/runtime/altair/src/xcm.rs @@ -14,44 +14,38 @@ use cfg_primitives::{ parachains, types::{EnsureRootOr, HalfOfCouncil}, }; -pub use cfg_types::tokens::CurrencyId; -pub use cumulus_primitives_core::ParaId; -pub use frame_support::{ - parameter_types, - traits::{Contains, Everything, Get, Nothing}, - weights::Weight, -}; +use cfg_types::tokens::CurrencyId; use frame_support::{ - sp_std::marker::PhantomData, - traits::{fungibles, fungibles::Mutate}, + parameter_types, + traits::{Everything, Get, Nothing}, }; use frame_system::EnsureRoot; use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key}; use orml_xcm_support::MultiNativeAsset; use pallet_xcm::XcmPassthrough; -use polkadot_parachain::primitives::Sibling; use runtime_common::{ transfer_filter::PreXcmTransfer, - xcm::{general_key, AccountIdToMultiLocation, FixedConversionRateProvider}, + xcm::{ + general_key, AccountIdToMultiLocation, Barrier, FixedConversionRateProvider, ToTreasury, + }, xcm_fees::native_per_second, }; use sp_core::ConstU32; -use sp_runtime::traits::{Convert, Zero}; -pub use xcm::v3::{MultiAsset, MultiLocation}; -use xcm::{prelude::*, v3::Weight as XcmWeight}; +use xcm::{ + prelude::*, + v3::{MultiLocation, Weight as XcmWeight}, +}; use xcm_builder::{ - AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, - AllowTopLevelPaidExecutionFrom, ConvertedConcreteId, EnsureXcmOrigin, FixedRateOfFungible, - FixedWeightBounds, FungiblesAdapter, NoChecking, ParentIsPreset, RelayChainAsNative, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, TakeRevenue, TakeWeightCredit, + ConvertedConcreteId, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, FungiblesAdapter, + NoChecking, RelayChainAsNative, SiblingParachainAsNative, SignedAccountId32AsNative, + SignedToAccountId32, SovereignSignedViaLocation, }; use xcm_executor::{traits::JustTry, XcmExecutor}; use super::{ AccountId, Balance, OrmlAssetRegistry, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, - RuntimeCall, RuntimeEvent, RuntimeOrigin, Tokens, TreasuryAccount, XcmpQueue, + RuntimeCall, RuntimeEvent, RuntimeOrigin, Tokens, XcmpQueue, }; /// A call filter for the XCM Transact instruction. This is a temporary @@ -80,7 +74,7 @@ impl frame_support::traits::Contains for SafeCallFilter { | RuntimeCall::Proxy(..) | RuntimeCall::LiquidityPoolsGateway( pallet_liquidity_pools_gateway::Call::process_msg { .. } - ) // TODO: Enable later: | RuntimeCall::OrderBook(..) + ) | RuntimeCall::OrderBook(..) ) } } @@ -97,7 +91,7 @@ impl xcm_executor::Config for XcmConfig { // How to withdraw and deposit an asset. type AssetTransactor = FungiblesTransactor; type AssetTrap = PolkadotXcm; - type Barrier = Barrier; + type Barrier = Barrier; type CallDispatcher = RuntimeCall; type FeeManager = (); type IsReserve = MultiNativeAsset; @@ -122,10 +116,10 @@ impl xcm_executor::Config for XcmConfig { /// else the xcm executor won't know how to charge fees for a transfer of said /// token. pub type Trader = ( - FixedRateOfFungible, + FixedRateOfFungible>, AssetRegistryTrader< FixedRateAssetRegistryTrader>, - ToTreasury, + ToTreasury, >, ); @@ -141,36 +135,6 @@ parameter_types! { ); } -pub struct ToTreasury; -impl TakeRevenue for ToTreasury { - fn take_revenue(revenue: MultiAsset) { - use xcm_executor::traits::Convert; - - if let MultiAsset { - id: Concrete(location), - fun: Fungible(amount), - } = revenue - { - if let Ok(currency_id) = - >::convert(location) - { - let _ = Tokens::mint_into(currency_id, &TreasuryAccount::get(), amount); - } - } - } -} - -/// Barrier is a filter-like option controlling what messages are allows to be -/// executed. -pub type Barrier = ( - TakeWeightCredit, - AllowTopLevelPaidExecutionFrom, - // Expected responses are OK. - AllowKnownQueryResponses, - // Subscriptions for version tracking are OK. - AllowSubscriptionsFrom, -); - /// Means for transacting the fungibles assets of this parachain. pub type FungiblesTransactor = FungiblesAdapter< // Use this fungibles implementation @@ -194,74 +158,6 @@ parameter_types! { pub const MaxInstructions: u32 = 100; } -/// Allow checking in assets that have issuance > 0. -pub struct NonZeroIssuance(PhantomData<(AccountId, Assets)>); -impl Contains<>::AssetId> - for NonZeroIssuance -where - Assets: fungibles::Inspect, -{ - fn contains(id: &>::AssetId) -> bool { - !Assets::total_issuance(id.clone()).is_zero() - } -} - -/// CurrencyIdConvert -/// This type implements conversions from our `CurrencyId` type into -/// `MultiLocation` and vice-versa. A currency locally is identified with a -/// `CurrencyId` variant but in the network it is identified in the form of a -/// `MultiLocation`. -pub struct CurrencyIdConvert; - -/// Convert our `CurrencyId` type into its `MultiLocation` representation. -/// We use the `OrmlAssetRegistry` to lookup the associated `MultiLocation` for -/// any given `CurrencyId`, while blocking tokens that are not Xcm-transferable. -impl Convert> for CurrencyIdConvert { - fn convert(id: CurrencyId) -> Option { - OrmlAssetRegistry::metadata(id) - .filter(|m| m.additional.transferability.includes_xcm()) - .and_then(|m| m.location) - .and_then(|l| l.try_into().ok()) - } -} - -/// Convert an incoming `MultiLocation` into a `CurrencyId` through a -/// reverse-lookup using the OrmlAssetRegistry. In the registry, we register CFG -/// using its absolute, non-anchored MultliLocation so we need to unanchor the -/// input location for Centrifuge-native assets for that to work. -impl xcm_executor::traits::Convert for CurrencyIdConvert { - fn convert(location: MultiLocation) -> Result { - let unanchored_location = match location { - MultiLocation { - parents: 0, - interior, - } => MultiLocation { - parents: 1, - interior: interior - .pushed_front_with(Parachain(u32::from(ParachainInfo::get()))) - .map_err(|_| location)?, - }, - x => x, - }; - - OrmlAssetRegistry::location_to_asset_id(unanchored_location).ok_or(location) - } -} - -impl Convert> for CurrencyIdConvert { - fn convert(asset: MultiAsset) -> Option { - if let MultiAsset { - id: Concrete(location), - .. - } = asset - { - >::convert(location).ok() - } else { - None - } - } -} - #[cfg(feature = "runtime-benchmarks")] parameter_types! { pub ReachableDest: Option = Some(Parent.into()); @@ -305,20 +201,8 @@ parameter_types! { pub CheckingAccount: AccountId = PolkadotXcm::check_account(); } -/// Type for specifying how a `MultiLocation` can be converted into an -/// `AccountId`. This is used when determining ownership of accounts for asset -/// transacting and when attempting to use XCM `Transact` in order to determine -/// the dispatch Origin. -pub type LocationToAccountId = ( - // The parent (Relay-chain) origin converts to the default `AccountId`. - ParentIsPreset, - // Sibling parachain origins convert to AccountId via the `ParaId::into`. - SiblingParachainConvertsVia, - // Straight up local `AccountId32` origins just alias directly to `AccountId`. - AccountId32Aliases, - // Generate remote accounts according to polkadot standards - cfg_primitives::xcm::HashedDescriptionDescribeFamilyAllTerminal, -); +pub type CurrencyIdConvert = runtime_common::xcm::CurrencyIdConvert; +pub type LocationToAccountId = runtime_common::xcm::LocationToAccountId; /// No local origins on this chain are allowed to dispatch XCM sends/executions. pub type LocalOriginToLocation = SignedToAccountId32; diff --git a/runtime/centrifuge/src/evm.rs b/runtime/centrifuge/src/evm.rs deleted file mode 100644 index 0856ef3956..0000000000 --- a/runtime/centrifuge/src/evm.rs +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2023 Centrifuge Foundation (centrifuge.io). -// -// This file is part of the Centrifuge chain project. -// Centrifuge is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version (see http://www.gnu.org/licenses). -// Centrifuge is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -use cfg_primitives::{TwoThirdOfCouncil, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO}; -use frame_support::{parameter_types, traits::FindAuthor, weights::Weight, ConsensusEngineId}; -use pallet_ethereum::PostLogContent; -use pallet_evm::{EnsureAddressRoot, EnsureAddressTruncated}; -use runtime_common::{ - account_conversion::AccountConverter, - evm::{precompile::Precompiles, BaseFeeThreshold, WEIGHT_PER_GAS}, - origin::EnsureAccountOrRootOr, -}; -use sp_core::{crypto::ByteArray, H160, U256}; -use sp_runtime::Permill; -use sp_std::marker::PhantomData; - -use crate::{Aura, LocationToAccountId}; - -// To create valid Ethereum-compatible blocks, we need a 20-byte -// "author" for the block. Since that author is purely informational, -// we do a simple truncation of the 32-byte Substrate author -pub struct FindAuthorTruncated(PhantomData); -impl> FindAuthor for FindAuthorTruncated { - fn find_author<'a, I>(digests: I) -> Option - where - I: 'a + IntoIterator, - { - if let Some(author_index) = F::find_author(digests) { - let authority_id = Aura::authorities()[author_index as usize].clone(); - return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24])); - } - None - } -} - -pub type CentrifugePrecompiles = Precompiles; - -parameter_types! { - pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS); - pub PrecompilesValue: CentrifugePrecompiles = Precompiles::<_, _>::new(); - pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0); - // - // pub GasLimitPovSizeRatio: u64 = { - // let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64(); - // block_gas_limit.saturating_div(MAX_POV_SIZE) - // }; - // - // NOTE: The above results in a value of 2. AS this factor is a divisor generating a - // a storage limit we are conservative and use the value that moonbeam is using - // in their staging environment - // (https://github.com/moonbeam-foundation/moonbeam/blob/973015c376e8741073013094be88e7c58c716a70/runtime/moonriver/src/lib.rs#L408) - pub const GasLimitPovSizeRatio: u64 = 4; - - // - // pub const GasLimitStorageGrowthRatio: u64 = - // BlockGasLimit::get().min(u64::MAX.into()).low_u64().saturating_div(BLOCK_STORAGE_LIMIT); - // - // NOTE: The above results in a value of 366 which is the same value that moonbeam is using - // in their staging environment. As we can not constantly assert this value we hardcode - // it for now. - pub const GasLimitStorageGrowthRatio: u64 = 366; - pub const TokenSymbol: &'static str = "CFG"; -} - -impl pallet_evm::Config for crate::Runtime { - type AddressMapping = AccountConverter; - type BlockGasLimit = BlockGasLimit; - type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping; - type CallOrigin = EnsureAddressRoot; - type ChainId = crate::EVMChainId; - type Currency = crate::Balances; - type FeeCalculator = crate::BaseFee; - type FindAuthor = FindAuthorTruncated; - type GasLimitPovSizeRatio = GasLimitPovSizeRatio; - type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio; - type GasWeightMapping = pallet_evm::FixedGasWeightMapping; - type OnChargeTransaction = (); - type OnCreate = (); - type PrecompilesType = CentrifugePrecompiles; - type PrecompilesValue = PrecompilesValue; - type Runner = pallet_evm::runner::stack::Runner; - type RuntimeEvent = crate::RuntimeEvent; - type Timestamp = crate::Timestamp; - type WeightInfo = (); - type WeightPerGas = WeightPerGas; - type WithdrawOrigin = EnsureAddressTruncated; -} - -impl pallet_evm_chain_id::Config for crate::Runtime {} - -parameter_types! { - pub DefaultBaseFeePerGas: U256 = U256::from(1_000_000_000); - pub DefaultElasticity: Permill = Permill::from_parts(125_000); -} - -impl pallet_base_fee::Config for crate::Runtime { - type DefaultBaseFeePerGas = DefaultBaseFeePerGas; - type DefaultElasticity = DefaultElasticity; - type RuntimeEvent = crate::RuntimeEvent; - type Threshold = BaseFeeThreshold; -} - -parameter_types! { - pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes; - pub const ExtraDataLength: u32 = 30; -} - -impl pallet_ethereum::Config for crate::Runtime { - type ExtraDataLength = ExtraDataLength; - type PostLogContent = PostBlockAndTxnHashes; - type RuntimeEvent = crate::RuntimeEvent; - type StateRoot = pallet_ethereum::IntermediateStateRoot; -} - -impl pallet_ethereum_transaction::Config for crate::Runtime {} - -impl axelar_gateway_precompile::Config for crate::Runtime { - type AdminOrigin = - EnsureAccountOrRootOr; - type RuntimeEvent = crate::RuntimeEvent; - type WeightInfo = (); -} diff --git a/runtime/centrifuge/src/lib.rs b/runtime/centrifuge/src/lib.rs index 2868da767f..161cc3790b 100644 --- a/runtime/centrifuge/src/lib.rs +++ b/runtime/centrifuge/src/lib.rs @@ -19,7 +19,16 @@ // Allow things like `1 * CFG` #![allow(clippy::identity_op)] -pub use cfg_primitives::{constants::*, types::*}; +use cfg_primitives::{ + constants::*, + liquidity_pools::GeneralCurrencyPrefix, + types::{ + AccountId, Address, AllOfCouncil, AuraId, Balance, BlockNumber, CollectionId, + CouncilCollective, EnsureRootOr, HalfOfCouncil, Hash, Hashing, Header, IBalance, Index, + ItemId, LoanId, OrderId, OutboundMessageNonce, PalletIndex, PoolEpochId, PoolFeeId, PoolId, + Signature, ThreeFourthOfCouncil, TrancheId, TrancheWeight, TwoThirdOfCouncil, + }, +}; use cfg_traits::{ investments::{OrderManager, TrancheCurrency as _}, Millis, Permissions as PermissionsT, PoolNAV, PoolUpdateGuard, PreConditions, Seconds, @@ -35,22 +44,24 @@ use cfg_types::{ PermissionRoles, PermissionScope, PermissionedCurrencyRole, PoolRole, Role, UNION, }, time::TimeProvider, - tokens::{CustomMetadata, StakingCurrency, TrancheCurrency}, + tokens::{CurrencyId, CustomMetadata, StakingCurrency, TrancheCurrency}, }; +use cumulus_primitives_core::{MultiAsset, MultiLocation}; use fp_rpc::TransactionStatus; use frame_support::{ construct_runtime, dispatch::DispatchClass, pallet_prelude::{DispatchError, DispatchResult}, + parameter_types, sp_std::marker::PhantomData, traits::{ - AsEnsureOriginWithArg, ConstU32, EitherOfDiverse, EqualPrivilegeOnly, InstanceFilter, - LockIdentifier, OnFinalize, PalletInfoAccess, U128CurrencyToVote, UnixTime, - WithdrawReasons, + AsEnsureOriginWithArg, ConstU32, ConstU64, Contains, EitherOfDiverse, EqualPrivilegeOnly, + Get, InstanceFilter, LockIdentifier, OnFinalize, PalletInfoAccess, U128CurrencyToVote, + UnixTime, WithdrawReasons, }, weights::{ constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}, - ConstantMultiplier, + ConstantMultiplier, Weight, }, PalletId, RuntimeDebug, }; @@ -60,11 +71,16 @@ use frame_system::{ }; use orml_traits::currency::MutationHooks; use pallet_anchors::AnchorData; -pub use pallet_balances::Call as BalancesCall; use pallet_collective::{EnsureMember, EnsureProportionAtLeast, EnsureProportionMoreThan}; -use pallet_ethereum::{Call::transact, Transaction as EthTransaction}; -use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, Runner}; +use pallet_ethereum::{Call::transact, PostLogContent, Transaction as EthTransaction}; +use pallet_evm::{ + Account as EVMAccount, EnsureAddressRoot, EnsureAddressTruncated, FeeCalculator, + GasWeightMapping, Runner, +}; use pallet_investments::OrderType; +use pallet_liquidity_pools::hooks::{ + CollectedForeignInvestmentHook, CollectedForeignRedemptionHook, DecreasedForeignInvestOrderHook, +}; use pallet_pool_system::{ pool_types::{PoolDetails, ScheduledUpdateDetails}, tranches::{TrancheIndex, TrancheLoc, TrancheSolution}, @@ -73,19 +89,26 @@ use pallet_pool_system::{ use pallet_restricted_tokens::{ FungibleInspectPassthrough, FungiblesInspectPassthrough, TransferDetails, }; -pub use pallet_timestamp::Call as TimestampCall; -pub use pallet_transaction_payment::{CurrencyAdapter, Multiplier, TargetedFeeAdjustment}; +use pallet_transaction_payment::CurrencyAdapter; use pallet_transaction_payment_rpc_runtime_api::{FeeDetails, RuntimeDispatchInfo}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use polkadot_runtime_common::{prod_or_fast, BlockHashCount, SlowAdjustingFeeUpdate}; use runtime_common::{ account_conversion::AccountConverter, asset_registry, + evm::{ + precompile::Precompiles, BaseFeeThreshold, FindAuthorTruncated, GAS_LIMIT_POV_SIZE_RATIO, + GAS_LIMIT_STORAGE_GROWTH_RATIO, WEIGHT_PER_GAS, + }, fees::{DealWithFees, FeeToTreasury, WeightToFee}, + gateway::GatewayAccountProvider, + liquidity_pools::LiquidityPoolsMessage, oracle::{ Feeder, OracleConverterBridge, OracleRatioProvider, OracleRatioProviderLocalAssetExtension, }, + origin::EnsureAccountOrRootOr, permissions::PoolAdminCheck, + transfer_filter::PreLpTransfer, xcm::AccountIdToMultiLocation, xcm_transactor, AllowanceDeposit, CurrencyED, HoldId, }; @@ -93,8 +116,6 @@ use scale_info::TypeInfo; use sp_api::impl_runtime_apis; use sp_core::{OpaqueMetadata, H160, H256, U256}; use sp_inherents::{CheckInherentsResult, InherentData}; -#[cfg(any(feature = "std", test))] -pub use sp_runtime::BuildStorage; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{ @@ -105,22 +126,16 @@ use sp_runtime::{ ApplyExtrinsicResult, FixedI128, Perbill, Permill, Perquintill, }; use sp_std::prelude::*; -#[cfg(any(feature = "std", test))] -use sp_version::NativeVersion; use sp_version::RuntimeVersion; use static_assertions::const_assert; use xcm_executor::XcmExecutor; -pub mod evm; -pub mod liquidity_pools; +use crate::xcm::*; + mod migrations; mod weights; pub mod xcm; -/// common types for the runtime. -//nuno: explict imports from runtime_common -pub use crate::xcm::*; - // Make the WASM binary available. #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); @@ -150,8 +165,8 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { /// Native version. #[cfg(any(feature = "std", test))] -pub fn native_version() -> NativeVersion { - NativeVersion { +pub fn native_version() -> sp_version::NativeVersion { + sp_version::NativeVersion { runtime_version: VERSION, can_author_with: Default::default(), } @@ -1181,7 +1196,7 @@ impl pallet_xcm_transactor::Config for Runtime { type Balance = Balance; type BaseXcmWeight = BaseXcmWeight; type CurrencyId = CurrencyId; - type CurrencyIdToMultiLocation = xcm::CurrencyIdConvert; + type CurrencyIdToMultiLocation = CurrencyIdConvert; type DerivativeAddressRegistrationOrigin = EnsureRootOr; type HrmpEncoder = moonbeam_relay_encoder::polkadot::PolkadotEncoder; type HrmpManipulatorOrigin = EnsureRootOr; @@ -1818,6 +1833,87 @@ impl pallet_swaps::Config for Runtime { type SwapId = pallet_foreign_investments::SwapId; } +impl pallet_foreign_investments::Config for Runtime { + type CollectedForeignInvestmentHook = CollectedForeignInvestmentHook; + type CollectedForeignRedemptionHook = CollectedForeignRedemptionHook; + type CurrencyId = CurrencyId; + type DecreasedForeignInvestOrderHook = DecreasedForeignInvestOrderHook; + type ForeignBalance = Balance; + type Investment = Investments; + type InvestmentId = TrancheCurrency; + type PoolBalance = Balance; + type PoolInspect = PoolSystem; + type SwapBalance = Balance; + type Swaps = Swaps; + type TrancheBalance = Balance; +} + +parameter_types! { + // To be used if we want to register a particular asset in the chain spec, when running the chain locally. + pub LiquidityPoolsPalletIndex: PalletIndex = ::index() as u8; +} + +impl pallet_liquidity_pools::Config for Runtime { + type AdminOrigin = EnsureRootOr; + type AssetRegistry = OrmlAssetRegistry; + type Balance = Balance; + type BalanceRatio = Ratio; + type CurrencyId = CurrencyId; + type DomainAccountToAccountId = AccountConverter; + type DomainAddressToAccountId = AccountConverter; + type ForeignInvestment = ForeignInvestments; + type GeneralCurrencyPrefix = GeneralCurrencyPrefix; + type OutboundQueue = LiquidityPoolsGateway; + type Permission = Permissions; + type PoolId = PoolId; + type PoolInspect = PoolSystem; + type PreTransferFilter = PreLpTransfer; + type RuntimeEvent = RuntimeEvent; + type Time = Timestamp; + type Tokens = Tokens; + type TrancheCurrency = TrancheCurrency; + type TrancheId = TrancheId; + type TrancheTokenPrice = PoolSystem; + type TreasuryAccount = TreasuryAccount; + type WeightInfo = (); +} + +parameter_types! { + pub const MaxIncomingMessageSize: u32 = 1024; + pub Sender: AccountId = GatewayAccountProvider::::get_gateway_account(); +} + +parameter_types! { + // A temporary admin account for the LP logic + // This is a multi-sig controlled pure proxy on mainnet + // - address: "4eEqmbQMbFfNUg6bQnqi9zgUvQvSpNbUgstEM64Xq9FW58Xv" (on Centrifuge) + // (pub key 0x80339e91a87b9c082705fd1a6d39b3e00b46e445ad8c80c127f6a56941c6aa57) + // + // This account is besides Root and 2/3-council able to + // - add valid relayer contracts + // - rm valid relayer contracts + // - add valid LP instance contracts + // - rm valid LP instance contracts + // - add conversions from Axelar `sourceChain` strings to `DomainAddress` + // - set the Axelar gateway contract in the Axelar gateway precompile + pub LpAdminAccount: AccountId = AccountId::new(hex_literal::hex!("80339e91a87b9c082705fd1a6d39b3e00b46e445ad8c80c127f6a56941c6aa57")); +} + +impl pallet_liquidity_pools_gateway::Config for Runtime { + type AdminOrigin = EnsureAccountOrRootOr; + type InboundQueue = LiquidityPools; + type LocalEVMOrigin = pallet_liquidity_pools_gateway::EnsureLocal; + type MaxIncomingMessageSize = MaxIncomingMessageSize; + type Message = LiquidityPoolsMessage; + type OriginRecovery = LiquidityPoolsAxelarGateway; + type OutboundMessageNonce = OutboundMessageNonce; + type Router = liquidity_pools_gateway_routers::DomainRouter; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; + type Sender = Sender; + type WeightInfo = (); +} + parameter_types! { pub const TokenMuxPalletId: PalletId = cfg_types::ids::TOKEN_MUX_PALLET_ID; } @@ -1849,7 +1945,7 @@ impl pallet_transfer_allowlist::Config for Runtime { } parameter_types! { - pub const MaxRemarksPerCall: u32 = 10; + pub const MaxRemarksPerCall: u32 = 10; } impl pallet_remarks::Config for Runtime { @@ -1861,6 +1957,108 @@ impl pallet_remarks::Config for Runtime { type WeightInfo = weights::pallet_remarks::WeightInfo; } +pub type CentrifugePrecompiles = Precompiles; + +parameter_types! { + pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS); + pub PrecompilesValue: CentrifugePrecompiles = Precompiles::<_, _>::new(); + pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0); + pub const TokenSymbol: &'static str = "CFG"; +} + +impl pallet_evm::Config for Runtime { + type AddressMapping = AccountConverter; + type BlockGasLimit = BlockGasLimit; + type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping; + type CallOrigin = EnsureAddressRoot; + type ChainId = EVMChainId; + type Currency = Balances; + type FeeCalculator = BaseFee; + type FindAuthor = FindAuthorTruncated; + type GasLimitPovSizeRatio = ConstU64; + type GasLimitStorageGrowthRatio = ConstU64; + type GasWeightMapping = pallet_evm::FixedGasWeightMapping; + type OnChargeTransaction = (); + type OnCreate = (); + type PrecompilesType = CentrifugePrecompiles; + type PrecompilesValue = PrecompilesValue; + type Runner = pallet_evm::runner::stack::Runner; + type RuntimeEvent = RuntimeEvent; + type Timestamp = Timestamp; + type WeightInfo = (); + type WeightPerGas = WeightPerGas; + type WithdrawOrigin = EnsureAddressTruncated; +} + +impl pallet_evm_chain_id::Config for Runtime {} + +parameter_types! { + pub DefaultBaseFeePerGas: U256 = U256::from(1_000_000_000); + pub DefaultElasticity: Permill = Permill::from_parts(125_000); +} + +impl pallet_base_fee::Config for Runtime { + type DefaultBaseFeePerGas = DefaultBaseFeePerGas; + type DefaultElasticity = DefaultElasticity; + type RuntimeEvent = RuntimeEvent; + type Threshold = BaseFeeThreshold; +} + +parameter_types! { + pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes; + pub const ExtraDataLength: u32 = 30; +} + +impl pallet_ethereum::Config for Runtime { + type ExtraDataLength = ExtraDataLength; + type PostLogContent = PostBlockAndTxnHashes; + type RuntimeEvent = RuntimeEvent; + type StateRoot = pallet_ethereum::IntermediateStateRoot; +} + +impl pallet_ethereum_transaction::Config for Runtime {} + +impl axelar_gateway_precompile::Config for Runtime { + type AdminOrigin = EnsureAccountOrRootOr; + type RuntimeEvent = RuntimeEvent; + type WeightInfo = (); +} + +/// Block type as expected by this runtime. +pub type Block = generic::Block; +/// A Block signed with a Justification +pub type SignedBlock = generic::SignedBlock; +/// BlockId type as expected by this runtime. +pub type BlockId = generic::BlockId; +/// The SignedExtension to the basic transaction logic. +pub type SignedExtra = ( + frame_system::CheckNonZeroSender, + frame_system::CheckSpecVersion, + frame_system::CheckTxVersion, + frame_system::CheckGenesis, + frame_system::CheckEra, + frame_system::CheckNonce, + frame_system::CheckWeight, + pallet_transaction_payment::ChargeTransactionPayment, + runtime_common::transfer_filter::PreBalanceTransferExtension, +); +/// Unchecked extrinsic type as expected by this runtime. +pub type UncheckedExtrinsic = + fp_self_contained::UncheckedExtrinsic; +/// Extrinsic type that has already been checked. +pub type CheckedExtrinsic = + fp_self_contained::CheckedExtrinsic; + +/// Executive: handles dispatch to the various modules. +pub type Executive = frame_executive::Executive< + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, + migrations::UpgradeCentrifuge1025, +>; + // Frame Order in this block dictates the index of each one in the metadata // Any addition should be done at the bottom // Any deletion affects the following frames during runtime upgrades @@ -1967,41 +2165,6 @@ construct_runtime!( } ); -/// Block type as expected by this runtime. -pub type Block = generic::Block; -/// A Block signed with a Justification -pub type SignedBlock = generic::SignedBlock; -/// BlockId type as expected by this runtime. -pub type BlockId = generic::BlockId; -/// The SignedExtension to the basic transaction logic. -pub type SignedExtra = ( - frame_system::CheckNonZeroSender, - frame_system::CheckSpecVersion, - frame_system::CheckTxVersion, - frame_system::CheckGenesis, - frame_system::CheckEra, - frame_system::CheckNonce, - frame_system::CheckWeight, - pallet_transaction_payment::ChargeTransactionPayment, - runtime_common::transfer_filter::PreBalanceTransferExtension, -); -/// Unchecked extrinsic type as expected by this runtime. -pub type UncheckedExtrinsic = - fp_self_contained::UncheckedExtrinsic; -/// Extrinsic type that has already been checked. -pub type CheckedExtrinsic = - fp_self_contained::CheckedExtrinsic; - -/// Executive: handles dispatch to the various modules. -pub type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext, - Runtime, - AllPalletsWithSystem, - migrations::UpgradeCentrifuge1025, ->; - pub struct TransactionConverter; impl fp_rpc::ConvertTransaction for TransactionConverter { diff --git a/runtime/centrifuge/src/xcm.rs b/runtime/centrifuge/src/xcm.rs index c847fd1e56..4ecafe7b1a 100644 --- a/runtime/centrifuge/src/xcm.rs +++ b/runtime/centrifuge/src/xcm.rs @@ -15,45 +15,39 @@ use cfg_primitives::{ types::{EnsureRootOr, HalfOfCouncil}, }; use cfg_traits::TryConvert; -pub use cfg_types::tokens::CurrencyId; -use cfg_types::EVMChainId; -pub use cumulus_primitives_core::ParaId; -pub use frame_support::{ - parameter_types, - traits::{Contains, Everything, Get, Nothing}, - weights::Weight, -}; +use cfg_types::{tokens::CurrencyId, EVMChainId}; use frame_support::{ - sp_std::marker::PhantomData, - traits::{fungibles, fungibles::Mutate}, + parameter_types, + traits::{Everything, Get, Nothing}, }; use frame_system::EnsureRoot; use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key}; use orml_xcm_support::MultiNativeAsset; use pallet_xcm::XcmPassthrough; -use polkadot_parachain::primitives::Sibling; use runtime_common::{ transfer_filter::PreXcmTransfer, - xcm::{general_key, AccountIdToMultiLocation, FixedConversionRateProvider, LpInstanceRelayer}, + xcm::{ + general_key, AccountIdToMultiLocation, Barrier, FixedConversionRateProvider, + LpInstanceRelayer, ToTreasury, + }, xcm_fees::native_per_second, }; use sp_core::ConstU32; -use sp_runtime::traits::{Convert, Zero}; -pub use xcm::v3::{MultiAsset, MultiLocation}; -use xcm::{prelude::*, v3::Weight as XcmWeight}; +use xcm::{ + prelude::*, + v3::{MultiLocation, Weight as XcmWeight}, +}; use xcm_builder::{ - AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, - AllowTopLevelPaidExecutionFrom, ConvertedConcreteId, EnsureXcmOrigin, FixedRateOfFungible, - FixedWeightBounds, FungiblesAdapter, NoChecking, ParentIsPreset, RelayChainAsNative, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, TakeRevenue, TakeWeightCredit, + ConvertedConcreteId, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, FungiblesAdapter, + NoChecking, RelayChainAsNative, SiblingParachainAsNative, SignedAccountId32AsNative, + SignedToAccountId32, SovereignSignedViaLocation, }; use xcm_executor::{traits::JustTry, XcmExecutor}; use super::{ AccountId, Balance, OrmlAssetRegistry, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, - RuntimeCall, RuntimeEvent, RuntimeOrigin, Tokens, TreasuryAccount, XcmpQueue, + RuntimeCall, RuntimeEvent, RuntimeOrigin, Tokens, XcmpQueue, }; /// A call filter for the XCM Transact instruction. This is a temporary @@ -82,7 +76,7 @@ impl frame_support::traits::Contains for SafeCallFilter { | RuntimeCall::Proxy(..) | RuntimeCall::LiquidityPoolsGateway( pallet_liquidity_pools_gateway::Call::process_msg { .. } - ) // TODO: Enable later: | RuntimeCall::OrderBook(..) + ) | RuntimeCall::OrderBook(..) ) } } @@ -99,7 +93,7 @@ impl xcm_executor::Config for XcmConfig { // How to withdraw and deposit an asset. type AssetTransactor = FungiblesTransactor; type AssetTrap = PolkadotXcm; - type Barrier = Barrier; + type Barrier = Barrier; type CallDispatcher = RuntimeCall; type FeeManager = (); type IsReserve = MultiNativeAsset; @@ -124,10 +118,10 @@ impl xcm_executor::Config for XcmConfig { /// else the xcm executor won't know how to charge fees for a transfer of said /// token. pub type Trader = ( - FixedRateOfFungible, + FixedRateOfFungible>, AssetRegistryTrader< FixedRateAssetRegistryTrader>, - ToTreasury, + ToTreasury, >, ); @@ -143,36 +137,6 @@ parameter_types! { ); } -pub struct ToTreasury; -impl TakeRevenue for ToTreasury { - fn take_revenue(revenue: MultiAsset) { - use xcm_executor::traits::Convert; - - if let MultiAsset { - id: Concrete(location), - fun: Fungible(amount), - } = revenue - { - if let Ok(currency_id) = - >::convert(location) - { - let _ = Tokens::mint_into(currency_id, &TreasuryAccount::get(), amount); - } - } - } -} - -/// Barrier is a filter-like option controlling what messages are allows to be -/// executed. -pub type Barrier = ( - TakeWeightCredit, - AllowTopLevelPaidExecutionFrom, - // Expected responses are OK. - AllowKnownQueryResponses, - // Subscriptions for version tracking are OK. - AllowSubscriptionsFrom, -); - /// Means for transacting the fungibles assets of this parachain. pub type FungiblesTransactor = FungiblesAdapter< // Use this fungibles implementation @@ -196,74 +160,6 @@ parameter_types! { pub const MaxInstructions: u32 = 100; } -/// Allow checking in assets that have issuance > 0. -pub struct NonZeroIssuance(PhantomData<(AccountId, Assets)>); -impl Contains<>::AssetId> - for NonZeroIssuance -where - Assets: fungibles::Inspect, -{ - fn contains(id: &>::AssetId) -> bool { - !Assets::total_issuance(id.clone()).is_zero() - } -} - -/// CurrencyIdConvert -/// This type implements conversions from our `CurrencyId` type into -/// `MultiLocation` and vice-versa. A currency locally is identified with a -/// `CurrencyId` variant but in the network it is identified in the form of a -/// `MultiLocation`. -pub struct CurrencyIdConvert; - -/// Convert our `CurrencyId` type into its `MultiLocation` representation. -/// We use the `OrmlAssetRegistry` to lookup the associated `MultiLocation` for -/// any given `CurrencyId`, while blocking tokens that are not Xcm-transferable. -impl Convert> for CurrencyIdConvert { - fn convert(id: CurrencyId) -> Option { - OrmlAssetRegistry::metadata(id) - .filter(|m| m.additional.transferability.includes_xcm()) - .and_then(|m| m.location) - .and_then(|l| l.try_into().ok()) - } -} - -/// Convert an incoming `MultiLocation` into a `CurrencyId` through a -/// reverse-lookup using the OrmlAssetRegistry. In the registry, we register CFG -/// using its absolute, non-anchored MultliLocation so we need to unanchor the -/// input location for Centrifuge-native assets for that to work. -impl xcm_executor::traits::Convert for CurrencyIdConvert { - fn convert(location: MultiLocation) -> Result { - let unanchored_location = match location { - MultiLocation { - parents: 0, - interior, - } => MultiLocation { - parents: 1, - interior: interior - .pushed_front_with(Parachain(u32::from(ParachainInfo::get()))) - .map_err(|_| location)?, - }, - x => x, - }; - - OrmlAssetRegistry::location_to_asset_id(unanchored_location).ok_or(location) - } -} - -impl Convert> for CurrencyIdConvert { - fn convert(asset: MultiAsset) -> Option { - if let MultiAsset { - id: Concrete(location), - .. - } = asset - { - >::convert(location).ok() - } else { - None - } - } -} - #[cfg(feature = "runtime-benchmarks")] parameter_types! { pub ReachableDest: Option = Some(Parent.into()); @@ -307,20 +203,8 @@ parameter_types! { pub CheckingAccount: AccountId = PolkadotXcm::check_account(); } -/// Type for specifying how a `MultiLocation` can be converted into an -/// `AccountId`. This is used when determining ownership of accounts for asset -/// transacting and when attempting to use XCM `Transact` in order to determine -/// the dispatch Origin. -pub type LocationToAccountId = ( - // The parent (Relay-chain) origin converts to the default `AccountId`. - ParentIsPreset, - // Sibling parachain origins convert to AccountId via the `ParaId::into`. - SiblingParachainConvertsVia, - // Straight up local `AccountId32` origins just alias directly to `AccountId`. - AccountId32Aliases, - // Generate remote accounts according to polkadot standards - cfg_primitives::xcm::HashedDescriptionDescribeFamilyAllTerminal, -); +pub type CurrencyIdConvert = runtime_common::xcm::CurrencyIdConvert; +pub type LocationToAccountId = runtime_common::xcm::LocationToAccountId; /// No local origins on this chain are allowed to dispatch XCM sends/executions. pub type LocalOriginToLocation = SignedToAccountId32; diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml index 552185897f..6fdb117339 100644 --- a/runtime/common/Cargo.toml +++ b/runtime/common/Cargo.toml @@ -29,6 +29,7 @@ sp-std = { workspace = true } polkadot-parachain = { workspace = true } xcm = { workspace = true } +xcm-builder = { workspace = true } xcm-executor = { workspace = true } orml-traits = { workspace = true } @@ -171,6 +172,7 @@ std = [ "sp-std/std", "xcm-executor/std", "xcm-primitives/std", + "xcm-builder/std", "xcm/std", # Locals @@ -257,6 +259,7 @@ runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", # Optional enabled "xcm-executor/runtime-benchmarks", "xcm-primitives/runtime-benchmarks", + "xcm-builder/runtime-benchmarks", "polkadot-parachain/runtime-benchmarks", # Locals diff --git a/runtime/common/src/evm/mod.rs b/runtime/common/src/evm/mod.rs index 0e4c31c296..bf0c4044da 100644 --- a/runtime/common/src/evm/mod.rs +++ b/runtime/common/src/evm/mod.rs @@ -10,9 +10,12 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -use frame_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND; +use cfg_primitives::AuraId; +use frame_support::{traits::FindAuthor, weights::constants::WEIGHT_REF_TIME_PER_SECOND}; use pallet_ethereum::{Transaction, TransactionAction}; -use sp_runtime::Permill; +use sp_core::{crypto::ByteArray, H160}; +use sp_runtime::{ConsensusEngineId, Permill}; +use sp_std::marker::PhantomData; pub mod precompile; @@ -32,6 +35,26 @@ pub const GAS_PER_SECOND: u64 = 40_000_000; // gas. pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND; +// pub GasLimitPovSizeRatio: u64 = { +// let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64(); +// block_gas_limit.saturating_div(MAX_POV_SIZE) +// }; +// +// NOTE: The above results in a value of 2. AS this factor is a divisor +// generating a a storage limit we are conservative and use the value that +// moonbeam is using in their staging environment +// (https://github.com/moonbeam-foundation/moonbeam/blob/973015c376e8741073013094be88e7c58c716a70/runtime/moonriver/src/lib.rs#L408) +pub const GAS_LIMIT_POV_SIZE_RATIO: u64 = 4; + +// pub const GasLimitStorageGrowthRatio: u64 = +// BlockGasLimit::get().min(u64::MAX.into()).low_u64(). +// saturating_div(BLOCK_STORAGE_LIMIT); +// +// NOTE: The above results in a value of 366 which is the same value that +// moonbeam is using in their staging environment. As we can not +// constantly assert this value we hardcode it for now. +pub const GAS_LIMIT_STORAGE_GROWTH_RATIO: u64 = 366; + pub struct BaseFeeThreshold; // Set our ideal block fullness to 50%. Anything between 50%-100% will cause the @@ -66,3 +89,21 @@ impl GetTransactionAction for Transaction { } } } + +// To create valid Ethereum-compatible blocks, we need a 20-byte +// "author" for the block. Since that author is purely informational, +// we do a simple truncation of the 32-byte Substrate author +pub struct FindAuthorTruncated(PhantomData); +impl> FindAuthor for FindAuthorTruncated { + fn find_author<'a, I>(digests: I) -> Option + where + I: 'a + IntoIterator, + { + if let Some(author_index) = pallet_aura::Pallet::::find_author(digests) { + let authority_id = + pallet_aura::Pallet::::authorities()[author_index as usize].clone(); + return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24])); + } + None + } +} diff --git a/runtime/common/src/migrations/local_currency.rs b/runtime/common/src/migrations/local_currency.rs index 7985eb67bf..d3f3ee222f 100644 --- a/runtime/common/src/migrations/local_currency.rs +++ b/runtime/common/src/migrations/local_currency.rs @@ -389,7 +389,7 @@ pub mod migrate_pool_currency { pub mod add_bidirectional_trading_pair { use cfg_primitives::Balance; #[cfg(feature = "try-runtime")] - use cfg_traits::TokenSwaps; + use cfg_traits::swaps::TokenSwaps; use frame_support::dispatch::RawOrigin; #[cfg(feature = "try-runtime")] use sp_std::vec::Vec; diff --git a/runtime/common/src/xcm.rs b/runtime/common/src/xcm.rs index 21e4700252..9ad03259ae 100644 --- a/runtime/common/src/xcm.rs +++ b/runtime/common/src/xcm.rs @@ -10,19 +10,29 @@ // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -use cfg_primitives::types::Balance; +use cfg_primitives::types::{AccountId, Balance}; use cfg_traits::TryConvert; use cfg_types::{ domain_address::{Domain, DomainAddress}, tokens::{CrossChainTransferability, CurrencyId, CustomMetadata}, EVMChainId, ParaId, }; -use frame_support::sp_std::marker::PhantomData; -use sp_runtime::traits::Convert; +use frame_support::{ + sp_std::marker::PhantomData, + traits::{fungibles::Mutate, Everything}, +}; +use polkadot_parachain::primitives::Sibling; +use sp_runtime::traits::{AccountIdConversion, Convert}; use xcm::v3::{ + prelude::*, Junction::{AccountId32, AccountKey20, GeneralKey, Parachain}, Junctions::{X1, X2}, - MultiLocation, OriginKind, + MultiAsset, MultiLocation, OriginKind, +}; +use xcm_builder::{ + AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, ParentIsPreset, SiblingParachainConvertsVia, TakeRevenue, + TakeWeightCredit, }; use crate::xcm_fees::default_per_second; @@ -120,6 +130,130 @@ where } } +/// CurrencyIdConvert +/// This type implements conversions from our `CurrencyId` type into +/// `MultiLocation` and vice-versa. A currency locally is identified with a +/// `CurrencyId` variant but in the network it is identified in the form of a +/// `MultiLocation`. +pub struct CurrencyIdConvert(PhantomData); + +/// Convert our `CurrencyId` type into its `MultiLocation` representation. +/// We use the `AssetRegistry` to lookup the associated `MultiLocation` for +/// any given `CurrencyId`, while blocking tokens that are not Xcm-transferable. +impl Convert> for CurrencyIdConvert +where + T: orml_asset_registry::Config, +{ + fn convert(id: CurrencyId) -> Option { + orml_asset_registry::Pallet::::metadata(&id) + .filter(|m| m.additional.transferability.includes_xcm()) + .and_then(|m| m.location) + .and_then(|l| l.try_into().ok()) + } +} + +/// Convert an incoming `MultiLocation` into a `CurrencyId` through a +/// reverse-lookup using the AssetRegistry. In the registry, we register CFG +/// using its absolute, non-anchored MultliLocation so we need to unanchor the +/// input location for Centrifuge-native assets for that to work. +impl xcm_executor::traits::Convert for CurrencyIdConvert +where + T: orml_asset_registry::Config + + parachain_info::Config, +{ + fn convert(location: MultiLocation) -> Result { + let para_id = parachain_info::Pallet::::parachain_id(); + let unanchored_location = match location { + MultiLocation { + parents: 0, + interior, + } => MultiLocation { + parents: 1, + interior: interior + .pushed_front_with(Parachain(u32::from(para_id))) + .map_err(|_| location)?, + }, + x => x, + }; + + orml_asset_registry::Pallet::::location_to_asset_id(unanchored_location).ok_or(location) + } +} + +impl Convert> for CurrencyIdConvert +where + T: orml_asset_registry::Config + + parachain_info::Config + + pallet_restricted_tokens::Config, +{ + fn convert(asset: MultiAsset) -> Option { + if let MultiAsset { + id: Concrete(location), + .. + } = asset + { + >::convert(location).ok() + } else { + None + } + } +} + +pub struct ToTreasury(PhantomData); +impl TakeRevenue for ToTreasury +where + T: orml_asset_registry::Config + + parachain_info::Config + + pallet_restricted_tokens::Config, +{ + fn take_revenue(revenue: MultiAsset) { + use xcm_executor::traits::Convert; + + if let MultiAsset { + id: Concrete(location), + fun: Fungible(amount), + } = revenue + { + if let Ok(currency_id) = + as Convert>::convert(location) + { + let treasury_account = cfg_types::ids::TREASURY_PALLET_ID.into_account_truncating(); + let _ = pallet_restricted_tokens::Pallet::::mint_into( + currency_id, + &treasury_account, + amount, + ); + } + } + } +} + +/// Barrier is a filter-like option controlling what messages are allows to be +/// executed. +pub type Barrier = ( + TakeWeightCredit, + AllowTopLevelPaidExecutionFrom, + // Expected responses are OK. + AllowKnownQueryResponses, + // Subscriptions for version tracking are OK. + AllowSubscriptionsFrom, +); + +/// Type for specifying how a `MultiLocation` can be converted into an +/// `AccountId`. This is used when determining ownership of accounts for asset +/// transacting and when attempting to use XCM `Transact` in order to determine +/// the dispatch Origin. +pub type LocationToAccountId = ( + // The parent (Relay-chain) origin converts to the default `AccountId`. + ParentIsPreset, + // Sibling parachain origins convert to AccountId via the `ParaId::into`. + SiblingParachainConvertsVia, + // Straight up local `AccountId32` origins just alias directly to `AccountId`. + AccountId32Aliases, + // Generate remote accounts according to polkadot standards + cfg_primitives::xcm::HashedDescriptionDescribeFamilyAllTerminal, +); + #[cfg(test)] mod test { use cfg_mocks::{ diff --git a/runtime/development/src/evm.rs b/runtime/development/src/evm.rs deleted file mode 100644 index 1a42523b31..0000000000 --- a/runtime/development/src/evm.rs +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2023 Centrifuge Foundation (centrifuge.io). -// -// This file is part of the Centrifuge chain project. -// Centrifuge is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version (see http://www.gnu.org/licenses). -// Centrifuge is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -use cfg_primitives::{AccountId, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO}; -use frame_support::{parameter_types, traits::FindAuthor, weights::Weight, ConsensusEngineId}; -use frame_system::EnsureRoot; -use pallet_ethereum::PostLogContent; -use pallet_evm::EnsureAddressTruncated; -use runtime_common::{ - account_conversion::AccountConverter, - evm::{precompile::Precompiles, BaseFeeThreshold, WEIGHT_PER_GAS}, -}; -use sp_core::{crypto::ByteArray, H160, U256}; -use sp_runtime::Permill; -use sp_std::marker::PhantomData; - -use crate::{Aura, LocationToAccountId, Runtime, RuntimeEvent}; - -// To create valid Ethereum-compatible blocks, we need a 20-byte -// "author" for the block. Since that author is purely informational, -// we do a simple truncation of the 32-byte Substrate author -pub struct FindAuthorTruncated(PhantomData); -impl> FindAuthor for FindAuthorTruncated { - fn find_author<'a, I>(digests: I) -> Option - where - I: 'a + IntoIterator, - { - if let Some(author_index) = F::find_author(digests) { - let authority_id = Aura::authorities()[author_index as usize].clone(); - return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24])); - } - None - } -} - -pub type DevelopmentPrecompiles = Precompiles; - -parameter_types! { - pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS); - pub PrecompilesValue: DevelopmentPrecompiles = Precompiles::<_, _>::new(); - pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0); - // - // pub GasLimitPovSizeRatio: u64 = { - // let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64(); - // block_gas_limit.saturating_div(MAX_POV_SIZE) - // }; - // - // NOTE: The above results in a value of 2. AS this factor is a divisor generating a - // a storage limit we are conservative and use the value that moonbeam is using - // in their staging environment - // (https://github.com/moonbeam-foundation/moonbeam/blob/973015c376e8741073013094be88e7c58c716a70/runtime/moonriver/src/lib.rs#L408) - pub const GasLimitPovSizeRatio: u64 = 4; - - // - // pub const GasLimitStorageGrowthRatio: u64 = - // BlockGasLimit::get().min(u64::MAX.into()).low_u64().saturating_div(BLOCK_STORAGE_LIMIT); - // - // NOTE: The above results in a value of 366 which is the same value that moonbeam is using - // in their staging environment. As we can not constantly assert this value we hardcode - // it for now. - pub const GasLimitStorageGrowthRatio: u64 = 366; - pub const TokenSymbol: &'static str = "DCFG"; -} - -impl pallet_evm::Config for Runtime { - type AddressMapping = AccountConverter; - type BlockGasLimit = BlockGasLimit; - type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping; - type CallOrigin = EnsureAddressTruncated; - type ChainId = crate::EVMChainId; - type Currency = crate::Balances; - type FeeCalculator = crate::BaseFee; - type FindAuthor = FindAuthorTruncated; - type GasLimitPovSizeRatio = GasLimitPovSizeRatio; - type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio; - type GasWeightMapping = pallet_evm::FixedGasWeightMapping; - type OnChargeTransaction = (); - type OnCreate = (); - type PrecompilesType = DevelopmentPrecompiles; - type PrecompilesValue = PrecompilesValue; - type Runner = pallet_evm::runner::stack::Runner; - type RuntimeEvent = RuntimeEvent; - type Timestamp = crate::Timestamp; - type WeightInfo = (); - type WeightPerGas = WeightPerGas; - type WithdrawOrigin = EnsureAddressTruncated; -} - -impl pallet_evm_chain_id::Config for Runtime {} - -parameter_types! { - pub DefaultBaseFeePerGas: U256 = U256::from(1_000_000_000); - pub DefaultElasticity: Permill = Permill::from_parts(125_000); -} - -impl pallet_base_fee::Config for Runtime { - type DefaultBaseFeePerGas = DefaultBaseFeePerGas; - type DefaultElasticity = DefaultElasticity; - type RuntimeEvent = RuntimeEvent; - type Threshold = BaseFeeThreshold; -} - -parameter_types! { - pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes; - pub const ExtraDataLength: u32 = 30; -} - -impl pallet_ethereum::Config for Runtime { - type ExtraDataLength = ExtraDataLength; - type PostLogContent = PostBlockAndTxnHashes; - type RuntimeEvent = RuntimeEvent; - type StateRoot = pallet_ethereum::IntermediateStateRoot; -} - -impl pallet_ethereum_transaction::Config for Runtime {} - -impl axelar_gateway_precompile::Config for Runtime { - type AdminOrigin = EnsureRoot; - type RuntimeEvent = RuntimeEvent; - type WeightInfo = (); -} diff --git a/runtime/development/src/lib.rs b/runtime/development/src/lib.rs index a11a62b8d3..815aa46192 100644 --- a/runtime/development/src/lib.rs +++ b/runtime/development/src/lib.rs @@ -19,9 +19,15 @@ // Allow things like `1 * CFG` #![allow(clippy::identity_op)] -pub use cfg_primitives::{ +use cfg_primitives::{ constants::*, - types::{PoolId, *}, + liquidity_pools::GeneralCurrencyPrefix, + types::{ + AccountId, Address, AllOfCouncil, AuraId, Balance, BlockNumber, CollectionId, + CouncilCollective, EnsureRootOr, HalfOfCouncil, Hash, Hashing, Header, IBalance, Index, + ItemId, LoanId, OrderId, OutboundMessageNonce, PalletIndex, PoolEpochId, PoolFeeId, PoolId, + Signature, TrancheId, TrancheWeight, TwoThirdOfCouncil, + }, }; use cfg_traits::{ investments::{OrderManager, TrancheCurrency as _}, @@ -29,7 +35,7 @@ use cfg_traits::{ TryConvert as _, }; use cfg_types::{ - consts::pools::*, + consts::pools::{MaxTrancheNameLengthBytes, MaxTrancheSymbolLengthBytes}, fee_keys::{Fee, FeeKey}, fixed_point::{Quantity, Rate, Ratio}, investments::InvestmentPortfolio, @@ -40,24 +46,27 @@ use cfg_types::{ }, time::TimeProvider, tokens::{ - CustomMetadata, StakingCurrency::BlockRewards as BlockRewardsCurrency, TrancheCurrency, + CurrencyId, CustomMetadata, StakingCurrency::BlockRewards as BlockRewardsCurrency, + TrancheCurrency, }, }; use chainbridge::constants::DEFAULT_RELAYER_VOTE_THRESHOLD; +use cumulus_primitives_core::{MultiAsset, MultiLocation}; use fp_rpc::TransactionStatus; use frame_support::{ construct_runtime, dispatch::DispatchClass, pallet_prelude::{DispatchError, DispatchResult}, + parameter_types, sp_std::marker::PhantomData, traits::{ - AsEnsureOriginWithArg, ConstU32, EitherOfDiverse, EqualPrivilegeOnly, InstanceFilter, - LockIdentifier, OnFinalize, PalletInfoAccess, U128CurrencyToVote, UnixTime, - WithdrawReasons, + AsEnsureOriginWithArg, ConstU32, ConstU64, Contains, EitherOfDiverse, EqualPrivilegeOnly, + Get, InstanceFilter, LockIdentifier, OnFinalize, PalletInfoAccess, U128CurrencyToVote, + UnixTime, WithdrawReasons, }, weights::{ constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}, - ConstantMultiplier, + ConstantMultiplier, Weight, }, PalletId, RuntimeDebug, }; @@ -67,11 +76,15 @@ use frame_system::{ }; use orml_traits::currency::MutationHooks; use pallet_anchors::AnchorData; -pub use pallet_balances::Call as BalancesCall; use pallet_collective::EnsureMember; -use pallet_ethereum::{Call::transact, Transaction as EthTransaction}; -use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, Runner}; +use pallet_ethereum::{Call::transact, PostLogContent, Transaction as EthTransaction}; +use pallet_evm::{ + Account as EVMAccount, EnsureAddressTruncated, FeeCalculator, GasWeightMapping, Runner, +}; use pallet_investments::OrderType; +use pallet_liquidity_pools::hooks::{ + CollectedForeignInvestmentHook, CollectedForeignRedemptionHook, DecreasedForeignInvestOrderHook, +}; use pallet_pool_system::{ pool_types::{PoolDetails, ScheduledUpdateDetails}, tranches::{TrancheIndex, TrancheLoc, TrancheSolution}, @@ -80,8 +93,7 @@ use pallet_pool_system::{ use pallet_restricted_tokens::{ FungibleInspectPassthrough, FungiblesInspectPassthrough, TransferDetails, }; -pub use pallet_timestamp::Call as TimestampCall; -pub use pallet_transaction_payment::{CurrencyAdapter, Multiplier, TargetedFeeAdjustment}; +use pallet_transaction_payment::CurrencyAdapter; use pallet_transaction_payment_rpc_runtime_api::{FeeDetails, RuntimeDispatchInfo}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; @@ -89,11 +101,18 @@ use runtime_common::{ account_conversion::AccountConverter, asset_registry, changes::FastDelay, + evm::{ + precompile::Precompiles, BaseFeeThreshold, FindAuthorTruncated, GAS_LIMIT_POV_SIZE_RATIO, + GAS_LIMIT_STORAGE_GROWTH_RATIO, WEIGHT_PER_GAS, + }, fees::{DealWithFees, FeeToTreasury, WeightToFee}, + gateway::GatewayAccountProvider, + liquidity_pools::LiquidityPoolsMessage, oracle::{ Feeder, OracleConverterBridge, OracleRatioProvider, OracleRatioProviderLocalAssetExtension, }, permissions::PoolAdminCheck, + transfer_filter::PreLpTransfer, xcm::AccountIdToMultiLocation, xcm_transactor, AllowanceDeposit, CurrencyED, HoldId, }; @@ -101,8 +120,6 @@ use scale_info::TypeInfo; use sp_api::impl_runtime_apis; use sp_core::{OpaqueMetadata, H160, H256, U256}; use sp_inherents::{CheckInherentsResult, InherentData}; -#[cfg(any(feature = "std", test))] -pub use sp_runtime::BuildStorage; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{ @@ -113,16 +130,12 @@ use sp_runtime::{ ApplyExtrinsicResult, FixedI128, Perbill, Permill, Perquintill, }; use sp_std::prelude::*; -#[cfg(any(feature = "std", test))] -use sp_version::NativeVersion; use sp_version::RuntimeVersion; use static_assertions::const_assert; use xcm_executor::XcmExecutor; -pub use crate::xcm::*; +use crate::xcm::*; -pub mod evm; -pub mod liquidity_pools; mod migrations; mod weights; pub mod xcm; @@ -156,8 +169,8 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { /// Native version. #[cfg(any(feature = "std", test))] -pub fn native_version() -> NativeVersion { - NativeVersion { +pub fn native_version() -> sp_version::NativeVersion { + sp_version::NativeVersion { runtime_version: VERSION, can_author_with: Default::default(), } @@ -1263,7 +1276,7 @@ impl pallet_xcm_transactor::Config for Runtime { type Balance = Balance; type BaseXcmWeight = BaseXcmWeight; type CurrencyId = CurrencyId; - type CurrencyIdToMultiLocation = xcm::CurrencyIdConvert; + type CurrencyIdToMultiLocation = CurrencyIdConvert; type DerivativeAddressRegistrationOrigin = EnsureRoot; type HrmpEncoder = moonbeam_relay_encoder::westend::WestendEncoder; type HrmpManipulatorOrigin = EnsureRootOr; @@ -1795,6 +1808,71 @@ impl pallet_swaps::Config for Runtime { type SwapId = pallet_foreign_investments::SwapId; } +impl pallet_foreign_investments::Config for Runtime { + type CollectedForeignInvestmentHook = CollectedForeignInvestmentHook; + type CollectedForeignRedemptionHook = CollectedForeignRedemptionHook; + type CurrencyId = CurrencyId; + type DecreasedForeignInvestOrderHook = DecreasedForeignInvestOrderHook; + type ForeignBalance = Balance; + type Investment = Investments; + type InvestmentId = TrancheCurrency; + type PoolBalance = Balance; + type PoolInspect = PoolSystem; + type SwapBalance = Balance; + type Swaps = Swaps; + type TrancheBalance = Balance; +} + +parameter_types! { + // To be used if we want to register a particular asset in the chain spec, when running the chain locally. + pub LiquidityPoolsPalletIndex: PalletIndex = ::index() as u8; +} + +impl pallet_liquidity_pools::Config for Runtime { + type AdminOrigin = EnsureRoot; + type AssetRegistry = OrmlAssetRegistry; + type Balance = Balance; + type BalanceRatio = Ratio; + type CurrencyId = CurrencyId; + type DomainAccountToAccountId = AccountConverter; + type DomainAddressToAccountId = AccountConverter; + type ForeignInvestment = ForeignInvestments; + type GeneralCurrencyPrefix = GeneralCurrencyPrefix; + type OutboundQueue = LiquidityPoolsGateway; + type Permission = Permissions; + type PoolId = PoolId; + type PoolInspect = PoolSystem; + type PreTransferFilter = PreLpTransfer; + type RuntimeEvent = RuntimeEvent; + type Time = Timestamp; + type Tokens = Tokens; + type TrancheCurrency = TrancheCurrency; + type TrancheId = TrancheId; + type TrancheTokenPrice = PoolSystem; + type TreasuryAccount = TreasuryAccount; + type WeightInfo = (); +} + +parameter_types! { + pub const MaxIncomingMessageSize: u32 = 1024; + pub Sender: AccountId = GatewayAccountProvider::::get_gateway_account(); +} + +impl pallet_liquidity_pools_gateway::Config for Runtime { + type AdminOrigin = EnsureRootOr; + type InboundQueue = LiquidityPools; + type LocalEVMOrigin = pallet_liquidity_pools_gateway::EnsureLocal; + type MaxIncomingMessageSize = MaxIncomingMessageSize; + type Message = LiquidityPoolsMessage; + type OriginRecovery = LiquidityPoolsAxelarGateway; + type OutboundMessageNonce = OutboundMessageNonce; + type Router = liquidity_pools_gateway_routers::DomainRouter; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; + type Sender = Sender; + type WeightInfo = (); +} + parameter_types! { pub const TokenMuxPalletId: PalletId = cfg_types::ids::TOKEN_MUX_PALLET_ID; } @@ -1828,6 +1906,140 @@ impl pallet_remarks::Config for Runtime { type WeightInfo = weights::pallet_remarks::WeightInfo; } +/// The config for the Downward Message Passing Queue, i.e., how messages coming +/// from the relay-chain are handled. +impl cumulus_pallet_dmp_queue::Config for Runtime { + type ExecuteOverweightOrigin = EnsureRoot; + type RuntimeEvent = RuntimeEvent; + type XcmExecutor = XcmExecutor; +} + +parameter_types! { + /// The amount of weight an XCM operation takes. This is a safe overestimate. + pub UnitWeightCost: Weight = Weight::from_parts(200_000_000u64, 0); + /// Maximum number of instructions in a single XCM message. + pub MaxInstructions: u32 = 100; +} + +/// Xcm Weigher shared between multiple Xcm-related configs. +pub type XcmWeigher = xcm_builder::FixedWeightBounds; + +/// XCMP Queue is responsible to handle XCM messages coming directly from +/// sibling parachains. +impl cumulus_pallet_xcmp_queue::Config for Runtime { + type ChannelInfo = ParachainSystem; + type ControllerOrigin = EnsureRoot; + type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; + type ExecuteOverweightOrigin = EnsureRoot; + type PriceForSiblingDelivery = (); + type RuntimeEvent = RuntimeEvent; + type VersionWrapper = PolkadotXcm; + type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo; + type XcmExecutor = XcmExecutor; +} + +pub type DevelopmentPrecompiles = Precompiles; + +parameter_types! { + pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS); + pub PrecompilesValue: DevelopmentPrecompiles = Precompiles::<_, _>::new(); + pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0); + pub const TokenSymbol: &'static str = "DCFG"; +} + +impl pallet_evm::Config for Runtime { + type AddressMapping = AccountConverter; + type BlockGasLimit = BlockGasLimit; + type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping; + type CallOrigin = EnsureAddressTruncated; + type ChainId = EVMChainId; + type Currency = Balances; + type FeeCalculator = BaseFee; + type FindAuthor = FindAuthorTruncated; + type GasLimitPovSizeRatio = ConstU64; + type GasLimitStorageGrowthRatio = ConstU64; + type GasWeightMapping = pallet_evm::FixedGasWeightMapping; + type OnChargeTransaction = (); + type OnCreate = (); + type PrecompilesType = DevelopmentPrecompiles; + type PrecompilesValue = PrecompilesValue; + type Runner = pallet_evm::runner::stack::Runner; + type RuntimeEvent = RuntimeEvent; + type Timestamp = Timestamp; + type WeightInfo = (); + type WeightPerGas = WeightPerGas; + type WithdrawOrigin = EnsureAddressTruncated; +} + +impl pallet_evm_chain_id::Config for Runtime {} + +parameter_types! { + pub DefaultBaseFeePerGas: U256 = U256::from(1_000_000_000); + pub DefaultElasticity: Permill = Permill::from_parts(125_000); +} + +impl pallet_base_fee::Config for Runtime { + type DefaultBaseFeePerGas = DefaultBaseFeePerGas; + type DefaultElasticity = DefaultElasticity; + type RuntimeEvent = RuntimeEvent; + type Threshold = BaseFeeThreshold; +} + +parameter_types! { + pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes; + pub const ExtraDataLength: u32 = 30; +} + +impl pallet_ethereum::Config for Runtime { + type ExtraDataLength = ExtraDataLength; + type PostLogContent = PostBlockAndTxnHashes; + type RuntimeEvent = RuntimeEvent; + type StateRoot = pallet_ethereum::IntermediateStateRoot; +} + +impl pallet_ethereum_transaction::Config for Runtime {} + +impl axelar_gateway_precompile::Config for Runtime { + type AdminOrigin = EnsureRoot; + type RuntimeEvent = RuntimeEvent; + type WeightInfo = (); +} + +/// Block type as expected by this runtime. +pub type Block = generic::Block; +/// A Block signed with a Justification +pub type SignedBlock = generic::SignedBlock; +/// BlockId type as expected by this runtime. +pub type BlockId = generic::BlockId; +/// The SignedExtension to the basic transaction logic. +pub type SignedExtra = ( + frame_system::CheckNonZeroSender, + frame_system::CheckSpecVersion, + frame_system::CheckTxVersion, + frame_system::CheckGenesis, + frame_system::CheckEra, + frame_system::CheckNonce, + frame_system::CheckWeight, + pallet_transaction_payment::ChargeTransactionPayment, + runtime_common::transfer_filter::PreBalanceTransferExtension, +); +/// Unchecked extrinsic type as expected by this runtime. +pub type UncheckedExtrinsic = + fp_self_contained::UncheckedExtrinsic; +/// Extrinsic type that has already been checked. +pub type CheckedExtrinsic = + fp_self_contained::CheckedExtrinsic; + +/// Executive: handles dispatch to the various modules. +pub type Executive = frame_executive::Executive< + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, + crate::migrations::UpgradeDevelopment1041, +>; + // Frame Order in this block dictates the index of each one in the metadata // Any addition should be done at the bottom // Any deletion affects the following frames during runtime upgrades @@ -1935,73 +2147,6 @@ construct_runtime!( } ); -/// The config for the Downward Message Passing Queue, i.e., how messages coming -/// from the relay-chain are handled. -impl cumulus_pallet_dmp_queue::Config for Runtime { - type ExecuteOverweightOrigin = EnsureRoot; - type RuntimeEvent = RuntimeEvent; - type XcmExecutor = XcmExecutor; -} - -parameter_types! { - /// The amount of weight an XCM operation takes. This is a safe overestimate. - pub UnitWeightCost: Weight = Weight::from_parts(200_000_000u64, 0); - /// Maximum number of instructions in a single XCM message. - pub MaxInstructions: u32 = 100; -} - -/// Xcm Weigher shared between multiple Xcm-related configs. -pub type XcmWeigher = xcm_builder::FixedWeightBounds; - -/// XCMP Queue is responsible to handle XCM messages coming directly from -/// sibling parachains. -impl cumulus_pallet_xcmp_queue::Config for Runtime { - type ChannelInfo = ParachainSystem; - type ControllerOrigin = EnsureRoot; - type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; - type ExecuteOverweightOrigin = EnsureRoot; - type PriceForSiblingDelivery = (); - type RuntimeEvent = RuntimeEvent; - type VersionWrapper = PolkadotXcm; - type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo; - type XcmExecutor = XcmExecutor; -} - -/// Block type as expected by this runtime. -pub type Block = generic::Block; -/// A Block signed with a Justification -pub type SignedBlock = generic::SignedBlock; -/// BlockId type as expected by this runtime. -pub type BlockId = generic::BlockId; -/// The SignedExtension to the basic transaction logic. -pub type SignedExtra = ( - frame_system::CheckNonZeroSender, - frame_system::CheckSpecVersion, - frame_system::CheckTxVersion, - frame_system::CheckGenesis, - frame_system::CheckEra, - frame_system::CheckNonce, - frame_system::CheckWeight, - pallet_transaction_payment::ChargeTransactionPayment, - runtime_common::transfer_filter::PreBalanceTransferExtension, -); -/// Unchecked extrinsic type as expected by this runtime. -pub type UncheckedExtrinsic = - fp_self_contained::UncheckedExtrinsic; -/// Extrinsic type that has already been checked. -pub type CheckedExtrinsic = - fp_self_contained::CheckedExtrinsic; - -/// Executive: handles dispatch to the various modules. -pub type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext, - Runtime, - AllPalletsWithSystem, - crate::migrations::UpgradeDevelopment1041, ->; - impl fp_self_contained::SelfContainedCall for RuntimeCall { type SignedInfo = H160; diff --git a/runtime/development/src/xcm.rs b/runtime/development/src/xcm.rs index 42b0e0eff3..64045a922d 100644 --- a/runtime/development/src/xcm.rs +++ b/runtime/development/src/xcm.rs @@ -14,45 +14,36 @@ use cfg_primitives::{ types::{EnsureRootOr, HalfOfCouncil}, }; use cfg_traits::TryConvert; -pub use cfg_types::tokens::CurrencyId; -use cfg_types::EVMChainId; -pub use cumulus_primitives_core::ParaId; -pub use frame_support::{ - parameter_types, - traits::{Contains, Everything, Get, Nothing}, - weights::Weight, -}; +use cfg_types::{tokens::CurrencyId, EVMChainId}; use frame_support::{ - sp_std::marker::PhantomData, - traits::{fungibles, fungibles::Mutate}, + parameter_types, + traits::{Everything, Get, Nothing}, }; use frame_system::EnsureRoot; use orml_asset_registry::{AssetRegistryTrader, FixedRateAssetRegistryTrader}; use orml_traits::{location::AbsoluteReserveProvider, parameter_type_with_key}; use orml_xcm_support::MultiNativeAsset; use pallet_xcm::XcmPassthrough; -use polkadot_parachain::primitives::Sibling; use runtime_common::{ transfer_filter::PreXcmTransfer, - xcm::{general_key, AccountIdToMultiLocation, FixedConversionRateProvider, LpInstanceRelayer}, + xcm::{ + general_key, AccountIdToMultiLocation, Barrier, FixedConversionRateProvider, + LpInstanceRelayer, ToTreasury, + }, xcm_fees::native_per_second, }; use sp_core::ConstU32; -use sp_runtime::traits::{Convert, Zero}; -pub use xcm::v3::{MultiAsset, MultiLocation}; -use xcm::{latest::Weight as XcmWeight, prelude::*}; +use xcm::{latest::Weight as XcmWeight, prelude::*, v3::MultiLocation}; use xcm_builder::{ - AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, - AllowTopLevelPaidExecutionFrom, ConvertedConcreteId, EnsureXcmOrigin, FixedRateOfFungible, - FixedWeightBounds, FungiblesAdapter, NoChecking, ParentIsPreset, RelayChainAsNative, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, TakeRevenue, TakeWeightCredit, + ConvertedConcreteId, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, FungiblesAdapter, + NoChecking, RelayChainAsNative, SiblingParachainAsNative, SignedAccountId32AsNative, + SignedToAccountId32, SovereignSignedViaLocation, }; use xcm_executor::{traits::JustTry, XcmExecutor}; use super::{ AccountId, Balance, OrmlAssetRegistry, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, - RuntimeCall, RuntimeEvent, RuntimeOrigin, Tokens, TreasuryAccount, XcmpQueue, + RuntimeCall, RuntimeEvent, RuntimeOrigin, Tokens, XcmpQueue, }; /// A call filter for the XCM Transact instruction. This is a temporary @@ -98,7 +89,7 @@ impl xcm_executor::Config for XcmConfig { // How to withdraw and deposit an asset. type AssetTransactor = FungiblesTransactor; type AssetTrap = PolkadotXcm; - type Barrier = Barrier; + type Barrier = Barrier; type CallDispatcher = RuntimeCall; type FeeManager = (); type IsReserve = MultiNativeAsset; @@ -123,10 +114,10 @@ impl xcm_executor::Config for XcmConfig { /// else the xcm executor won't know how to charge fees for a transfer of said /// token. pub type Trader = ( - FixedRateOfFungible, + FixedRateOfFungible>, AssetRegistryTrader< FixedRateAssetRegistryTrader>, - ToTreasury, + ToTreasury, >, ); @@ -143,38 +134,6 @@ parameter_types! { } -pub struct ToTreasury; -impl TakeRevenue for ToTreasury { - fn take_revenue(revenue: MultiAsset) { - use xcm_executor::traits::Convert; - - if let MultiAsset { - id: Concrete(location), - fun: Fungible(amount), - } = revenue - { - if let Ok(currency_id) = - >::convert(location) - { - let _ = Tokens::mint_into(currency_id, &TreasuryAccount::get(), amount); - } - } - } -} - -/// Barrier is a filter-like option controlling what messages are allows to be -/// executed. -pub type Barrier = ( - TakeWeightCredit, - // todo(nuno): revisit this - // xcm_primitives::AllowTopLevelPaidExecutionDescendOriginFirst, - AllowTopLevelPaidExecutionFrom, - // Expected responses are OK. - AllowKnownQueryResponses, - // Subscriptions for version tracking are OK. - AllowSubscriptionsFrom, -); - /// Means for transacting the fungibles assets of this parachain. pub type FungiblesTransactor = FungiblesAdapter< // Use this fungibles implementation @@ -198,74 +157,6 @@ parameter_types! { pub const MaxInstructions: u32 = 100; } -/// Allow checking in assets that have issuance > 0. -pub struct NonZeroIssuance(PhantomData<(AccountId, Assets)>); -impl Contains<>::AssetId> - for NonZeroIssuance -where - Assets: fungibles::Inspect, -{ - fn contains(id: &>::AssetId) -> bool { - !Assets::total_issuance(id.clone()).is_zero() - } -} - -/// CurrencyIdConvert -/// This type implements conversions from our `CurrencyId` type into -/// `MultiLocation` and vice-versa. A currency locally is identified with a -/// `CurrencyId` variant but in the network it is identified in the form of a -/// `MultiLocation`. -pub struct CurrencyIdConvert; - -/// Convert our `CurrencyId` type into its `MultiLocation` representation. -/// We use the `OrmlAssetRegistry` to lookup the associated `MultiLocation` for -/// any given `CurrencyId`, while blocking tokens that are not Xcm-transferable. -impl Convert> for CurrencyIdConvert { - fn convert(id: CurrencyId) -> Option { - OrmlAssetRegistry::metadata(id) - .filter(|m| m.additional.transferability.includes_xcm()) - .and_then(|m| m.location) - .and_then(|l| l.try_into().ok()) - } -} - -/// Convert an incoming `MultiLocation` into a `CurrencyId` through a -/// reverse-lookup using the OrmlAssetRegistry. In the registry, we register CFG -/// using its absolute, non-anchored MultliLocation so we need to unanchor the -/// input location for Centrifuge-native assets for that to work. -impl xcm_executor::traits::Convert for CurrencyIdConvert { - fn convert(location: MultiLocation) -> Result { - let unanchored_location = match location { - MultiLocation { - parents: 0, - interior, - } => MultiLocation { - parents: 1, - interior: interior - .pushed_front_with(Parachain(u32::from(ParachainInfo::get()))) - .map_err(|_| location)?, - }, - x => x, - }; - - OrmlAssetRegistry::location_to_asset_id(unanchored_location).ok_or(location) - } -} - -impl Convert> for CurrencyIdConvert { - fn convert(asset: MultiAsset) -> Option { - if let MultiAsset { - id: Concrete(location), - .. - } = asset - { - >::convert(location).ok() - } else { - None - } - } -} - #[cfg(feature = "runtime-benchmarks")] parameter_types! { pub ReachableDest: Option = Some(Parent.into()); @@ -309,21 +200,8 @@ parameter_types! { pub CheckingAccount: AccountId = PolkadotXcm::check_account(); } -/// Type for specifying how a `MultiLocation` can be converted into an -/// `AccountId`. This is used when determining ownership of accounts for asset -/// transacting and when attempting to use XCM `Transact` in order to determine -/// the dispatch Origin. -pub type LocationToAccountId = ( - // The parent (Relay-chain) origin converts to the default `AccountId`. - ParentIsPreset, - // Sibling parachain origins convert to AccountId via the `ParaId::into`. - SiblingParachainConvertsVia, - // If we receive a MultiLocation of type AccountId32 that is within Centrifuge, - // just alias it to a local [AccountId]. - AccountId32Aliases, - // Generate remote accounts according to polkadot standards - cfg_primitives::xcm::HashedDescriptionDescribeFamilyAllTerminal, -); +pub type CurrencyIdConvert = runtime_common::xcm::CurrencyIdConvert; +pub type LocationToAccountId = runtime_common::xcm::LocationToAccountId; /// No local origins on this chain are allowed to dispatch XCM sends/executions. pub type LocalOriginToLocation = SignedToAccountId32; diff --git a/runtime/integration-tests/src/evm/ethereum_transaction.rs b/runtime/integration-tests/src/evm/ethereum_transaction.rs index cb146b6abd..ad783c1d48 100644 --- a/runtime/integration-tests/src/evm/ethereum_transaction.rs +++ b/runtime/integration-tests/src/evm/ethereum_transaction.rs @@ -10,7 +10,7 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -use cfg_primitives::CFG; +use cfg_primitives::{AccountId, CouncilCollective, CFG}; use cfg_traits::ethereum::EthereumTransactor; use ethereum::{LegacyTransaction, TransactionAction, TransactionSignature, TransactionV2}; use frame_support::{assert_err, dispatch::RawOrigin}; @@ -22,8 +22,7 @@ use tokio::runtime::Handle; use crate::{ chain::centrifuge::{ - AccountId, CouncilCollective, FastTrackVotingPeriod, MinimumDeposit, Runtime, RuntimeCall, - RuntimeEvent, PARA_ID, + FastTrackVotingPeriod, MinimumDeposit, Runtime, RuntimeCall, RuntimeEvent, PARA_ID, }, utils::{ env, diff --git a/runtime/integration-tests/src/evm/precompile.rs b/runtime/integration-tests/src/evm/precompile.rs index 58f8eadf3e..835130af9f 100644 --- a/runtime/integration-tests/src/evm/precompile.rs +++ b/runtime/integration-tests/src/evm/precompile.rs @@ -13,7 +13,7 @@ use std::collections::BTreeMap; use axelar_gateway_precompile::SourceConverter; -use cfg_primitives::{Balance, PoolId, TrancheId, CFG}; +use cfg_primitives::{AccountId, Balance, CouncilCollective, PoolId, TrancheId, CFG}; use cfg_traits::{ethereum::EthereumTransactor, liquidity_pools::Codec}; use cfg_types::{ domain_address::{Domain, DomainAddress}, @@ -37,8 +37,8 @@ use xcm::{v3::MultiLocation, VersionedMultiLocation}; use crate::{ chain::centrifuge::{ - AccountId, CouncilCollective, FastTrackVotingPeriod, MinimumDeposit, Runtime, RuntimeCall, - RuntimeEvent, RuntimeOrigin, PARA_ID, + FastTrackVotingPeriod, MinimumDeposit, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, + PARA_ID, }, evm::ethereum_transaction::TEST_CONTRACT_CODE, utils::{ diff --git a/runtime/integration-tests/src/generic/cases/liquidity_pools.rs b/runtime/integration-tests/src/generic/cases/liquidity_pools.rs index d0cc2b3309..8c1f25fadb 100644 --- a/runtime/integration-tests/src/generic/cases/liquidity_pools.rs +++ b/runtime/integration-tests/src/generic/cases/liquidity_pools.rs @@ -263,7 +263,7 @@ type FudgeRelayRuntime = <::FudgeHandle as FudgeHandle> use utils::*; mod development { - use development_runtime::LocationToAccountId; + use development_runtime::xcm::LocationToAccountId; use super::*; @@ -5461,7 +5461,7 @@ mod development { } mod altair { - use altair_runtime::{CurrencyIdConvert, PoolPalletIndex}; + use altair_runtime::{xcm::CurrencyIdConvert, PoolPalletIndex}; pub const KSM_ASSET_ID: CurrencyId = CurrencyId::ForeignAsset(1000); @@ -6441,7 +6441,7 @@ mod altair { } mod centrifuge { - use centrifuge_runtime::CurrencyIdConvert; + use centrifuge_runtime::xcm::CurrencyIdConvert; use super::*; diff --git a/runtime/integration-tests/src/generic/envs/fudge_env/handle.rs b/runtime/integration-tests/src/generic/envs/fudge_env/handle.rs index ac029df3ac..9ad667a5da 100644 --- a/runtime/integration-tests/src/generic/envs/fudge_env/handle.rs +++ b/runtime/integration-tests/src/generic/envs/fudge_env/handle.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use cfg_primitives::{AuraId, Balance, BlockNumber}; +use cfg_primitives::{AuraId, Balance, BlockNumber, Header}; use cumulus_primitives_core::CollectCollationInfo; use frame_support::traits::GenesisBuild; use fudge::{ @@ -29,7 +29,7 @@ use sp_runtime::{traits::AccountIdLookup, Storage}; use sp_transaction_pool::runtime_api::TaggedTransactionQueue; use tokio::runtime::Handle; -use crate::{chain::centrifuge::Header, generic::config::Runtime, utils::time::START_DATE}; +use crate::{generic::config::Runtime, utils::time::START_DATE}; type InherentCreator = Box< dyn CreateInherentDataProviders<