Skip to content

Commit

Permalink
Respect V2 contract
Browse files Browse the repository at this point in the history
  • Loading branch information
yrong committed Oct 20, 2024
1 parent 738a2de commit f6b9968
Show file tree
Hide file tree
Showing 6 changed files with 29 additions and 514 deletions.
16 changes: 5 additions & 11 deletions bridges/snowbridge/pallets/inbound-queue-v2/src/envelope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
use snowbridge_core::inbound::Log;

use sp_core::{RuntimeDebug, H160, H256};
use sp_core::{RuntimeDebug, H160};
use sp_std::prelude::*;

use alloy_primitives::B256;
use alloy_sol_types::{sol, SolEvent};

sol! {
event OutboundMessageAccepted(uint64 indexed nonce, bytes32 indexed message_id, uint32 indexed para_id, bytes32 reward_address, uint128 fee, bytes payload);
event OutboundMessageAccepted(uint64 indexed nonce, uint128 fee, bytes32 reward_address, bytes payload);
}

/// An inbound message that has had its outer envelope decoded.
Expand All @@ -19,14 +19,10 @@ pub struct Envelope {
pub gateway: H160,
/// A nonce for enforcing replay protection and ordering.
pub nonce: u64,
/// An id for tracing the message on its route (has no role in bridge consensus)
pub message_id: H256,
/// Destination ParaId
pub para_id: u32,
/// The reward address
pub reward_address: [u8; 32],
/// Total fee paid on source chain
pub fee: u128,
/// The reward address
pub reward_address: [u8; 32],
/// The inner payload generated from the source application.
pub payload: Vec<u8>,
}
Expand All @@ -46,10 +42,8 @@ impl TryFrom<&Log> for Envelope {
Ok(Self {
gateway: log.address,
nonce: event.nonce,
message_id: H256::from(event.message_id.as_ref()),
reward_address: event.reward_address.clone().into(),
fee: event.fee,
para_id: event.para_id,
reward_address: event.reward_address.clone().into(),
payload: event.payload,
})
}
Expand Down
67 changes: 18 additions & 49 deletions bridges/snowbridge/pallets/inbound-queue-v2/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,28 +39,24 @@ mod test;
use codec::{Decode, DecodeAll, Encode};
use envelope::Envelope;
use frame_support::{
traits::{
fungible::{Inspect, Mutate},
tokens::{Fortitude, Precision, Preservation},
},
traits::fungible::{Inspect, Mutate},
weights::WeightToFee,
PalletError,
};
use frame_system::ensure_signed;
use scale_info::TypeInfo;
use sp_core::H160;
use sp_std::vec;
use xcm::prelude::{
send_xcm, Junction::*, Location, SendError as XcmpSendError, SendXcm, Xcm, XcmHash,
use xcm::{
prelude::{send_xcm, Junction::*, Location, SendError as XcmpSendError, SendXcm, Xcm, XcmHash},
VersionedXcm, MAX_XCM_DECODE_DEPTH,
};

use snowbridge_core::{
inbound::{Message, VerificationError, Verifier},
sibling_sovereign_account, BasicOperatingMode, ParaId,
};
use snowbridge_router_primitives_v2::inbound::{
ConvertMessage, ConvertMessageError, VersionedMessage,
};
use snowbridge_router_primitives_v2::inbound::Message as MessageV2;

pub use weights::WeightInfo;

Expand All @@ -77,6 +73,7 @@ pub const LOG_TARGET: &str = "snowbridge-inbound-queue:v2";
#[frame_support::pallet]
pub mod pallet {
use super::*;
use codec::DecodeLimit;

use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
Expand Down Expand Up @@ -107,12 +104,6 @@ pub mod pallet {
#[pallet::constant]
type GatewayAddress: Get<H160>;

/// Convert inbound message to XCM
type MessageConverter: ConvertMessage<
AccountId = Self::AccountId,
Balance = BalanceOf<Self>,
>;

type WeightInfo: WeightInfo;

#[cfg(feature = "runtime-benchmarks")]
Expand Down Expand Up @@ -140,8 +131,6 @@ pub mod pallet {
nonce: u64,
/// ID of the XCM message which was forwarded to the final destination parachain
message_id: [u8; 32],
/// Fee burned for the teleport
fee_burned: BalanceOf<T>,
},
/// Set OperatingMode
OperatingModeChanged { mode: BasicOperatingMode },
Expand Down Expand Up @@ -169,8 +158,6 @@ pub mod pallet {
Verification(VerificationError),
/// XCMP send failure
Send(SendError),
/// Message conversion error
ConvertMessage(ConvertMessageError),
}

#[derive(Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo, PalletError)]
Expand Down Expand Up @@ -215,7 +202,7 @@ pub mod pallet {
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::submit())]
pub fn submit(origin: OriginFor<T>, message: Message) -> DispatchResult {
let who = ensure_signed(origin)?;
ensure_signed(origin)?;
ensure!(!Self::operating_mode().is_halted(), Error::<T>::Halted);

// submit message to verifier for verification
Expand All @@ -233,30 +220,25 @@ pub mod pallet {
ensure!(!<Nonce<T>>::contains_key(envelope.nonce), Error::<T>::InvalidNonce);

// Decode payload into `VersionedMessage`
let message = VersionedMessage::decode_all(&mut envelope.payload.as_ref())
let message = MessageV2::decode_all(&mut envelope.payload.as_ref())
.map_err(|_| Error::<T>::InvalidPayload)?;

// Decode message into XCM
let (xcm, fee) = Self::do_convert(envelope.message_id, message.clone())?;
let versioned_xcm = VersionedXcm::<()>::decode_with_depth_limit(
MAX_XCM_DECODE_DEPTH,
&mut message.xcm.as_ref(),
)
.map_err(|_| Error::<T>::InvalidPayload)?;

let xcm: Xcm<()> = versioned_xcm.try_into().unwrap();

log::info!(
target: LOG_TARGET,
"💫 xcm decoded as {:?} with fee {:?}",
"💫 xcm decoded as {:?}",
xcm,
fee
);

// Burning fees for teleport
T::Token::burn_from(
&who,
fee,
Preservation::Preserve,
Precision::BestEffort,
Fortitude::Polite,
)?;

// Attempt to send XCM to a dest parachain
let message_id = Self::send_xcm(xcm, envelope.para_id.into())?;
let message_id = Self::send_xcm(xcm, 1000.into())?;

// Set nonce flag to true
<Nonce<T>>::try_mutate(envelope.nonce, |done| -> DispatchResult {
Expand All @@ -273,11 +255,7 @@ pub mod pallet {

// T::RewardLeger::deposit(envelope.reward_address.into(), envelope.fee.into())?;

Self::deposit_event(Event::MessageReceived {
nonce: envelope.nonce,
message_id,
fee_burned: fee,
});
Self::deposit_event(Event::MessageReceived { nonce: envelope.nonce, message_id });

Ok(())
}
Expand All @@ -297,15 +275,6 @@ pub mod pallet {
}

impl<T: Config> Pallet<T> {
pub fn do_convert(
message_id: H256,
message: VersionedMessage,
) -> Result<(Xcm<()>, BalanceOf<T>), Error<T>> {
let (xcm, fee) = T::MessageConverter::convert(message_id, message)
.map_err(|e| Error::<T>::ConvertMessage(e))?;
Ok((xcm, fee))
}

pub fn send_xcm(xcm: Xcm<()>, dest: ParaId) -> Result<XcmHash, Error<T>> {
let dest = Location::new(1, [Parachain(dest.into())]);
let (xcm_hash, _) = send_xcm::<T::XcmSender>(dest, xcm).map_err(Error::<T>::from)?;
Expand Down
11 changes: 0 additions & 11 deletions bridges/snowbridge/pallets/inbound-queue-v2/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use snowbridge_core::{
inbound::{Log, Proof, VerificationError},
TokenId,
};
use snowbridge_router_primitives_v2::inbound::MessageToXcm;
use sp_core::{H160, H256};
use sp_runtime::{
traits::{IdentifyAccount, IdentityLookup, MaybeEquivalence, Verify},
Expand Down Expand Up @@ -170,16 +169,6 @@ impl inbound_queue::Config for Test {
type XcmSender = MockXcmSender;
type WeightInfo = ();
type GatewayAddress = GatewayAddress;
type MessageConverter = MessageToXcm<
CreateAssetCall,
CreateAssetDeposit,
InboundQueuePalletInstance,
AccountId,
Balance,
MockTokenIdConvert,
UniversalLocation,
AssetHubFromEthereum,
>;
#[cfg(feature = "runtime-benchmarks")]
type Helper = Test;
type WeightToFee = IdentityFee<u128>;
Expand Down
9 changes: 0 additions & 9 deletions bridges/snowbridge/pallets/inbound-queue-v2/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,17 +41,8 @@ fn test_submit_happy_path() {
255, 125, 48, 71, 174, 185, 100, 26, 159, 43, 108, 6, 116, 218, 55, 155, 223, 143,
141, 22, 124, 110, 241, 18, 122, 217, 130, 29, 139, 76, 97, 201,
],
fee_burned: 110000000000,
}
.into()]);

let delivery_cost = InboundQueue::calculate_delivery_cost(message.encode().len() as u32);

assert_eq!(Balances::balance(&relayer), delivery_cost, "relayer was rewarded");
assert!(
Balances::balance(&channel_sovereign) <= initial_fund - delivery_cost,
"sovereign account paid reward"
);
});
}

Expand Down
Loading

0 comments on commit f6b9968

Please sign in to comment.