From a82ff8e7afe4c47b7e3d5d1543b09d26b4cd489e Mon Sep 17 00:00:00 2001 From: Alastair Holmes Date: Tue, 6 Feb 2024 14:28:48 +0100 Subject: [PATCH] Add serde impl for Asset squash Add back chain::Asset serde impls (Needed for GenesisConfig `dust_limits`) squash squash squash --- Cargo.lock | 3 + api/lib/src/queries.rs | 6 +- state-chain/custom-rpc/src/lib.rs | 7 +- state-chain/pallets/cf-swapping/src/tests.rs | 12 +- state-chain/primitives/Cargo.toml | 5 + state-chain/primitives/src/chains/assets.rs | 431 +++++++++++------- state-chain/runtime/src/chainflip.rs | 13 +- state-chain/runtime/src/lib.rs | 76 +-- .../traits/src/mocks/swap_deposit_handler.rs | 2 +- 9 files changed, 325 insertions(+), 230 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e6c02d6d1d5..ddef23f4d60 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1487,14 +1487,17 @@ dependencies = [ "ethabi", "frame-support", "hex", + "lazy_format", "parity-scale-codec", "scale-info", "serde", + "serde_json", "sp-core 21.0.0 (git+https://github.com/chainflip-io/polkadot-sdk.git?tag=chainflip-substrate-1.1+3)", "sp-runtime 24.0.0 (git+https://github.com/chainflip-io/polkadot-sdk.git?tag=chainflip-substrate-1.1+3)", "sp-std 8.0.0 (git+https://github.com/chainflip-io/polkadot-sdk.git?tag=chainflip-substrate-1.1+3)", "strum 0.24.1", "strum_macros 0.24.3", + "utilities", ] [[package]] diff --git a/api/lib/src/queries.rs b/api/lib/src/queries.rs index b7a0bb7d7f3..aea84bfa5a7 100644 --- a/api/lib/src/queries.rs +++ b/api/lib/src/queries.rs @@ -102,14 +102,14 @@ impl QueryApi { let block_hash = block_hash.unwrap_or_else(|| self.state_chain_client.latest_finalized_block().hash); - futures::future::join_all(Asset::all().iter().map(|asset| async { + futures::future::join_all(Asset::all().map(|asset| async move { Ok(( - *asset, + asset, self.state_chain_client .storage_double_map_entry::>( block_hash, &self.state_chain_client.account_id(), - asset, + &asset, ) .await? .unwrap_or_default(), diff --git a/state-chain/custom-rpc/src/lib.rs b/state-chain/custom-rpc/src/lib.rs index b3072c8c0ed..61fe08198cc 100644 --- a/state-chain/custom-rpc/src/lib.rs +++ b/state-chain/custom-rpc/src/lib.rs @@ -1163,11 +1163,8 @@ where fn cf_supported_assets(&self) -> RpcResult>> { let mut chain_to_asset: HashMap> = HashMap::new(); - Asset::all().iter().for_each(|asset| { - chain_to_asset - .entry((*asset).into()) - .and_modify(|asset_vec| asset_vec.push(*asset)) - .or_insert(vec![*asset]); + Asset::all().for_each(|asset| { + chain_to_asset.entry((asset).into()).or_default().push(asset); }); Ok(chain_to_asset) } diff --git a/state-chain/pallets/cf-swapping/src/tests.rs b/state-chain/pallets/cf-swapping/src/tests.rs index a4ec2732d01..ba9f42b92ca 100644 --- a/state-chain/pallets/cf-swapping/src/tests.rs +++ b/state-chain/pallets/cf-swapping/src/tests.rs @@ -1846,10 +1846,10 @@ fn swap_broker_fee_calculated_correctly() { const AMOUNT: AssetAmount = 100000; // calculate broker fees for each asset available - Asset::all().iter().for_each(|asset| { + Asset::all().for_each(|asset| { let total_fees: u128 = fees.iter().fold(0, |total_fees: u128, fee_bps: &BasisPoints| { - swap_with_custom_broker_fee(*asset, Asset::Usdc, AMOUNT, *fee_bps); + swap_with_custom_broker_fee(asset, Asset::Usdc, AMOUNT, *fee_bps); total_fees + Permill::from_parts(*fee_bps as u32 * BASIS_POINTS_PER_MILLION) * AMOUNT }); @@ -1896,17 +1896,17 @@ fn swap_broker_fee_subtracted_from_swap_amount() { let combinations = amounts.iter().cartesian_product(fees); let mut swap_id = 1; - Asset::all().iter().for_each(|asset| { + Asset::all().for_each(|asset| { let mut total_fees = 0; combinations.clone().for_each(|(amount, broker_fee)| { - swap_with_custom_broker_fee(*asset, Asset::Flip, *amount, broker_fee); + swap_with_custom_broker_fee(asset, Asset::Flip, *amount, broker_fee); let broker_commission = Permill::from_parts(broker_fee as u32 * BASIS_POINTS_PER_MILLION) * *amount; total_fees += broker_commission; - assert_eq!(EarnedBrokerFees::::get(ALICE, *asset), total_fees); + assert_eq!(EarnedBrokerFees::::get(ALICE, asset), total_fees); swap_scheduled_event_witnessed( swap_id, - *asset, + asset, *amount, Asset::Flip, broker_commission, diff --git a/state-chain/primitives/Cargo.toml b/state-chain/primitives/Cargo.toml index 44d807cb806..2a8817adea4 100644 --- a/state-chain/primitives/Cargo.toml +++ b/state-chain/primitives/Cargo.toml @@ -15,6 +15,9 @@ ethabi = { default-features = false, version = '18.0' } strum = { default-features = false, version = '0.24' } strum_macros = { default-features = false, version = '0.24' } sp-core = { git = "https://github.com/chainflip-io/polkadot-sdk.git", tag = "chainflip-substrate-1.1+3", default_features = false } +lazy_format = "2.0" + +cf-utilities = { package = 'utilities', path = '../../utilities', default-features = false } frame-support = { git = "https://github.com/chainflip-io/polkadot-sdk.git", tag = "chainflip-substrate-1.1+3", default-features = false } sp-std = { git = "https://github.com/chainflip-io/polkadot-sdk.git", tag = "chainflip-substrate-1.1+3", default-features = false } @@ -29,11 +32,13 @@ scale-info = { version = "2.5.0", default-features = false, features = [ [dev-dependencies] sp-runtime = { git = "https://github.com/chainflip-io/polkadot-sdk.git", tag = "chainflip-substrate-1.1+3" } sp-core = { git = "https://github.com/chainflip-io/polkadot-sdk.git", tag = "chainflip-substrate-1.1+3" } +serde_json = "1.0" [features] default = ['std'] std = [ 'sp-core/std', + 'cf-utilities/std', 'codec/std', 'ethabi/std', 'frame-support/std', diff --git a/state-chain/primitives/src/chains/assets.rs b/state-chain/primitives/src/chains/assets.rs index 98b29cb30c1..66fe1487d90 100644 --- a/state-chain/primitives/src/chains/assets.rs +++ b/state-chain/primitives/src/chains/assets.rs @@ -13,182 +13,307 @@ //! //! assert_eq!(any::Asset::Flip, any::Asset::from(eth::Asset::Flip)); //! ``` -use super::*; -use serde::{Deserialize, Serialize}; +macro_rules! assets { + (pub enum Asset { + $(($chain_mod:ident, $chain:ident) => { + ($gas_asset:ident, $gas_string:literal) = $gas_value:literal (GAS_ASSET) + $(,($asset:ident, $string:literal) = $value:literal)* $(,)? + }),*$(,)? + }) => { + pub mod any { + use strum_macros::EnumIter; + use codec::{MaxEncodedLen, Encode, Decode}; + use scale_info::TypeInfo; -use strum_macros::EnumIter; - -/// Defines all Assets, and the Chain each asset belongs to. -/// There's a unique 1:1 relationship between an Asset and a Chain. -pub mod any { - use core::str::FromStr; + #[derive( + Copy, + Clone, + Debug, + PartialEq, + Eq, + Encode, + Decode, + TypeInfo, + MaxEncodedLen, + Hash, + PartialOrd, + Ord, + EnumIter, + )] + #[repr(u32)] + pub enum Asset { + $( + $gas_asset = $gas_value, + $($asset = $value,)* + )* + } + impl TryFrom for Asset { + type Error = &'static str; - use super::*; - pub type Chain = AnyChain; - - /// A token or currency that can be swapped natively in the Chainflip AMM. - #[derive( - Copy, - Clone, - Debug, - PartialEq, - Eq, - Encode, - Decode, - TypeInfo, - MaxEncodedLen, - Hash, - PartialOrd, - Ord, - EnumIter, - Serialize, - Deserialize, - )] - #[repr(u32)] - #[serde(rename_all = "UPPERCASE")] - // !!!!!! IMPORTANT !!!!!! - // Do not change these indices. - pub enum Asset { - // 0 is reserved for particular cross chain messaging scenarios where we want to pass - // through a message without making a swap. - Eth = 1u32, - Flip = 2u32, - Usdc = 3u32, - Dot = 4u32, - Btc = 5u32, - } + fn try_from(n: u32) -> Result { + match n { + $( + x if x == Self::$gas_asset as u32 => Ok(Self::$gas_asset), + $(x if x == Self::$asset as u32 => Ok(Self::$asset),)* + )* + _ => Err("Invalid asset id"), + } + } + } + impl Asset { + pub fn all() -> impl Iterator + 'static { + use strum::IntoEnumIterator; + Self::iter() + } + } + impl From for $crate::ForeignChain { + fn from(asset: Asset) -> Self { + match asset { + $( + Asset::$gas_asset $(| Asset::$asset)* => Self::$chain, + )* + } + } + } + impl core::fmt::Display for Asset { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{}", match self { + $( + Asset::$gas_asset => stringify!($gas_asset), + $( + Asset::$asset => stringify!($asset), + )* + )* + }.to_uppercase()) + } + } + impl core::str::FromStr for Asset { + type Err = &'static str; - impl TryFrom for Asset { - type Error = &'static str; - - fn try_from(n: u32) -> Result { - match n { - x if x == Self::Eth as u32 => Ok(Self::Eth), - x if x == Self::Flip as u32 => Ok(Self::Flip), - x if x == Self::Usdc as u32 => Ok(Self::Usdc), - x if x == Self::Dot as u32 => Ok(Self::Dot), - x if x == Self::Btc as u32 => Ok(Self::Btc), - _ => Err("Invalid asset id"), + fn from_str(s: &str) -> Result { + match s.to_lowercase().as_str() { + $( + $gas_string => Ok(Asset::$gas_asset), + $($string => Ok(Asset::$asset),)* + )* + _ => Err("Unrecognized asset"), + } + } } - } - } + mod asset_serde_impls { + use serde::{Serialize, Deserialize}; - impl Asset { - pub fn all() -> Vec { - use strum::IntoEnumIterator; - Self::iter().collect() - } - } + #[derive(Copy, Clone, Serialize, Deserialize)] + #[repr(u32)] + #[serde(rename_all = "UPPERCASE")] + enum SerdeAsset { + $( + $gas_asset = $gas_value, + $($asset = $value,)* + )* + } + impl From for super::Asset { + fn from(serde_asset: SerdeAsset) -> Self { + match serde_asset { + $( + SerdeAsset::$gas_asset => super::Asset::$gas_asset, + $(SerdeAsset::$asset => super::Asset::$asset,)* + )* + } + } + } - impl From for ForeignChain { - fn from(asset: Asset) -> Self { - match asset { - Asset::Eth => Self::Ethereum, - Asset::Flip => Self::Ethereum, - Asset::Usdc => Self::Ethereum, - Asset::Dot => Self::Polkadot, - Asset::Btc => Self::Bitcoin, - } - } - } + #[derive(Serialize, Deserialize)] + #[serde(untagged)] + #[serde( + expecting = r#"Expected a valid asset specifier. Assets should be specified as upper-case strings, e.g. `"ETH"`, and can be optionally distinguished by chain, e.g. `{ chain: "Ethereum", asset: "ETH" }."# + )] + enum SerdeAssetOptionalExplicitChain { + ImplicitChain(SerdeAsset), + ExplicitChain { chain: Option<$crate::ForeignChain>, asset: SerdeAsset }, + } - impl FromStr for Asset { - type Err = &'static str; - - fn from_str(s: &str) -> Result { - match s.to_lowercase().as_str() { - "eth" => Ok(Asset::Eth), - "flip" => Ok(Asset::Flip), - "usdc" => Ok(Asset::Usdc), - "dot" => Ok(Asset::Dot), - "btc" => Ok(Asset::Btc), - _ => Err("Unrecognized asset"), - } - } - } -} + impl Serialize for super::Asset { + fn serialize(&self, serializer: S) -> Result + where S: serde::Serializer + { + Serialize::serialize(&SerdeAssetOptionalExplicitChain::ExplicitChain { + chain: Some((*self).into()), asset: match self { + $( + super::Asset::$gas_asset => SerdeAsset::$gas_asset, + $(super::Asset::$asset => SerdeAsset::$asset,)* + )* + } + }, serializer) + } + } + impl<'de> Deserialize<'de> for super::Asset { + fn deserialize(deserializer: D) -> Result + where D: serde::Deserializer<'de> { + >::deserialize(deserializer).and_then(|serde_asset_optional_explicit_chain| { + let serde_asset = match serde_asset_optional_explicit_chain { + SerdeAssetOptionalExplicitChain::ImplicitChain(serde_asset) | SerdeAssetOptionalExplicitChain::ExplicitChain { chain: None, asset: serde_asset } => serde_asset, + SerdeAssetOptionalExplicitChain::ExplicitChain { + chain: Some(serde_chain), + asset: serde_asset + } => { + let asset_chain = match serde_asset { + $( + SerdeAsset::$gas_asset $(| SerdeAsset::$asset)* => $crate::ForeignChain::$chain, + )* + }; -#[derive(Clone, Debug, TypeInfo, Encode, Decode, MaxEncodedLen, Serialize, Deserialize)] -pub enum AssetError { - Unsupported, -} + if asset_chain != serde_chain { + return Err(<>::Error as serde::de::Error>::custom(lazy_format::lazy_format!("The asset '{asset}' does not exist on the '{serde_chain}' chain, but is instead a '{asset_chain}' asset. Either try using '{{\"chain\":\"{asset_chain}\", \"asset\":\"{asset}\"}}', or use a different asset (i.e. '{example_chain_asset}') ", asset = super::Asset::from(serde_asset), example_chain_asset = match serde_chain { + $( + $crate::ForeignChain::$chain => super::Asset::$gas_asset, + )* + }))) + } else { + serde_asset + } + }, + }; -/// Defines the assets types for a chain and some useful conversion traits. See the module level -/// docs for more detail. -macro_rules! chain_assets { - ( $mod:ident, $chain:ident, $( $asset:ident ),+ ) => { - /// Chain-specific assets types. - pub mod $mod { - use $crate::chains::*; - use $crate::chains::assets::*; + Ok(serde_asset.into()) + }) + } + } - pub type Chain = $chain; + #[cfg(test)] + mod tests { + use serde_json; + use cf_utilities::assert_ok; + use super::super::Asset; - #[derive(Copy, Clone, Debug, PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen, Hash, serde::Serialize, serde::Deserialize)] - pub enum Asset { - $( - $asset, - )+ + #[test] + fn test_asset_serde_encoding() { + assert_eq!(assert_ok!(serde_json::to_string(&Asset::Eth)), "{\"chain\":\"Ethereum\",\"asset\":\"ETH\"}"); + assert_eq!(assert_ok!(serde_json::to_string(&Asset::Dot)), "{\"chain\":\"Polkadot\",\"asset\":\"DOT\"}"); + assert_eq!(assert_ok!(serde_json::to_string(&Asset::Btc)), "{\"chain\":\"Bitcoin\",\"asset\":\"BTC\"}"); + + assert_eq!(assert_ok!(serde_json::from_str::("{\"chain\":\"Ethereum\",\"asset\":\"ETH\"}")), Asset::Eth); + assert_eq!(assert_ok!(serde_json::from_str::("{\"chain\":\"Polkadot\",\"asset\":\"DOT\"}")), Asset::Dot); + assert_eq!(assert_ok!(serde_json::from_str::("{\"chain\":\"Bitcoin\",\"asset\":\"BTC\"}")), Asset::Btc); + + assert_eq!(assert_ok!(serde_json::from_str::("{\"asset\":\"ETH\"}")), Asset::Eth); + assert_eq!(assert_ok!(serde_json::from_str::("{\"asset\":\"DOT\"}")), Asset::Dot); + assert_eq!(assert_ok!(serde_json::from_str::("{\"asset\":\"BTC\"}")), Asset::Btc); + + assert_eq!(assert_ok!(serde_json::from_str::("\"ETH\"")), Asset::Eth); + assert_eq!(assert_ok!(serde_json::from_str::("\"DOT\"")), Asset::Dot); + assert_eq!(assert_ok!(serde_json::from_str::("\"BTC\"")), Asset::Btc); + } + } } - pub const GAS_ASSET: Asset = [ + #[derive( + Copy, + Clone, + Debug, + PartialEq, + Eq, + Hash, + )] + pub enum ForeignChainAndAsset { $( - Asset::$asset, - )+ - ][0]; - - impl From for any::Asset { - fn from(asset: Asset) -> Self { - match asset { + $chain(super::$chain_mod::Asset), + )* + } + impl From for ForeignChainAndAsset { + fn from(value: Asset) -> Self { + match value { $( - Asset::$asset => any::Asset::$asset, - )+ + Asset::$gas_asset => Self::$chain(super::$chain_mod::Asset::$gas_asset), + $(Asset::$asset => Self::$chain(super::$chain_mod::Asset::$asset),)* + )* } } } - - impl TryFrom for Asset { - type Error = AssetError; - - fn try_from(asset: any::Asset) -> Result { - match asset { + impl From for Asset { + fn from(value: ForeignChainAndAsset) -> Self { + match value { $( - any::Asset::$asset => Ok(Asset::$asset), - )+ - _ => Err(AssetError::Unsupported), + ForeignChainAndAsset::$chain(super::$chain_mod::Asset::$gas_asset) => Self::$gas_asset, + $(ForeignChainAndAsset::$chain(super::$chain_mod::Asset::$asset) => Self::$asset,)* + )* } } } + } + + $( + pub mod $chain_mod { + use super::any; + use codec::{MaxEncodedLen, Encode, Decode}; + use scale_info::TypeInfo; + use serde::{Serialize, Deserialize}; + + pub type Chain = $crate::chains::$chain; + pub const GAS_ASSET: Asset = Asset::$gas_asset; - impl From for ForeignChain { - fn from(_asset: Asset) -> Self { - ForeignChain::$chain + #[derive(Copy, Clone, Debug, PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen, Hash, Serialize, Deserialize)] + pub enum Asset { + $gas_asset, + $($asset,)* } - } + impl From for any::Asset { + fn from(asset: Asset) -> Self { + match asset { + Asset::$gas_asset => any::Asset::$gas_asset, + $( + Asset::$asset => any::Asset::$asset, + )* + } + } + } + impl From for $crate::ForeignChain { + fn from(_asset: Asset) -> Self { + Self::$chain + } + } + impl TryFrom for Asset { + type Error = AssetError; - #[test] - fn consistency_check() { - $( - assert_eq!( - ForeignChain::from(any::Asset::from(Asset::$asset)), - ForeignChain::from(Asset::$asset), - "Inconsistent asset type definition. Asset {} defined in {}, but mapped to chain {:?}", - stringify!($asset), - stringify!($mod), - ForeignChain::from(any::Asset::from(Asset::$asset)), - ); - )+ + fn try_from(asset: super::any::Asset) -> Result { + match asset { + super::any::Asset::$gas_asset => Ok(Asset::$gas_asset), + $( + super::any::Asset::$asset => Ok(Asset::$asset), + )* + _ => Err(AssetError::Unsupported), + } + } + } + + #[derive(Clone, Debug, TypeInfo, Encode, Decode, MaxEncodedLen)] + pub enum AssetError { + Unsupported, + } } - } - }; + + )* + } } -// Defines each chain's Asset enum. -// Must be consistent with the mapping defined in any::Asset -chain_assets!(eth, Ethereum, Eth, Flip, Usdc); -chain_assets!(dot, Polkadot, Dot); -chain_assets!(btc, Bitcoin, Btc); +// !!!!!! IMPORTANT !!!!!! +// Do not change these indices. +assets!(pub enum Asset { + // 0 is reserved for particular cross chain messaging scenarios where we want to pass + // through a message without making a swap. + (eth, Ethereum) => { + (Eth, "eth") = 1u32 (GAS_ASSET), + (Flip, "flip") = 2u32, + (Usdc, "usdc") = 3u32, + }, + (dot, Polkadot) => { + (Dot, "dot") = 4u32 (GAS_ASSET), + }, + (btc, Bitcoin) => { + (Btc, "btc") = 5u32 (GAS_ASSET), + }, +}); #[cfg(test)] mod test_assets { @@ -209,12 +334,12 @@ mod test_assets { #[test] fn asset_id_to_asset() { - assert!(Asset::try_from(0).is_err()); - assert_eq!(Asset::try_from(1).unwrap(), Asset::Eth); - assert_eq!(Asset::try_from(2).unwrap(), Asset::Flip); - assert_eq!(Asset::try_from(3).unwrap(), Asset::Usdc); - assert_eq!(Asset::try_from(4).unwrap(), Asset::Dot); - assert_eq!(Asset::try_from(5).unwrap(), Asset::Btc); + assert!(any::Asset::try_from(0).is_err()); + assert_eq!(any::Asset::try_from(1).unwrap(), any::Asset::Eth); + assert_eq!(any::Asset::try_from(2).unwrap(), any::Asset::Flip); + assert_eq!(any::Asset::try_from(3).unwrap(), any::Asset::Usdc); + assert_eq!(any::Asset::try_from(4).unwrap(), any::Asset::Dot); + assert_eq!(any::Asset::try_from(5).unwrap(), any::Asset::Btc); } #[test] diff --git a/state-chain/runtime/src/chainflip.rs b/state-chain/runtime/src/chainflip.rs index 592874ef6f8..2bad4a46cea 100644 --- a/state-chain/runtime/src/chainflip.rs +++ b/state-chain/runtime/src/chainflip.rs @@ -21,6 +21,7 @@ use cf_chains::{ to_encoded_address, try_from_encoded_address, AddressConverter, EncodedAddress, ForeignChainAddress, }, + assets::any::ForeignChainAndAsset, btc::{ api::{BitcoinApi, SelectedUtxosAndChangeAmount, UtxoSelectionType}, Bitcoin, BitcoinCrypto, BitcoinFeeInfo, BitcoinTransactionData, UtxoId, @@ -440,10 +441,10 @@ macro_rules! impl_deposit_api_for_anychain { ) -> Result<(ChannelId, ForeignChainAddress, ::ChainBlockNumber), DispatchError> { match source_asset.into() { $( - ForeignChain::$chain => + ForeignChainAndAsset::$chain(source_asset) => $pallet::request_liquidity_deposit_address( lp_account, - source_asset.try_into().unwrap(), + source_asset, ).map(|(channel, address, block_number)| (channel, address, block_number.into())), )+ } @@ -459,8 +460,8 @@ macro_rules! impl_deposit_api_for_anychain { ) -> Result<(ChannelId, ForeignChainAddress, ::ChainBlockNumber), DispatchError> { match source_asset.into() { $( - ForeignChain::$chain => $pallet::request_swap_deposit_address( - source_asset.try_into().unwrap(), + ForeignChainAndAsset::$chain(source_asset) => $pallet::request_swap_deposit_address( + source_asset, destination_asset, destination_address, broker_commission_bps, @@ -488,8 +489,8 @@ macro_rules! impl_egress_api_for_anychain { ) -> Result, DispatchError> { match asset.into() { $( - ForeignChain::$chain => $pallet::schedule_egress( - asset.try_into().expect("Checked for asset compatibility"), + ForeignChainAndAsset::$chain(asset) => $pallet::schedule_egress( + asset, amount.try_into().expect("Checked for amount compatibility"), destination_address .try_into() diff --git a/state-chain/runtime/src/lib.rs b/state-chain/runtime/src/lib.rs index f7f893a780a..ae2d00dc719 100644 --- a/state-chain/runtime/src/lib.rs +++ b/state-chain/runtime/src/lib.rs @@ -21,6 +21,7 @@ use cf_amm::{ range_orders::Liquidity, }; use cf_chains::{ + assets::any::ForeignChainAndAsset, btc::{BitcoinCrypto, BitcoinRetryPolicy}, dot::{self, PolkadotCrypto}, eth::{self, api::EthereumApi, Address as EthereumAddress, Ethereum}, @@ -1156,21 +1157,10 @@ impl_runtime_apis! { fn cf_min_deposit_amount(asset: Asset) -> AssetAmount { use pallet_cf_ingress_egress::MinimumDeposit; - use cf_chains::assets::{eth, dot, btc}; - - match ForeignChain::from(asset) { - ForeignChain::Ethereum => MinimumDeposit::::get( - eth::Asset::try_from(asset) - .expect("Conversion must succeed: ForeignChain checked in match clause.") - ), - ForeignChain::Polkadot => MinimumDeposit::::get( - dot::Asset::try_from(asset) - .expect("Conversion must succeed: ForeignChain checked in match clause.") - ), - ForeignChain::Bitcoin => MinimumDeposit::::get( - btc::Asset::try_from(asset) - .expect("Conversion must succeed: ForeignChain checked in match clause.") - ).into(), + match asset.into() { + ForeignChainAndAsset::Ethereum(asset) => MinimumDeposit::::get(asset), + ForeignChainAndAsset::Polkadot(asset) => MinimumDeposit::::get(asset), + ForeignChainAndAsset::Bitcoin(asset) => MinimumDeposit::::get(asset).into(), } } @@ -1195,50 +1185,24 @@ impl_runtime_apis! { } fn cf_ingress_fee(asset: Asset) -> AssetAmount { - match ForeignChain::from(asset) { - ForeignChain::Ethereum => pallet_cf_chain_tracking::Pallet::::get_tracked_data() - .estimate_ingress_fee( - asset - .try_into() - .expect("Conversion must succeed: ForeignChain checked in match clause.") - ), - ForeignChain::Polkadot => pallet_cf_chain_tracking::Pallet::::get_tracked_data() - .estimate_ingress_fee( - asset - .try_into() - .expect("Conversion must succeed: ForeignChain checked in match clause.") - ), - ForeignChain::Bitcoin => pallet_cf_chain_tracking::Pallet::::get_tracked_data() - .estimate_ingress_fee( - asset - .try_into() - .expect("Conversion must succeed: ForeignChain checked in match clause.") - ) - .into(), + match asset.into() { + ForeignChainAndAsset::Ethereum(asset) => pallet_cf_chain_tracking::Pallet::::get_tracked_data() + .estimate_ingress_fee(asset), + ForeignChainAndAsset::Polkadot(asset) => pallet_cf_chain_tracking::Pallet::::get_tracked_data() + .estimate_ingress_fee(asset), + ForeignChainAndAsset::Bitcoin(asset) => pallet_cf_chain_tracking::Pallet::::get_tracked_data() + .estimate_ingress_fee(asset).into(), } } fn cf_egress_fee(asset: Asset) -> AssetAmount { - match ForeignChain::from(asset) { - ForeignChain::Ethereum => pallet_cf_chain_tracking::Pallet::::get_tracked_data() - .estimate_egress_fee( - asset - .try_into() - .expect("Conversion must succeed: ForeignChain checked in match clause.") - ), - ForeignChain::Polkadot => pallet_cf_chain_tracking::Pallet::::get_tracked_data() - .estimate_egress_fee( - asset - .try_into() - .expect("Conversion must succeed: ForeignChain checked in match clause.") - ), - ForeignChain::Bitcoin => pallet_cf_chain_tracking::Pallet::::get_tracked_data() - .estimate_egress_fee( - asset - .try_into() - .expect("Conversion must succeed: ForeignChain checked in match clause.") - ) - .into(), + match asset.into() { + ForeignChainAndAsset::Ethereum(asset) => pallet_cf_chain_tracking::Pallet::::get_tracked_data() + .estimate_egress_fee(asset), + ForeignChainAndAsset::Polkadot(asset) => pallet_cf_chain_tracking::Pallet::::get_tracked_data() + .estimate_egress_fee(asset), + ForeignChainAndAsset::Bitcoin(asset) => pallet_cf_chain_tracking::Pallet::::get_tracked_data() + .estimate_egress_fee(asset).into(), } } @@ -1265,7 +1229,7 @@ impl_runtime_apis! { LiquidityPools::sweep(&account_id).unwrap(); - let balances = Asset::all().iter().map(|&asset| + let balances = Asset::all().map(|asset| (asset, pallet_cf_lp::FreeBalances::::get(&account_id, asset).unwrap_or(0)) ).collect(); diff --git a/state-chain/traits/src/mocks/swap_deposit_handler.rs b/state-chain/traits/src/mocks/swap_deposit_handler.rs index 3b1580254f6..9e2e09624df 100644 --- a/state-chain/traits/src/mocks/swap_deposit_handler.rs +++ b/state-chain/traits/src/mocks/swap_deposit_handler.rs @@ -8,7 +8,7 @@ pub struct MockSwapDepositHandler(sp_std::marker::PhantomData); impl> SwapDepositHandler for MockSwapDepositHandler<(C, E)> where - C::ChainAsset: TryFrom, + cf_primitives::Asset: TryInto, { type AccountId = u64;