Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SYS-3941 add log lowered claimed event #373

Merged
merged 2 commits into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions pallets/ethereum-events/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ use codec::{Decode, Encode, MaxEncodedLen};
use sp_application_crypto::RuntimeAppPublic;
use sp_avn_common::{
event_types::{
AddedValidatorData, AvtGrowthLiftedData, Challenge, ChallengeReason, CheckResult,
EthEventCheckResult, EthEventId, EventData, LiftedData, NftCancelListingData,
AddedValidatorData, AvtGrowthLiftedData, AvtLowerClaimedData, Challenge, ChallengeReason,
CheckResult, EthEventCheckResult, EthEventId, EventData, LiftedData, NftCancelListingData,
NftEndBatchListingData, NftMintData, NftTransferToData, ProcessedEventHandler, ValidEvents,
Validator,
},
Expand Down Expand Up @@ -1078,6 +1078,12 @@ impl<T: Config> Pallet<T> {
Error::<T>::EventParsingFailed
})?;
return Ok(EventData::LogAvtGrowthLifted(event_data))
} else if event_id.signature == ValidEvents::AvtLowerClaimed.signature() {
let event_data = <AvtLowerClaimedData>::parse_bytes(data, topics).map_err(|e| {
log::warn!("Error parsing T1 LogLowerClaimed Event: {:#?}", e);
Error::<T>::EventParsingFailed
})?;
return Ok(EventData::LogLowerClaimed(event_data))
} else {
return Err(Error::<T>::UnrecognizedEventSignature)
}
Expand Down
1 change: 1 addition & 0 deletions pallets/ethereum-events/src/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ mod test_get_contract_address_for {
ValidEvents::NftCancelListing => H160::from(NFT_CONTRACT),
ValidEvents::NftEndBatchListing => H160::from(NFT_CONTRACT),
ValidEvents::AvtGrowthLifted => H160::from(BRIDGE_CONTRACT),
ValidEvents::AvtLowerClaimed => H160::from(BRIDGE_CONTRACT),
}
}

Expand Down
46 changes: 33 additions & 13 deletions pallets/token-manager/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,10 @@ use pallet_avn::{
LowerParams, OnGrowthLiftedHandler, ProcessedEventsChecker, PACKED_LOWER_PARAM_SIZE,
};
use sp_avn_common::{
event_types::{AvtGrowthLiftedData, EthEvent, EventData, LiftedData, ProcessedEventHandler},
event_types::{
AvtGrowthLiftedData, AvtLowerClaimedData, EthEvent, EventData, LiftedData,
ProcessedEventHandler,
},
verify_signature, CallDecoder, InnerCallValidator, Proof,
};
use sp_core::{ConstU32, MaxEncodedLen, H160, H256};
Expand Down Expand Up @@ -85,6 +88,7 @@ mod test_deferred_lower;
mod test_growth;
#[cfg(test)]
mod test_lower_proof_generation;

#[cfg(test)]
mod test_non_avt_tokens;
#[cfg(test)]
Expand Down Expand Up @@ -219,6 +223,9 @@ pub mod pallet {
LowerReadyToClaim {
lower_id: LowerId,
},
AvtLowerClaimed {
lower_id: LowerId,
},
FailedToGenerateLowerProof {
lower_id: LowerId,
},
Expand All @@ -238,6 +245,7 @@ pub mod pallet {
#[pallet::error]
pub enum Error<T> {
NoTier1EventForLogLifted,
NoTier1EventForLogLowerClaimed,
AmountOverflow,
DepositFailed,
LowerFailed,
Expand Down Expand Up @@ -611,16 +619,6 @@ impl<T: Config> Pallet<T> {
Ok(())
}

fn lift(event: &EthEvent) -> DispatchResult {
return match &event.event_data {
EventData::LogLifted(d) => return Self::process_lift(event, d),
EventData::LogAvtGrowthLifted(d) => return Self::process_avt_growth_lift(event, d),

// Event handled or it is not for us, in which case ignore it.
_ => Ok(()),
}
}

fn settle_lower(
token_id: T::TokenId,
from: &T::AccountId,
Expand Down Expand Up @@ -915,6 +913,21 @@ impl<T: Config> Pallet<T> {
Ok(())
}

fn process_lower_claim(event: &EthEvent, data: &AvtLowerClaimedData) -> DispatchResult {
let event_id = &event.event_id;
let event_validity = T::ProcessedEventsChecker::check_event(event_id);
ensure!(event_validity, Error::<T>::NoTier1EventForLogLowerClaimed);

if !data.is_valid() {
Err(Error::<T>::InvalidLowerId)?
}
LowersReadyToClaim::<T>::remove(data.lower_id);

Self::deposit_event(Event::<T>::AvtLowerClaimed { lower_id: data.lower_id });

Ok(())
}

/// The account ID of the AvN treasury.
/// This actually does computation. If you need to keep using it, then make sure you cache
/// the value and only call this once.
Expand Down Expand Up @@ -958,7 +971,7 @@ impl<T: Config> Pallet<T> {
.map_err(|_| Error::<T>::InvalidLowerCall)?,
)?;

<LowerNonce<T>>::mutate(|nonce| *nonce += 1);
<LowerNonce<T>>::mutate(|mut nonce| *nonce += 1);

Self::deposit_event(Event::<T>::LowerRequested {
token_id,
Expand All @@ -976,7 +989,14 @@ impl<T: Config> Pallet<T> {

impl<T: Config> ProcessedEventHandler for Pallet<T> {
fn on_event_processed(event: &EthEvent) -> DispatchResult {
return Self::lift(event)
return match &event.event_data {
EventData::LogLifted(d) => return Self::process_lift(event, d),
EventData::LogAvtGrowthLifted(d) => return Self::process_avt_growth_lift(event, d),
EventData::LogLowerClaimed(d) => return Self::process_lower_claim(event, d),

// Event handled or it is not for us, in which case ignore it.
_ => Ok(()),
}
Comment on lines +996 to +1003
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💯

}
}

Expand Down
11 changes: 7 additions & 4 deletions pallets/token-manager/src/test_avt_tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ fn avn_test_lift_to_zero_balance_account_should_succeed() {
assert_eq!(TokenManager::balance((AVT_TOKEN_CONTRACT, mock_data.receiver_account_id)), 0);

assert_eq!(Balances::free_balance(mock_data.receiver_account_id), 0);
assert_ok!(TokenManager::lift(&mock_event));
assert_ok!(TokenManager::on_event_processed(&mock_event));
assert_eq!(Balances::free_balance(mock_data.receiver_account_id), AMOUNT_123_TOKEN);

// check that TokenManager.balance for AVT contract is still 0
Expand Down Expand Up @@ -75,7 +75,7 @@ fn avn_test_lift_to_non_zero_balance_account_should_succeed() {
assert_eq!(Balances::free_balance(mock_data.receiver_account_id), AMOUNT_100_TOKEN);
let new_balance = Balances::free_balance(mock_data.receiver_account_id) + AMOUNT_123_TOKEN;

assert_ok!(TokenManager::lift(&mock_event));
assert_ok!(TokenManager::on_event_processed(&mock_event));
assert_eq!(Balances::free_balance(mock_data.receiver_account_id), new_balance);

// check that TokenManager.balance for AVT contract is still 0
Expand Down Expand Up @@ -104,7 +104,7 @@ fn avn_test_lift_max_balance_to_zero_balance_account_should_succeed() {
insert_to_mock_processed_events(&mock_event.event_id);

assert_eq!(Balances::free_balance(mock_data.receiver_account_id), 0);
assert_ok!(TokenManager::lift(&mock_event));
assert_ok!(TokenManager::on_event_processed(&mock_event));
assert_eq!(Balances::free_balance(mock_data.receiver_account_id), u128_max_amount);

assert!(System::events().iter().any(|a| a.event ==
Expand All @@ -130,7 +130,10 @@ fn avn_test_lift_max_balance_to_non_zero_balance_account_should_return_deposit_f
insert_to_mock_processed_events(&mock_event.event_id);
let balance_before = Balances::free_balance(mock_data.receiver_account_id);

assert_noop!(TokenManager::lift(&mock_event), Error::<TestRuntime>::DepositFailed);
assert_noop!(
TokenManager::on_event_processed(&mock_event),
Error::<TestRuntime>::DepositFailed
);
assert_eq!(Balances::free_balance(mock_data.receiver_account_id), balance_before);

assert!(!System::events().iter().any(|a| a.event ==
Expand Down
9 changes: 6 additions & 3 deletions pallets/token-manager/src/test_common_cases.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ fn avn_test_lift_ignored_when_event_type_does_not_match() {
0
);

assert_ok!(TokenManager::lift(&mock_data.empty_data_lift_event));
assert_ok!(TokenManager::on_event_processed(&mock_data.empty_data_lift_event));

assert_eq!(Balances::free_balance(mock_data.receiver_account_id), 0);
assert_eq!(
Expand Down Expand Up @@ -86,7 +86,10 @@ fn avn_test_lift_zero_amount_should_fail() {
mock_data.receiver_account_id,
));

assert_noop!(TokenManager::lift(&mock_event), Error::<TestRuntime>::AmountIsZero);
assert_noop!(
TokenManager::on_event_processed(&mock_event),
Error::<TestRuntime>::AmountIsZero
);
assert_eq!(Balances::free_balance(mock_data.receiver_account_id), avt_token_balance_before);
assert_eq!(
<TokenManager as Store>::Balances::get((
Expand Down Expand Up @@ -128,7 +131,7 @@ fn avn_test_lift_should_fail_when_event_is_not_in_processed_events() {
));

assert_noop!(
TokenManager::lift(&mock_event),
TokenManager::on_event_processed(&mock_event),
Error::<TestRuntime>::NoTier1EventForLogLifted
);
assert_eq!(Balances::free_balance(mock_data.receiver_account_id), avt_token_balance_before);
Expand Down
11 changes: 7 additions & 4 deletions pallets/token-manager/src/test_non_avt_tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ fn avn_test_lift_to_zero_balance_account_should_succeed() {
)),
0
);
assert_ok!(TokenManager::lift(&mock_event));
assert_ok!(TokenManager::on_event_processed(&mock_event));
assert_eq!(
<TokenManager as Store>::Balances::get((
NON_AVT_TOKEN_ID,
Expand Down Expand Up @@ -74,7 +74,7 @@ fn avn_test_lift_to_non_zero_balance_account_should_succeed() {
));
assert_eq!(token_balance_before, AMOUNT_100_TOKEN);
let expected_token_balance = token_balance_before + AMOUNT_123_TOKEN;
assert_ok!(TokenManager::lift(&mock_event));
assert_ok!(TokenManager::on_event_processed(&mock_event));
let new_token_balance = <TokenManager as Store>::Balances::get((
NON_AVT_TOKEN_ID,
mock_data.receiver_account_id,
Expand Down Expand Up @@ -108,7 +108,7 @@ fn avn_test_lift_max_balance_to_zero_balance_account_should_succeed() {
)),
0
);
assert_ok!(TokenManager::lift(&mock_event));
assert_ok!(TokenManager::on_event_processed(&mock_event));
assert_eq!(
<TokenManager as Store>::Balances::get((
NON_AVT_TOKEN_ID,
Expand Down Expand Up @@ -142,7 +142,10 @@ fn avn_test_lift_max_balance_to_non_zero_balance_account_should_fail_with_overfl
mock_data.receiver_account_id,
));

assert_noop!(TokenManager::lift(&mock_event), Error::<TestRuntime>::AmountOverflow);
assert_noop!(
TokenManager::on_event_processed(&mock_event),
Error::<TestRuntime>::AmountOverflow
);
assert_eq!(
<TokenManager as Store>::Balances::get((
NON_AVT_TOKEN_ID,
Expand Down
61 changes: 60 additions & 1 deletion primitives/avn-common/src/event_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ use crate::bounds::NftExternalRefBound;
use codec::{Decode, Encode, MaxEncodedLen};
use hex_literal::hex;
use sp_core::{bounded::BoundedVec, H160, H256, H512, U256};
use sp_runtime::{scale_info::TypeInfo, traits::Member, DispatchResult};
use sp_runtime::{
scale_info::TypeInfo,
traits::{Member, Zero},
DispatchResult,
};
use sp_std::{convert::TryInto, vec::Vec};

// ================================= Events Types ====================================
Expand Down Expand Up @@ -54,6 +58,11 @@ pub enum Error {
AvtGrowthLiftedEventBadTopicLength,
AvtGrowthLiftedEventDataOverflow,
AvtGrowthLiftedEventPeriodConversion,

AvtLowerClaimedEventMissingData,
AvtLowerClaimedEventWrongTopicCount,
AvtLowerClaimedEventBadTopicLength,
AvtLowerClaimedEventIdConversion,
}

#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq, TypeInfo)]
Expand All @@ -65,6 +74,7 @@ pub enum ValidEvents {
NftCancelListing,
NftEndBatchListing,
AvtGrowthLifted,
AvtLowerClaimed,
}

impl ValidEvents {
Expand Down Expand Up @@ -102,6 +112,10 @@ impl ValidEvents {
// hex string of Keccak-256 for LogGrowth(uint256,uint32)
ValidEvents::AvtGrowthLifted =>
H256(hex!("3ad58a8dc1110baa37ad88a68db14181b4ef0c69192dfa7699a9588960eca7fd")),

// hex string of Keccak-256 for LogLowerClaimed(uint32)
ValidEvents::AvtLowerClaimed =>
H256(hex!("9853e4c075911a10a89a0f7a46bac6f8a246c4e9152480d16d86aa6a2391a4f1")),
}
}

Expand All @@ -120,6 +134,8 @@ impl ValidEvents {
return Some(ValidEvents::NftEndBatchListing)
} else if signature == &ValidEvents::AvtGrowthLifted.signature() {
return Some(ValidEvents::AvtGrowthLifted)
} else if signature == &ValidEvents::AvtLowerClaimed.signature() {
return Some(ValidEvents::AvtLowerClaimed)
} else {
return None
}
Expand Down Expand Up @@ -555,6 +571,43 @@ impl AvtGrowthLiftedData {
}
}

// T1 Event definition:
// event LogLowerClaimed(uint32 lowerId);
#[derive(Encode, Decode, Default, Clone, PartialEq, Debug, Eq, TypeInfo, MaxEncodedLen)]
pub struct AvtLowerClaimedData {
pub lower_id: u32,
}

impl AvtLowerClaimedData {
const TOPIC_LOWER_ID: usize = 1;

pub fn is_valid(&self) -> bool {
return !self.lower_id.is_zero()
}

pub fn parse_bytes(data: Option<Vec<u8>>, topics: Vec<Vec<u8>>) -> Result<Self, Error> {
if data.is_some() {
return Err(Error::AvtLowerClaimedEventMissingData)
}

if topics.len() != 2 {
return Err(Error::AvtLowerClaimedEventWrongTopicCount)
}

if topics[Self::TOPIC_LOWER_ID].len() != WORD_LENGTH {
return Err(Error::AvtLowerClaimedEventBadTopicLength)
}

let lower_id: u32 = u32::from_be_bytes(
topics[Self::TOPIC_LOWER_ID][TWENTY_EIGHT_BYTES..WORD_LENGTH]
.try_into()
.map_err(|_| Error::AvtLowerClaimedEventIdConversion)?,
);

return Ok(AvtLowerClaimedData { lower_id })
}
}

#[derive(Encode, Decode, Clone, PartialEq, Debug, Eq, TypeInfo, MaxEncodedLen)]
pub enum EventData {
LogAddedValidator(AddedValidatorData),
Expand All @@ -565,6 +618,7 @@ pub enum EventData {
LogNftCancelListing(NftCancelListingData),
LogNftEndBatchListing(NftEndBatchListingData),
LogAvtGrowthLifted(AvtGrowthLiftedData),
LogLowerClaimed(AvtLowerClaimedData),
}

impl EventData {
Expand All @@ -578,6 +632,7 @@ impl EventData {
EventData::LogNftCancelListing(d) => d.is_valid(),
EventData::LogNftEndBatchListing(d) => d.is_valid(),
EventData::LogAvtGrowthLifted(d) => d.is_valid(),
EventData::LogLowerClaimed(d) => d.is_valid(),
EventData::EmptyEvent => true,
_ => false,
}
Expand Down Expand Up @@ -750,3 +805,7 @@ mod nft_event_tests;
#[cfg(test)]
#[path = "tests/test_avt_growth_event_parsing.rs"]
mod test_avt_growth_event_parsing;

#[cfg(test)]
#[path = "tests/test_lower_claim.rs"]
mod test_lower_claim;
Loading
Loading