Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Expose vault swaps from ingress-egress-tracker #5463

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions api/bin/chainflip-ingress-egress-tracker/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ pallet-cf-ingress-egress = { workspace = true, default-features = true }
pallet-cf-broadcast = { workspace = true, default-features = true }
state-chain-runtime = { workspace = true, default-features = true }
cf-chains = { workspace = true, default-features = true }
custom-rpc = { workspace = true }
chainflip-api = { workspace = true }

[build-dependencies]
substrate-build-script-utils = { workspace = true }
Expand Down
1 change: 1 addition & 0 deletions api/bin/chainflip-ingress-egress-tracker/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ async fn start(

#[tokio::main]
async fn main() -> anyhow::Result<()> {
chainflip_api::use_chainflip_account_id_encoding();
let settings = DepositTrackerSettings::load_settings_from_all_sources(
// Not using the config root or settings dir.
"".to_string(),
Expand Down
6 changes: 3 additions & 3 deletions api/bin/chainflip-ingress-egress-tracker/src/store.rs
dandanlen marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl Store for RedisStore {
type Output = ();

async fn save_to_array<S: Storable>(&mut self, storable: &S) -> anyhow::Result<()> {
let key = storable.get_key();
let key = storable.get_key()?;
self.con
.rpush::<String, String, ()>(key.clone(), serde_json::to_string(storable)?)
.await?;
Expand All @@ -41,7 +41,7 @@ impl Store for RedisStore {
async fn save_singleton<S: Storable>(&mut self, storable: &S) -> anyhow::Result<()> {
self.con
.set_ex::<String, String, ()>(
storable.get_key(),
storable.get_key()?,
serde_json::to_string(storable)?,
storable.get_expiry_duration().as_secs(),
)
Expand All @@ -54,7 +54,7 @@ impl Store for RedisStore {
pub trait Storable: Serialize + Sized + Sync + 'static {
const DEFAULT_EXPIRY_DURATION: Duration = Duration::from_secs(3600);

fn get_key(&self) -> String;
fn get_key(&self) -> anyhow::Result<String>;

fn get_expiry_duration(&self) -> Duration {
Self::DEFAULT_EXPIRY_DURATION
Expand Down
64 changes: 61 additions & 3 deletions api/bin/chainflip-ingress-egress-tracker/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,28 @@
use cf_chains::instances::{ChainInstanceAlias, ChainInstanceFor};
use cf_primitives::BroadcastId;
use cf_chains::{
address::EncodedAddress,
instances::{ChainInstanceAlias, ChainInstanceFor},
ForeignChainAddress,
};
use cf_primitives::{AffiliateShortId, Affiliates, Beneficiary, BroadcastId, NetworkEnvironment};
use chainflip_api::TrackerApi;
use chainflip_engine::state_chain_observer::client::{
chain_api::ChainApi, storage_api::StorageApi, STATE_CHAIN_CONNECTION,
};
use pallet_cf_broadcast::TransactionOutIdFor;
use sp_core::{
bounded::alloc::{collections::BTreeMap, sync::Arc},
crypto::AccountId32,
};

use anyhow::anyhow;
use tracing::log;

pub fn hex_encode_bytes(bytes: &[u8]) -> String {
format!("0x{}", hex::encode(bytes))
}

pub async fn get_broadcast_id<I, StateChainClient>(
state_chain_client: &StateChainClient,
state_chain_client: Arc<StateChainClient>,
tx_out_id: &TransactionOutIdFor<state_chain_runtime::Runtime, ChainInstanceFor<I>>,
) -> Option<BroadcastId>
where
Expand All @@ -34,3 +45,50 @@ where

id
}

pub fn destination_address_from_encoded_address(
address: EncodedAddress,
network: NetworkEnvironment,
) -> anyhow::Result<ForeignChainAddress> {
cf_chains::address::try_from_encoded_address(address, || network)
.map_err(|_| anyhow!("Invalid destination address"))
}

// Get a list of registered affiliates for the given broker and map the short ids to their account
// ids
pub async fn map_affiliates<StateChainClient>(
state_chain_client: Arc<StateChainClient>,
affiliates: Affiliates<AffiliateShortId>,
broker_id: AccountId32,
) -> Affiliates<AccountId32>
where
StateChainClient: StorageApi + ChainApi + TrackerApi + 'static + Send + Sync,
{
if affiliates.is_empty() {
return Affiliates::default();
}

let registered_affiliates: BTreeMap<_, _> = state_chain_client
.get_affiliates(broker_id.clone())
.await
.expect(STATE_CHAIN_CONNECTION)
.into_iter()
.collect();

affiliates
.into_iter()
.map(|affiliate| {
Beneficiary { account: registered_affiliates.get(&affiliate.account).cloned()
.unwrap_or_else(|| {
log::warn!(
"Affiliate not found for short id {} on broker {}",
affiliate.account,
broker_id
);
AccountId32::from([0; 32])
}), bps: affiliate.bps }
})
.collect::<Vec<Beneficiary<AccountId32>>>()
.try_into()
.expect("We collect into the same Affiliates type we started with, so the Vec bound is the same.")
}
9 changes: 5 additions & 4 deletions api/bin/chainflip-ingress-egress-tracker/src/witnessing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ pub mod state_chain;

use self::state_chain::handle_call;
use crate::{settings::DepositTrackerSettings, store::RedisStore};
use anyhow::anyhow;
use cf_chains::dot::PolkadotHash;
use cf_primitives::{chains::assets::eth::Asset, NetworkEnvironment};
use cf_utilities::task_scope;
Expand All @@ -18,8 +17,10 @@ use chainflip_engine::{
},
witness::common::epoch_source::EpochSource,
};

use anyhow::anyhow;
use sp_core::H160;
use std::{collections::HashMap, ops::Deref};
use std::collections::HashMap;

#[derive(Clone)]
pub(super) struct EnvironmentParameters {
Expand Down Expand Up @@ -112,7 +113,7 @@ pub(super) async fn start(
store: RedisStore,
) -> anyhow::Result<()> {
let (state_chain_stream, unfinalized_chain_stream, state_chain_client) = {
state_chain_observer::client::StateChainClient::connect_without_account(
state_chain_observer::client::StateChainClient::<(), _>::connect_without_account(
scope,
&settings.state_chain_ws_endpoint,
)
Expand All @@ -132,7 +133,7 @@ pub(super) async fn start(
let state_chain_client = state_chain_client.clone();

async move {
handle_call(call, &mut store, chainflip_network, state_chain_client.deref())
handle_call(call, &mut store, chainflip_network, state_chain_client)
.await
.map_err(|err| anyhow!("failed to handle call: {err:?}"))
.unwrap()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
source: api/bin/chainflip-ingress-egress-tracker/src/witnessing/state_chain.rs
expression: "store.storage.get(\"vault_deposit:Ethereum:b5c8bd9430b6cc87a0e2fe110ece6bf527fa4f170a4bc8cd032f768fc5219838\").unwrap()"
---
{"affiliate_fees":[{"account":"cFHtoB6DrnqUVY4DwMHCVCtgCLsiHvv98oGw8k66tazF2ToFv","bps":10}],"amount":"0x64","boost_fee":5,"broker_fee":{"account":"cFHsUq1uK5opJudRDczhdPVj6LGoVTqYsfj71tbHfKsTAzkJJ","bps":10},"ccm_deposit_metadata":null,"dca_params":{"chunk_interval":100,"number_of_chunks":5},"deposit_chain_block_height":1,"deposit_details":null,"destination_address":{"Dot":"111111111111111111111111111111111HC1"},"input_asset":{"asset":"ETH","chain":"Ethereum"},"output_asset":{"asset":"FLIP","chain":"Ethereum"},"refund_params":{"min_price":"0x0","refund_address":{"Eth":"0x541f563237a309b3a61e33bdf07a8930bdba8d99"},"retry_duration":0}}
Loading
Loading