Skip to content

Commit

Permalink
listen to ForeignAssets.Transferred events on target_b
Browse files Browse the repository at this point in the history
  • Loading branch information
brenzi committed Feb 7, 2025
1 parent 8990cae commit 1ed6bb3
Show file tree
Hide file tree
Showing 16 changed files with 347 additions and 47 deletions.
9 changes: 8 additions & 1 deletion Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2227,6 +2227,12 @@ version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ebdb29d2ea9ed0083cd8cece49bbd968021bd99b0849edb4a9a7ee0fdf6a4e0"

[[package]]
name = "hex-literal"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46"

[[package]]
name = "hmac"
version = "0.8.1"
Expand Down Expand Up @@ -2788,6 +2794,7 @@ version = "0.9.0"
dependencies = [
"bs58",
"env_logger 0.9.3",
"hex-literal 0.4.1",
"ita-sgx-runtime",
"ita-stf",
"itc-parentchain",
Expand Down Expand Up @@ -6862,7 +6869,7 @@ dependencies = [
"der 0.6.1",
"frame-support",
"hex",
"hex-literal",
"hex-literal 0.3.4",
"log 0.4.22",
"parity-scale-codec",
"ring 0.16.20",
Expand Down
1 change: 1 addition & 0 deletions app-libs/parentchain-interface/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ bs58 = { version = "0.4.0", default-features = false, features = ["alloc"] }
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
log = { version = "0.4", default-features = false }
regex = { optional = true, version = "1.9.5" }
hex-literal = "0.4.1"

substrate-api-client = { default-features = false, git = "https://github.com/encointer/substrate-api-client.git", branch = "v0.9.42-tag-v0.14.0-retracted-check-metadata-hash" }

Expand Down
9 changes: 4 additions & 5 deletions app-libs/parentchain-interface/src/integritee/event_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,9 @@
use itc_parentchain_indirect_calls_executor::event_filter::ToEvents;
use itp_api_client_types::Events;

use crate::StaticEvent;
use itp_types::{
parentchain::{
BalanceTransfer, ExtrinsicFailed, ExtrinsicStatus, ExtrinsicSuccess, FilterEvents,
},
parentchain::{ExtrinsicFailed, ExtrinsicStatus, ExtrinsicSuccess, FilterEvents},
H256,
};
use std::vec::Vec;
Expand Down Expand Up @@ -68,12 +67,12 @@ impl FilterEvents for FilterableEvents {
.collect())
}

fn get_transfer_events(&self) -> core::result::Result<Vec<BalanceTransfer>, Self::Error> {
fn get_events<Event: StaticEvent>(&self) -> core::result::Result<Vec<Event>, Self::Error> {
Ok(self
.to_events()
.iter()
.flatten() // flatten filters out the nones
.filter_map(|ev| match ev.as_event::<BalanceTransfer>() {
.filter_map(|ev| match ev.as_event::<Event>() {
Ok(maybe_event) => maybe_event,
Err(e) => {
log::error!("Could not decode event: {:?}", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ use ita_stf::{Getter, TrustedCall, TrustedCallSigned};
use itc_parentchain_indirect_calls_executor::error::Error;
use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation};
use itp_types::parentchain::{
AccountId, FilterEvents, HandleParentchainEvents, ParentchainError, ParentchainId,
AccountId, BalanceTransfer, FilterEvents, HandleParentchainEvents, ParentchainError,
ParentchainId,
};
use itp_utils::hex::hex_encode;
use log::*;
Expand Down Expand Up @@ -65,7 +66,7 @@ where
events: impl FilterEvents,
vault_account: &AccountId,
) -> Result<(), Error> {
let filter_events = events.get_transfer_events();
let filter_events = events.get_events::<BalanceTransfer>();
trace!(
"filtering transfer events to shard vault account: {}",
hex_encode(vault_account.encode().as_slice())
Expand Down
1 change: 1 addition & 0 deletions app-libs/parentchain-interface/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#![cfg_attr(all(not(target_env = "sgx"), not(feature = "std")), no_std)]
#![cfg_attr(target_env = "sgx", feature(rustc_private))]

extern crate alloc;
#[cfg(all(not(feature = "std"), feature = "sgx"))]
extern crate sgx_tstd as std;

Expand Down
9 changes: 4 additions & 5 deletions app-libs/parentchain-interface/src/target_a/event_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,9 @@
use itc_parentchain_indirect_calls_executor::event_filter::ToEvents;
use itp_api_client_types::Events;

use crate::StaticEvent;
use itp_types::{
parentchain::{
BalanceTransfer, ExtrinsicFailed, ExtrinsicStatus, ExtrinsicSuccess, FilterEvents,
},
parentchain::{ExtrinsicFailed, ExtrinsicStatus, ExtrinsicSuccess, FilterEvents},
H256,
};
use std::vec::Vec;
Expand Down Expand Up @@ -67,12 +66,12 @@ impl FilterEvents for FilterableEvents {
.collect())
}

fn get_transfer_events(&self) -> core::result::Result<Vec<BalanceTransfer>, Self::Error> {
fn get_events<Event: StaticEvent>(&self) -> core::result::Result<Vec<Event>, Self::Error> {
Ok(self
.to_events()
.iter()
.flatten() // flatten filters out the nones
.filter_map(|ev| match ev.as_event::<BalanceTransfer>() {
.filter_map(|ev| match ev.as_event::<Event>() {
Ok(maybe_event) => maybe_event,
Err(e) => {
log::error!("Could not decode event: {:?}", e);
Expand Down
5 changes: 3 additions & 2 deletions app-libs/parentchain-interface/src/target_a/event_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ use ita_stf::{Getter, TrustedCall, TrustedCallSigned};
use itc_parentchain_indirect_calls_executor::error::Error;
use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation};
use itp_types::parentchain::{
AccountId, FilterEvents, HandleParentchainEvents, ParentchainError, ParentchainId,
AccountId, BalanceTransfer, FilterEvents, HandleParentchainEvents, ParentchainError,
ParentchainId,
};
use itp_utils::hex::hex_encode;
use log::*;
Expand Down Expand Up @@ -65,7 +66,7 @@ where
events: impl FilterEvents,
vault_account: &AccountId,
) -> Result<(), Error> {
let filter_events = events.get_transfer_events();
let filter_events = events.get_events::<BalanceTransfer>();
trace!(
"[TargetA] filtering transfer events to shard vault account: {}",
hex_encode(vault_account.encode().as_slice())
Expand Down
9 changes: 4 additions & 5 deletions app-libs/parentchain-interface/src/target_b/event_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,9 @@
use itc_parentchain_indirect_calls_executor::event_filter::ToEvents;
use itp_api_client_types::Events;

use crate::StaticEvent;
use itp_types::{
parentchain::{
BalanceTransfer, ExtrinsicFailed, ExtrinsicStatus, ExtrinsicSuccess, FilterEvents,
},
parentchain::{ExtrinsicFailed, ExtrinsicStatus, ExtrinsicSuccess, FilterEvents},
H256,
};
use std::vec::Vec;
Expand Down Expand Up @@ -67,12 +66,12 @@ impl FilterEvents for FilterableEvents {
.collect())
}

fn get_transfer_events(&self) -> core::result::Result<Vec<BalanceTransfer>, Self::Error> {
fn get_events<Event: StaticEvent>(&self) -> core::result::Result<Vec<Event>, Self::Error> {
Ok(self
.to_events()
.iter()
.flatten() // flatten filters out the nones
.filter_map(|ev| match ev.as_event::<BalanceTransfer>() {
.filter_map(|ev| match ev.as_event::<Event>() {
Ok(maybe_event) => maybe_event,
Err(e) => {
log::error!("Could not decode event: {:?}", e);
Expand Down
72 changes: 60 additions & 12 deletions app-libs/parentchain-interface/src/target_b/event_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,22 @@
*/
use codec::Encode;
use ita_sgx_runtime::Balance;
use hex_literal::hex;
use ita_sgx_runtime::{AssetId, Balance};
use ita_stf::{Getter, TrustedCall, TrustedCallSigned};
use itc_parentchain_indirect_calls_executor::error::Error;
use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation};
use itp_types::parentchain::{
AccountId, FilterEvents, HandleParentchainEvents, ParentchainError, ParentchainId,
use itp_types::{
parentchain::{
AccountId, BalanceTransfer, FilterEvents, ForeignAssetsTransferred,
HandleParentchainEvents, ParentchainError, ParentchainId,
},
xcm::{
Junction::{AccountKey20, GlobalConsensus},
Junctions::X2,
Location,
NetworkId::Ethereum,
},
};
use itp_utils::hex::hex_encode;
use log::*;
Expand Down Expand Up @@ -63,21 +73,59 @@ where
events: impl FilterEvents,
vault_account: &AccountId,
) -> Result<(), Error> {
let filter_events = events.get_transfer_events();
trace!(
"[TargetB] filtering transfer events to shard vault account: {}",
"[TargetB] filtering balance transfer events to shard vault account: {}",
hex_encode(vault_account.encode().as_slice())
);
let filter_events = events.get_events::<BalanceTransfer>();
if let Ok(events) = filter_events {
events
.iter()
.filter(|&event| event.to == *vault_account)
.try_for_each(|event| {
info!("[TargetB] found transfer event to shard vault account: {} will shield to {}", event.amount, hex_encode(event.from.encode().as_ref()));
Self::shield_funds(executor, &event.from, event.amount)
})
.map_err(|_| ParentchainError::ShieldFundsFailure)?;
.iter()
.filter(|&event| event.to == *vault_account)
.try_for_each(|event| {
info!("[TargetB] found balance transfer event to shard vault account: {} will shield to {}", event.amount, hex_encode(event.from.encode().as_ref()));
Self::shield_funds(executor, &event.from, event.amount)
})
.map_err(|_| ParentchainError::ShieldFundsFailure)?;
}
trace!(
"[TargetB] filtering foreign assets transferred events to shard vault account: {}",
hex_encode(vault_account.encode().as_slice())
);
let filter_asset_events = events.get_events::<ForeignAssetsTransferred>();
if let Ok(events) = filter_asset_events {
events
.iter()
.filter(|&event| event.to == *vault_account)
.try_for_each(|event| {
let stf_asset_id = location_to_sgx_runtime_asset_id(&event.asset_id);
info!("[TargetB] found foreign assets ({:?}) transferred event to shard vault account: {} will shield to {}", stf_asset_id, event.amount, hex_encode(event.from.encode().as_ref()));

//Self::shield_assets(executor, location_to_sgx_runtime_asset_id(&event.asset_id), &event.from, event.amount)
Ok(())
})
.map_err(|_: Error| ParentchainError::ShieldFundsFailure)?;
}

Ok(())
}
}

const USDC_E_CONTRACT_ADDRESS: [u8; 20] = hex!("a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48");

fn location_to_sgx_runtime_asset_id(location: &Location) -> Option<AssetId> {
if location.parents == 2 {
if let X2(junctions) = &location.interior {
match junctions.as_slice() {
[GlobalConsensus(Ethereum { chain_id: 1 }), AccountKey20 { key: contract, network: None }]
if *contract == USDC_E_CONTRACT_ADDRESS =>
Some(1),
_ => None,
}
} else {
None
}
} else {
None
}
}
9 changes: 5 additions & 4 deletions app-libs/sgx-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ use sp_version::RuntimeVersion;
pub use itp_sgx_runtime_primitives::{
constants::SLOT_DURATION,
types::{
AccountData, AccountId, Address, Balance, BlockNumber, Hash, Header, Index, Signature,
AccountData, AccountId, Address, AssetId, Balance, BlockNumber, Hash, Header, Index,
Signature,
},
};

Expand All @@ -71,7 +72,7 @@ pub use frame_support::{
StorageValue,
};
use frame_support::{
traits::{AsEnsureOriginWithArg, ConstU128, ConstU64, ConstU8, EitherOfDiverse},
traits::{AsEnsureOriginWithArg, ConstU128, ConstU8, EitherOfDiverse},
PalletId,
};
use frame_system::{EnsureRoot, EnsureSignedBy};
Expand Down Expand Up @@ -341,8 +342,8 @@ impl pallet_session_proxy::Config for Runtime {
impl pallet_assets::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Balance = u64;
type AssetId = u32;
type AssetIdParameter = codec::Compact<u32>;
type AssetId = AssetId;
type AssetIdParameter = codec::Compact<AssetId>;
type Currency = Balances;
type CreateOrigin = AsEnsureOriginWithArg<frame_system::EnsureSigned<AccountId>>;
type ForceOrigin = frame_system::EnsureRoot<AccountId>;
Expand Down
2 changes: 2 additions & 0 deletions core-primitives/sgx-runtime-primitives/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ pub type DigestItem = generic::DigestItem;
/// A type to hold UTC unix epoch [ms]
pub type Moment = u64;

pub type AssetId = u32;

pub type Block = BlockG<Header, OpaqueExtrinsic>;
pub type SignedBlock = SignedBlockG<Block>;
pub type BlockHash = sp_core::H256;
Expand Down
1 change: 1 addition & 0 deletions core-primitives/types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use sp_std::vec::Vec;

pub mod parentchain;
pub mod storage;
pub mod xcm;

/// Substrate runtimes provide no string type. Hence, for arbitrary data of varying length the
/// `Vec<u8>` is used. In the polkadot-js the typedef `Text` is used to automatically
Expand Down
49 changes: 47 additions & 2 deletions core-primitives/types/src/parentchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
*/

use crate::{OpaqueCall, PalletString, ShardIdentifier};
use crate::{xcm::Location, OpaqueCall, PalletString, ShardIdentifier};
use alloc::{format, vec::Vec};
use codec::{Decode, Encode};
use core::fmt::Debug;
Expand All @@ -37,6 +37,7 @@ use substrate_api_client::{
};
use teeracle_primitives::ExchangeRate;
use teerex_primitives::{SgxAttestationMethod, SgxStatus};

pub type StorageProof = Vec<Vec<u8>>;

// Basic Types.
Expand Down Expand Up @@ -100,7 +101,9 @@ pub trait FilterEvents {
type Error: From<ParentchainError> + core::fmt::Debug;
fn get_extrinsic_statuses(&self) -> core::result::Result<Vec<ExtrinsicStatus>, Self::Error>;

fn get_transfer_events(&self) -> core::result::Result<Vec<BalanceTransfer>, Self::Error>;
fn get_events<Event: Default + StaticEvent>(
&self,
) -> core::result::Result<Vec<Event>, Self::Error>;
}

#[derive(Encode, Decode, Debug)]
Expand Down Expand Up @@ -156,11 +159,53 @@ impl core::fmt::Display for BalanceTransfer {
}
}

impl Default for BalanceTransfer {
fn default() -> Self {
BalanceTransfer { from: [0u8; 32].into(), to: [0u8; 32].into(), amount: 0 }
}
}

impl StaticEvent for BalanceTransfer {
const PALLET: &'static str = "Balances";
const EVENT: &'static str = "Transfer";
}

#[derive(Encode, Decode, Debug)]
pub struct ForeignAssetsTransferred {
pub asset_id: Location,
pub from: AccountId,
pub to: AccountId,
pub amount: Balance,
}

impl core::fmt::Display for ForeignAssetsTransferred {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
let message = format!(
"ForeignAssetsTransferred :: asset: {:?}, from: {}, to: {}, amount: {}",
&self.asset_id,
account_id_to_string::<AccountId>(&self.from),
account_id_to_string::<AccountId>(&self.to),
self.amount
);
write!(f, "{}", message)
}
}

impl Default for ForeignAssetsTransferred {
fn default() -> Self {
ForeignAssetsTransferred {
asset_id: Default::default(),
from: [0u8; 32].into(),
to: [0u8; 32].into(),
amount: 0,
}
}
}
impl StaticEvent for ForeignAssetsTransferred {
const PALLET: &'static str = "ForeignAssets";
const EVENT: &'static str = "Transferred";
}

#[derive(Encode, Decode, Debug)]
pub struct AddedSgxEnclave {
pub registered_by: AccountId,
Expand Down
Loading

0 comments on commit 1ed6bb3

Please sign in to comment.