Skip to content

Commit

Permalink
fix: SC recycles based on external chain block
Browse files Browse the repository at this point in the history
  • Loading branch information
kylezs committed Sep 20, 2023
1 parent 292b98e commit 9e5b4d2
Show file tree
Hide file tree
Showing 24 changed files with 266 additions and 674 deletions.
2 changes: 0 additions & 2 deletions api/bin/chainflip-broker-api/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand All @@ -33,7 +32,6 @@ impl From<chainflip_api::SwapDepositAddress> 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,
}
Expand Down
3 changes: 1 addition & 2 deletions api/bin/chainflip-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 },
Expand Down
7 changes: 1 addition & 6 deletions api/lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down Expand Up @@ -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!(
Expand All @@ -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,
})
Expand Down
58 changes: 22 additions & 36 deletions api/lib/src/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -15,7 +16,6 @@ pub struct SwapChannelInfo<C: Chain> {
deposit_address: <C::ChainAccount as ToHumanreadableAddress>::Humanreadable,
source_asset: any::Asset,
destination_asset: any::Asset,
expiry_block: state_chain_runtime::BlockNumber,
}

pub struct QueryApi {
Expand Down Expand Up @@ -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::<pallet_cf_ingress_egress::DepositChannelLookup<
state_chain_runtime::Runtime,
C::Instance,
>, Vec<_>>(block_hash)
.map(|result| {
result.map(|channels| channels.into_iter().collect::<BTreeMap<_, _>>())
}),
self.state_chain_client.storage_map::<pallet_cf_ingress_egress::ChannelActions<
let (channel_details, network_environment) = tokio::try_join!(
self.state_chain_client
.storage_map::<pallet_cf_ingress_egress::DepositChannelLookup<
state_chain_runtime::Runtime,
C::Instance,
>, Vec<_>>(block_hash,),
self.state_chain_client
.storage_value::<pallet_cf_environment::ChainflipNetworkEnvironment<
state_chain_runtime::Runtime,
>>(block_hash),
)?;
>, Vec<_>>(block_hash)
.map(|result| {
result.map(|channels| channels.into_iter().collect::<BTreeMap<_, _>>())
}),
self.state_chain_client
.storage_value::<pallet_cf_environment::ChainflipNetworkEnvironment<state_chain_runtime::Runtime>>(
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::<Vec<_>>())
}
Expand Down
5 changes: 5 additions & 0 deletions engine/src/witness/btc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<TxOut>) -> Transaction {
Transaction {
Expand All @@ -217,6 +219,9 @@ mod tests {
asset: btc::Asset::Btc,
state: DepositAddress::new([0; 32], 1),
},
action: ChannelAction::<AccountId32>::LiquidityProvision {
lp_account: AccountId32::new([0xab; 32]),
},
}
}

Expand Down
4 changes: 3 additions & 1 deletion state-chain/cf-integration-tests/src/mock_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
})
}
}
1 change: 1 addition & 0 deletions state-chain/chains/src/deposit_channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ impl<C: Chain<DepositFetchId = ChannelId>> From<&DepositChannel<C>> for ChannelI
}
}

// Do we need to return bools???? We should be checking against the state instead.
/// Defines the interface for chain-specific aspects of address management.
pub trait ChannelLifecycleHooks: Sized {
/// Returns true if fetches can be made from the channel in the current state.
Expand Down
9 changes: 4 additions & 5 deletions state-chain/node/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,6 @@ pub fn cf_development_config() -> Result<ChainSpec, String> {
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,
)
Expand Down Expand Up @@ -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,
)
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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(),
}
}

Expand Down
1 change: 0 additions & 1 deletion state-chain/node/src/chain_spec/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 12 additions & 8 deletions state-chain/pallets/cf-ingress-egress/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T, I> =
<<T as Config<I>>::TargetChain as Chain>::ChainBlockNumber;
Expand All @@ -27,16 +26,17 @@ benchmarks_instance_pallet! {
let deposit_address: <<T as Config<I>>::TargetChain as Chain>::ChainAccount = BenchmarkValue::benchmark_value();
let source_asset: <<T as Config<I>>::TargetChain as Chain>::ChainAsset = BenchmarkValue::benchmark_value();
let deposit_amount: <<T as Config<I>>::TargetChain as Chain>::ChainAmount = BenchmarkValue::benchmark_value();
let block_number: TargetChainBlockNumber<T, I> = BenchmarkValue::benchmark_value();
DepositChannelLookup::<T, I>::insert(&deposit_address, DepositChannelDetails {
opened_at: TargetChainBlockNumber::<T, I>::benchmark_value(),
opened_at: block_number,
expires_at: block_number,
deposit_channel: DepositChannel::generate_new::<<T as Config<I>>::AddressDerivation>(
1,
source_asset,
).unwrap(),
expires_at: BlockNumberFor::<T>::from(1_000u32),
});
ChannelActions::<T, I>::insert(&deposit_address, ChannelAction::<T::AccountId>::LiquidityProvision {
lp_account: account("doogle", 0, 0),
action: ChannelAction::<T::AccountId>::LiquidityProvision {
lp_account: account("doogle", 0, 0),
},
});
}: {
Pallet::<T, I>::process_single_deposit(deposit_address, source_asset, deposit_amount, BenchmarkValue::benchmark_value(), BenchmarkValue::benchmark_value()).unwrap()
Expand All @@ -61,13 +61,17 @@ benchmarks_instance_pallet! {
let deposit_address = <<T as Config<I>>::TargetChain as Chain>::ChainAccount::benchmark_value_by_id(a as u8);
let deposit_fetch_id = <<T as Config<I>>::TargetChain as Chain>::DepositFetchId::benchmark_value_by_id(a as u8);
let source_asset: <<T as Config<I>>::TargetChain as Chain>::ChainAsset = BenchmarkValue::benchmark_value();
let block_number = TargetChainBlockNumber::<T, I>::benchmark_value();
let mut channel = DepositChannelDetails::<T, I> {
opened_at: TargetChainBlockNumber::<T, I>::benchmark_value(),
opened_at: block_number,
expires_at: block_number,
deposit_channel: DepositChannel::generate_new::<<T as Config<I>>::AddressDerivation>(
1,
source_asset,
).unwrap(),
expires_at: BlockNumberFor::<T>::from(1_000u32),
action: ChannelAction::<T::AccountId>::LiquidityProvision {
lp_account: account("doogle", 0, 0),
},
};
channel.deposit_channel.state.on_fetch_scheduled();
DepositChannelLookup::<T, I>::insert(deposit_address.clone(), channel);
Expand Down
Loading

0 comments on commit 9e5b4d2

Please sign in to comment.