Skip to content

Commit

Permalink
chore: remove unused StartWitnessing and StopWitnessing events (#3995)
Browse files Browse the repository at this point in the history
* refactor: use trait in tests

* chore: remove unused events


chore: clean up

* feat: add account_id to the LiquidityDepositAddressReady event

* chore: fmt

* chore: clippy
  • Loading branch information
kylezs authored and dandanlen committed Sep 28, 2023
1 parent 48ffd71 commit 1a9c991
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 84 deletions.
30 changes: 12 additions & 18 deletions bouncer/shared/provide_liquidity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { send } from '../shared/send';
export async function provideLiquidity(ccy: Asset, amount: number) {
const chainflip = await getChainflipApi();
await cryptoWaitReady();
const chain = assetToChain(ccy);

const keyring = new Keyring({ type: 'sr25519' });
const lpUri = process.env.LP_URI || '//LP_1';
Expand All @@ -29,39 +30,31 @@ export async function provideLiquidity(ccy: Asset, amount: number) {
)
).toJSON() === null
) {
let refundAddress = await newAddress(assetToChain(ccy).toUpperCase() as Asset, 'LP_1');
let refundAddress = await newAddress(chain.toUpperCase() as Asset, 'LP_1');
refundAddress = ccy === 'DOT' ? decodeDotAddressForContract(refundAddress) : refundAddress;

console.log('Registering Liquidity Refund Address for ' + ccy + ': ' + refundAddress);
await lpMutex.runExclusive(async () => {
await chainflip.tx.liquidityProvider
.registerLiquidityRefundAddress({ [assetToChain(ccy)]: refundAddress })
.registerLiquidityRefundAddress({ [chain]: refundAddress })
.signAndSend(lp, { nonce: -1 }, handleSubstrateError(chainflip));
});
}

let eventHandle = observeEvent(
'liquidityProvider:LiquidityDepositAddressReady',
chainflip,
(event) => event.data.asset.toUpperCase() === ccy,
);

console.log('Requesting ' + ccy + ' deposit address');
let eventHandle =
assetToChain(ccy) === 'Eth'
? observeEvent(
'ethereumIngressEgress:StartWitnessing',
chainflip,
(event) => event.data.sourceAsset.toUpperCase() === ccy,
)
: observeEvent(
'liquidityProvider:LiquidityDepositAddressReady',
chainflip,
(event) => event.data.depositAddress[assetToChain(ccy)] !== undefined,
);
await lpMutex.runExclusive(async () => {
await chainflip.tx.liquidityProvider
.requestLiquidityDepositAddress(ccy.toLowerCase())
.signAndSend(lp, { nonce: -1 }, handleSubstrateError(chainflip));
});
const ingressAddress =
assetToChain(ccy) === 'Eth'
? (await eventHandle).data.depositAddress
: (await eventHandle).data.depositAddress[assetToChain(ccy)];

const ingressAddress = (await eventHandle).data.depositAddress[chain];

console.log('Received ' + ccy + ' address: ' + ingressAddress);
console.log('Sending ' + amount + ' ' + ccy + ' to ' + ingressAddress);
Expand All @@ -71,5 +64,6 @@ export async function provideLiquidity(ccy: Asset, amount: number) {
(event) => event.data.asset.toUpperCase() === ccy,
);
send(ccy, ingressAddress, String(amount));

await eventHandle;
}
9 changes: 1 addition & 8 deletions state-chain/cf-integration-tests/src/swapping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use cf_chains::{
};
use cf_primitives::{AccountId, AccountRole, Asset, AssetAmount, STABLE_ASSET};
use cf_test_utilities::{assert_events_eq, assert_events_match};
use cf_traits::{AccountRoleRegistry, EpochInfo, GetBlockHeight, LpBalanceApi};
use cf_traits::{AccountRoleRegistry, EpochInfo, LpBalanceApi};
use frame_support::{
assert_ok,
traits::{OnFinalize, OnIdle, OnNewAccount},
Expand All @@ -24,8 +24,6 @@ use state_chain_runtime::{
RuntimeEvent, RuntimeOrigin, Swapping, System, Timestamp, Validator, Weight, Witnesser,
};

use state_chain_runtime::EthereumChainTracking;

const DORIS: AccountId = AccountId::new([0x11; 32]);
const ZION: AccountId = AccountId::new([0x22; 32]);

Expand Down Expand Up @@ -211,11 +209,6 @@ fn basic_pool_setup_provision_and_swap() {
pallet_cf_ingress_egress::ChannelIdCounter::<Runtime, EthereumInstance>::get(),
).unwrap();

let opened_at = EthereumChainTracking::get_block_height();

assert_events_eq!(Runtime, RuntimeEvent::EthereumIngressEgress(
pallet_cf_ingress_egress::Event::StartWitnessing { deposit_address, source_asset: cf_primitives::chains::assets::eth::Asset::Eth, opened_at },
));
System::reset_events();

let current_epoch = Validator::current_epoch();
Expand Down
3 changes: 3 additions & 0 deletions state-chain/pallets/cf-ingress-egress/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ use cf_chains::{
use frame_benchmarking::{account, benchmarks_instance_pallet};
use frame_system::pallet_prelude::BlockNumberFor;

pub(crate) type TargetChainBlockNumber<T, I> =
<<T as Config<I>>::TargetChain as Chain>::ChainBlockNumber;

benchmarks_instance_pallet! {
disable_asset_egress {
let origin = T::EnsureGovernance::try_successful_origin().unwrap();
Expand Down
51 changes: 13 additions & 38 deletions state-chain/pallets/cf-ingress-egress/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,6 @@ pub mod pallet {
pub(crate) type TargetChainAccount<T, I> =
<<T as Config<I>>::TargetChain as Chain>::ChainAccount;
pub(crate) type TargetChainAmount<T, I> = <<T as Config<I>>::TargetChain as Chain>::ChainAmount;
pub(crate) type TargetChainBlockNumber<T, I> =
<<T as Config<I>>::TargetChain as Chain>::ChainBlockNumber;

#[derive(Clone, RuntimeDebug, PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen)]
pub struct DepositWitness<C: Chain> {
Expand Down Expand Up @@ -320,15 +318,6 @@ pub mod pallet {
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config<I>, I: 'static = ()> {
StartWitnessing {
deposit_address: TargetChainAccount<T, I>,
source_asset: TargetChainAsset<T, I>,
opened_at: TargetChainBlockNumber<T, I>,
},
StopWitnessing {
deposit_address: TargetChainAccount<T, I>,
source_asset: TargetChainAsset<T, I>,
},
DepositReceived {
deposit_address: TargetChainAccount<T, I>,
asset: TargetChainAsset<T, I>,
Expand Down Expand Up @@ -799,7 +788,6 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
}

/// Opens a channel for the given asset and registers it with the given action.
/// Emits the `StartWitnessing` event so CFEs can start watching for deposits to the address.
///
/// May re-use an existing deposit address, depending on chain configuration.
fn open_channel(
Expand Down Expand Up @@ -830,37 +818,17 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
let deposit_address = deposit_channel.address.clone();

ChannelActions::<T, I>::insert(&deposit_address, channel_action);

let opened_at = T::ChainTracking::get_block_height();

Self::deposit_event(Event::StartWitnessing {
deposit_address: deposit_address.clone(),
source_asset,
opened_at,
});

DepositChannelLookup::<T, I>::insert(
&deposit_address,
DepositChannelDetails { deposit_channel, opened_at, expires_at },
DepositChannelDetails {
deposit_channel,
opened_at: T::ChainTracking::get_block_height(),
expires_at,
},
);

Ok((channel_id, deposit_address))
}

fn close_channel(address: TargetChainAccount<T, I>) {
ChannelActions::<T, I>::remove(&address);
if let Some(deposit_channel_details) = DepositChannelLookup::<T, I>::get(&address) {
Self::deposit_event(Event::<T, I>::StopWitnessing {
deposit_address: address,
source_asset: deposit_channel_details.deposit_channel.asset,
});
if let Some(channel) = deposit_channel_details.deposit_channel.maybe_recycle() {
DepositChannelPool::<T, I>::insert(channel.channel_id, channel);
}
} else {
log_or_panic!("Tried to close an unknown channel.");
}
}
}

impl<T: Config<I>, I: 'static> EgressApi<T::TargetChain> for Pallet<T, I> {
Expand Down Expand Up @@ -960,6 +928,13 @@ impl<T: Config<I>, I: 'static> DepositApi<T::TargetChain> for Pallet<T, I> {
// 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<T, I>) {
Self::close_channel(address);
ChannelActions::<T, I>::remove(&address);
if let Some(deposit_channel_details) = DepositChannelLookup::<T, I>::get(&address) {
if let Some(channel) = deposit_channel_details.deposit_channel.maybe_recycle() {
DepositChannelPool::<T, I>::insert(channel.channel_id, channel);
}
} else {
log_or_panic!("Tried to close an unknown channel.");
}
}
}
33 changes: 15 additions & 18 deletions state-chain/pallets/cf-ingress-egress/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{
mock::*, Call as PalletCall, ChannelAction, ChannelIdCounter, CrossChainMessage,
DepositChannelLookup, DepositChannelPool, DepositWitness, DisabledEgressAssets, Error,
Event as PalletEvent, FailedVaultTransfers, FetchOrTransfer, MinimumDeposit, Pallet,
ScheduledEgressCcm, ScheduledEgressFetchOrTransfer, VaultTransfer,
ScheduledEgressCcm, ScheduledEgressFetchOrTransfer, TargetChainAccount, VaultTransfer,
};
use cf_chains::{
address::AddressConverter, evm::EvmFetchId, CcmChannelMetadata, DepositChannel,
Expand Down Expand Up @@ -351,10 +351,9 @@ fn addresses_are_getting_reused() {
}
channels
})
// Close the channels.
.then_execute_at_next_block(|channels| {
for (_request, _id, address) in &channels {
IngressEgress::close_channel(*address);
IngressEgress::expire_channel(*address);
}
channels[0].clone()
})
Expand Down Expand Up @@ -387,7 +386,7 @@ fn proof_address_pool_integrity() {
IngressEgress::on_finalize(1);
for (_id, address) in channel_details {
assert_ok!(IngressEgress::finalise_ingress(RuntimeOrigin::root(), vec![address]));
IngressEgress::close_channel(address);
IngressEgress::expire_channel(address);
}
// Expect all addresses to be available
expect_size_of_address_pool(3);
Expand All @@ -406,7 +405,7 @@ fn create_new_address_while_pool_is_empty() {
IngressEgress::on_finalize(1);
for (_id, address) in channel_details {
assert_ok!(IngressEgress::finalise_ingress(RuntimeOrigin::root(), vec![address]));
IngressEgress::close_channel(address);
IngressEgress::expire_channel(address);
}
IngressEgress::on_initialize(EXPIRY_BLOCK);
assert_eq!(ChannelIdCounter::<Test>::get(), 2);
Expand Down Expand Up @@ -458,24 +457,23 @@ fn can_process_ccm_deposit() {
let amount = 5_000;

// Register swap deposit with CCM
assert_ok!(IngressEgress::request_swap_deposit_address(

let (_, deposit_address) = IngressEgress::request_swap_deposit_address(
from_asset,
to_asset,
destination_address.clone(),
0,
1,
Some(channel_metadata),
1_000u64,
));
)
.unwrap();

// CCM action is stored.
let deposit_address = cf_test_utilities::assert_events_match!(
Test,
RuntimeEvent::IngressEgress(crate::Event::<Test>::StartWitnessing {
deposit_address,
opened_at,
..
}) if opened_at == BlockNumberProvider::get_block_height() => deposit_address
let deposit_address: TargetChainAccount<Test, _> = deposit_address.try_into().unwrap();

assert_eq!(
DepositChannelLookup::<Test>::get(deposit_address).unwrap().opened_at,
BlockNumberProvider::get_block_height()
);

// Making a deposit should trigger CcmHandler.
Expand Down Expand Up @@ -591,7 +589,7 @@ fn multi_use_deposit_address_different_blocks() {
})
.then_execute_at_next_block(|(_, deposit_address)| {
// Closing the channel should invalidate the deposit address.
IngressEgress::close_channel(deposit_address);
IngressEgress::expire_channel(deposit_address);
assert_noop!(
IngressEgress::process_deposits(
RuntimeOrigin::root(),
Expand Down Expand Up @@ -881,8 +879,7 @@ fn channel_reuse_with_different_assets() {
);
})
.then_execute_at_next_block(|(_, channel_id, channel_address)| {
// Close the channel.
IngressEgress::close_channel(channel_address);
IngressEgress::expire_channel(channel_address);
channel_id
})
.inspect_storage(|channel_id| {
Expand Down
7 changes: 6 additions & 1 deletion state-chain/pallets/cf-lp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,11 @@ pub mod pallet {
},
LiquidityDepositAddressReady {
channel_id: ChannelId,
asset: Asset,
deposit_address: EncodedAddress,
expiry_block: BlockNumberFor<T>,
// account the funds will be credited to upon deposit
account_id: T::AccountId,
},
LiquidityDepositAddressExpired {
address: EncodedAddress,
Expand Down Expand Up @@ -212,7 +215,7 @@ pub mod pallet {

let (channel_id, deposit_address) =
T::DepositHandler::request_liquidity_deposit_address(
account_id,
account_id.clone(),
asset,
expiry_block,
)?;
Expand All @@ -224,8 +227,10 @@ pub mod pallet {

Self::deposit_event(Event::LiquidityDepositAddressReady {
channel_id,
asset,
deposit_address: T::AddressConverter::to_encoded_address(deposit_address),
expiry_block,
account_id,
});

Ok(())
Expand Down
4 changes: 3 additions & 1 deletion state-chain/pallets/cf-lp/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,12 @@ fn deposit_channel_expires() {
));

let (channel_id, deposit_address) = assert_events_match!(Test, RuntimeEvent::LiquidityProvider(crate::Event::LiquidityDepositAddressReady {
asset: event_asset,
channel_id,
deposit_address,
expiry_block,
}) if expiry_block == expiry => (channel_id, deposit_address));
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,
Expand Down

0 comments on commit 1a9c991

Please sign in to comment.