From d489756d0426629849c3108a98781278c0453a3f Mon Sep 17 00:00:00 2001 From: ron Date: Tue, 23 Jul 2024 08:42:39 +0800 Subject: [PATCH 1/6] Focus on the xcm construction & Remove reward --- .../primitives/router/src/outbound/mod.rs | 27 +-- .../primitives/router/src/outbound/tests.rs | 224 +++--------------- .../snowbridge/runtime/test-common/src/lib.rs | 4 +- .../bridge-hub-rococo/src/tests/snowbridge.rs | 151 ++++++------ .../assets/asset-hub-rococo/src/xcm_config.rs | 7 +- .../bridge-hub-rococo/src/xcm_config.rs | 35 +-- .../bridge-hub-rococo/tests/snowbridge.rs | 6 +- 7 files changed, 137 insertions(+), 317 deletions(-) diff --git a/bridges/snowbridge/primitives/router/src/outbound/mod.rs b/bridges/snowbridge/primitives/router/src/outbound/mod.rs index ddc36ce8cb61..3d705f7cdeb0 100644 --- a/bridges/snowbridge/primitives/router/src/outbound/mod.rs +++ b/bridges/snowbridge/primitives/router/src/outbound/mod.rs @@ -117,7 +117,7 @@ where })?; // convert fee to Asset - let fee = Asset::from((Location::parent(), fee.total())).into(); + let fee = Asset::from((Location::parent(), fee.local)).into(); Ok(((ticket.encode(), message_id), fee)) } @@ -148,12 +148,12 @@ enum XcmConverterError { DepositAssetExpected, NoReserveAssets, FilterDoesNotConsumeAllAssets, - TooManyAssets, ZeroAssetTransfer, BeneficiaryResolutionFailed, AssetResolutionFailed, - InvalidFeeAsset, SetTopicExpected, + FeeAssetExpected, + FeeAssetInvalid, } macro_rules! match_expression { @@ -202,10 +202,13 @@ impl<'a, Call> XcmConverter<'a, Call> { } // Get the fee asset item from BuyExecution or continue parsing. - let fee_asset = match_expression!(self.peek(), Ok(BuyExecution { fees, .. }), fees); - if fee_asset.is_some() { - let _ = self.next(); - } + let fee_asset = match_expression!(self.next()?, BuyExecution { fees, .. }, fees) + .ok_or(FeeAssetExpected)?; + ensure!(fee_asset.clone().id == AssetId::from(Location::parent()), FeeAssetInvalid); + let _fee_amount = match fee_asset.clone().fun { + Fungible(fee_amount) => Ok(fee_amount), + _ => Err(FeeAssetInvalid), + }?; let (deposit_assets, beneficiary) = match_expression!( self.next()?, @@ -233,18 +236,8 @@ impl<'a, Call> XcmConverter<'a, Call> { return Err(FilterDoesNotConsumeAllAssets) } - // We only support a single asset at a time. - ensure!(reserve_assets.len() == 1, TooManyAssets); let reserve_asset = reserve_assets.get(0).ok_or(AssetResolutionFailed)?; - // If there was a fee specified verify it. - if let Some(fee_asset) = fee_asset { - // The fee asset must be the same as the reserve asset. - if fee_asset.id != reserve_asset.id || fee_asset.fun > reserve_asset.fun { - return Err(InvalidFeeAsset) - } - } - let (token, amount) = match reserve_asset { Asset { id: AssetId(inner_location), fun: Fungible(amount) } => match inner_location.unpack() { diff --git a/bridges/snowbridge/primitives/router/src/outbound/tests.rs b/bridges/snowbridge/primitives/router/src/outbound/tests.rs index 111243bb45a7..54513396c765 100644 --- a/bridges/snowbridge/primitives/router/src/outbound/tests.rs +++ b/bridges/snowbridge/primitives/router/src/outbound/tests.rs @@ -345,14 +345,14 @@ fn exporter_validate_xcm_success_case_1() { fun: Fungible(1000), }] .into(); - let fee = assets.clone().get(0).unwrap().clone(); + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; let filter: AssetFilter = assets.clone().into(); let mut message: Option> = Some( vec![ WithdrawAsset(assets.clone()), ClearOrigin, - BuyExecution { fees: fee, weight_limit: Unlimited }, + BuyExecution { fees: fee_asset, weight_limit: Unlimited }, DepositAsset { assets: filter, beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), @@ -398,44 +398,12 @@ fn xcm_converter_convert_success() { }] .into(); let filter: AssetFilter = assets.clone().into(); + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; let message: Xcm<()> = vec![ WithdrawAsset(assets.clone()), ClearOrigin, - BuyExecution { fees: assets.get(0).unwrap().clone(), weight_limit: Unlimited }, - DepositAsset { - assets: filter, - beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), - }, - SetTopic([0; 32]), - ] - .into(); - let mut converter = XcmConverter::new(&message, &network); - let expected_payload = AgentExecuteCommand::TransferToken { - token: token_address.into(), - recipient: beneficiary_address.into(), - amount: 1000, - }; - let result = converter.convert(); - assert_eq!(result, Ok((expected_payload, [0; 32]))); -} - -#[test] -fn xcm_converter_convert_without_buy_execution_yields_success() { - let network = BridgedNetwork::get(); - - let token_address: [u8; 20] = hex!("1000000000000000000000000000000000000000"); - let beneficiary_address: [u8; 20] = hex!("2000000000000000000000000000000000000000"); - - let assets: Assets = vec![Asset { - id: AssetId([AccountKey20 { network: None, key: token_address }].into()), - fun: Fungible(1000), - }] - .into(); - let filter: AssetFilter = assets.clone().into(); - - let message: Xcm<()> = vec![ - WithdrawAsset(assets.clone()), + BuyExecution { fees: fee_asset, weight_limit: Unlimited }, DepositAsset { assets: filter, beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), @@ -467,40 +435,7 @@ fn xcm_converter_convert_with_wildcard_all_asset_filter_succeeds() { .into(); let filter: AssetFilter = Wild(All); - let message: Xcm<()> = vec![ - WithdrawAsset(assets.clone()), - ClearOrigin, - BuyExecution { fees: assets.get(0).unwrap().clone(), weight_limit: Unlimited }, - DepositAsset { - assets: filter, - beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), - }, - SetTopic([0; 32]), - ] - .into(); - let mut converter = XcmConverter::new(&message, &network); - let expected_payload = AgentExecuteCommand::TransferToken { - token: token_address.into(), - recipient: beneficiary_address.into(), - amount: 1000, - }; - let result = converter.convert(); - assert_eq!(result, Ok((expected_payload, [0; 32]))); -} - -#[test] -fn xcm_converter_convert_with_fees_less_than_reserve_yields_success() { - let network = BridgedNetwork::get(); - - let token_address: [u8; 20] = hex!("1000000000000000000000000000000000000000"); - let beneficiary_address: [u8; 20] = hex!("2000000000000000000000000000000000000000"); - - let asset_location: Location = [AccountKey20 { network: None, key: token_address }].into(); - let fee_asset = Asset { id: AssetId(asset_location.clone()), fun: Fungible(500) }; - - let assets: Assets = vec![Asset { id: AssetId(asset_location), fun: Fungible(1000) }].into(); - - let filter: AssetFilter = assets.clone().into(); + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; let message: Xcm<()> = vec![ WithdrawAsset(assets.clone()), @@ -537,9 +472,11 @@ fn xcm_converter_convert_without_set_topic_yields_set_topic_expected() { .into(); let filter: AssetFilter = assets.clone().into(); + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; + let message: Xcm<()> = vec![ WithdrawAsset(assets.clone()), - BuyExecution { fees: assets.get(0).unwrap().clone(), weight_limit: Unlimited }, + BuyExecution { fees: fee_asset, weight_limit: Unlimited }, DepositAsset { assets: filter, beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), @@ -569,67 +506,6 @@ fn xcm_converter_convert_with_partial_message_yields_unexpected_end_of_xcm() { assert_eq!(result.err(), Some(XcmConverterError::UnexpectedEndOfXcm)); } -#[test] -fn xcm_converter_with_different_fee_asset_fails() { - let network = BridgedNetwork::get(); - - let token_address: [u8; 20] = hex!("1000000000000000000000000000000000000000"); - let beneficiary_address: [u8; 20] = hex!("2000000000000000000000000000000000000000"); - - let asset_location = [AccountKey20 { network: None, key: token_address }].into(); - let fee_asset = - Asset { id: AssetId(Location { parents: 0, interior: Here }), fun: Fungible(1000) }; - - let assets: Assets = vec![Asset { id: AssetId(asset_location), fun: Fungible(1000) }].into(); - - let filter: AssetFilter = assets.clone().into(); - - let message: Xcm<()> = vec![ - WithdrawAsset(assets.clone()), - ClearOrigin, - BuyExecution { fees: fee_asset, weight_limit: Unlimited }, - DepositAsset { - assets: filter, - beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), - }, - SetTopic([0; 32]), - ] - .into(); - let mut converter = XcmConverter::new(&message, &network); - let result = converter.convert(); - assert_eq!(result.err(), Some(XcmConverterError::InvalidFeeAsset)); -} - -#[test] -fn xcm_converter_with_fees_greater_than_reserve_fails() { - let network = BridgedNetwork::get(); - - let token_address: [u8; 20] = hex!("1000000000000000000000000000000000000000"); - let beneficiary_address: [u8; 20] = hex!("2000000000000000000000000000000000000000"); - - let asset_location: Location = [AccountKey20 { network: None, key: token_address }].into(); - let fee_asset = Asset { id: AssetId(asset_location.clone()), fun: Fungible(1001) }; - - let assets: Assets = vec![Asset { id: AssetId(asset_location), fun: Fungible(1000) }].into(); - - let filter: AssetFilter = assets.clone().into(); - - let message: Xcm<()> = vec![ - WithdrawAsset(assets.clone()), - ClearOrigin, - BuyExecution { fees: fee_asset, weight_limit: Unlimited }, - DepositAsset { - assets: filter, - beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), - }, - SetTopic([0; 32]), - ] - .into(); - let mut converter = XcmConverter::new(&message, &network); - let result = converter.convert(); - assert_eq!(result.err(), Some(XcmConverterError::InvalidFeeAsset)); -} - #[test] fn xcm_converter_convert_with_empty_xcm_yields_unexpected_end_of_xcm() { let network = BridgedNetwork::get(); @@ -656,10 +532,12 @@ fn xcm_converter_convert_with_extra_instructions_yields_end_of_xcm_message_expec .into(); let filter: AssetFilter = assets.clone().into(); + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; + let message: Xcm<()> = vec![ WithdrawAsset(assets.clone()), ClearOrigin, - BuyExecution { fees: assets.get(0).unwrap().clone(), weight_limit: Unlimited }, + BuyExecution { fees: fee_asset, weight_limit: Unlimited }, DepositAsset { assets: filter, beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), @@ -716,10 +594,12 @@ fn xcm_converter_convert_without_withdraw_asset_yields_deposit_expected() { }] .into(); + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; + let message: Xcm<()> = vec![ WithdrawAsset(assets.clone()), ClearOrigin, - BuyExecution { fees: assets.get(0).unwrap().clone(), weight_limit: Unlimited }, + BuyExecution { fees: fee_asset, weight_limit: Unlimited }, SetTopic([0; 32]), ] .into(); @@ -733,22 +613,17 @@ fn xcm_converter_convert_without_withdraw_asset_yields_deposit_expected() { fn xcm_converter_convert_without_assets_yields_no_reserve_assets() { let network = BridgedNetwork::get(); - let token_address: [u8; 20] = hex!("1000000000000000000000000000000000000000"); - let beneficiary_address: [u8; 20] = hex!("2000000000000000000000000000000000000000"); let assets: Assets = vec![].into(); let filter: AssetFilter = assets.clone().into(); - let fee = Asset { - id: AssetId(AccountKey20 { network: None, key: token_address }.into()), - fun: Fungible(1000), - }; + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; let message: Xcm<()> = vec![ WithdrawAsset(assets.clone()), ClearOrigin, - BuyExecution { fees: fee, weight_limit: Unlimited }, + BuyExecution { fees: fee_asset, weight_limit: Unlimited }, DepositAsset { assets: filter, beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), @@ -762,44 +637,6 @@ fn xcm_converter_convert_without_assets_yields_no_reserve_assets() { assert_eq!(result.err(), Some(XcmConverterError::NoReserveAssets)); } -#[test] -fn xcm_converter_convert_with_two_assets_yields_too_many_assets() { - let network = BridgedNetwork::get(); - - let token_address_1: [u8; 20] = hex!("1000000000000000000000000000000000000000"); - let token_address_2: [u8; 20] = hex!("1100000000000000000000000000000000000000"); - let beneficiary_address: [u8; 20] = hex!("2000000000000000000000000000000000000000"); - - let assets: Assets = vec![ - Asset { - id: AssetId(AccountKey20 { network: None, key: token_address_1 }.into()), - fun: Fungible(1000), - }, - Asset { - id: AssetId(AccountKey20 { network: None, key: token_address_2 }.into()), - fun: Fungible(500), - }, - ] - .into(); - let filter: AssetFilter = assets.clone().into(); - - let message: Xcm<()> = vec![ - WithdrawAsset(assets.clone()), - ClearOrigin, - BuyExecution { fees: assets.get(0).unwrap().clone(), weight_limit: Unlimited }, - DepositAsset { - assets: filter, - beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), - }, - SetTopic([0; 32]), - ] - .into(); - let mut converter = XcmConverter::new(&message, &network); - - let result = converter.convert(); - assert_eq!(result.err(), Some(XcmConverterError::TooManyAssets)); -} - #[test] fn xcm_converter_convert_without_consuming_filter_yields_filter_does_not_consume_all_assets() { let network = BridgedNetwork::get(); @@ -814,10 +651,12 @@ fn xcm_converter_convert_without_consuming_filter_yields_filter_does_not_consume .into(); let filter: AssetFilter = Wild(WildAsset::AllCounted(0)); + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; + let message: Xcm<()> = vec![ WithdrawAsset(assets.clone()), ClearOrigin, - BuyExecution { fees: assets.get(0).unwrap().clone(), weight_limit: Unlimited }, + BuyExecution { fees: fee_asset, weight_limit: Unlimited }, DepositAsset { assets: filter, beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), @@ -845,10 +684,12 @@ fn xcm_converter_convert_with_zero_amount_asset_yields_zero_asset_transfer() { .into(); let filter: AssetFilter = Wild(WildAsset::AllCounted(1)); + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; + let message: Xcm<()> = vec![ WithdrawAsset(assets.clone()), ClearOrigin, - BuyExecution { fees: assets.get(0).unwrap().clone(), weight_limit: Unlimited }, + BuyExecution { fees: fee_asset, weight_limit: Unlimited }, DepositAsset { assets: filter, beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), @@ -875,10 +716,12 @@ fn xcm_converter_convert_non_ethereum_asset_yields_asset_resolution_failed() { .into(); let filter: AssetFilter = Wild(WildAsset::AllCounted(1)); + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; + let message: Xcm<()> = vec![ WithdrawAsset(assets.clone()), ClearOrigin, - BuyExecution { fees: assets.get(0).unwrap().clone(), weight_limit: Unlimited }, + BuyExecution { fees: fee_asset, weight_limit: Unlimited }, DepositAsset { assets: filter, beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), @@ -908,10 +751,12 @@ fn xcm_converter_convert_non_ethereum_chain_asset_yields_asset_resolution_failed .into(); let filter: AssetFilter = Wild(WildAsset::AllCounted(1)); + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; + let message: Xcm<()> = vec![ WithdrawAsset(assets.clone()), ClearOrigin, - BuyExecution { fees: assets.get(0).unwrap().clone(), weight_limit: Unlimited }, + BuyExecution { fees: fee_asset, weight_limit: Unlimited }, DepositAsset { assets: filter, beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), @@ -941,10 +786,12 @@ fn xcm_converter_convert_non_ethereum_chain_yields_asset_resolution_failed() { .into(); let filter: AssetFilter = Wild(WildAsset::AllCounted(1)); + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; + let message: Xcm<()> = vec![ WithdrawAsset(assets.clone()), ClearOrigin, - BuyExecution { fees: assets.get(0).unwrap().clone(), weight_limit: Unlimited }, + BuyExecution { fees: fee_asset, weight_limit: Unlimited }, DepositAsset { assets: filter, beneficiary: AccountKey20 { network: None, key: beneficiary_address }.into(), @@ -973,10 +820,13 @@ fn xcm_converter_convert_with_non_ethereum_beneficiary_yields_beneficiary_resolu }] .into(); let filter: AssetFilter = Wild(WildAsset::AllCounted(1)); + + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; + let message: Xcm<()> = vec![ WithdrawAsset(assets.clone()), ClearOrigin, - BuyExecution { fees: assets.get(0).unwrap().clone(), weight_limit: Unlimited }, + BuyExecution { fees: fee_asset, weight_limit: Unlimited }, DepositAsset { assets: filter, beneficiary: [ @@ -1010,10 +860,12 @@ fn xcm_converter_convert_with_non_ethereum_chain_beneficiary_yields_beneficiary_ .into(); let filter: AssetFilter = Wild(WildAsset::AllCounted(1)); + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; + let message: Xcm<()> = vec![ WithdrawAsset(assets.clone()), ClearOrigin, - BuyExecution { fees: assets.get(0).unwrap().clone(), weight_limit: Unlimited }, + BuyExecution { fees: fee_asset, weight_limit: Unlimited }, DepositAsset { assets: filter, beneficiary: AccountKey20 { diff --git a/bridges/snowbridge/runtime/test-common/src/lib.rs b/bridges/snowbridge/runtime/test-common/src/lib.rs index 8f36313e360f..51bf04eb30d1 100644 --- a/bridges/snowbridge/runtime/test-common/src/lib.rs +++ b/bridges/snowbridge/runtime/test-common/src/lib.rs @@ -67,10 +67,12 @@ where }; let assets = vec![asset.clone()]; + let fee_asset = Asset { id: AssetId::from(Location::parent()), fun: Fungible(1000) }; + let inner_xcm = Xcm(vec![ WithdrawAsset(Assets::from(assets.clone())), ClearOrigin, - BuyExecution { fees: asset, weight_limit: Unlimited }, + BuyExecution { fees: fee_asset, weight_limit: Unlimited }, DepositAsset { assets: Wild(All), beneficiary: Location::new( diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs index 8856fe8eca51..955903a5c631 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs @@ -383,6 +383,7 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { use asset_hub_rococo_runtime::xcm_config::bridging::to_ethereum::DefaultBridgeHubEthereumBaseFee; let assethub_location = BridgeHubRococo::sibling_location_of(AssetHubRococo::para_id()); let assethub_sovereign = BridgeHubRococo::sovereign_account_id_of(assethub_location); + let bridgehub_location = AssetHubRococo::sibling_location_of(BridgeHubRococo::para_id()); AssetHubRococo::force_default_xcm_version(Some(XCM_VERSION)); BridgeHubRococo::force_default_xcm_version(Some(XCM_VERSION)); @@ -392,80 +393,103 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { ); BridgeHubRococo::fund_accounts(vec![(assethub_sovereign.clone(), INITIAL_FUND)]); - AssetHubRococo::fund_accounts(vec![(AssetHubRococoReceiver::get(), INITIAL_FUND)]); const WETH_AMOUNT: u128 = 1_000_000_000; + const FEE_AMOUNT: u128 = 2_750_872_500_000; + const LOCAL_FEE_AMOUNT: u128 = 16903333; + const REMOTE_FEE_AMOUNT: u128 = FEE_AMOUNT - LOCAL_FEE_AMOUNT; - BridgeHubRococo::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; + let weth_asset_location: Location = Location::new( + 2, + [EthereumNetwork::get().into(), AccountKey20 { network: None, key: WETH }], + ); - // Construct RegisterToken message and sent to inbound queue - send_inbound_message(make_register_token_message()).unwrap(); + // Register WETH and Mint some to AssetHubRococoReceiver + AssetHubRococo::execute_with(|| { + type RuntimeOrigin = ::RuntimeOrigin; - // Check that the register token message was sent using xcm - assert_expected_events!( - BridgeHubRococo, - vec![ - RuntimeEvent::XcmpQueue(cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. }) => {}, - ] - ); + assert_ok!(::ForeignAssets::force_create( + RuntimeOrigin::root(), + weth_asset_location.clone().try_into().unwrap(), + AssetHubRococoReceiver::get().into(), + false, + 1, + )); - // Construct SendToken message and sent to inbound queue - send_inbound_message(make_send_token_message()).unwrap(); + assert!(::ForeignAssets::asset_exists( + weth_asset_location.clone().try_into().unwrap(), + )); - // Check that the send token message was sent using xcm - assert_expected_events!( - BridgeHubRococo, - vec![ - RuntimeEvent::XcmpQueue(cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. }) => {}, - ] - ); + assert_ok!(::ForeignAssets::mint( + RuntimeOrigin::signed(AssetHubRococoReceiver::get()), + weth_asset_location.clone().try_into().unwrap(), + AssetHubRococoReceiver::get().into(), + WETH_AMOUNT, + )); }); AssetHubRococo::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; type RuntimeOrigin = ::RuntimeOrigin; - // Check that AssetHub has issued the foreign asset - assert_expected_events!( - AssetHubRococo, - vec![ - RuntimeEvent::ForeignAssets(pallet_assets::Event::Issued { .. }) => {}, - ] - ); - let assets = vec![Asset { - id: AssetId(Location::new( - 2, - [ - GlobalConsensus(Ethereum { chain_id: CHAIN_ID }), - AccountKey20 { network: None, key: WETH }, - ], - )), - fun: Fungible(WETH_AMOUNT), - }]; - let multi_assets = VersionedAssets::V4(Assets::from(assets)); - - let destination = VersionedLocation::V4(Location::new( - 2, - [GlobalConsensus(Ethereum { chain_id: CHAIN_ID })], - )); + // DOT as fee asset + let fee_asset = Asset { id: AssetId(Location::parent()), fun: Fungible(FEE_AMOUNT) }; + + let remote_fee_asset = + Asset { id: AssetId(Location::parent()), fun: Fungible(REMOTE_FEE_AMOUNT) }; + + let local_fee_asset = + Asset { id: AssetId(Location::parent()), fun: Fungible(LOCAL_FEE_AMOUNT) }; + + let weth_asset = Asset { id: weth_asset_location.into(), fun: Fungible(WETH_AMOUNT) }; - let beneficiary = VersionedLocation::V4(Location::new( + // Send both assets to BH + let assets = vec![fee_asset.clone(), weth_asset.clone()]; + + let destination = Location::new(2, [GlobalConsensus(Ethereum { chain_id: CHAIN_ID })]); + + let beneficiary = Location::new( 0, [AccountKey20 { network: None, key: ETHEREUM_DESTINATION_ADDRESS.into() }], - )); + ); + // Internal xcm of InitiateReserveWithdraw, WithdrawAssets + ClearOrigin instructions will + // be appended to the front of the list by the xcm executor + let withdraw_xcm_on_bh = Xcm(vec![ + BuyExecution { fees: remote_fee_asset.clone(), weight_limit: Unlimited }, + DepositAsset { assets: Wild(AllCounted(2)), beneficiary }, + ]); + + let teleport_xcm_on_bh = Xcm(vec![ + BuyExecution { fees: local_fee_asset.clone(), weight_limit: Unlimited }, + DepositAsset { + assets: Wild(AllCounted(1)), + beneficiary: (AccountId32 { id: assethub_sovereign.into(), network: None },).into(), + }, + ]); + + let xcms = VersionedXcm::from(Xcm(vec![ + WithdrawAsset(assets.clone().into()), + SetFeesMode { jit_withdraw: true }, + InitiateReserveWithdraw { + assets: Definite(vec![remote_fee_asset.clone(), weth_asset.clone()].into()), + // with reserve set to Ethereum destination, the ExportMessage will + // be appended to the front of the list by the SovereignPaidRemoteExporter + reserve: destination, + xcm: withdraw_xcm_on_bh, + }, + InitiateTeleport { + assets: Definite(vec![local_fee_asset.clone()].into()), + xcm: teleport_xcm_on_bh, + dest: bridgehub_location, + }, + ])); let free_balance_before = ::Balances::free_balance( AssetHubRococoReceiver::get(), ); - // Send the Weth back to Ethereum - ::PolkadotXcm::limited_reserve_transfer_assets( + ::PolkadotXcm::execute( RuntimeOrigin::signed(AssetHubRococoReceiver::get()), - Box::new(destination), - Box::new(beneficiary), - Box::new(multi_assets), - 0, - Unlimited, + bx!(xcms), + Weight::from(8_000_000_000), ) .unwrap(); let free_balance_after = ::Balances::free_balance( @@ -486,25 +510,6 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { RuntimeEvent::EthereumOutboundQueue(snowbridge_pallet_outbound_queue::Event::MessageQueued {..}) => {}, ] ); - let events = BridgeHubRococo::events(); - // Check that the local fee was credited to the Snowbridge sovereign account - assert!( - events.iter().any(|event| matches!( - event, - RuntimeEvent::Balances(pallet_balances::Event::Minted { who, amount }) - if *who == TREASURY_ACCOUNT.into() && *amount == 16903333 - )), - "Snowbridge sovereign takes local fee." - ); - // Check that the remote fee was credited to the AssetHub sovereign account - assert!( - events.iter().any(|event| matches!( - event, - RuntimeEvent::Balances(pallet_balances::Event::Minted { who, amount }) - if *who == assethub_sovereign && *amount == 2680000000000, - )), - "AssetHub sovereign takes remote fee." - ); }); } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs index 664d2b9c9dd5..0054cf306044 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs @@ -635,11 +635,8 @@ pub mod bridging { use super::*; parameter_types! { - /// User fee for ERC20 token transfer back to Ethereum. - /// (initially was calculated by test `OutboundQueue::calculate_fees` - ETH/ROC 1/400 and fee_per_gas 20 GWEI = 2200698000000 + *25%) - /// Needs to be more than fee calculated from DefaultFeeConfig FeeConfigRecord in snowbridge:parachain/pallets/outbound-queue/src/lib.rs - /// Polkadot uses 10 decimals, Kusama and Rococo 12 decimals. - pub const DefaultBridgeHubEthereumBaseFee: Balance = 2_750_872_500_000; + /// User fee for delivery cost on bridge hub. Leave some buffer here for avoid spamming + pub const DefaultBridgeHubEthereumBaseFee: Balance = 4_000_000_000; pub storage BridgeHubEthereumBaseFee: Balance = DefaultBridgeHubEthereumBaseFee::get(); pub SiblingBridgeHubWithEthereumInboundQueueInstance: Location = Location::new( 1, diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs index a0d2e91dffd2..4d479fff47c7 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs @@ -38,11 +38,9 @@ use parachains_common::{ }; use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; -use snowbridge_runtime_common::XcmExportFeeToSibling; use sp_core::Get; use sp_runtime::traits::AccountIdConversion; use sp_std::marker::PhantomData; -use testnet_parachains_constants::rococo::snowbridge::EthereumNetwork; use xcm::latest::prelude::*; use xcm_builder::{ deposit_or_burn_fee, AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, @@ -52,10 +50,10 @@ use xcm_builder::{ ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, - XcmFeeToAccount, + XcmFeeManagerFromComponents, XcmFeeToAccount, }; use xcm_executor::{ - traits::{FeeManager, FeeReason, FeeReason::Export, TransactAsset}, + traits::{FeeReason, TransactAsset}, XcmExecutor, }; @@ -205,7 +203,7 @@ impl xcm_executor::Config for XcmConfig { type SubscriptionService = PolkadotXcm; type PalletInstancesInfo = AllPalletsWithSystem; type MaxAssetsIntoHolding = MaxAssetsIntoHolding; - type FeeManager = XcmFeeManagerFromComponentsBridgeHub< + type FeeManager = XcmFeeManagerFromComponents< WaivedLocations, ( XcmExportFeeToRelayerRewardAccounts< @@ -215,14 +213,6 @@ impl xcm_executor::Config for XcmConfig { crate::bridge_to_westend_config::BridgeHubWestendChainId, crate::bridge_to_westend_config::AssetHubRococoToAssetHubWestendMessagesLane, >, - XcmExportFeeToSibling< - bp_rococo::Balance, - AccountId, - TokenLocation, - EthereumNetwork, - Self::AssetTransactor, - crate::EthereumOutboundQueue, - >, XcmFeeToAccount, ), >; @@ -383,22 +373,3 @@ impl< fee } } - -pub struct XcmFeeManagerFromComponentsBridgeHub( - PhantomData<(WaivedLocations, HandleFee)>, -); -impl, FeeHandler: HandleFee> FeeManager - for XcmFeeManagerFromComponentsBridgeHub -{ - fn is_waived(origin: Option<&Location>, fee_reason: FeeReason) -> bool { - let Some(loc) = origin else { return false }; - if let Export { network, destination: Here } = fee_reason { - return !(network == EthereumNetwork::get()) - } - WaivedLocations::contains(loc) - } - - fn handle_fee(fee: Assets, context: Option<&XcmContext>, reason: FeeReason) { - FeeHandler::handle_fee(fee, context, reason); - } -} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/snowbridge.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/snowbridge.rs index 5960ab7b5505..733126c03461 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/snowbridge.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/snowbridge.rs @@ -25,7 +25,7 @@ use bridge_hub_rococo_runtime::{ SignedExtra, UncheckedExtrinsic, }; use codec::{Decode, Encode}; -use cumulus_primitives_core::XcmError::{FailedToTransactAsset, NotHoldingFees}; +use cumulus_primitives_core::XcmError::{FailedToTransactAsset, TooExpensive}; use frame_support::parameter_types; use parachains_common::{AccountId, AuraId, Balance}; use snowbridge_pallet_ethereum_client::WeightInfo; @@ -90,8 +90,8 @@ pub fn transfer_token_to_ethereum_fee_not_enough() { H160::random(), H160::random(), // fee not enough - 1_000_000_000, - NotHoldingFees, + 4_000_000, + TooExpensive, ) } From 6729e4b948d2b87e8dcd358f59eeec2aa850dee0 Mon Sep 17 00:00:00 2001 From: ron Date: Tue, 23 Jul 2024 09:50:10 +0800 Subject: [PATCH 2/6] Change the value of local fee --- .../tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs | 6 +++--- .../runtimes/assets/asset-hub-rococo/src/xcm_config.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs index 955903a5c631..4ef81fb224b2 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs @@ -36,8 +36,6 @@ use testnet_parachains_constants::rococo::snowbridge::EthereumNetwork; const INITIAL_FUND: u128 = 5_000_000_000 * ROCOCO_ED; const CHAIN_ID: u64 = 11155111; -const TREASURY_ACCOUNT: [u8; 32] = - hex!("6d6f646c70792f74727372790000000000000000000000000000000000000000"); const WETH: [u8; 20] = hex!("87d1f7fdfEe7f651FaBc8bFCB6E086C278b77A7d"); const ETHEREUM_DESTINATION_ADDRESS: [u8; 20] = hex!("44a57ee2f2FCcb85FDa2B0B18EBD0D8D2333700e"); const INSUFFICIENT_XCM_FEE: u128 = 1000; @@ -396,7 +394,9 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { const WETH_AMOUNT: u128 = 1_000_000_000; const FEE_AMOUNT: u128 = 2_750_872_500_000; - const LOCAL_FEE_AMOUNT: u128 = 16903333; + // To cover the delivery cost on BH + const LOCAL_FEE_AMOUNT: u128 = 1_000_000_000; + // To cover the delivery cost on Ethereum const REMOTE_FEE_AMOUNT: u128 = FEE_AMOUNT - LOCAL_FEE_AMOUNT; let weth_asset_location: Location = Location::new( diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs index 0054cf306044..a2ccedf2b87e 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs @@ -636,7 +636,7 @@ pub mod bridging { parameter_types! { /// User fee for delivery cost on bridge hub. Leave some buffer here for avoid spamming - pub const DefaultBridgeHubEthereumBaseFee: Balance = 4_000_000_000; + pub const DefaultBridgeHubEthereumBaseFee: Balance = 1_000_000_000; pub storage BridgeHubEthereumBaseFee: Balance = DefaultBridgeHubEthereumBaseFee::get(); pub SiblingBridgeHubWithEthereumInboundQueueInstance: Location = Location::new( 1, From e927ced0f1c97666f9f6a459cebf1b7916fea448 Mon Sep 17 00:00:00 2001 From: ron Date: Mon, 29 Jul 2024 21:01:19 +0800 Subject: [PATCH 3/6] Improve test checking balance --- .../bridge-hub-rococo/src/tests/snowbridge.rs | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs index 87be4675eb33..22644dc00b03 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs @@ -381,19 +381,15 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { let assethub_sovereign = BridgeHubRococo::sovereign_account_id_of(assethub_location); let bridgehub_location = AssetHubRococo::sibling_location_of(BridgeHubRococo::para_id()); - AssetHubRococo::force_default_xcm_version(Some(XCM_VERSION)); - BridgeHubRococo::force_default_xcm_version(Some(XCM_VERSION)); AssetHubRococo::force_xcm_version( Location::new(2, [GlobalConsensus(Ethereum { chain_id: CHAIN_ID })]), XCM_VERSION, ); - BridgeHubRococo::fund_accounts(vec![(assethub_sovereign.clone(), INITIAL_FUND)]); - const WETH_AMOUNT: u128 = 1_000_000_000; const FEE_AMOUNT: u128 = 2_750_872_500_000; // To cover the delivery cost on BH - const LOCAL_FEE_AMOUNT: u128 = 1_000_000_000; + const LOCAL_FEE_AMOUNT: u128 = DefaultBridgeHubEthereumBaseFee::get() + 12_000_000; // To cover the delivery cost on Ethereum const REMOTE_FEE_AMOUNT: u128 = FEE_AMOUNT - LOCAL_FEE_AMOUNT; @@ -457,13 +453,19 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { BuyExecution { fees: local_fee_asset.clone(), weight_limit: Unlimited }, DepositAsset { assets: Wild(AllCounted(1)), - beneficiary: (AccountId32 { id: assethub_sovereign.into(), network: None },).into(), + beneficiary: + (AccountId32 { id: assethub_sovereign.clone().into(), network: None },).into(), }, ]); let xcms = VersionedXcm::from(Xcm(vec![ WithdrawAsset(assets.clone().into()), SetFeesMode { jit_withdraw: true }, + InitiateTeleport { + assets: Definite(vec![local_fee_asset.clone()].into()), + xcm: teleport_xcm_on_bh, + dest: bridgehub_location, + }, InitiateReserveWithdraw { assets: Definite(vec![remote_fee_asset.clone(), weth_asset.clone()].into()), // with reserve set to Ethereum destination, the ExportMessage will @@ -471,15 +473,16 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { reserve: destination, xcm: withdraw_xcm_on_bh, }, - InitiateTeleport { - assets: Definite(vec![local_fee_asset.clone()].into()), - xcm: teleport_xcm_on_bh, - dest: bridgehub_location, - }, ])); let free_balance_before = ::Balances::free_balance( AssetHubRococoReceiver::get(), ); + // Assert there is no balance left in the assethub_sovereign on BH + let free_balance_of_sovereign_on_bh_before = + ::Balances::free_balance( + assethub_sovereign.clone(), + ); + assert_eq!(free_balance_of_sovereign_on_bh_before, 0); ::PolkadotXcm::execute( RuntimeOrigin::signed(AssetHubRococoReceiver::get()), bx!(xcms), @@ -504,6 +507,9 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { RuntimeEvent::EthereumOutboundQueue(snowbridge_pallet_outbound_queue::Event::MessageQueued {..}) => {}, ] ); + let free_balance_of_sovereign_on_bh_after = + ::Balances::free_balance(assethub_sovereign); + assert_eq!(free_balance_of_sovereign_on_bh_after, 955613334); }); } From 93f952e1a9a478c36023a7a2f7c76124b8c61f94 Mon Sep 17 00:00:00 2001 From: ron Date: Tue, 30 Jul 2024 09:25:46 +0800 Subject: [PATCH 4/6] Adjust fees more accurate --- .../bridges/bridge-hub-rococo/src/tests/snowbridge.rs | 8 +++++--- .../runtimes/assets/asset-hub-rococo/src/xcm_config.rs | 3 ++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs index 22644dc00b03..25e583286a32 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs @@ -388,8 +388,9 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { const WETH_AMOUNT: u128 = 1_000_000_000; const FEE_AMOUNT: u128 = 2_750_872_500_000; - // To cover the delivery cost on BH - const LOCAL_FEE_AMOUNT: u128 = DefaultBridgeHubEthereumBaseFee::get() + 12_000_000; + const TELEPORT_FEE_AMOUNT: u128 = 12_000_000; + // To cover the delivery cost on BH and + const LOCAL_FEE_AMOUNT: u128 = DefaultBridgeHubEthereumBaseFee::get() + TELEPORT_FEE_AMOUNT; // To cover the delivery cost on Ethereum const REMOTE_FEE_AMOUNT: u128 = FEE_AMOUNT - LOCAL_FEE_AMOUNT; @@ -507,9 +508,10 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { RuntimeEvent::EthereumOutboundQueue(snowbridge_pallet_outbound_queue::Event::MessageQueued {..}) => {}, ] ); + // Assert there is still some fee left in sov account after the transfer let free_balance_of_sovereign_on_bh_after = ::Balances::free_balance(assethub_sovereign); - assert_eq!(free_balance_of_sovereign_on_bh_after, 955613334); + assert_eq!(free_balance_of_sovereign_on_bh_after, 3613334); }); } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs index eb2f4ba2514f..bc66f936c00c 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs @@ -628,7 +628,8 @@ pub mod bridging { parameter_types! { /// User fee for delivery cost on bridge hub. Leave some buffer here for avoid spamming - pub const DefaultBridgeHubEthereumBaseFee: Balance = 1_000_000_000; + /// should cover at least the BuyExecution on BH + pub const DefaultBridgeHubEthereumBaseFee: Balance = 48_000_000; pub storage BridgeHubEthereumBaseFee: Balance = DefaultBridgeHubEthereumBaseFee::get(); pub SiblingBridgeHubWithEthereumInboundQueueInstance: Location = Location::new( 1, From 88c31b1bc95d61fc999cd14208912ca68b6721c4 Mon Sep 17 00:00:00 2001 From: ron Date: Tue, 30 Jul 2024 18:36:46 +0800 Subject: [PATCH 5/6] Add a custom SovereignReceiveTeleportRemoteExporter --- Cargo.lock | 2 + .../bridge-hub-rococo/src/tests/snowbridge.rs | 21 +-- .../assets/asset-hub-rococo/Cargo.toml | 4 + .../assets/asset-hub-rococo/src/xcm_config.rs | 125 ++++++++++++++++-- 4 files changed, 120 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 70a8e72fe36f..61ba9d99e1f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -893,9 +893,11 @@ dependencies = [ "sp-core", "sp-genesis-builder", "sp-inherents", + "sp-io", "sp-offchain", "sp-runtime", "sp-session", + "sp-std 14.0.0", "sp-storage 19.0.0", "sp-transaction-pool", "sp-version", diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs index 25e583286a32..dceee4c83afd 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs @@ -379,7 +379,6 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { use ahr_xcm_config::bridging::to_ethereum::DefaultBridgeHubEthereumBaseFee; let assethub_location = BridgeHubRococo::sibling_location_of(AssetHubRococo::para_id()); let assethub_sovereign = BridgeHubRococo::sovereign_account_id_of(assethub_location); - let bridgehub_location = AssetHubRococo::sibling_location_of(BridgeHubRococo::para_id()); AssetHubRococo::force_xcm_version( Location::new(2, [GlobalConsensus(Ethereum { chain_id: CHAIN_ID })]), @@ -388,9 +387,8 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { const WETH_AMOUNT: u128 = 1_000_000_000; const FEE_AMOUNT: u128 = 2_750_872_500_000; - const TELEPORT_FEE_AMOUNT: u128 = 12_000_000; // To cover the delivery cost on BH and - const LOCAL_FEE_AMOUNT: u128 = DefaultBridgeHubEthereumBaseFee::get() + TELEPORT_FEE_AMOUNT; + const LOCAL_FEE_AMOUNT: u128 = DefaultBridgeHubEthereumBaseFee::get(); // To cover the delivery cost on Ethereum const REMOTE_FEE_AMOUNT: u128 = FEE_AMOUNT - LOCAL_FEE_AMOUNT; @@ -450,23 +448,10 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { DepositAsset { assets: Wild(AllCounted(2)), beneficiary }, ]); - let teleport_xcm_on_bh = Xcm(vec![ - BuyExecution { fees: local_fee_asset.clone(), weight_limit: Unlimited }, - DepositAsset { - assets: Wild(AllCounted(1)), - beneficiary: - (AccountId32 { id: assethub_sovereign.clone().into(), network: None },).into(), - }, - ]); - let xcms = VersionedXcm::from(Xcm(vec![ WithdrawAsset(assets.clone().into()), + BurnAsset(local_fee_asset.clone().into()), SetFeesMode { jit_withdraw: true }, - InitiateTeleport { - assets: Definite(vec![local_fee_asset.clone()].into()), - xcm: teleport_xcm_on_bh, - dest: bridgehub_location, - }, InitiateReserveWithdraw { assets: Definite(vec![remote_fee_asset.clone(), weth_asset.clone()].into()), // with reserve set to Ethereum destination, the ExportMessage will @@ -511,7 +496,7 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { // Assert there is still some fee left in sov account after the transfer let free_balance_of_sovereign_on_bh_after = ::Balances::free_balance(assethub_sovereign); - assert_eq!(free_balance_of_sovereign_on_bh_after, 3613334); + assert_eq!(free_balance_of_sovereign_on_bh_after, 15590000); }); } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml b/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml index 98df41090a40..6e48248b7c72 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml @@ -49,10 +49,12 @@ sp-block-builder = { workspace = true } sp-consensus-aura = { workspace = true } sp-core = { workspace = true } sp-inherents = { workspace = true } +sp-io = { workspace = true } sp-genesis-builder = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } +sp-std = { workspace = true } sp-storage = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -237,9 +239,11 @@ std = [ "sp-core/std", "sp-genesis-builder/std", "sp-inherents/std", + "sp-io/std", "sp-offchain/std", "sp-runtime/std", "sp-session/std", + "sp-std/std", "sp-storage/std", "sp-transaction-pool/std", "sp-version/std", diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs index bc66f936c00c..65c470870303 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs @@ -20,15 +20,17 @@ use super::{ ToWestendXcmRouter, TransactionByteFee, TrustBackedAssetsInstance, Uniques, WeightToFee, XcmpQueue, }; +use crate::{vec, Vec}; use assets_common::{ matching::{FromNetwork, FromSiblingParachain, IsForeignConcreteAsset}, TrustBackedAssetsAsLocation, }; +use codec::Encode; use frame_support::{ parameter_types, traits::{ tokens::imbalance::{ResolveAssetTo, ResolveTo}, - ConstU32, Contains, Equals, Everything, Nothing, PalletInfoAccess, + ConstU32, Contains, Equals, Everything, Get, Nothing, PalletInfoAccess, }, }; use frame_system::EnsureRoot; @@ -44,22 +46,27 @@ use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; use snowbridge_router_primitives::inbound::GlobalConsensusEthereumConvertsFor; use sp_runtime::traits::{AccountIdConversion, ConvertInto}; +use sp_std::marker::PhantomData; use testnet_parachains_constants::rococo::snowbridge::{ EthereumNetwork, INBOUND_QUEUE_PALLET_INDEX, }; -use xcm::latest::prelude::*; +use xcm::{ + latest::prelude::*, + prelude::SendError::{MissingArgument, NotApplicable, Unroutable}, + VersionedLocation, VersionedXcm, +}; use xcm_builder::{ - AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowHrmpNotificationsFromRelayChain, - AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, - DenyReserveTransferToRelayChain, DenyThenTry, DescribeAllTerminal, DescribeFamily, - EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, - GlobalConsensusParachainConvertsFor, HashedDescription, IsConcrete, LocalMint, - NetworkExportTableItem, NoChecking, NonFungiblesAdapter, ParentAsSuperuser, ParentIsPreset, - RelayChainAsNative, SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignPaidRemoteExporter, - SovereignSignedViaLocation, StartsWith, StartsWithExplicitGlobalConsensus, TakeWeightCredit, - TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, - XcmFeeManagerFromComponents, + ensure_is_remote, AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, + AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, DenyThenTry, + DescribeAllTerminal, DescribeFamily, EnsureXcmOrigin, ExporterFor, FrameTransactionalProcessor, + FungibleAdapter, FungiblesAdapter, GlobalConsensusParachainConvertsFor, HashedDescription, + InspectMessageQueues, IsConcrete, LocalMint, NetworkExportTableItem, NoChecking, + NonFungiblesAdapter, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, + SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, StartsWith, + StartsWithExplicitGlobalConsensus, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, + WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, }; use xcm_executor::XcmExecutor; @@ -443,6 +450,92 @@ type LocalXcmRouter = ( XcmpQueue, ); +pub struct SovereignReceiveTeleportRemoteExporter( + PhantomData<(Bridges, Router, UniversalLocation)>, +); +impl> SendXcm + for SovereignReceiveTeleportRemoteExporter +{ + type Ticket = Router::Ticket; + + fn validate( + dest: &mut Option, + msg: &mut Option>, + ) -> SendResult { + let d = dest.as_ref().ok_or(MissingArgument)?; + let devolved = + ensure_is_remote(UniversalLocation::get(), d.clone()).map_err(|_| NotApplicable)?; + let (remote_network, remote_location) = devolved; + let xcm = msg.take().ok_or(MissingArgument)?; + + // find exporter + let Some((bridge, maybe_payment)) = + Bridges::exporter_for(&remote_network, &remote_location, &xcm) + else { + // We need to make sure that msg is not consumed in case of `NotApplicable`. + *msg = Some(xcm); + return Err(NotApplicable) + }; + + // `xcm` should already end with `SetTopic` - if it does, then extract and derive into + // an onward topic ID. + let maybe_forward_id = match xcm.last() { + Some(SetTopic(t)) => + Some((b"forward_id_for", t).using_encoded(sp_io::hashing::blake2_256)), + _ => None, + }; + + let local_from_bridge = + UniversalLocation::get().invert_target(&bridge).map_err(|_| Unroutable)?; + let export_instruction = + ExportMessage { network: remote_network, destination: remote_location, xcm }; + + let mut message = Xcm(if let Some(ref payment) = maybe_payment { + let fees = payment + .clone() + .reanchored(&bridge, &UniversalLocation::get()) + .map_err(|_| Unroutable)?; + vec![ + ReceiveTeleportedAsset(fees.clone().into()), + BuyExecution { fees, weight_limit: Unlimited }, + // `SetAppendix` ensures that `fees` are not trapped in any case, for example, when + // `ExportXcm::validate` encounters an error during the processing of + // `ExportMessage`. + SetAppendix(Xcm(vec![DepositAsset { + assets: AllCounted(1).into(), + beneficiary: local_from_bridge, + }])), + export_instruction, + ] + } else { + vec![export_instruction] + }); + if let Some(forward_id) = maybe_forward_id { + message.0.push(SetTopic(forward_id)); + } + + // We then send a normal message to the bridge asking it to export the prepended + // message to the remote chain. + let (v, mut cost) = validate_send::(bridge, message)?; + if let Some(bridge_payment) = maybe_payment { + cost.push(bridge_payment); + } + Ok((v, cost)) + } + + fn deliver(ticket: Router::Ticket) -> Result { + Router::deliver(ticket) + } +} + +impl InspectMessageQueues + for SovereignReceiveTeleportRemoteExporter +{ + fn get_messages() -> Vec<(VersionedLocation, Vec>)> { + Router::get_messages() + } +} + /// The means for routing XCM messages which are not for local execution into the right message /// queues. pub type XcmRouter = WithUniqueTopic<( @@ -452,7 +545,11 @@ pub type XcmRouter = WithUniqueTopic<( ToWestendXcmRouter, // Router which wraps and sends xcm to BridgeHub to be delivered to the Ethereum // GlobalConsensus - SovereignPaidRemoteExporter, + SovereignReceiveTeleportRemoteExporter< + bridging::EthereumNetworkExportTable, + XcmpQueue, + UniversalLocation, + >, )>; impl pallet_xcm::Config for Runtime { From a5a384cacd8200c1009c0a241f5b8c29a82578c2 Mon Sep 17 00:00:00 2001 From: ron Date: Wed, 31 Jul 2024 18:46:15 +0800 Subject: [PATCH 6/6] Revamp the xcm --- .../bridge-hub-rococo/src/tests/snowbridge.rs | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs index dceee4c83afd..ca5e761ea5af 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs @@ -388,9 +388,9 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { const WETH_AMOUNT: u128 = 1_000_000_000; const FEE_AMOUNT: u128 = 2_750_872_500_000; // To cover the delivery cost on BH and - const LOCAL_FEE_AMOUNT: u128 = DefaultBridgeHubEthereumBaseFee::get(); + let local_fee_amount: u128 = DefaultBridgeHubEthereumBaseFee::get(); // To cover the delivery cost on Ethereum - const REMOTE_FEE_AMOUNT: u128 = FEE_AMOUNT - LOCAL_FEE_AMOUNT; + let remote_fee_amount: u128 = FEE_AMOUNT - local_fee_amount; let weth_asset_location: Location = Location::new( 2, @@ -420,19 +420,13 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { AssetHubRococo::execute_with(|| { type RuntimeOrigin = ::RuntimeOrigin; - // DOT as fee asset - let fee_asset = Asset { id: AssetId(Location::parent()), fun: Fungible(FEE_AMOUNT) }; - let remote_fee_asset = - Asset { id: AssetId(Location::parent()), fun: Fungible(REMOTE_FEE_AMOUNT) }; - - let local_fee_asset = - Asset { id: AssetId(Location::parent()), fun: Fungible(LOCAL_FEE_AMOUNT) }; + Asset { id: AssetId(Location::parent()), fun: Fungible(remote_fee_amount) }; let weth_asset = Asset { id: weth_asset_location.into(), fun: Fungible(WETH_AMOUNT) }; // Send both assets to BH - let assets = vec![fee_asset.clone(), weth_asset.clone()]; + let assets = vec![remote_fee_asset.clone(), weth_asset.clone()]; let destination = Location::new(2, [GlobalConsensus(Ethereum { chain_id: CHAIN_ID })]); @@ -450,10 +444,9 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { let xcms = VersionedXcm::from(Xcm(vec![ WithdrawAsset(assets.clone().into()), - BurnAsset(local_fee_asset.clone().into()), SetFeesMode { jit_withdraw: true }, InitiateReserveWithdraw { - assets: Definite(vec![remote_fee_asset.clone(), weth_asset.clone()].into()), + assets: Definite(assets.clone().into()), // with reserve set to Ethereum destination, the ExportMessage will // be appended to the front of the list by the SovereignPaidRemoteExporter reserve: destination,