Skip to content

Commit

Permalink
lp-gateway: Unit test WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
cdamian committed Aug 13, 2024
1 parent 82d8304 commit 9a22092
Show file tree
Hide file tree
Showing 4 changed files with 156 additions and 247 deletions.
35 changes: 21 additions & 14 deletions pallets/liquidity-pools-gateway/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ use message::GatewayMessage;
use orml_traits::GetByKey;
pub use pallet::*;
use parity_scale_codec::FullCodec;
use sp_arithmetic::traits::{BaseArithmetic, EnsureAdd, EnsureAddAssign, One};
use sp_arithmetic::traits::{BaseArithmetic, EnsureAdd, EnsureAddAssign, One, Zero};
use sp_std::convert::TryInto;

use crate::{message_processing::InboundEntry, weights::WeightInfo};
Expand Down Expand Up @@ -177,7 +177,7 @@ pub mod pallet {
#[pallet::storage]
#[pallet::getter(fn routers)]
pub type Routers<T: Config> =
StorageValue<_, BoundedVec<T::RouterId, T::MaxRouterCount>, ValueQuery>;
StorageValue<_, BoundedVec<T::RouterId, T::MaxRouterCount>, OptionQuery>;

/// Storage that contains a limited number of whitelisted instances of
/// deployed liquidity pools for a particular domain.
Expand Down Expand Up @@ -218,7 +218,7 @@ pub mod pallet {

/// Storage for inbound message session IDs.
#[pallet::storage]
pub type SessionIdStore<T: Config> = StorageValue<_, T::SessionId, ValueQuery>;
pub type SessionIdStore<T: Config> = StorageValue<_, T::SessionId, OptionQuery>;

/// Storage that keeps track of invalid session IDs.
///
Expand Down Expand Up @@ -259,8 +259,8 @@ pub mod pallet {
/// Invalid multi router.
InvalidMultiRouter,

/// Inbound domain session not found.
InboundDomainSessionNotFound,
/// Session ID not found.
SessionIdNotFound,

/// Unknown router.
UnknownRouter,
Expand All @@ -285,6 +285,9 @@ pub mod pallet {

/// Recovery message not found.
RecoveryMessageNotFound,

/// Not enough routers are stored for a domain.
NotEnoughRoutersForDomain,
}

#[pallet::call]
Expand All @@ -298,16 +301,20 @@ pub mod pallet {
) -> DispatchResult {
T::AdminOrigin::ensure_origin(origin)?;

<Routers<T>>::set(router_ids.clone());
<Routers<T>>::set(Some(router_ids.clone()));

let (old_session_id, new_session_id) = SessionIdStore::<T>::try_mutate(|n| {
let old_session_id = *n;
let new_session_id = n.ensure_add(One::one())?;
let (old_session_id, new_session_id) =
SessionIdStore::<T>::try_mutate(|storage_entry| {
let old_session_id = storage_entry.unwrap_or(T::SessionId::zero());
let new_session_id = old_session_id.ensure_add(One::one())?;

*n = new_session_id;
*storage_entry = Some(new_session_id);

Ok::<(T::SessionId, T::SessionId), DispatchError>((old_session_id, new_session_id))
})?;
Ok::<(T::SessionId, T::SessionId), DispatchError>((
old_session_id,
new_session_id,
))
})?;

InvalidMessageSessions::<T>::insert(old_session_id, ());

Expand Down Expand Up @@ -446,9 +453,9 @@ pub mod pallet {
) -> DispatchResult {
T::AdminOrigin::ensure_origin(origin)?;

let session_id = SessionIdStore::<T>::get();
let session_id = SessionIdStore::<T>::get().ok_or(Error::<T>::SessionIdNotFound)?;

let routers = Routers::<T>::get();
let routers = Routers::<T>::get().ok_or(Error::<T>::RoutersNotFound)?;

ensure!(
routers.iter().any(|x| x == &router_id),
Expand Down
34 changes: 28 additions & 6 deletions pallets/liquidity-pools-gateway/src/message_processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use sp_runtime::DispatchError;

use crate::{
message::GatewayMessage, Config, Error, InvalidMessageSessions, Pallet, PendingInboundEntries,
SessionIdStore,
Routers, SessionIdStore,
};

/// The limit used when clearing the `PendingInboundEntries` for invalid
Expand Down Expand Up @@ -46,12 +46,34 @@ pub struct InboundProcessingInfo<T: Config> {
}

impl<T: Config> Pallet<T> {
/// Retrieves all available routers for a domain and then filters them based
/// on the routers that we have in storage.
fn get_router_ids_for_domain(domain: Domain) -> Result<Vec<T::RouterId>, DispatchError> {
let all_routers_for_domain = T::RouterId::for_domain(domain);

let stored_routers = Routers::<T>::get().ok_or(Error::<T>::RoutersNotFound)?;

let res = all_routers_for_domain
.iter()
.filter(|x| stored_routers.iter().any(|y| *x == y))
.map(|x| x.clone())
.collect::<Vec<_>>();

if res.is_empty() {
return Err(Error::<T>::NotEnoughRoutersForDomain.into());
}

Ok(res)
}

/// Calculates and returns the proof count required for processing one
/// inbound message.
fn get_expected_proof_count(domain: Domain) -> Result<u32, DispatchError> {
let routers_count = T::RouterId::for_domain(domain).len();
let routers_count = Self::get_router_ids_for_domain(domain)?.len();

let expected_proof_count = routers_count.ensure_sub(1)?;
let expected_proof_count = routers_count
.ensure_sub(1)
.map_err(|_| Error::<T>::NotEnoughRoutersForDomain)?;

Ok(expected_proof_count as u32)
}
Expand Down Expand Up @@ -294,11 +316,11 @@ impl<T: Config> Pallet<T> {
domain_address: DomainAddress,
weight: &mut Weight,
) -> Result<InboundProcessingInfo<T>, DispatchError> {
let router_ids = T::RouterId::for_domain(domain_address.domain());
let router_ids = Self::get_router_ids_for_domain(domain_address.domain())?;

weight.saturating_accrue(T::DbWeight::get().reads(1));

let current_session_id = SessionIdStore::<T>::get();
let current_session_id = SessionIdStore::<T>::get().ok_or(Error::<T>::SessionIdNotFound)?;

weight.saturating_accrue(T::DbWeight::get().reads(1));

Expand Down Expand Up @@ -395,7 +417,7 @@ impl<T: Config> Pallet<T> {
destination: Domain,
message: T::Message,
) -> DispatchResult {
let router_ids = T::RouterId::for_domain(destination);
let router_ids = Self::get_router_ids_for_domain(destination)?;

let message_proof = message.to_message_proof();
let mut message_opt = Some(message);
Expand Down
19 changes: 16 additions & 3 deletions pallets/liquidity-pools-gateway/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ use std::fmt::{Debug, Formatter};

use cfg_mocks::{pallet_mock_liquidity_pools, pallet_mock_liquidity_pools_gateway_queue};
use cfg_traits::liquidity_pools::{LPEncoding, Proof, RouterSupport};
use cfg_types::domain_address::{Domain, DomainAddress};
use cfg_types::{
domain_address::{Domain, DomainAddress},
EVMChainId,
};
use frame_support::{derive_impl, weights::constants::RocksDbWeight};
use frame_system::EnsureRoot;
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
Expand All @@ -12,6 +15,13 @@ use sp_runtime::{traits::IdentityLookup, DispatchError, DispatchResult};

use crate::{pallet as pallet_liquidity_pools_gateway, EnsureLocal, GatewayMessage};

pub const TEST_EVM_CHAIN: EVMChainId = 1;
pub const TEST_DOMAIN_ADDRESS: DomainAddress = DomainAddress::EVM(TEST_EVM_CHAIN, [1; 20]);

pub const ROUTER_ID_1: RouterId = RouterId(1);
pub const ROUTER_ID_2: RouterId = RouterId(2);
pub const ROUTER_ID_3: RouterId = RouterId(3);

pub const LP_ADMIN_ACCOUNT: AccountId32 = AccountId32::new([u8::MAX; 32]);

pub const MAX_PACKED_MESSAGES_ERR: &str = "packed limit error";
Expand Down Expand Up @@ -106,8 +116,11 @@ impl LPEncoding for Message {
pub struct RouterId(pub u32);

impl RouterSupport<Domain> for RouterId {
fn for_domain(_domain: Domain) -> Vec<RouterId> {
vec![] // TODO
fn for_domain(domain: Domain) -> Vec<RouterId> {
match domain {
Domain::Centrifuge => vec![],
Domain::EVM(_) => vec![ROUTER_ID_1, ROUTER_ID_2, ROUTER_ID_3],
}
}
}

Expand Down
Loading

0 comments on commit 9a22092

Please sign in to comment.