Skip to content

Commit

Permalink
update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
claravanstaden committed Oct 31, 2024
1 parent 2afc09f commit 8dadc2d
Show file tree
Hide file tree
Showing 9 changed files with 103 additions and 68 deletions.
96 changes: 60 additions & 36 deletions bridges/modules/relayers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,21 @@ use sp_arithmetic::traits::{AtLeast32BitUnsigned, Zero};
use sp_runtime::{traits::CheckedSub, Saturating};
use sp_std::marker::PhantomData;

pub use pallet::*;
pub use payment_adapter::DeliveryConfirmationPaymentsAdapter;
pub use stake_adapter::StakeAndSlashNamed;
pub use weights::WeightInfo;
pub use weights_ext::WeightInfoExt;
use frame_support::{
traits::fungible::{Inspect, Mutate},
traits::{
fungible::{Inspect, Mutate},
tokens::Preservation,
},
PalletError,
};
use frame_system::pallet_prelude::*;
pub use pallet::*;
pub use payment_adapter::DeliveryConfirmationPaymentsAdapter;
use snowbridge_core::rewards::RewardLedger;
use sp_core::H160;
pub use stake_adapter::StakeAndSlashNamed;
pub use weights::WeightInfo;
pub use weights_ext::WeightInfoExt;
use xcm::prelude::{send_xcm, SendError as XcmpSendError, *};
use xcm_executor::traits::TransactAsset;

Expand All @@ -62,7 +65,7 @@ pub const LOG_TARGET: &str = "runtime::bridge-relayers";

pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
pub type BalanceOf<T, I = ()> =
<<T as Config<I>>::Token as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
<<T as Config<I>>::Token as Inspect<<T as frame_system::Config>::AccountId>>::Balance;

#[frame_support::pallet]
pub mod pallet {
Expand Down Expand Up @@ -109,6 +112,9 @@ pub mod pallet {
type AssetTransactor: TransactAsset;
type AssetHubXCMFee: Get<u128>;
type Token: Mutate<Self::AccountId> + Inspect<Self::AccountId>;
/// TreasuryAccount to collect fees
#[pallet::constant]
type TreasuryAccount: Get<Self::AccountId>;
}

#[pallet::pallet]
Expand Down Expand Up @@ -256,13 +262,14 @@ pub mod pallet {
)
}

/// Claim accumulated rewards.
/// Claim accumulated relayer rewards. Balance is minted on AH.
/// Fees:
/// BH execution fee - paid in DOT when executing the claim extrinsic
/// XCM delivery fee to AH - paid in DOT to Treasury on BH
/// AH execution fee - paid in Weth, deducated from relayer accumulated rewards
#[pallet::call_index(3)]
#[pallet::weight((T::WeightInfo::claim(), DispatchClass::Operational))]
pub fn claim(
origin: OriginFor<T>,
deposit_location: Location,
) -> DispatchResult {
pub fn claim(origin: OriginFor<T>, deposit_location: Location) -> DispatchResult {
let account_id = ensure_signed(origin)?;
Self::process_claim(account_id, deposit_location)?;
Ok(())
Expand Down Expand Up @@ -431,10 +438,8 @@ pub mod pallet {
Ok(())
}

fn process_claim(
account_id: AccountIdOf<T>,
deposit_location: Location,
) -> DispatchResult {
/// Claim rewards on AH, based on accumulated rewards balance in storage.
fn process_claim(account_id: AccountIdOf<T>, deposit_location: Location) -> DispatchResult {
let value = RewardsMapping::<T, I>::get(account_id.clone());
if value.is_zero() {
return Err(Error::<T, I>::InsufficientFunds.into());
Expand All @@ -454,26 +459,45 @@ pub mod pallet {
UniversalOrigin(GlobalConsensus(T::EthereumNetwork::get())),
ReserveAssetDeposited(reward_asset.clone().into()),
BuyExecution { fees: fee_asset, weight_limit: Unlimited },
DepositAsset { assets: AllCounted(1).into(), beneficiary: deposit_location.clone() },
DepositAsset {
assets: AllCounted(1).into(),
beneficiary: deposit_location.clone()
},
SetAppendix(Xcm(alloc::vec![
RefundSurplus,
DepositAsset { assets: AllCounted(1).into(), beneficiary: deposit_location.clone() },
DepositAsset {
assets: AllCounted(1).into(),
beneficiary: deposit_location.clone()
},
])),
]
.into();
.into();

// Remove the reward since it has been claimed.
RewardsMapping::<T, I>::remove(account_id.clone());

let dest = Location::new(1, [Parachain(T::AssetHubParaId::get().into())]);
let (_xcm_hash, xcm_delivery_fee) = send_xcm::<T::XcmSender>(dest, xcm).map_err(Error::<T, I>::from)?;
let (_xcm_hash, xcm_delivery_fee) =
send_xcm::<T::XcmSender>(dest, xcm).map_err(Error::<T, I>::from)?;

match xcm_delivery_fee.get(0) {
Some(fee_asset) =>
if let Fungible(amount) = fee_asset.fun {
let xcm_delivery_fee_balance: BalanceOf<T, I> =
TryInto::<BalanceOf<T, I>>::try_into(amount)
.map_err(|_| Error::<T, I>::InvalidAmount)?;
let treasury_account = T::TreasuryAccount::get();
T::Token::transfer(
&account_id,
&treasury_account,
xcm_delivery_fee_balance,
Preservation::Preserve,
)?;
},
None => (),
};

// TODO charge delivery fee
Self::deposit_event(Event::RewardClaimed {
account_id,
deposit_location,
value,
});
Self::deposit_event(Event::RewardClaimed { account_id, deposit_location, value });
Ok(())
}
}
Expand Down Expand Up @@ -619,7 +643,7 @@ pub mod pallet {

#[pallet::storage]
pub type RewardsMapping<T: Config<I>, I: 'static = ()> =
StorageMap<_, Identity, AccountIdOf<T>, BalanceOf<T, I>, ValueQuery>;
StorageMap<_, Identity, AccountIdOf<T>, BalanceOf<T, I>, ValueQuery>;

impl<T: Config<I>, I: 'static> RewardLedger<AccountIdOf<T>, BalanceOf<T, I>> for Pallet<T, I> {
fn deposit(account_id: AccountIdOf<T>, value: BalanceOf<T, I>) -> DispatchResult {
Expand All @@ -636,19 +660,18 @@ pub mod pallet {
#[cfg(test)]
mod tests {
use super::*;
use sp_core::H256;
use bp_messages::LaneIdType;
use mock::{RuntimeEvent as TestEvent, *};
use sp_core::H256;

use crate::Event::{RewardPaid, RewardRegistered};
use bp_relayers::RewardsAccountOwner;
use frame_support::{
assert_noop, assert_ok,
assert_err, assert_noop, assert_ok,
traits::fungible::{Inspect, Mutate},
};
use frame_system::{EventRecord, Pallet as System, Phase};
use sp_runtime::DispatchError;
use frame_support::assert_err;

fn get_ready_for_events() {
System::<TestRuntime>::set_block_number(1);
Expand Down Expand Up @@ -1121,7 +1144,11 @@ mod tests {
fn test_claim() {
run_test(|| {
let relayer: u64 = 1;
let interior: InteriorLocation = [Parachain(1000), Junction::AccountId32{network: None, id: H256::random().into()}].into();
let interior: InteriorLocation = [
Parachain(1000),
Junction::AccountId32 { network: None, id: H256::random().into() },
]
.into();
let claim_location = Location::new(1, interior);

let result = Pallet::<TestRuntime>::claim(
Expand All @@ -1136,13 +1163,10 @@ mod tests {
assert_ok!(result2);

// Claim rewards
let result3 = Pallet::<TestRuntime>::claim(
RuntimeOrigin::signed(relayer),
claim_location,
);
let result3 =
Pallet::<TestRuntime>::claim(RuntimeOrigin::signed(relayer), claim_location);
assert_ok!(result3);
assert_eq!(<RewardsMapping<TestRuntime>>::get(relayer), 0);
});
}

}
15 changes: 6 additions & 9 deletions bridges/modules/relayers/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

use crate as pallet_bridge_relayers;

use crate::XcmpSendError;
use bp_header_chain::ChainWithGrandpa;
use bp_messages::{
target_chain::{DispatchMessage, MessageDispatch},
Expand All @@ -34,19 +35,15 @@ use frame_support::{
traits::fungible::Mutate,
weights::{ConstantMultiplier, IdentityFee, RuntimeDbWeight, Weight},
};
use hex_literal::hex;
use pallet_transaction_payment::Multiplier;
use sp_core::{ConstU64, ConstU8, H256};
use sp_core::{ConstU64, ConstU8, H160, H256};
use sp_runtime::{
traits::{BlakeTwo256, ConstU32},
traits::{BlakeTwo256, ConstU128, ConstU32},
BuildStorage, FixedPointNumber, Perquintill, StateVersion,
};
use sp_core::H160;
use xcm::{latest::SendXcm, prelude::*};
use crate::XcmpSendError;
use hex_literal::hex;
use xcm_executor::AssetsInHolding;
use xcm_executor::traits::TransactAsset;
use sp_runtime::traits::ConstU128;
use xcm_executor::{traits::TransactAsset, AssetsInHolding};

/// Account identifier at `ThisChain`.
pub type ThisChainAccountId = u64;
Expand Down Expand Up @@ -305,6 +302,7 @@ impl pallet_bridge_relayers::Config for TestRuntime {

type AssetTransactor = SuccessfulTransactor;
type AssetHubXCMFee = ConstU128<1_000_000_000_000u128>;
type InboundQueuePalletInstance = ConstU8<80>;
}

#[cfg(feature = "runtime-benchmarks")]
Expand Down Expand Up @@ -450,7 +448,6 @@ impl TransactAsset for SuccessfulTransactor {
}
}


/// Reward account params that we are using in tests.
pub fn test_reward_account_param() -> RewardsAccountParams<TestLaneIdType> {
RewardsAccountParams::new(
Expand Down
8 changes: 5 additions & 3 deletions bridges/snowbridge/pallets/inbound-queue-v2/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use super::*;

use bp_messages::{HashedLaneId, LaneIdType};
use bp_relayers::{PayRewardFromAccount, PaymentProcedure, RewardsAccountParams};
use frame_support::{derive_impl, parameter_types, traits::ConstU32};
use frame_support::{derive_impl, parameter_types, traits::ConstU32, PalletId};
use hex_literal::hex;
use snowbridge_beacon_primitives::{
types::deneb, BeaconHeader, ExecutionProof, Fork, ForkVersions, VersionedExecutionPayloadHeader,
Expand All @@ -15,7 +15,7 @@ use snowbridge_core::{
};
use sp_core::{ConstU128, ConstU8, H160};
use sp_runtime::{
traits::{IdentifyAccount, IdentityLookup, MaybeEquivalence, Verify},
traits::{AccountIdConversion, IdentifyAccount, IdentityLookup, MaybeEquivalence, Verify},
BuildStorage, MultiSignature,
};
use sp_std::{convert::From, default::Default};
Expand Down Expand Up @@ -177,6 +177,7 @@ impl inbound_queue::Config for Test {

parameter_types! {
pub WethAddress: H160 = hex!("774667629726ec1FaBEbCEc0D9139bD1C8f72a23").into();
pub TreasuryAccount: AccountId = PalletId(*b"py/trsry").into_account_truncating();
}

pub type TestLaneIdType = HashedLaneId;
Expand Down Expand Up @@ -216,7 +217,8 @@ impl pallet_bridge_relayers::Config for Test {
type WethAddress = WethAddress;
type XcmSender = MockXcmSender;
type AssetTransactor = SuccessfulTransactor;
type AssetHubXCMFee = ConstU128<1_000_000_000_000u128>;
type AssetHubXCMFee = ConstU128<15u128>;
type TreasuryAccount = TreasuryAccount;
}

pub fn last_events(n: usize) -> Vec<RuntimeEvent> {
Expand Down
3 changes: 2 additions & 1 deletion bridges/snowbridge/pallets/inbound-queue/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,8 @@ pub mod pallet {
);

// Burning fees for teleport
burn_fees::<T::AssetTransactor, BalanceOf<T>>(channel.para_id, fee)?;
let parachain_location = Location::new(1, [Parachain(channel.para_id.into())]);
burn_fees::<T::AssetTransactor, BalanceOf<T>>(parachain_location, fee)?;

// Attempt to send XCM to a dest parachain
let message_id = Self::send_xcm(xcm, channel.para_id)?;
Expand Down
7 changes: 5 additions & 2 deletions bridges/snowbridge/pallets/outbound-queue-v2/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use frame_support::{
use bp_messages::HashedLaneId;
use bp_relayers::{PayRewardFromAccount, PaymentProcedure, RewardsAccountParams};
use codec::Encode;
use frame_support::PalletId;
use hex_literal::hex;
use snowbridge_core::{
gwei,
Expand All @@ -23,7 +24,7 @@ use snowbridge_core::{
};
use sp_core::{ConstU128, ConstU32, ConstU8, H160, H256};
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup, Keccak256},
traits::{AccountIdConversion, BlakeTwo256, IdentityLookup, Keccak256},
AccountId32, BuildStorage, FixedU128,
};
use sp_std::marker::PhantomData;
Expand Down Expand Up @@ -137,6 +138,7 @@ impl crate::Config for Test {

parameter_types! {
pub WethAddress: H160 = hex!("774667629726ec1FaBEbCEc0D9139bD1C8f72a23").into();
pub TreasuryAccount: AccountId = PalletId(*b"py/trsry").into_account_truncating();
}

pub type TestLaneIdType = HashedLaneId;
Expand Down Expand Up @@ -181,7 +183,8 @@ impl pallet_bridge_relayers::Config for Test {
type XcmSender = MockXcmSender;

type AssetTransactor = SuccessfulTransactor;
type AssetHubXCMFee = ConstU128<1_000_000_000_000u128>;
type AssetHubXCMFee = ConstU128<15u128>;
type TreasuryAccount = TreasuryAccount;
}

// Mock XCM sender that always succeeds
Expand Down
6 changes: 2 additions & 4 deletions bridges/snowbridge/primitives/core/src/fees.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
use crate::ParaId;
use log;
use sp_runtime::{DispatchResult, SaturatedConversion, Saturating, TokenError};
use xcm::opaque::lts::{Junction::Parachain, Location, XcmContext};
use xcm::opaque::lts::{Location, XcmContext};
use xcm_executor::traits::TransactAsset;
const LOG_TARGET: &str = "xcm_fees";

/// Burns the fees embedded in the XCM for teleports.
pub fn burn_fees<AssetTransactor, Balance>(para_id: ParaId, fee: Balance) -> DispatchResult
pub fn burn_fees<AssetTransactor, Balance>(dest: Location, fee: Balance) -> DispatchResult
where
AssetTransactor: TransactAsset,
Balance: Saturating + TryInto<u128> + Copy,
{
let dummy_context = XcmContext { origin: None, message_id: Default::default(), topic: None };
let dest = Location::new(1, [Parachain(para_id.into())]);
let fees = (Location::parent(), fee.saturated_into::<u128>()).into();

// Check if the asset can be checked out
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,12 @@ fn claim_rewards_works() {
let weth_asset_location: Location =
(Parent, Parent, EthereumNetwork::get(), AccountKey20 { network: None, key: weth }).into();

BridgeHubWestend::fund_accounts(vec![(assethub_sovereign.clone(), INITIAL_FUND)]);
let relayer = BridgeHubWestendSender::get();

BridgeHubWestend::fund_accounts(vec![
(assethub_sovereign.clone(), INITIAL_FUND),
(relayer.clone(), INITIAL_FUND),
]);

AssetHubWestend::execute_with(|| {
type RuntimeOrigin = <AssetHubWestend as Chain>::RuntimeOrigin;
Expand All @@ -189,7 +194,6 @@ fn claim_rewards_works() {
type RuntimeEvent = <BridgeHubWestend as Chain>::RuntimeEvent;
type RuntimeOrigin = <BridgeHubWestend as Chain>::RuntimeOrigin;

let relayer = BridgeHubWestendSender::get();
let reward_address = AssetHubWestendReceiver::get();
type BridgeRelayers = <BridgeHubWestend as BridgeHubWestendPallet>::BridgeRelayers;
assert_ok!(BridgeRelayers::deposit(relayer.clone().into(), 2 * ETH));
Expand Down
Loading

0 comments on commit 8dadc2d

Please sign in to comment.