diff --git a/api/bin/chainflip-broker-api/src/main.rs b/api/bin/chainflip-broker-api/src/main.rs index b8dfd3eca95..291d039fd27 100644 --- a/api/bin/chainflip-broker-api/src/main.rs +++ b/api/bin/chainflip-broker-api/src/main.rs @@ -24,7 +24,6 @@ use tracing::log; #[derive(Serialize, Deserialize, Clone)] pub struct BrokerSwapDepositAddress { pub address: String, - pub expiry_block: BlockNumber, pub issued_block: BlockNumber, pub channel_id: ChannelId, } @@ -33,7 +32,6 @@ impl From for BrokerSwapDepositAddress { fn from(value: chainflip_api::SwapDepositAddress) -> Self { Self { address: value.address, - expiry_block: value.expiry_block, issued_block: value.issued_block, channel_id: value.channel_id, } diff --git a/api/bin/chainflip-cli/src/main.rs b/api/bin/chainflip-cli/src/main.rs index 76d949cb6d5..2bbf400c84e 100644 --- a/api/bin/chainflip-cli/src/main.rs +++ b/api/bin/chainflip-cli/src/main.rs @@ -57,7 +57,7 @@ async fn run_cli() -> Result<()> { let api = StateChainApi::connect(scope, cli_settings.state_chain).await?; match command_line_opts.cmd { Broker(BrokerSubcommands::RequestSwapDepositAddress(params)) => { - let SwapDepositAddress { address, expiry_block, .. } = api + let SwapDepositAddress { address, .. } = api .broker_api() .request_swap_deposit_address( params.source_asset, @@ -71,7 +71,6 @@ async fn run_cli() -> Result<()> { ) .await?; println!("Deposit Address: {address}"); - println!("Address expires at block {expiry_block}"); }, LiquidityProvider( LiquidityProviderSubcommands::RequestLiquidityDepositAddress { asset }, diff --git a/api/lib/src/lib.rs b/api/lib/src/lib.rs index fcbfd933eee..0559d49f3e6 100644 --- a/api/lib/src/lib.rs +++ b/api/lib/src/lib.rs @@ -307,7 +307,6 @@ pub trait GovernanceApi: SignedExtrinsicApi { pub struct SwapDepositAddress { pub address: String, - pub expiry_block: state_chain_runtime::BlockNumber, pub issued_block: state_chain_runtime::BlockNumber, pub channel_id: ChannelId, } @@ -336,10 +335,7 @@ pub trait BrokerApi: SignedExtrinsicApi { if let Some(state_chain_runtime::RuntimeEvent::Swapping( pallet_cf_swapping::Event::SwapDepositAddressReady { - deposit_address, - expiry_block, - channel_id, - .. + deposit_address, channel_id, .. }, )) = events.iter().find(|event| { matches!( @@ -351,7 +347,6 @@ pub trait BrokerApi: SignedExtrinsicApi { }) { Ok(SwapDepositAddress { address: deposit_address.to_string(), - expiry_block: *expiry_block, issued_block: header.number, channel_id: *channel_id, }) diff --git a/api/lib/src/queries.rs b/api/lib/src/queries.rs index e5e999c3471..b099adce200 100644 --- a/api/lib/src/queries.rs +++ b/api/lib/src/queries.rs @@ -4,6 +4,7 @@ use cf_primitives::{chains::assets::any, AssetAmount}; use chainflip_engine::state_chain_observer::client::{ chain_api::ChainApi, storage_api::StorageApi, }; +use pallet_cf_ingress_egress::DepositChannelDetails; use serde::Deserialize; use state_chain_runtime::PalletInstanceAlias; use std::{collections::BTreeMap, sync::Arc}; @@ -15,7 +16,6 @@ pub struct SwapChannelInfo { deposit_address: ::Humanreadable, source_asset: any::Asset, destination_asset: any::Asset, - expiry_block: state_chain_runtime::BlockNumber, } pub struct QueryApi { @@ -52,47 +52,33 @@ impl QueryApi { let block_hash = block_hash.unwrap_or_else(|| self.state_chain_client.latest_finalized_hash()); - let (channel_details, channel_actions, network_environment) = tokio::try_join!( - self.state_chain_client - .storage_map::, Vec<_>>(block_hash) - .map(|result| { - result.map(|channels| channels.into_iter().collect::>()) - }), - self.state_chain_client.storage_map::, Vec<_>>(block_hash,), - self.state_chain_client - .storage_value::>(block_hash), - )?; + >, Vec<_>>(block_hash) + .map(|result| { + result.map(|channels| channels.into_iter().collect::>()) + }), + self.state_chain_client + .storage_value::>( + block_hash + ), + )?; - Ok(channel_actions + Ok(channel_details .iter() - .filter_map(|(address, action)| { - match action { - pallet_cf_ingress_egress::ChannelAction::Swap { destination_asset, .. } | - pallet_cf_ingress_egress::ChannelAction::CcmTransfer { - destination_asset, - .. - } => Some(destination_asset), - _ => None, - } - .and_then(|destination_asset| { - channel_details.get(address).map(|details| { - (destination_asset, details.deposit_channel.clone(), details.expires_at) - }) - }) - .map(|(&destination_asset, deposit_channel, expiry)| SwapChannelInfo { + .filter_map(|(_, DepositChannelDetails { action, deposit_channel, .. })| match action { + pallet_cf_ingress_egress::ChannelAction::Swap { destination_asset, .. } | + pallet_cf_ingress_egress::ChannelAction::CcmTransfer { + destination_asset, .. + } => Some(SwapChannelInfo { deposit_address: deposit_channel.address.to_humanreadable(network_environment), source_asset: deposit_channel.asset.into(), - destination_asset, - expiry_block: expiry, - }) + destination_asset: *destination_asset, + }), + _ => None, }) .collect::>()) } diff --git a/engine/src/witness/btc.rs b/engine/src/witness/btc.rs index fa0cfbcbe40..67ebd114022 100644 --- a/engine/src/witness/btc.rs +++ b/engine/src/witness/btc.rs @@ -195,6 +195,8 @@ mod tests { btc::{deposit_address::DepositAddress, ScriptPubkey}, DepositChannel, }; + use pallet_cf_ingress_egress::ChannelAction; + use sp_runtime::AccountId32; fn fake_transaction(tx_outs: Vec) -> Transaction { Transaction { @@ -217,6 +219,9 @@ mod tests { asset: btc::Asset::Btc, state: DepositAddress::new([0; 32], 1), }, + action: ChannelAction::::LiquidityProvision { + lp_account: AccountId32::new([0xab; 32]), + }, } } diff --git a/state-chain/cf-integration-tests/src/mock_runtime.rs b/state-chain/cf-integration-tests/src/mock_runtime.rs index 7ae8a3f3bca..bee02a5d54c 100644 --- a/state-chain/cf-integration-tests/src/mock_runtime.rs +++ b/state-chain/cf-integration-tests/src/mock_runtime.rs @@ -212,9 +212,11 @@ impl ExtBuilder { environment: Default::default(), liquidity_pools: Default::default(), swapping: Default::default(), - liquidity_provider: Default::default(), system: Default::default(), transaction_payment: Default::default(), + bitcoin_ingress_egress: Default::default(), + polkadot_ingress_egress: Default::default(), + ethereum_ingress_egress: Default::default(), }) } } diff --git a/state-chain/node/src/chain_spec.rs b/state-chain/node/src/chain_spec.rs index c900e443eff..b698fba6e2b 100644 --- a/state-chain/node/src/chain_spec.rs +++ b/state-chain/node/src/chain_spec.rs @@ -267,7 +267,6 @@ pub fn cf_development_config() -> Result { common::PENALTIES.to_vec(), common::KEYGEN_CEREMONY_TIMEOUT_BLOCKS, common::THRESHOLD_SIGNATURE_CEREMONY_TIMEOUT_BLOCKS, - common::SWAP_TTL, common::MINIMUM_SWAP_AMOUNTS.to_vec(), dot_runtime_version, ) @@ -390,7 +389,6 @@ macro_rules! network_spec { PENALTIES.to_vec(), KEYGEN_CEREMONY_TIMEOUT_BLOCKS, THRESHOLD_SIGNATURE_CEREMONY_TIMEOUT_BLOCKS, - SWAP_TTL, MINIMUM_SWAP_AMOUNTS.to_vec(), dot_runtime_version, ) @@ -445,7 +443,6 @@ fn testnet_genesis( penalties: Vec<(Offence, (i32, BlockNumber))>, keygen_ceremony_timeout_blocks: BlockNumber, threshold_signature_ceremony_timeout_blocks: BlockNumber, - swap_ttl: BlockNumber, minimum_swap_amounts: Vec<(assets::any::Asset, AssetAmount)>, dot_runtime_version: RuntimeVersion, ) -> RuntimeGenesisConfig { @@ -650,8 +647,10 @@ fn testnet_genesis( }, transaction_payment: Default::default(), liquidity_pools: Default::default(), - swapping: SwappingConfig { swap_ttl, minimum_swap_amounts }, - liquidity_provider: Default::default(), + swapping: SwappingConfig { minimum_swap_amounts, _phantom: PhantomData }, + bitcoin_ingress_egress: Default::default(), + ethereum_ingress_egress: Default::default(), + polkadot_ingress_egress: Default::default(), } } diff --git a/state-chain/node/src/chain_spec/common.rs b/state-chain/node/src/chain_spec/common.rs index 0ec7b19c1ab..d5d925bb02d 100644 --- a/state-chain/node/src/chain_spec/common.rs +++ b/state-chain/node/src/chain_spec/common.rs @@ -40,7 +40,6 @@ pub const PENALTIES: &[(Offence, (i32, BlockNumber))] = &[ (Offence::GrandpaEquivocation, (50, HEARTBEAT_BLOCK_INTERVAL * 5)), ]; -pub const SWAP_TTL: BlockNumber = 2 * HOURS; pub const MINIMUM_SWAP_AMOUNTS: &[(Asset, AssetAmount)] = &[ (Asset::Eth, 580_000_000_000_000u128), // 1usd worth of Eth = 0.00058 * 18 d.p (Asset::Flip, FLIPPERINOS_PER_FLIP), // 1 Flip diff --git a/state-chain/pallets/cf-ingress-egress/src/benchmarking.rs b/state-chain/pallets/cf-ingress-egress/src/benchmarking.rs index 695a7a72540..da65ff89722 100644 --- a/state-chain/pallets/cf-ingress-egress/src/benchmarking.rs +++ b/state-chain/pallets/cf-ingress-egress/src/benchmarking.rs @@ -7,7 +7,6 @@ use cf_chains::{ DepositChannel, }; use frame_benchmarking::{account, benchmarks_instance_pallet}; -use frame_system::pallet_prelude::BlockNumberFor; pub(crate) type TargetChainBlockNumber = <>::TargetChain as Chain>::ChainBlockNumber; @@ -27,16 +26,17 @@ benchmarks_instance_pallet! { let deposit_address: <>::TargetChain as Chain>::ChainAccount = BenchmarkValue::benchmark_value(); let source_asset: <>::TargetChain as Chain>::ChainAsset = BenchmarkValue::benchmark_value(); let deposit_amount: <>::TargetChain as Chain>::ChainAmount = BenchmarkValue::benchmark_value(); + let block_number: TargetChainBlockNumber = BenchmarkValue::benchmark_value(); DepositChannelLookup::::insert(&deposit_address, DepositChannelDetails { - opened_at: TargetChainBlockNumber::::benchmark_value(), + opened_at: block_number, + expires_at: block_number, deposit_channel: DepositChannel::generate_new::<>::AddressDerivation>( 1, source_asset, ).unwrap(), - expires_at: BlockNumberFor::::from(1_000u32), - }); - ChannelActions::::insert(&deposit_address, ChannelAction::::LiquidityProvision { - lp_account: account("doogle", 0, 0), + action: ChannelAction::::LiquidityProvision { + lp_account: account("doogle", 0, 0), + }, }); }: { Pallet::::process_single_deposit(deposit_address, source_asset, deposit_amount, BenchmarkValue::benchmark_value(), BenchmarkValue::benchmark_value()).unwrap() @@ -61,13 +61,17 @@ benchmarks_instance_pallet! { let deposit_address = <>::TargetChain as Chain>::ChainAccount::benchmark_value_by_id(a as u8); let deposit_fetch_id = <>::TargetChain as Chain>::DepositFetchId::benchmark_value_by_id(a as u8); let source_asset: <>::TargetChain as Chain>::ChainAsset = BenchmarkValue::benchmark_value(); + let block_number = TargetChainBlockNumber::::benchmark_value(); let mut channel = DepositChannelDetails:: { - opened_at: TargetChainBlockNumber::::benchmark_value(), + opened_at: block_number, + expires_at: block_number, deposit_channel: DepositChannel::generate_new::<>::AddressDerivation>( 1, source_asset, ).unwrap(), - expires_at: BlockNumberFor::::from(1_000u32), + action: ChannelAction::::LiquidityProvision { + lp_account: account("doogle", 0, 0), + }, }; channel.deposit_channel.state.on_fetch_scheduled(); DepositChannelLookup::::insert(deposit_address.clone(), channel); diff --git a/state-chain/pallets/cf-ingress-egress/src/lib.rs b/state-chain/pallets/cf-ingress-egress/src/lib.rs index 59afc93e291..52a4494b203 100644 --- a/state-chain/pallets/cf-ingress-egress/src/lib.rs +++ b/state-chain/pallets/cf-ingress-egress/src/lib.rs @@ -21,7 +21,6 @@ use cf_chains::{ use cf_primitives::{ Asset, AssetAmount, BasisPoints, ChannelId, EgressCounter, EgressId, ForeignChain, }; -use cf_runtime_utilities::log_or_panic; use cf_traits::{ liquidity::LpBalanceApi, Broadcaster, CcmHandler, Chainflip, DepositApi, DepositHandler, EgressApi, GetBlockHeight, SwapDepositHandler, @@ -106,6 +105,8 @@ pub mod pallet { pub(crate) type TargetChainAccount = <>::TargetChain as Chain>::ChainAccount; pub(crate) type TargetChainAmount = <>::TargetChain as Chain>::ChainAmount; + pub(crate) type TargetChainBlockNumber = + <>::TargetChain as Chain>::ChainBlockNumber; #[derive(Clone, RuntimeDebug, PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen)] pub struct DepositWitness { @@ -123,12 +124,13 @@ pub mod pallet { pub deposit_channel: DepositChannel, /// The block number at which the deposit channel was opened, expressed as a block number /// on the external Chain. - pub opened_at: ::ChainBlockNumber, - /// The block number at which the deposit channel will be closed, expressed as a - /// Chainflip-native block number. - // TODO: We should consider changing this to also be an external block number and expire - // based on external block numbers. See PRO-689. - pub expires_at: BlockNumberFor, + pub opened_at: TargetChainBlockNumber, + /// The last block on the target chain that the witnessing will witness it in. If funds are + /// sent after this block, they will not be witnessed. + pub expires_at: TargetChainBlockNumber, + + /// The action to be taken when the DepositChannel is deposited to. + pub action: ChannelAction, } /// Determines the action to take when a deposit is made to a channel. @@ -196,6 +198,24 @@ pub mod pallet { } } + #[pallet::genesis_config] + pub struct GenesisConfig, I: 'static = ()> { + pub deposit_channel_lifetime: TargetChainBlockNumber, + } + + impl, I: 'static> Default for GenesisConfig { + fn default() -> Self { + Self { deposit_channel_lifetime: Default::default() } + } + } + + #[pallet::genesis_build] + impl, I: 'static> BuildGenesisConfig for GenesisConfig { + fn build(&self) { + DepositChannelLifetime::::put(self.deposit_channel_lifetime); + } + } + #[pallet::pallet] #[pallet::without_storage_info] pub struct Pallet(PhantomData<(T, I)>); @@ -259,16 +279,6 @@ pub mod pallet { OptionQuery, >; - /// Stores the channel action against the address - #[pallet::storage] - pub type ChannelActions, I: 'static = ()> = StorageMap< - _, - Twox64Concat, - TargetChainAccount, - ChannelAction, - OptionQuery, - >; - /// Stores the latest channel id used to generate an address. #[pallet::storage] pub type ChannelIdCounter, I: 'static = ()> = @@ -304,6 +314,10 @@ pub mod pallet { pub type MinimumDeposit, I: 'static = ()> = StorageMap<_, Twox64Concat, TargetChainAsset, TargetChainAmount, ValueQuery>; + #[pallet::storage] + pub type DepositChannelLifetime, I: 'static = ()> = + StorageValue<_, TargetChainBlockNumber, ValueQuery>; + /// Stores any failed transfers by the Vault contract. /// Without dealing with the underlying reason for the failure, retrying is unlike to succeed. /// Therefore these calls are stored here, until we can react to the reason for failure and @@ -381,6 +395,33 @@ pub mod pallet { #[pallet::hooks] impl, I: 'static> Hooks> for Pallet { + /// Recycle addresses if we can + fn on_idle(_n: BlockNumberFor, remaining_weight: Weight) -> Weight { + let current_target_chain_height = T::ChainTracking::get_block_height(); + let channel_lifetime = DepositChannelLifetime::::get(); + + for (_, details) in DepositChannelLookup::::iter() { + // We add an extra lifetime of safety. + // The CFEs will stop witnessing the address of this deposit channel at the + // expires_at block number. However, because the CFE uses a safety margin, and here + // we're using teh ChainTracking block number, we don't want to expire + // this too early. Even accounting for the safety margin, there is potential for + // latency, full SC blocks which might block ingress witnesses getting in etc. By + // having this buffer we protect against this probabilistically. + if details.expires_at + channel_lifetime <= current_target_chain_height { + if let Some(state) = details.deposit_channel.state.maybe_recycle() { + DepositChannelPool::::insert( + details.deposit_channel.channel_id, + DepositChannel { state, ..details.deposit_channel }, + ); + } + } + } + + // TODO: return the actual weight + remaining_weight + } + /// Take all scheduled Egress and send them out fn on_finalize(_n: BlockNumberFor) { // Send all fetch/transfer requests as a batch. Revert storage if failed. @@ -403,6 +444,7 @@ pub mod pallet { addresses: Vec>, ) -> DispatchResult { T::EnsureWitnessedAtCurrentEpoch::ensure_origin(origin)?; + for deposit_address in addresses { DepositChannelLookup::::mutate(deposit_address, |deposit_channel_details| { deposit_channel_details @@ -529,6 +571,7 @@ pub mod pallet { } impl, I: 'static> Pallet { + // TODO: Test this function. /// Take all scheduled egress requests and send them out in an `AllBatch` call. /// /// Note: Egress transactions with Blacklisted assets are not sent, and kept in storage. @@ -583,6 +626,7 @@ impl, I: 'static> Pallet { let mut addresses = vec![]; for request in batch_to_send { + // We need to pull out what we need above. match request { FetchOrTransfer::::Fetch { asset, @@ -690,6 +734,13 @@ impl, I: 'static> Pallet { let deposit_channel_details = DepositChannelLookup::::get(&deposit_address) .ok_or(Error::::InvalidDepositAddress)?; + // The address should not be used if it's being recycled + ensure!( + DepositChannelPool::::get(&deposit_channel_details.deposit_channel.channel_id) + .is_none(), + Error::::InvalidDepositAddress + ); + ensure!( deposit_channel_details.deposit_channel.asset == asset, Error::::AssetMismatch @@ -716,12 +767,7 @@ impl, I: 'static> Pallet { let channel_id = deposit_channel_details.deposit_channel.channel_id; Self::deposit_event(Event::::DepositFetchesScheduled { channel_id, asset }); - // NB: Don't take here. We should continue witnessing this address - // even after an deposit to it has occurred. - // https://github.com/chainflip-io/chainflip-eth-contracts/pull/226 - match ChannelActions::::get(&deposit_address) - .ok_or(Error::::InvalidDepositAddress)? - { + match deposit_channel_details.action { ChannelAction::LiquidityProvision { lp_account, .. } => T::LpBalance::try_credit_account(&lp_account, asset.into(), amount.into())?, ChannelAction::Swap { @@ -788,8 +834,7 @@ impl, I: 'static> Pallet { /// May re-use an existing deposit address, depending on chain configuration. fn open_channel( source_asset: TargetChainAsset, - channel_action: ChannelAction, - expires_at: BlockNumberFor, + action: ChannelAction, ) -> Result<(ChannelId, TargetChainAccount), DispatchError> { let (deposit_channel, channel_id) = if let Some((channel_id, mut deposit_channel)) = DepositChannelPool::::drain().next() @@ -813,13 +858,15 @@ impl, I: 'static> Pallet { let deposit_address = deposit_channel.address.clone(); - ChannelActions::::insert(&deposit_address, channel_action); + let current_target_chain_height = T::ChainTracking::get_block_height(); + DepositChannelLookup::::insert( &deposit_address, DepositChannelDetails { deposit_channel, - opened_at: T::ChainTracking::get_block_height(), - expires_at, + opened_at: current_target_chain_height, + expires_at: current_target_chain_height + DepositChannelLifetime::::get(), + action, }, ); @@ -882,13 +929,9 @@ impl, I: 'static> DepositApi for Pallet { fn request_liquidity_deposit_address( lp_account: T::AccountId, source_asset: TargetChainAsset, - expiry_block: BlockNumberFor, ) -> Result<(ChannelId, ForeignChainAddress), DispatchError> { - let (channel_id, deposit_address) = Self::open_channel( - source_asset, - ChannelAction::LiquidityProvision { lp_account }, - expiry_block, - )?; + let (channel_id, deposit_address) = + Self::open_channel(source_asset, ChannelAction::LiquidityProvision { lp_account })?; Ok((channel_id, deposit_address.into())) } @@ -901,7 +944,6 @@ impl, I: 'static> DepositApi for Pallet { broker_commission_bps: BasisPoints, broker_id: T::AccountId, channel_metadata: Option, - expiry_block: BlockNumberFor, ) -> Result<(ChannelId, ForeignChainAddress), DispatchError> { let (channel_id, deposit_address) = Self::open_channel( source_asset, @@ -918,25 +960,8 @@ impl, I: 'static> DepositApi for Pallet { broker_id, }, }, - expiry_block, )?; Ok((channel_id, deposit_address.into())) } - - // Note: we expect that the mapping from any instantiable pallet to the instance of this pallet - // is matching to the right chain. Because of that we can ignore the chain parameter. - fn expire_channel(address: TargetChainAccount) { - ChannelActions::::remove(&address); - if let Some(deposit_channel_details) = DepositChannelLookup::::get(&address) { - if let Some(state) = deposit_channel_details.deposit_channel.state.maybe_recycle() { - DepositChannelPool::::insert( - deposit_channel_details.deposit_channel.channel_id, - DepositChannel { state, ..deposit_channel_details.deposit_channel }, - ); - } - } else { - log_or_panic!("Tried to close an unknown channel."); - } - } } diff --git a/state-chain/pallets/cf-ingress-egress/src/mock.rs b/state-chain/pallets/cf-ingress-egress/src/mock.rs index f5fb366b92e..e59f979b583 100644 --- a/state-chain/pallets/cf-ingress-egress/src/mock.rs +++ b/state-chain/pallets/cf-ingress-egress/src/mock.rs @@ -1,5 +1,5 @@ pub use crate::{self as pallet_cf_ingress_egress}; -use crate::{DepositBalances, DepositWitness}; +use crate::{DepositBalances, DepositChannelLifetime, DepositWitness}; pub use cf_chains::{ address::{AddressDerivationApi, ForeignChainAddress}, @@ -26,7 +26,6 @@ use cf_traits::{ }; use frame_support::traits::{OriginTrait, UnfilteredDispatchable}; use frame_system as system; -use frame_system::pallet_prelude::BlockNumberFor; use sp_core::H256; use sp_runtime::traits::{BlakeTwo256, IdentityLookup, Zero}; @@ -116,8 +115,18 @@ impl crate::Config for Test { pub const ALICE: ::AccountId = 123u64; pub const BROKER: ::AccountId = 456u64; +// TODO: Use genesis config here? // Configure a mock runtime to test the pallet. -impl_test_helpers!(Test); +impl_test_helpers! { + Test, + RuntimeGenesisConfig { + system: Default::default(), + ingress_egress: Default::default(), + }, + || { + DepositChannelLifetime::::put(100); + }, +} type TestChainAccount = <::TargetChain as Chain>::ChainAccount; type TestChainAmount = <::TargetChain as Chain>::ChainAmount; @@ -131,6 +140,7 @@ pub trait RequestAddressAndDeposit { } impl RequestAddressAndDeposit for TestRunner { + /// Request desposit addresses and complete the deposit of funds into those addresses. #[track_caller] fn request_address_and_deposit( self, @@ -168,14 +178,12 @@ pub enum DepositRequest { Liquidity { lp_account: AccountId, asset: TestChainAsset, - expiry_block: BlockNumberFor, }, /// Do a non-ccm swap using a default broker and no fees. SimpleSwap { source_asset: TestChainAsset, destination_asset: TestChainAsset, destination_address: ForeignChainAddress, - expiry_block: BlockNumberFor, }, } @@ -206,19 +214,16 @@ impl RequestAddress for TestExternalities { .iter() .cloned() .map(|request| match request { - DepositRequest::Liquidity { lp_account, asset, expiry_block } => - IngressEgress::request_liquidity_deposit_address( - lp_account, - asset, - expiry_block, - ) - .map(|(id, addr)| (request, id, TestChainAccount::try_from(addr).unwrap())) - .unwrap(), + DepositRequest::Liquidity { lp_account, asset } => + IngressEgress::request_liquidity_deposit_address(lp_account, asset) + .map(|(id, addr)| { + (request, id, TestChainAccount::try_from(addr).unwrap()) + }) + .unwrap(), DepositRequest::SimpleSwap { source_asset, destination_asset, ref destination_address, - expiry_block, } => IngressEgress::request_swap_deposit_address( source_asset, destination_asset.into(), @@ -226,7 +231,6 @@ impl RequestAddress for TestExternalities { Default::default(), BROKER, None, - expiry_block, ) .map(|(channel_id, deposit_address)| { (request, channel_id, TestChainAccount::try_from(deposit_address).unwrap()) diff --git a/state-chain/pallets/cf-ingress-egress/src/tests.rs b/state-chain/pallets/cf-ingress-egress/src/tests.rs index fc086e4f3d6..cd359594fcd 100644 --- a/state-chain/pallets/cf-ingress-egress/src/tests.rs +++ b/state-chain/pallets/cf-ingress-egress/src/tests.rs @@ -1,8 +1,9 @@ use crate::{ mock::*, Call as PalletCall, ChannelAction, ChannelIdCounter, CrossChainMessage, - DepositChannelLookup, DepositChannelPool, DepositWitness, DisabledEgressAssets, Error, - Event as PalletEvent, FailedVaultTransfers, FetchOrTransfer, MinimumDeposit, Pallet, - ScheduledEgressCcm, ScheduledEgressFetchOrTransfer, TargetChainAccount, VaultTransfer, + DepositChannelLifetime, DepositChannelLookup, DepositChannelPool, DepositWitness, + DisabledEgressAssets, Error, Event as PalletEvent, FailedVaultTransfers, FetchOrTransfer, + MinimumDeposit, Pallet, ScheduledEgressCcm, ScheduledEgressFetchOrTransfer, TargetChainAccount, + VaultTransfer, }; use cf_chains::{ address::AddressConverter, evm::EvmFetchId, mocks::MockEthereum, CcmChannelMetadata, @@ -22,6 +23,7 @@ use cf_traits::{ use frame_support::{ assert_noop, assert_ok, traits::{Hooks, OriginTrait}, + weights::Weight, }; use sp_core::H160; @@ -29,7 +31,6 @@ const ALICE_ETH_ADDRESS: EthereumAddress = H160([100u8; 20]); const BOB_ETH_ADDRESS: EthereumAddress = H160([101u8; 20]); const ETH_ETH: eth::Asset = eth::Asset::Eth; const ETH_FLIP: eth::Asset = eth::Asset::Flip; -const EXPIRY_BLOCK: u64 = 6; #[track_caller] fn expect_size_of_address_pool(size: usize) { @@ -200,10 +201,8 @@ fn can_schedule_swap_egress_to_batch() { fn request_address_and_deposit( who: ChannelId, asset: eth::Asset, - expiry: u64, ) -> (ChannelId, ::ChainAccount) { - let (id, address) = - IngressEgress::request_liquidity_deposit_address(who, asset, expiry).unwrap(); + let (id, address) = IngressEgress::request_liquidity_deposit_address(who, asset).unwrap(); let address: ::ChainAccount = address.try_into().unwrap(); assert_ok!(IngressEgress::process_single_deposit( address, @@ -220,9 +219,9 @@ fn can_schedule_deposit_fetch() { new_test_ext().execute_with(|| { assert!(ScheduledEgressFetchOrTransfer::::get().is_empty()); - request_address_and_deposit(1u64, eth::Asset::Eth, 1_000u64); - request_address_and_deposit(2u64, eth::Asset::Eth, 1_000u64); - request_address_and_deposit(3u64, eth::Asset::Flip, 1_000u64); + request_address_and_deposit(1u64, eth::Asset::Eth); + request_address_and_deposit(2u64, eth::Asset::Eth); + request_address_and_deposit(3u64, eth::Asset::Flip); assert!(matches!( &ScheduledEgressFetchOrTransfer::::get()[..], @@ -237,7 +236,7 @@ fn can_schedule_deposit_fetch() { crate::Event::DepositFetchesScheduled { channel_id: 1, asset: eth::Asset::Eth }, )); - request_address_and_deposit(4u64, eth::Asset::Eth, 1_000u64); + request_address_and_deposit(4u64, eth::Asset::Eth); assert!(matches!( &ScheduledEgressFetchOrTransfer::::get()[..], @@ -258,16 +257,16 @@ fn on_finalize_can_send_batch_all() { IngressEgress::schedule_egress(ETH_ETH, 2_000, ALICE_ETH_ADDRESS, None); IngressEgress::schedule_egress(ETH_ETH, 3_000, BOB_ETH_ADDRESS, None); IngressEgress::schedule_egress(ETH_ETH, 4_000, BOB_ETH_ADDRESS, None); - request_address_and_deposit(1u64, eth::Asset::Eth, 1_000u64); - request_address_and_deposit(2u64, eth::Asset::Eth, 1_000u64); - request_address_and_deposit(3u64, eth::Asset::Eth, 1_000u64); - request_address_and_deposit(4u64, eth::Asset::Eth, 1_000u64); + request_address_and_deposit(1u64, eth::Asset::Eth); + request_address_and_deposit(2u64, eth::Asset::Eth); + request_address_and_deposit(3u64, eth::Asset::Eth); + request_address_and_deposit(4u64, eth::Asset::Eth); IngressEgress::schedule_egress(ETH_FLIP, 5_000, ALICE_ETH_ADDRESS, None); IngressEgress::schedule_egress(ETH_FLIP, 6_000, ALICE_ETH_ADDRESS, None); IngressEgress::schedule_egress(ETH_FLIP, 7_000, BOB_ETH_ADDRESS, None); IngressEgress::schedule_egress(ETH_FLIP, 8_000, BOB_ETH_ADDRESS, None); - request_address_and_deposit(5u64, eth::Asset::Flip, 1_000u64); + request_address_and_deposit(5u64, eth::Asset::Flip); // Take all scheduled Egress and Broadcast as batch IngressEgress::on_finalize(1); @@ -299,19 +298,19 @@ fn all_batch_apicall_creation_failure_should_rollback_storage() { IngressEgress::schedule_egress(ETH_ETH, 2_000, ALICE_ETH_ADDRESS, None); IngressEgress::schedule_egress(ETH_ETH, 3_000, BOB_ETH_ADDRESS, None); IngressEgress::schedule_egress(ETH_ETH, 4_000, BOB_ETH_ADDRESS, None); - request_address_and_deposit(1u64, eth::Asset::Eth, 1_000u64); - request_address_and_deposit(2u64, eth::Asset::Eth, 1_000u64); - request_address_and_deposit(3u64, eth::Asset::Eth, 1_000u64); - request_address_and_deposit(4u64, eth::Asset::Eth, 1_000u64); + request_address_and_deposit(1u64, eth::Asset::Eth); + request_address_and_deposit(2u64, eth::Asset::Eth); + request_address_and_deposit(3u64, eth::Asset::Eth); + request_address_and_deposit(4u64, eth::Asset::Eth); IngressEgress::schedule_egress(ETH_FLIP, 5_000, ALICE_ETH_ADDRESS, None); IngressEgress::schedule_egress(ETH_FLIP, 6_000, ALICE_ETH_ADDRESS, None); IngressEgress::schedule_egress(ETH_FLIP, 7_000, BOB_ETH_ADDRESS, None); IngressEgress::schedule_egress(ETH_FLIP, 8_000, BOB_ETH_ADDRESS, None); - request_address_and_deposit(5u64, eth::Asset::Flip, 1_000u64); + request_address_and_deposit(5u64, eth::Asset::Flip); MockAllBatch::::set_success(false); - request_address_and_deposit(4u64, eth::Asset::Usdc, 1_000u64); + request_address_and_deposit(4u64, eth::Asset::Usdc); let scheduled_requests = ScheduledEgressFetchOrTransfer::::get(); @@ -329,21 +328,10 @@ fn addresses_are_getting_reused() { // Request 2 deposit addresses and deposit to one of them. .request_address_and_deposit(&[ ( - DepositRequest::Liquidity { - lp_account: ALICE, - asset: eth::Asset::Eth, - expiry_block: 1000_u64, - }, + DepositRequest::Liquidity { lp_account: ALICE, asset: eth::Asset::Eth }, 100u32.into(), ), - ( - DepositRequest::Liquidity { - lp_account: ALICE, - asset: eth::Asset::Eth, - expiry_block: 1000_u64, - }, - 0u32.into(), - ), + (DepositRequest::Liquidity { lp_account: ALICE, asset: eth::Asset::Eth }, 0u32.into()), ]) .inspect_storage(|deposit_details| { assert_eq!(ChannelIdCounter::::get(), deposit_details.len() as u64); @@ -365,9 +353,10 @@ fn addresses_are_getting_reused() { channels }) .then_execute_at_next_block(|channels| { - for (_request, _id, address) in &channels { - IngressEgress::expire_channel(*address); - } + let recycle_block = BlockHeightProvider::::get_block_height() + + DepositChannelLifetime::::get() * 2; + BlockHeightProvider::::set_block_height(recycle_block); + channels[0].clone() }) // Check that the used address is now deployed and in the pool of available addresses. @@ -379,7 +368,6 @@ fn addresses_are_getting_reused() { .request_deposit_addresses(&[(DepositRequest::Liquidity { lp_account: ALICE, asset: eth::Asset::Eth, - expiry_block: 1000_u64, })]) // The address should have been taken from the pool and the id counter unchanged. .inspect_storage(|_| { @@ -392,18 +380,23 @@ fn addresses_are_getting_reused() { fn proof_address_pool_integrity() { new_test_ext().execute_with(|| { let channel_details = (0..3) - .map(|id| request_address_and_deposit(id, eth::Asset::Eth, 1_000u64)) + .map(|id| request_address_and_deposit(id, eth::Asset::Eth)) .collect::>(); // All addresses in use expect_size_of_address_pool(0); IngressEgress::on_finalize(1); for (_id, address) in channel_details { assert_ok!(IngressEgress::finalise_ingress(RuntimeOrigin::root(), vec![address])); - IngressEgress::expire_channel(address); } + let recycle_block = BlockHeightProvider::::get_block_height() + + DepositChannelLifetime::::get() * 2; + BlockHeightProvider::::set_block_height(recycle_block); + + IngressEgress::on_idle(1, Weight::MAX); + // Expect all addresses to be available expect_size_of_address_pool(3); - request_address_and_deposit(4u64, eth::Asset::Eth, 1_000u64); + request_address_and_deposit(4u64, eth::Asset::Eth); // Expect one address to be in use expect_size_of_address_pool(2); }); @@ -413,19 +406,21 @@ fn proof_address_pool_integrity() { fn create_new_address_while_pool_is_empty() { new_test_ext().execute_with(|| { let channel_details = (0..2) - .map(|id| request_address_and_deposit(id, eth::Asset::Eth, 1_000u64)) + .map(|id| request_address_and_deposit(id, eth::Asset::Eth)) .collect::>(); IngressEgress::on_finalize(1); for (_id, address) in channel_details { assert_ok!(IngressEgress::finalise_ingress(RuntimeOrigin::root(), vec![address])); - IngressEgress::expire_channel(address); } - IngressEgress::on_initialize(EXPIRY_BLOCK); + let recycle_block = BlockHeightProvider::::get_block_height() + + DepositChannelLifetime::::get() * 2; + BlockHeightProvider::::set_block_height(recycle_block); + IngressEgress::on_idle(1, Weight::MAX); + assert_eq!(ChannelIdCounter::::get(), 2); - request_address_and_deposit(3u64, eth::Asset::Eth, 1_000u64); + request_address_and_deposit(3u64, eth::Asset::Eth); assert_eq!(ChannelIdCounter::::get(), 2); IngressEgress::on_finalize(1); - IngressEgress::on_initialize(EXPIRY_BLOCK); assert_eq!(ChannelIdCounter::::get(), 2); }); } @@ -442,7 +437,6 @@ fn reused_address_channel_id_matches() { let (reused_channel_id, reused_address) = IngressEgress::open_channel( eth::Asset::Eth, ChannelAction::LiquidityProvision { lp_account: 0 }, - 1_000u64, ) .unwrap(); // The reused details should be the same as before. @@ -478,7 +472,6 @@ fn can_process_ccm_deposit() { 0, 1, Some(channel_metadata), - 1_000u64, ) .unwrap(); @@ -590,7 +583,7 @@ fn multi_use_deposit_address_different_blocks() { const ETH: eth::Asset = eth::Asset::Eth; new_test_ext() - .then_execute_at_next_block(|_| request_address_and_deposit(ALICE, ETH, 1_000u64)) + .then_execute_at_next_block(|_| request_address_and_deposit(ALICE, ETH)) .then_execute_at_next_block(|channel @ (_, deposit_address)| { // Set the address to deployed. // Do another, should succeed. @@ -601,11 +594,14 @@ fn multi_use_deposit_address_different_blocks() { (), Default::default() )); + let recycle_block = BlockHeightProvider::::get_block_height() + + DepositChannelLifetime::::get() * 2; + BlockHeightProvider::::set_block_height(recycle_block); + channel }) .then_execute_at_next_block(|(_, deposit_address)| { // Closing the channel should invalidate the deposit address. - IngressEgress::expire_channel(deposit_address); assert_noop!( IngressEgress::process_deposits( RuntimeOrigin::root(), @@ -628,11 +624,7 @@ fn multi_use_deposit_same_block() { const FLIP: eth::Asset = eth::Asset::Flip; const DEPOSIT_AMOUNT: ::ChainAmount = 1_000; new_test_ext() - .request_deposit_addresses(&[DepositRequest::Liquidity { - lp_account: ALICE, - asset: FLIP, - expiry_block: 1_000u64, - }]) + .request_deposit_addresses(&[DepositRequest::Liquidity { lp_account: ALICE, asset: FLIP }]) .map_context(|mut ctx| { assert!(ctx.len() == 1); ctx.pop().unwrap() @@ -785,7 +777,7 @@ fn deposits_below_minimum_are_rejected() { )); // Observe that eth deposit gets rejected. - let (_, deposit_address) = request_address_and_deposit(0, eth, 1_000u64); + let (_, deposit_address) = request_address_and_deposit(0, eth); System::assert_last_event(RuntimeEvent::IngressEgress( crate::Event::::DepositIgnored { deposit_address, @@ -796,7 +788,7 @@ fn deposits_below_minimum_are_rejected() { )); // Flip deposit should succeed. - let (_, deposit_address) = request_address_and_deposit(0, flip, 1_000u64); + let (_, deposit_address) = request_address_and_deposit(0, flip); System::assert_last_event(RuntimeEvent::IngressEgress( crate::Event::::DepositReceived { deposit_address, @@ -813,7 +805,7 @@ fn handle_pending_deployment() { const ETH: eth::Asset = eth::Asset::Eth; new_test_ext().execute_with(|| { // Initial request. - let (_, deposit_address) = request_address_and_deposit(ALICE, eth::Asset::Eth, 1_000u64); + let (_, deposit_address) = request_address_and_deposit(ALICE, eth::Asset::Eth); assert_eq!(ScheduledEgressFetchOrTransfer::::decode_len().unwrap_or_default(), 1); // Process deposits. IngressEgress::on_finalize(1); @@ -822,8 +814,8 @@ fn handle_pending_deployment() { Pallet::::process_single_deposit(deposit_address, ETH, 1, (), Default::default()) .unwrap(); // None-pending requests can still be sent - request_address_and_deposit(1u64, eth::Asset::Eth, 1_000u64); - request_address_and_deposit(2u64, eth::Asset::Eth, 1_000u64); + request_address_and_deposit(1u64, eth::Asset::Eth); + request_address_and_deposit(2u64, eth::Asset::Eth); assert_eq!(ScheduledEgressFetchOrTransfer::::decode_len().unwrap_or_default(), 3); // Process deposit again. IngressEgress::on_finalize(1); @@ -841,7 +833,7 @@ fn handle_pending_deployment() { fn handle_pending_deployment_same_block() { new_test_ext().execute_with(|| { // Initial request. - let (_, deposit_address) = request_address_and_deposit(ALICE, eth::Asset::Eth, 1_000u64); + let (_, deposit_address) = request_address_and_deposit(ALICE, eth::Asset::Eth); Pallet::::process_single_deposit( deposit_address, eth::Asset::Eth, @@ -877,7 +869,7 @@ fn channel_reuse_with_different_assets() { new_test_ext() // First, request a deposit address and use it, then close it so it gets recycled. .request_address_and_deposit(&[( - DepositRequest::Liquidity { lp_account: ALICE, asset: ASSET_1, expiry_block: 1_000u64 }, + DepositRequest::Liquidity { lp_account: ALICE, asset: ASSET_1 }, 100_000, )]) .map_context(|mut result| result.pop().unwrap()) @@ -894,8 +886,11 @@ fn channel_reuse_with_different_assets() { asset ); }) - .then_execute_at_next_block(|(_, channel_id, channel_address)| { - IngressEgress::expire_channel(channel_address); + // move forward expired blocks + .then_execute_at_next_block(|(_, channel_id, _)| { + let recycle_block = BlockHeightProvider::::get_block_height() + + DepositChannelLifetime::::get() * 2; + BlockHeightProvider::::set_block_height(recycle_block); channel_id }) .inspect_storage(|channel_id| { @@ -909,7 +904,6 @@ fn channel_reuse_with_different_assets() { .request_deposit_addresses(&[DepositRequest::Liquidity { lp_account: ALICE, asset: ASSET_2, - expiry_block: 1_000u64, }]) .map_context(|mut result| result.pop().unwrap()) // Ensure that the deposit channel's asset is updated. @@ -923,6 +917,28 @@ fn channel_reuse_with_different_assets() { }); } +/// This is the sequence we're testing. +/// 1. Request deposit address +/// 2. Deposit to address when it's almost expired +/// 3. The channel is expired +/// 4. We need to finalise the ingress, by fetching +/// 5. The fetch should succeed. +#[test] +fn ingress_finalisation_succeeds_after_channel_recycled() { + new_test_ext().execute_with(|| { + request_address_and_deposit(ALICE, eth::Asset::Eth); + + let recycle_block = BlockHeightProvider::::get_block_height() + + DepositChannelLifetime::::get() * 2; + BlockHeightProvider::::set_block_height(recycle_block); + IngressEgress::on_idle(1, Weight::MAX); + + IngressEgress::on_finalize(1); + + assert!(ScheduledEgressFetchOrTransfer::::get().is_empty()); + }); +} + #[test] fn can_store_failed_vault_transfers() { new_test_ext().execute_with(|| { @@ -953,8 +969,6 @@ fn basic_balance_tracking() { const ETH_DEPOSIT_AMOUNT: u128 = 1_000; const FLIP_DEPOSIT_AMOUNT: u128 = 2_000; const USDC_DEPOSIT_AMOUNT: u128 = 3_000; - // Expiry just needs to be sufficiently high so that it won't trigger. - const EXPIRY_BLOCK: u64 = 1_000; new_test_ext() .check_deposit_balances(&[ @@ -963,11 +977,7 @@ fn basic_balance_tracking() { (eth::Asset::Usdc, 0), ]) .request_address_and_deposit(&[( - DepositRequest::Liquidity { - lp_account: ALICE, - asset: eth::Asset::Eth, - expiry_block: EXPIRY_BLOCK, - }, + DepositRequest::Liquidity { lp_account: ALICE, asset: eth::Asset::Eth }, ETH_DEPOSIT_AMOUNT, )]) .check_deposit_balances(&[ @@ -976,11 +986,7 @@ fn basic_balance_tracking() { (eth::Asset::Usdc, 0), ]) .request_address_and_deposit(&[( - DepositRequest::Liquidity { - lp_account: ALICE, - asset: eth::Asset::Flip, - expiry_block: EXPIRY_BLOCK, - }, + DepositRequest::Liquidity { lp_account: ALICE, asset: eth::Asset::Flip }, FLIP_DEPOSIT_AMOUNT, )]) .check_deposit_balances(&[ @@ -989,11 +995,7 @@ fn basic_balance_tracking() { (eth::Asset::Usdc, 0), ]) .request_address_and_deposit(&[( - DepositRequest::Liquidity { - lp_account: ALICE, - asset: eth::Asset::Usdc, - expiry_block: EXPIRY_BLOCK, - }, + DepositRequest::Liquidity { lp_account: ALICE, asset: eth::Asset::Usdc }, USDC_DEPOSIT_AMOUNT, )]) .check_deposit_balances(&[ @@ -1002,11 +1004,7 @@ fn basic_balance_tracking() { (eth::Asset::Usdc, USDC_DEPOSIT_AMOUNT), ]) .request_address_and_deposit(&[( - DepositRequest::Liquidity { - lp_account: ALICE, - asset: eth::Asset::Eth, - expiry_block: EXPIRY_BLOCK, - }, + DepositRequest::Liquidity { lp_account: ALICE, asset: eth::Asset::Eth }, ETH_DEPOSIT_AMOUNT, )]) .check_deposit_balances(&[ @@ -1019,7 +1017,6 @@ fn basic_balance_tracking() { source_asset: eth::Asset::Eth, destination_asset: eth::Asset::Flip, destination_address: ForeignChainAddress::Eth(Default::default()), - expiry_block: EXPIRY_BLOCK, }, ETH_DEPOSIT_AMOUNT, )]) diff --git a/state-chain/pallets/cf-lp/src/benchmarking.rs b/state-chain/pallets/cf-lp/src/benchmarking.rs index a341899a2c4..9f6123a72f2 100644 --- a/state-chain/pallets/cf-lp/src/benchmarking.rs +++ b/state-chain/pallets/cf-lp/src/benchmarking.rs @@ -5,7 +5,7 @@ use cf_chains::{address::EncodedAddress, benchmarking_value::BenchmarkValue}; use cf_primitives::Asset; use cf_traits::AccountRoleRegistry; use frame_benchmarking::{benchmarks, whitelisted_caller}; -use frame_support::{assert_ok, dispatch::UnfilteredDispatchable, traits::OnNewAccount}; +use frame_support::{assert_ok, traits::OnNewAccount}; use frame_system::RawOrigin; benchmarks! { @@ -40,38 +40,6 @@ benchmarks! { verify { assert_ok!(T::AccountRoleRegistry::ensure_liquidity_provider(RawOrigin::Signed(caller).into())); } - - on_initialize { - let a in 1..100; - let caller: T::AccountId = whitelisted_caller(); - ::OnNewAccount::on_new_account(&caller); - let _ = Pallet::::register_lp_account(RawOrigin::Signed(caller.clone()).into()); - let _ = Pallet::::register_liquidity_refund_address( - RawOrigin::Signed(caller.clone()).into(), - EncodedAddress::Eth(Default::default()), - ); - for i in 0..a { - assert_ok!(Pallet::::request_liquidity_deposit_address(RawOrigin::Signed(caller.clone()).into(), Asset::Eth)); - } - let expiry = LpTTL::::get() + frame_system::Pallet::::current_block_number(); - assert!(!LiquidityChannelExpiries::::get(expiry).is_empty()); - }: { - Pallet::::on_initialize(expiry); - } verify { - assert!(LiquidityChannelExpiries::::get(expiry).is_empty()); - } - - set_lp_ttl { - let ttl = BlockNumberFor::::from(1_000u32); - let call = Call::::set_lp_ttl { - ttl, - }; - }: { - let _ = call.dispatch_bypass_filter(T::EnsureGovernance::try_successful_origin().unwrap()); - } verify { - assert_eq!(crate::LpTTL::::get(), ttl); - } - register_liquidity_refund_address { let caller: T::AccountId = whitelisted_caller(); ::OnNewAccount::on_new_account(&caller); diff --git a/state-chain/pallets/cf-lp/src/lib.rs b/state-chain/pallets/cf-lp/src/lib.rs index 5c112da763b..8f781fe1846 100644 --- a/state-chain/pallets/cf-lp/src/lib.rs +++ b/state-chain/pallets/cf-lp/src/lib.rs @@ -7,13 +7,9 @@ use cf_traits::{ impl_pallet_safe_mode, liquidity::LpBalanceApi, AccountRoleRegistry, Chainflip, DepositApi, EgressApi, }; -use frame_support::{ - pallet_prelude::*, - sp_runtime::{traits::BlockNumberProvider, DispatchResult, Saturating}, -}; +use frame_support::{pallet_prelude::*, sp_runtime::DispatchResult}; use frame_system::pallet_prelude::*; pub use pallet::*; -use sp_std::vec::Vec; mod benchmarking; @@ -83,21 +79,6 @@ pub mod pallet { WithdrawalsDisabled, } - #[pallet::hooks] - impl Hooks> for Pallet { - fn on_initialize(n: BlockNumberFor) -> Weight { - let expired = LiquidityChannelExpiries::::take(n); - let expired_count = expired.len(); - for (_, address) in expired { - T::DepositHandler::expire_channel(address.clone()); - Self::deposit_event(Event::LiquidityDepositAddressExpired { - address: T::AddressConverter::to_encoded_address(address), - }); - } - T::WeightInfo::on_initialize(expired_count as u32) - } - } - #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { @@ -115,22 +96,15 @@ pub mod pallet { channel_id: ChannelId, asset: Asset, deposit_address: EncodedAddress, - expiry_block: BlockNumberFor, // account the funds will be credited to upon deposit account_id: T::AccountId, }, - LiquidityDepositAddressExpired { - address: EncodedAddress, - }, WithdrawalEgressScheduled { egress_id: EgressId, asset: Asset, amount: AssetAmount, destination_address: EncodedAddress, }, - LpTtlSet { - ttl: BlockNumberFor, - }, LiquidityRefundAddressRegistered { account_id: T::AccountId, chain: ForeignChain, @@ -138,24 +112,6 @@ pub mod pallet { }, } - #[pallet::genesis_config] - pub struct GenesisConfig { - pub lp_ttl: BlockNumberFor, - } - - #[pallet::genesis_build] - impl BuildGenesisConfig for GenesisConfig { - fn build(&self) { - LpTTL::::put(self.lp_ttl); - } - } - - impl Default for GenesisConfig { - fn default() -> Self { - Self { lp_ttl: BlockNumberFor::::from(1200u32) } - } - } - #[pallet::pallet] #[pallet::without_storage_info] pub struct Pallet(PhantomData); @@ -165,18 +121,7 @@ pub mod pallet { pub type FreeBalances = StorageDoubleMap<_, Twox64Concat, T::AccountId, Identity, Asset, AssetAmount>; - /// For a given block number, stores the list of liquidity deposit channels that expire at that - /// block. - #[pallet::storage] - pub(super) type LiquidityChannelExpiries = StorageMap< - _, - Twox64Concat, - BlockNumberFor, - Vec<(ChannelId, cf_chains::ForeignChainAddress)>, - ValueQuery, - >; - - /// Stores the registered refund address for an Account + /// Stores the registered energency withdrawal address for an Account #[pallet::storage] pub type LiquidityRefundAddress = StorageDoubleMap< _, @@ -187,10 +132,6 @@ pub mod pallet { ForeignChainAddress, >; - /// The TTL for liquidity channels. - #[pallet::storage] - pub type LpTTL = StorageValue<_, BlockNumberFor, ValueQuery>; - #[pallet::call] impl Pallet { /// For when the user wants to deposit assets into the Chain. @@ -210,26 +151,13 @@ pub mod pallet { Error::::NoLiquidityRefundAddressRegistered ); - let expiry_block = - frame_system::Pallet::::current_block_number().saturating_add(LpTTL::::get()); - let (channel_id, deposit_address) = - T::DepositHandler::request_liquidity_deposit_address( - account_id.clone(), - asset, - expiry_block, - )?; - - LiquidityChannelExpiries::::append( - expiry_block, - (channel_id, deposit_address.clone()), - ); + T::DepositHandler::request_liquidity_deposit_address(account_id.clone(), asset)?; Self::deposit_event(Event::LiquidityDepositAddressReady { channel_id, asset, deposit_address: T::AddressConverter::to_encoded_address(deposit_address), - expiry_block, account_id, }); @@ -296,23 +224,6 @@ pub mod pallet { Ok(()) } - /// Sets the lifetime of liquidity deposit channels. - /// - /// Requires Governance - /// - /// ## Events - /// - /// - [On update](Event::LpTtlSet) - #[pallet::call_index(3)] - #[pallet::weight(T::WeightInfo::set_lp_ttl())] - pub fn set_lp_ttl(origin: OriginFor, ttl: BlockNumberFor) -> DispatchResult { - T::EnsureGovernance::ensure_origin(origin)?; - LpTTL::::set(ttl); - - Self::deposit_event(Event::::LpTtlSet { ttl }); - Ok(()) - } - /// Registers an Liquidity Refund Address(LRA) for an account. /// To request deposit address for a chain, an LRA must be registered for that chain. /// diff --git a/state-chain/pallets/cf-lp/src/tests.rs b/state-chain/pallets/cf-lp/src/tests.rs index 8b1731dcea4..57b99deb447 100644 --- a/state-chain/pallets/cf-lp/src/tests.rs +++ b/state-chain/pallets/cf-lp/src/tests.rs @@ -1,20 +1,11 @@ -use crate::{mock::*, FreeBalances, LiquidityChannelExpiries, LiquidityRefundAddress, LpTTL}; +use crate::{mock::*, FreeBalances, LiquidityRefundAddress}; -use cf_chains::{ - address::{AddressConverter, EncodedAddress}, - AnyChain, ForeignChainAddress, -}; +use cf_chains::{address::EncodedAddress, ForeignChainAddress}; use cf_primitives::{AccountId, Asset, ForeignChain}; use cf_test_utilities::assert_events_match; -use cf_traits::{ - mocks::{ - address_converter::MockAddressConverter, - deposit_handler::{LpChannel, MockDepositHandler}, - }, - SetSafeMode, -}; -use frame_support::{assert_noop, assert_ok, error::BadOrigin, traits::Hooks}; +use cf_traits::SetSafeMode; +use frame_support::{assert_noop, assert_ok, error::BadOrigin}; #[test] fn egress_chain_and_asset_must_match() { @@ -118,75 +109,6 @@ fn cannot_deposit_and_withdrawal_during_safe_mode() { }); } -#[test] -fn deposit_channel_expires() { - new_test_ext().execute_with(|| { - assert_ok!(LiquidityProvider::register_liquidity_refund_address( - RuntimeOrigin::signed(LP_ACCOUNT.into()), - EncodedAddress::Eth(Default::default()), - )); - // Expiry = current (1) + ttl - let expiry = LpTTL::::get() + 1; - let asset = Asset::Eth; - assert_ok!(LiquidityProvider::request_liquidity_deposit_address( - RuntimeOrigin::signed(LP_ACCOUNT.into()), - asset, - )); - - let (channel_id, deposit_address) = assert_events_match!(Test, RuntimeEvent::LiquidityProvider(crate::Event::LiquidityDepositAddressReady { - asset: event_asset, - channel_id, - deposit_address, - expiry_block, - account_id, - }) if expiry_block == expiry && event_asset == asset && account_id == LP_ACCOUNT.into() => (channel_id, deposit_address)); - let lp_channel = LpChannel { - deposit_address: MockAddressConverter::try_from_encoded_address(deposit_address.clone()).unwrap(), - source_asset: asset, - lp_account: LP_ACCOUNT.into(), - expiry, - }; - - assert_eq!( - LiquidityChannelExpiries::::get(expiry), - vec![(channel_id, MockAddressConverter::try_from_encoded_address(deposit_address.clone()).unwrap())] - ); - assert_eq!( - MockDepositHandler::::get_liquidity_channels(), - vec![lp_channel.clone()] - ); - - // Does not expire until expiry - LiquidityProvider::on_initialize(expiry - 1); - assert_eq!( - LiquidityChannelExpiries::::get(expiry), - vec![(channel_id, MockAddressConverter::try_from_encoded_address(deposit_address.clone()).unwrap())] - ); - assert_eq!( - MockDepositHandler::::get_liquidity_channels(), - vec![lp_channel] - ); - - // Expire the address on the expiry block - LiquidityProvider::on_initialize(expiry); - - assert_eq!(LiquidityChannelExpiries::::get(expiry), vec![]); - System::assert_last_event(RuntimeEvent::LiquidityProvider( - crate::Event::::LiquidityDepositAddressExpired { address: deposit_address }, - )); - assert!(MockDepositHandler::::get_liquidity_channels().is_empty()); - }); -} - -#[test] -fn can_set_lp_ttl() { - new_test_ext().execute_with(|| { - assert_eq!(LpTTL::::get(), 1_200); - assert_ok!(LiquidityProvider::set_lp_ttl(RuntimeOrigin::root(), 10)); - assert_eq!(LpTTL::::get(), 10); - }); -} - #[test] fn can_register_and_deregister_liquidity_refund_address() { new_test_ext().execute_with(|| { diff --git a/state-chain/pallets/cf-swapping/src/benchmarking.rs b/state-chain/pallets/cf-swapping/src/benchmarking.rs index 0440e2cb7fc..ba5ce5a8b25 100644 --- a/state-chain/pallets/cf-swapping/src/benchmarking.rs +++ b/state-chain/pallets/cf-swapping/src/benchmarking.rs @@ -123,41 +123,6 @@ benchmarks! { )]); } - on_initialize { - let a in 1..100; - let caller: T::AccountId = whitelisted_caller(); - ::OnNewAccount::on_new_account(&caller); - T::AccountRoleRegistry::register_as_broker(&caller).unwrap(); - let origin = RawOrigin::Signed(caller); - for i in 0..a { - let call = Call::::request_swap_deposit_address{ - source_asset: Asset::Usdc, - destination_asset: Asset::Eth, - destination_address: EncodedAddress::Eth(Default::default()), - broker_commission_bps: Default::default(), - channel_metadata: None, - }; - call.dispatch_bypass_filter(origin.clone().into())?; - } - let expiry = SwapTTL::::get() + frame_system::Pallet::::current_block_number(); - assert!(!SwapChannelExpiries::::get(expiry).is_empty()); - }: { - Pallet::::on_initialize(expiry); - } verify { - assert!(SwapChannelExpiries::::get(expiry).is_empty()); - } - - set_swap_ttl { - let ttl = BlockNumberFor::::from(1_000u32); - let call = Call::::set_swap_ttl { - ttl - }; - }: { - let _ = call.dispatch_bypass_filter(::EnsureGovernance::try_successful_origin().unwrap()); - } verify { - assert_eq!(crate::SwapTTL::::get(), ttl); - } - set_minimum_swap_amount { let asset = Asset::Eth; let amount = 1_000; diff --git a/state-chain/pallets/cf-swapping/src/lib.rs b/state-chain/pallets/cf-swapping/src/lib.rs index 488a68918c9..3cd21a03705 100644 --- a/state-chain/pallets/cf-swapping/src/lib.rs +++ b/state-chain/pallets/cf-swapping/src/lib.rs @@ -7,14 +7,17 @@ use cf_primitives::{ Asset, AssetAmount, ChannelId, ForeignChain, SwapLeg, TransactionHash, STABLE_ASSET, }; use cf_traits::{impl_pallet_safe_mode, liquidity::SwappingApi, CcmHandler, DepositApi}; -use frame_support::{pallet_prelude::*, storage::with_storage_layer}; +use frame_support::{ + pallet_prelude::*, + sp_runtime::{ + traits::{Get, Saturating}, + DispatchError, Permill, + }, + storage::with_storage_layer, +}; use frame_system::pallet_prelude::*; pub use pallet::*; use sp_arithmetic::{helpers_128bit::multiply_by_rational_with_rounding, traits::Zero, Rounding}; -use sp_runtime::{ - traits::{BlockNumberProvider, Get, Saturating}, - DispatchError, Permill, -}; use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec}; #[cfg(test)] @@ -223,23 +226,10 @@ pub mod pallet { #[pallet::storage] pub type CcmGasBudget = StorageMap<_, Twox64Concat, u64, (Asset, AssetAmount)>; - /// Stores the swap TTL in blocks. - #[pallet::storage] - pub type SwapTTL = StorageValue<_, BlockNumberFor, ValueQuery>; - /// Storage for storing CCMs pending assets to be swapped. #[pallet::storage] pub(crate) type PendingCcms = StorageMap<_, Twox64Concat, u64, CcmSwap>; - /// For a given block number, stores the list of swap channels that expire at that block. - #[pallet::storage] - pub type SwapChannelExpiries = StorageMap< - _, - Twox64Concat, - BlockNumberFor, - Vec<(ChannelId, ForeignChainAddress)>, - ValueQuery, - >; /// Tracks the outputs of Ccm swaps. #[pallet::storage] pub(crate) type CcmOutputs = StorageMap<_, Twox64Concat, u64, CcmSwapOutput>; @@ -262,7 +252,6 @@ pub mod pallet { SwapDepositAddressReady { deposit_address: EncodedAddress, destination_address: EncodedAddress, - expiry_block: BlockNumberFor, source_asset: Asset, destination_asset: Asset, channel_id: ChannelId, @@ -313,13 +302,6 @@ pub mod pallet { ccm_id: u64, egress_id: EgressId, }, - SwapDepositAddressExpired { - deposit_address: EncodedAddress, - channel_id: ChannelId, - }, - SwapTtlSet { - ttl: BlockNumberFor, - }, CcmDepositReceived { ccm_id: u64, principal_swap_id: Option, @@ -370,14 +352,13 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig { - pub swap_ttl: BlockNumberFor, pub minimum_swap_amounts: Vec<(Asset, AssetAmount)>, + pub _phantom: PhantomData, } #[pallet::genesis_build] impl BuildGenesisConfig for GenesisConfig { fn build(&self) { - SwapTTL::::put(self.swap_ttl); for (asset, min) in &self.minimum_swap_amounts { MinimumSwapAmount::::insert(asset, min); } @@ -386,27 +367,12 @@ pub mod pallet { impl Default for GenesisConfig { fn default() -> Self { - // 1200 = 2 hours (6 sec per block) - Self { swap_ttl: BlockNumberFor::::from(1_200u32), minimum_swap_amounts: vec![] } + Self { minimum_swap_amounts: vec![], _phantom: PhantomData } } } #[pallet::hooks] impl Hooks> for Pallet { - /// Clean up expired deposit channels - fn on_initialize(n: BlockNumberFor) -> Weight { - let expired = SwapChannelExpiries::::take(n); - let expired_count = expired.len(); - for (channel_id, address) in expired { - T::DepositHandler::expire_channel(address.clone()); - Self::deposit_event(Event::::SwapDepositAddressExpired { - deposit_address: T::AddressConverter::to_encoded_address(address), - channel_id, - }); - } - T::WeightInfo::on_initialize(expired_count as u32) - } - /// Execute all swaps in the SwapQueue fn on_finalize(_n: BlockNumberFor) { if !T::SafeMode::get().swaps_enabled { @@ -528,9 +494,6 @@ pub mod pallet { ); } - let expiry_block = frame_system::Pallet::::current_block_number() - .saturating_add(SwapTTL::::get()); - let (channel_id, deposit_address) = T::DepositHandler::request_swap_deposit_address( source_asset, destination_asset, @@ -538,15 +501,11 @@ pub mod pallet { broker_commission_bps, broker, channel_metadata.clone(), - expiry_block, )?; - SwapChannelExpiries::::append(expiry_block, (channel_id, deposit_address.clone())); - Self::deposit_event(Event::::SwapDepositAddressReady { deposit_address: T::AddressConverter::to_encoded_address(deposit_address), destination_address, - expiry_block, source_asset, destination_asset, channel_id, @@ -684,23 +643,6 @@ pub mod pallet { Ok(()) } - /// Sets the lifetime of swap channels. - /// - /// Requires Governance. - /// - /// ## Events - /// - /// - [On update](Event::SwapTtlSet) - #[pallet::call_index(5)] - #[pallet::weight(T::WeightInfo::set_swap_ttl())] - pub fn set_swap_ttl(origin: OriginFor, ttl: BlockNumberFor) -> DispatchResult { - T::EnsureGovernance::ensure_origin(origin)?; - SwapTTL::::set(ttl); - - Self::deposit_event(Event::::SwapTtlSet { ttl }); - Ok(()) - } - /// Sets the Minimum swap amount allowed for an asset. /// /// Requires Governance. diff --git a/state-chain/pallets/cf-swapping/src/mock.rs b/state-chain/pallets/cf-swapping/src/mock.rs index 11c57c0a83b..37799067375 100644 --- a/state-chain/pallets/cf-swapping/src/mock.rs +++ b/state-chain/pallets/cf-swapping/src/mock.rs @@ -1,3 +1,5 @@ +use core::marker::PhantomData; + use crate::{self as pallet_cf_swapping, PalletSafeMode, WeightInfo}; use cf_chains::AnyChain; use cf_primitives::{Asset, AssetAmount}; @@ -112,10 +114,6 @@ impl WeightInfo for MockWeightInfo { Weight::from_parts(100, 0) } - fn set_swap_ttl() -> Weight { - Weight::from_parts(100, 0) - } - fn set_minimum_swap_amount() -> Weight { Weight::from_parts(100, 0) } @@ -137,7 +135,7 @@ cf_test_utilities::impl_test_helpers! { Test, RuntimeGenesisConfig { system: Default::default(), - swapping: SwappingConfig { swap_ttl: 5, minimum_swap_amounts: vec![] }, + swapping: SwappingConfig { minimum_swap_amounts: vec![], _phantom: PhantomData }, }, || { >::register_as_broker(&ALICE).unwrap(); diff --git a/state-chain/pallets/cf-swapping/src/tests.rs b/state-chain/pallets/cf-swapping/src/tests.rs index 2e9943a0191..4f08a0fb31b 100644 --- a/state-chain/pallets/cf-swapping/src/tests.rs +++ b/state-chain/pallets/cf-swapping/src/tests.rs @@ -2,7 +2,7 @@ use crate::{ mock::{RuntimeEvent, *}, CcmFailReason, CcmGasBudget, CcmIdCounter, CcmOutputs, CcmSwap, CcmSwapOutput, CollectedRejectedFunds, EarnedBrokerFees, Error, Event, MinimumSwapAmount, Pallet, PendingCcms, - Swap, SwapChannelExpiries, SwapOrigin, SwapQueue, SwapTTL, SwapType, + Swap, SwapOrigin, SwapQueue, SwapType, }; use cf_chains::{ address::{to_encoded_address, AddressConverter, EncodedAddress, ForeignChainAddress}, @@ -11,11 +11,10 @@ use cf_chains::{ AnyChain, CcmChannelMetadata, CcmDepositMetadata, }; use cf_primitives::{Asset, AssetAmount, ForeignChain, NetworkEnvironment}; -use cf_test_utilities::{assert_event_sequence, assert_events_match}; +use cf_test_utilities::assert_event_sequence; use cf_traits::{ mocks::{ address_converter::MockAddressConverter, - deposit_handler::{MockDepositHandler, SwapChannel}, egress_handler::{MockEgressHandler, MockEgressParameter}, }, CcmHandler, SetSafeMode, SwapDepositHandler, SwappingApi, @@ -23,7 +22,6 @@ use cf_traits::{ use frame_support::{assert_noop, assert_ok, sp_std::iter}; use frame_support::traits::Hooks; -use sp_runtime::traits::BlockNumberProvider; // Returns some test data fn generate_test_swaps() -> Vec { @@ -229,12 +227,11 @@ fn expect_swap_id_to_be_emitted() { RuntimeEvent::Swapping(Event::SwapDepositAddressReady { deposit_address: EncodedAddress::Eth(..), destination_address: EncodedAddress::Eth(..), - expiry_block, source_asset: Asset::Eth, destination_asset: Asset::Usdc, channel_id: 0, .. - }) if expiry_block == SwapTTL::::get() + System::current_block_number(), + }), RuntimeEvent::Swapping(Event::SwapScheduled { swap_id: 1, source_asset: Asset::Eth, @@ -246,7 +243,9 @@ fn expect_swap_id_to_be_emitted() { channel_id: 1, deposit_block_height: 0 }, - swap_type: SwapType::Swap(ForeignChainAddress::Eth(..)), broker_commission: _ }), + swap_type: SwapType::Swap(ForeignChainAddress::Eth(..)), + broker_commission: _ + }), RuntimeEvent::Swapping(Event::SwapExecuted { swap_id: 1, .. }), RuntimeEvent::Swapping(Event::SwapEgressScheduled { swap_id: 1, @@ -315,78 +314,6 @@ fn can_swap_using_witness_origin() { }); } -#[test] -fn swap_expires() { - new_test_ext().execute_with(|| { - let expiry = SwapTTL::::get() + 1; - assert_eq!(expiry, 6); // Expiry = current(1) + TTL (5) - assert_ok!(Swapping::request_swap_deposit_address( - RuntimeOrigin::signed(ALICE), - Asset::Eth, - Asset::Usdc, - EncodedAddress::Eth(Default::default()), - 0, - None - )); - - let deposit_address = assert_events_match!(Test, RuntimeEvent::Swapping(Event::SwapDepositAddressReady { - deposit_address, - .. - }) => deposit_address); - let swap_channel = SwapChannel { - deposit_address: MockAddressConverter::try_from_encoded_address(deposit_address).unwrap(), - source_asset: Asset::Eth, - destination_asset: Asset::Usdc, - destination_address: ForeignChainAddress::Eth(Default::default()), - broker_commission_bps: 0, - broker_id: ALICE, - channel_metadata: None, - expiry, - }; - - assert_eq!( - SwapChannelExpiries::::get(expiry), - vec![(0, ForeignChainAddress::Eth(Default::default()))] - ); - assert_eq!( - MockDepositHandler::::get_swap_channels(), - vec![swap_channel.clone()] - ); - - // Does not expire until expiry block. - Swapping::on_initialize(expiry - 1); - assert_eq!( - SwapChannelExpiries::::get(expiry), - vec![(0, ForeignChainAddress::Eth(Default::default()))] - ); - assert_eq!( - MockDepositHandler::::get_swap_channels(), - vec![swap_channel] - ); - - Swapping::on_initialize(6); - assert_eq!(SwapChannelExpiries::::get(6), vec![]); - System::assert_last_event(RuntimeEvent::Swapping( - Event::::SwapDepositAddressExpired { - deposit_address: EncodedAddress::Eth(Default::default()), - channel_id: 0, - }, - )); - assert!( - MockDepositHandler::::get_swap_channels().is_empty() - ); - }); -} - -#[test] -fn can_set_swap_ttl() { - new_test_ext().execute_with(|| { - assert_eq!(crate::SwapTTL::::get(), 5); - assert_ok!(Swapping::set_swap_ttl(RuntimeOrigin::root(), 10)); - assert_eq!(crate::SwapTTL::::get(), 10); - }); -} - #[test] fn reject_invalid_ccm_deposit() { new_test_ext().execute_with(|| { diff --git a/state-chain/pallets/cf-swapping/src/weights.rs b/state-chain/pallets/cf-swapping/src/weights.rs index e3a61e8c1a2..8614b2a5e38 100644 --- a/state-chain/pallets/cf-swapping/src/weights.rs +++ b/state-chain/pallets/cf-swapping/src/weights.rs @@ -36,7 +36,6 @@ pub trait WeightInfo { fn schedule_swap_from_contract() -> Weight; fn ccm_deposit() -> Weight; fn on_initialize(a: u32, ) -> Weight; - fn set_swap_ttl() -> Weight; fn set_minimum_swap_amount() -> Weight; } @@ -48,7 +47,6 @@ impl WeightInfo for PalletWeight { // Storage: EthereumIngressEgress ChannelIdCounter (r:1 w:1) // Storage: Environment EthereumVaultAddress (r:1 w:0) // Storage: Swapping SwapTTL (r:1 w:0) - // Storage: Swapping SwapChannelExpiries (r:1 w:1) // Storage: EthereumIngressEgress ChannelActions (r:0 w:1) // Storage: EthereumIngressEgress FetchParamDetails (r:0 w:1) // Storage: EthereumIngressEgress AddressStatus (r:0 w:1) @@ -91,7 +89,6 @@ impl WeightInfo for PalletWeight { .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(5)) } - // Storage: Swapping SwapChannelExpiries (r:1 w:1) // Storage: EthereumIngressEgress AddressStatus (r:1 w:0) // Storage: EthereumIngressEgress DepositAddressDetailsLookup (r:1 w:1) // Storage: EthereumIngressEgress ChannelActions (r:0 w:1) @@ -106,12 +103,6 @@ impl WeightInfo for PalletWeight { .saturating_add(T::DbWeight::get().writes(1)) .saturating_add(T::DbWeight::get().writes((2_u64).saturating_mul(a.into()))) } - // Storage: Swapping SwapTTL (r:0 w:1) - fn set_swap_ttl() -> Weight { - // Minimum execution time: 13_000 nanoseconds. - Weight::from_parts(14_000_000, 0) - .saturating_add(T::DbWeight::get().writes(1)) - } // Storage: AccountRoles SwappingEnabled (r:1 w:0) // Storage: AccountRoles AccountRoles (r:1 w:1) fn register_as_broker() -> Weight { @@ -133,7 +124,6 @@ impl WeightInfo for () { // Storage: EthereumIngressEgress ChannelIdCounter (r:1 w:1) // Storage: Environment EthereumVaultAddress (r:1 w:0) // Storage: Swapping SwapTTL (r:1 w:0) - // Storage: Swapping SwapChannelExpiries (r:1 w:1) // Storage: EthereumIngressEgress ChannelActions (r:0 w:1) // Storage: EthereumIngressEgress FetchParamDetails (r:0 w:1) // Storage: EthereumIngressEgress AddressStatus (r:0 w:1) @@ -176,7 +166,6 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(3)) .saturating_add(RocksDbWeight::get().writes(5)) } - // Storage: Swapping SwapChannelExpiries (r:1 w:1) // Storage: EthereumIngressEgress AddressStatus (r:1 w:0) // Storage: EthereumIngressEgress DepositAddressDetailsLookup (r:1 w:1) // Storage: EthereumIngressEgress ChannelActions (r:0 w:1) @@ -191,12 +180,6 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().writes(1)) .saturating_add(RocksDbWeight::get().writes((2_u64).saturating_mul(a.into()))) } - // Storage: Swapping SwapTTL (r:0 w:1) - fn set_swap_ttl() -> Weight { - // Minimum execution time: 13_000 nanoseconds. - Weight::from_parts(14_000_000, 0) - .saturating_add(RocksDbWeight::get().writes(1)) - } // Storage: AccountRoles SwappingEnabled (r:1 w:0) // Storage: AccountRoles AccountRoles (r:1 w:1) fn register_as_broker() -> Weight { diff --git a/state-chain/runtime/src/chainflip.rs b/state-chain/runtime/src/chainflip.rs index 29ede494021..d1bfd70fdd1 100644 --- a/state-chain/runtime/src/chainflip.rs +++ b/state-chain/runtime/src/chainflip.rs @@ -475,7 +475,6 @@ macro_rules! impl_deposit_api_for_anychain { fn request_liquidity_deposit_address( lp_account: Self::AccountId, source_asset: Asset, - expiry: Self::BlockNumber, ) -> Result<(ChannelId, ForeignChainAddress), DispatchError> { match source_asset.into() { $( @@ -483,7 +482,6 @@ macro_rules! impl_deposit_api_for_anychain { $pallet::request_liquidity_deposit_address( lp_account, source_asset.try_into().unwrap(), - expiry, ), )+ } @@ -496,7 +494,6 @@ macro_rules! impl_deposit_api_for_anychain { broker_commission_bps: BasisPoints, broker_id: Self::AccountId, channel_metadata: Option, - expiry: Self::BlockNumber, ) -> Result<(ChannelId, ForeignChainAddress), DispatchError> { match source_asset.into() { $( @@ -507,23 +504,10 @@ macro_rules! impl_deposit_api_for_anychain { broker_commission_bps, broker_id, channel_metadata, - expiry, ), )+ } } - - fn expire_channel(address: ForeignChainAddress) { - match address.chain() { - $( - ForeignChain::$chain => { - <$pallet as DepositApi<$chain>>::expire_channel( - address.try_into().expect("Checked for address compatibility") - ); - }, - )+ - } - } } } } diff --git a/state-chain/traits/src/lib.rs b/state-chain/traits/src/lib.rs index 52f36cb51e3..6498b052ab7 100644 --- a/state-chain/traits/src/lib.rs +++ b/state-chain/traits/src/lib.rs @@ -640,7 +640,6 @@ pub trait DepositApi { fn request_liquidity_deposit_address( lp_account: Self::AccountId, source_asset: C::ChainAsset, - expiry: Self::BlockNumber, ) -> Result<(ChannelId, ForeignChainAddress), DispatchError>; /// Issues a channel id and deposit address for a new swap. @@ -651,11 +650,7 @@ pub trait DepositApi { broker_commission_bps: BasisPoints, broker_id: Self::AccountId, channel_metadata: Option, - expiry: Self::BlockNumber, ) -> Result<(ChannelId, ForeignChainAddress), DispatchError>; - - /// Expires a channel. - fn expire_channel(address: C::ChainAccount); } pub trait AccountRoleRegistry { diff --git a/state-chain/traits/src/mocks/deposit_handler.rs b/state-chain/traits/src/mocks/deposit_handler.rs index 185d3f8e56c..27b6e19a00b 100644 --- a/state-chain/traits/src/mocks/deposit_handler.rs +++ b/state-chain/traits/src/mocks/deposit_handler.rs @@ -30,7 +30,6 @@ pub struct SwapChannel { pub broker_commission_bps: BasisPoints, pub broker_id: ::AccountId, pub channel_metadata: Option, - pub expiry: BlockNumberFor, } #[derive(Clone, Debug, PartialEq, Eq, Encode, Decode, TypeInfo)] @@ -38,7 +37,6 @@ pub struct LpChannel { pub deposit_address: ForeignChainAddress, pub source_asset: ::ChainAsset, pub lp_account: ::AccountId, - pub expiry: BlockNumberFor, } impl MockDepositHandler { @@ -85,7 +83,6 @@ impl DepositApi for MockDepositHandler { fn request_liquidity_deposit_address( lp_account: Self::AccountId, source_asset: ::ChainAsset, - expiry: Self::BlockNumber, ) -> Result<(cf_primitives::ChannelId, ForeignChainAddress), sp_runtime::DispatchError> { let (channel_id, deposit_address) = Self::get_new_deposit_address(SwapOrLp::Lp, source_asset); @@ -98,7 +95,6 @@ impl DepositApi for MockDepositHandler { deposit_address: deposit_address.clone(), source_asset, lp_account, - expiry, }); } }); @@ -112,7 +108,6 @@ impl DepositApi for MockDepositHandler { broker_commission_bps: BasisPoints, broker_id: Self::AccountId, channel_metadata: Option, - expiry: Self::BlockNumber, ) -> Result<(cf_primitives::ChannelId, ForeignChainAddress), sp_runtime::DispatchError> { let (channel_id, deposit_address) = Self::get_new_deposit_address(SwapOrLp::Swap, source_asset); @@ -129,29 +124,9 @@ impl DepositApi for MockDepositHandler { broker_commission_bps, broker_id, channel_metadata, - expiry, }); }; }); Ok((channel_id, deposit_address)) } - - fn expire_channel(address: ::ChainAccount) { - ::mutate_value( - b"SWAP_INGRESS_CHANNELS", - |storage: &mut Option>>| { - if let Some(inner) = storage.as_mut() { - inner.retain(|x| x.deposit_address != address.clone().into()); - } - }, - ); - ::mutate_value( - b"LP_INGRESS_CHANNELS", - |storage: &mut Option>>| { - if let Some(inner) = storage.as_mut() { - inner.retain(|x| x.deposit_address != address.clone().into()); - } - }, - ); - } }