From f3061a6bdb36b22b54abdff878ad6bf6e92e759e Mon Sep 17 00:00:00 2001 From: stanieltron Date: Tue, 19 Dec 2023 13:53:56 +0100 Subject: [PATCH] comments and fmt --- pallets/rolldown/src/lib.rs | 393 ++++++++++++++++++++---------------- 1 file changed, 219 insertions(+), 174 deletions(-) diff --git a/pallets/rolldown/src/lib.rs b/pallets/rolldown/src/lib.rs index 5083785733..193549ecaa 100644 --- a/pallets/rolldown/src/lib.rs +++ b/pallets/rolldown/src/lib.rs @@ -5,16 +5,16 @@ use frame_support::{ ensure, pallet_prelude::*, + traits::{tokens::currency::MultiTokenCurrency, Get, StorageVersion}, StorageHasher, - traits::{Get, StorageVersion, tokens::currency::MultiTokenCurrency}, }; use frame_system::{ensure_signed, pallet_prelude::*}; use sp_runtime::traits::BlakeTwo256; use sp_std::collections::btree_map::BTreeMap; -use sp_std::{convert::TryInto, prelude::*}; -use mangata_support::traits::{SequencerStakingProviderTrait, RolldownProviderTrait}; use codec::alloc::string::{String, ToString}; +use mangata_support::traits::{RolldownProviderTrait, SequencerStakingProviderTrait}; +use orml_tokens::{MultiTokenCurrencyExtended, MultiTokenReservableCurrency}; use scale_info::prelude::format; use sha3::{Digest, Keccak256}; use sp_core::U256; @@ -22,12 +22,10 @@ use sp_runtime::{ serde::{Deserialize, Serialize}, traits::TryConvert, }; -use orml_tokens::{MultiTokenCurrencyExtended, MultiTokenReservableCurrency}; +use sp_std::{convert::TryInto, prelude::*}; -pub type BalanceOf = <::Tokens as MultiTokenCurrency< - ::AccountId, - >>::Balance; - +pub type BalanceOf = + <::Tokens as MultiTokenCurrency<::AccountId>>::Balance; type AccountIdOf = ::AccountId; @@ -87,7 +85,7 @@ pub mod pallet { PendingUpdatesU256Array::::insert(n, pending_updates_u256_array.clone()); let hash_of_pending_updates_u256_array = Self::calculate_hash_of_u256_array(pending_updates_u256_array); - HashPendingUpdatesU256Array::::insert(n,hash_of_pending_updates_u256_array); + HashPendingUpdatesU256Array::::insert(n, hash_of_pending_updates_u256_array); } } @@ -201,12 +199,14 @@ pub mod pallet { #[pallet::storage] #[pallet::unbounded] #[pallet::getter(fn get_pending_updates_u256_array)] - pub type PendingUpdatesU256Array = StorageMap<_, Blake2_128Concat, BlockNumberFor, Vec, OptionQuery>; + pub type PendingUpdatesU256Array = + StorageMap<_, Blake2_128Concat, BlockNumberFor, Vec, OptionQuery>; #[pallet::storage] #[pallet::unbounded] #[pallet::getter(fn get_hash_pending_updates_u256_array)] - pub type HashPendingUpdatesU256Array = StorageMap<_, Blake2_128Concat, BlockNumberFor, U256, OptionQuery>; + pub type HashPendingUpdatesU256Array = + StorageMap<_, Blake2_128Concat, BlockNumberFor, U256, OptionQuery>; #[pallet::storage] #[pallet::unbounded] @@ -240,7 +240,10 @@ pub mod pallet { pub trait Config: frame_system::Config { type RuntimeEvent: From> + IsType<::RuntimeEvent>; type AddressConverter: TryConvert; - type SequencerStakingProvider: SequencerStakingProviderTrait>; + type SequencerStakingProvider: SequencerStakingProviderTrait< + Self::AccountId, + BalanceOf, + >; // Dummy so that we can have the BalanceOf type here for the SequencerStakingProviderTrait type Tokens: MultiTokenCurrency + MultiTokenReservableCurrency @@ -261,7 +264,7 @@ pub mod pallet { // check json length to prevent big data spam, maybe not necessary as it will be checked later and slashed let current_block_number = >::block_number(); let dispute_period_end = current_block_number + (DISPUTE_PERIOD_LENGTH as u32).into(); - + let l1_pending_requests_json = input_json.trim().to_string(); // ensure sequencer has rights to update @@ -288,7 +291,6 @@ pub mod pallet { (sequencer.clone(), l1_pending_requests_json), ); - log!(info, "Pending Requests:"); for (dispute_period_end, (origin, json)) in PENDING_REQUESTS::::iter() { log!( @@ -346,7 +348,7 @@ pub mod pallet { // create cancel request let cancel_request = Cancel { updater: pending_requests_to_cancel.0.clone(), - canceler: canceler, + canceler, lastProccessedRequestOnL1: last_processed_request_on_l1, lastAcceptedRequestOnL1: last_accepted_request_on_l1, hash: hash_of_pending_request, @@ -395,77 +397,103 @@ pub mod pallet { match Self::deserialize_json(&input_json) { Ok(deserialized) => { log!(info, "Deserialized struct: {:?}", deserialized); - + // Add a new variable of type Requests let requests: Requests = deserialized; - - if requests.lastProccessedRequestOnL1 < Self::get_prev_last_processed_request_on_l2() + + if requests.lastProccessedRequestOnL1 < + Self::get_prev_last_processed_request_on_l2() { - log!(info, - "lastProccessedRequestOnL1 is less than prev_last_processed_request_on_l2" - ); + log!(info, "lastProccessedRequestOnL1 is less than prev_last_processed_request_on_l2"); } else { - for request_id in - (requests.lastProccessedRequestOnL1 + 1_u128)..=requests.lastAcceptedRequestOnL1 - { - if let Some(request) = requests.requests.get(&request_id) { - // ignore if already processed - if request_id > Self::get_last_processed_request_on_l2() { - log!(info, "EXECUTING: "); - let mut success = true; - match request { - Request::Deposit(deposit_request_details) => { - log!(info, "Deposit: {:?}", deposit_request_details); - match Self::process_deposit(deposit_request_details) { - Ok(_) => (), - Err(_) => success = false, - }; - PENDING_UPDATES::::insert(request_id, Update::DepositUpdate(success)); - } - Request::Withdraw(withdraw_request_details) => { - log!(info, "Withdraw: {:?}", withdraw_request_details); - match Self::process_withdraw(withdraw_request_details) { - Ok(_) => (), - Err(_) => success = false, - }; - PENDING_UPDATES::::insert(request_id, Update::WithdrawUpdate(success)); - } - Request::CancelResolution(cancel_resolution_request_details) => { - log!(info, "CancelResolution: {:?}", cancel_resolution_request_details); - match Self::process_cancel_resolution(cancel_resolution_request_details) { - Ok(_) => (), - Err(_) => success = false, - }; - PENDING_UPDATES::::insert(request_id, Update::ProcessedOnlyInfoUpdate(success)); - } - - Request::L2UpdatesToRemove(updates_to_remove_request_details) => { - log!(info, "L2UpdatesToRemove: {:?}", updates_to_remove_request_details); - match Self::process_l2_updates_to_remove(updates_to_remove_request_details) { - Ok(_) => (), - Err(_) => success = false, - }; - PENDING_UPDATES::::insert(request_id, Update::ProcessedOnlyInfoUpdate(success)); + for request_id in (requests.lastProccessedRequestOnL1 + 1_u128)..= + requests.lastAcceptedRequestOnL1 + { + if let Some(request) = requests.requests.get(&request_id) { + // ignore if already processed + if request_id > Self::get_last_processed_request_on_l2() { + log!(info, "EXECUTING: "); + let mut success = true; + match request { + Request::Deposit(deposit_request_details) => { + log!(info, "Deposit: {:?}", deposit_request_details); + match Self::process_deposit(deposit_request_details) { + Ok(_) => (), + Err(_) => success = false, + }; + PENDING_UPDATES::::insert( + request_id, + Update::DepositUpdate(success), + ); + }, + Request::Withdraw(withdraw_request_details) => { + log!(info, "Withdraw: {:?}", withdraw_request_details); + match Self::process_withdraw(withdraw_request_details) { + Ok(_) => (), + Err(_) => success = false, + }; + PENDING_UPDATES::::insert( + request_id, + Update::WithdrawUpdate(success), + ); + }, + Request::CancelResolution( + cancel_resolution_request_details, + ) => { + log!( + info, + "CancelResolution: {:?}", + cancel_resolution_request_details + ); + match Self::process_cancel_resolution( + cancel_resolution_request_details, + ) { + Ok(_) => (), + Err(_) => success = false, + }; + PENDING_UPDATES::::insert( + request_id, + Update::ProcessedOnlyInfoUpdate(success), + ); + }, + + Request::L2UpdatesToRemove( + updates_to_remove_request_details, + ) => { + log!( + info, + "L2UpdatesToRemove: {:?}", + updates_to_remove_request_details + ); + match Self::process_l2_updates_to_remove( + updates_to_remove_request_details, + ) { + Ok(_) => (), + Err(_) => success = false, + }; + PENDING_UPDATES::::insert( + request_id, + Update::ProcessedOnlyInfoUpdate(success), + ); + }, + } + // if success, increase last_processed_request_on_l2 + last_processed_request_on_l2::::put(request_id); + } + } else { + log!(info, "No request found for request_id: {:?}", request_id); + } } - } - // if success, increase last_processed_request_on_l2 - last_processed_request_on_l2::::put(request_id); - } - } else { - log!(info, "No request found for request_id: {:?}", request_id); - } - } - log!(info, "Pending Updates:"); - for (request_id, update) in PENDING_UPDATES::::iter() { - log!(info, "request_id: {:?}: {:?} ", request_id, update); - } + log!(info, "Pending Updates:"); + for (request_id, update) in PENDING_UPDATES::::iter() { + log!(info, "request_id: {:?}: {:?} ", request_id, update); + } } - } + }, Err(e) => { log!(info, "Error deserializing JSON: {:?}", e); - - } + }, } Ok(().into()) } @@ -494,32 +522,36 @@ impl Pallet { // Iterate over requests from lastProccessedRequestOnL1 to lastAcceptedRequestOnL1 - if requests.lastProccessedRequestOnL1 < Self::get_prev_last_processed_request_on_l2() + if requests.lastProccessedRequestOnL1 < + Self::get_prev_last_processed_request_on_l2() { - log!(info, - "lastProccessedRequestOnL1 is less than prev_last_processed_request_on_l2" - ); + log!(info, "lastProccessedRequestOnL1 is less than prev_last_processed_request_on_l2"); // SLASH sequencer for bringing unnecessary past requests, to be tested Self::slash(sequencer); } else { // return readRights to sequencer - SEQUENCER_RIGHTS::::mutate_exists(sequencer.clone(), |maybe_sequencer| { - match maybe_sequencer{ - &mut Some(ref mut sequencer_rights) if T::SequencerStakingProvider::is_active_sequencer(sequencer.clone()) => { - sequencer_rights.readRights += 1; + SEQUENCER_RIGHTS::::mutate_exists( + sequencer.clone(), + |maybe_sequencer| match maybe_sequencer { + &mut Some(ref mut sequencer_rights) + if T::SequencerStakingProvider::is_active_sequencer( + sequencer.clone(), + ) => + { + sequencer_rights.readRights += 1; + }, + _ => {}, }, - _ => {}, - } - }); + ); Self::process_requests(sequencer, &requests); } - } + }, Err(e) => { log!(info, "Error deserializing JSON: {:?}", e); // SLASH sequencer for invalid json Self::slash(sequencer); - } + }, } } PENDING_REQUESTS::::remove(>::block_number()); @@ -531,13 +563,14 @@ impl Pallet { fn process_requests(sequencer: &T::AccountId, requests: &Requests) { // check if not missing any request, not processing requests. This is double check, first should be done by sequencers and requests with missing request should be canceled - for key in (requests.lastProccessedRequestOnL1 + 1_u128)..=requests.lastAcceptedRequestOnL1 { + for key in (requests.lastProccessedRequestOnL1 + 1_u128)..=requests.lastAcceptedRequestOnL1 + { if let Some(_request) = requests.requests.get(&key) { } else { log!(info, "No request found for key: {:?}", key); // SLASH sequencer for missing request Self::slash(sequencer); - return; + return } } // process requests and checks if all requests are present from starting to ending one @@ -556,33 +589,52 @@ impl Pallet { Ok(_) => (), Err(_) => success = false, }; - PENDING_UPDATES::::insert(request_id, Update::DepositUpdate(success)); - } + PENDING_UPDATES::::insert( + request_id, + Update::DepositUpdate(success), + ); + }, Request::Withdraw(withdraw_request_details) => { log!(info, "Withdraw: {:?}", withdraw_request_details); match Self::process_withdraw(withdraw_request_details) { Ok(_) => (), Err(_) => success = false, }; - PENDING_UPDATES::::insert(request_id, Update::WithdrawUpdate(success)); - } + PENDING_UPDATES::::insert( + request_id, + Update::WithdrawUpdate(success), + ); + }, Request::CancelResolution(cancel_resolution_request_details) => { log!(info, "CancelResolution: {:?}", cancel_resolution_request_details); - match Self::process_cancel_resolution(cancel_resolution_request_details) { + match Self::process_cancel_resolution(cancel_resolution_request_details) + { Ok(_) => (), Err(_) => success = false, }; - PENDING_UPDATES::::insert(request_id, Update::ProcessedOnlyInfoUpdate(success)); - } - + PENDING_UPDATES::::insert( + request_id, + Update::ProcessedOnlyInfoUpdate(success), + ); + }, + Request::L2UpdatesToRemove(updates_to_remove_request_details) => { - log!(info, "L2UpdatesToRemove: {:?}", updates_to_remove_request_details); - match Self::process_l2_updates_to_remove(updates_to_remove_request_details) { + log!( + info, + "L2UpdatesToRemove: {:?}", + updates_to_remove_request_details + ); + match Self::process_l2_updates_to_remove( + updates_to_remove_request_details, + ) { Ok(_) => (), Err(_) => success = false, }; - PENDING_UPDATES::::insert(request_id, Update::ProcessedOnlyInfoUpdate(success)); - } + PENDING_UPDATES::::insert( + request_id, + Update::ProcessedOnlyInfoUpdate(success), + ); + }, } // if success, increase last_processed_request_on_l2 last_processed_request_on_l2::::put(request_id); @@ -591,7 +643,7 @@ impl Pallet { log!(info, "No request found for request_id: {:?}", request_id); // SLASH sequencer for missing request Self::slash(sequencer); - return; + return } } log!(info, "Pending Updates:"); @@ -600,38 +652,30 @@ impl Pallet { } } - fn process_deposit(deposit_request_details: &DepositRequestDetails) -> Result<(), &'static str> { - let account : T::AccountId = Self::eth_to_dot_address(deposit_request_details.depositRecipient.clone())?; + fn process_deposit( + deposit_request_details: &DepositRequestDetails, + ) -> Result<(), &'static str> { + let account: T::AccountId = + Self::eth_to_dot_address(deposit_request_details.depositRecipient.clone())?; // check ferried - // check if token exists, if not create one - log!(info, - "Deposit processed successfully: {:?}", - deposit_request_details - ); - - // tokens: mint tokens for user + + // Add check if token exists, if not create one + log!(info, "Deposit processed successfully: {:?}", deposit_request_details); + + // ADD tokens: mint tokens for user Ok(()) } - - fn process_withdraw(withdraw_request_details: &WithdrawRequestDetails) -> Result<(), &'static str> { - + + fn process_withdraw( + withdraw_request_details: &WithdrawRequestDetails, + ) -> Result<(), &'static str> { // fail will occur if user has not enough balance - - // if user has enought balance - if withdraw_request_details.amount > 0 { - // Successful deposit handling logic goes here - log!(info, - "Withdraw processed successfully: {:?}", - withdraw_request_details - ); - Ok(()) - } else { - // Failed deposit handling logic goes here - log!(info, "Withdraw handling failed: Not enough balance"); - Err("Not enough balance") - } - + + let account: T::AccountId = + Self::eth_to_dot_address(withdraw_request_details.withdrawRecipient.clone())?; + + // Add ensure // ::Currency::ensure_can_withdraw( // sold_asset_id.into(), // sender, @@ -642,46 +686,46 @@ impl Pallet { // ) // .or(Err(Error::::NotEnoughAssets))?; - // burn tokes for user + // Add burn tokes for user + Ok(()) } - + fn process_cancel_resolution( cancel_resolution_request_details: &CancelResolutionRequestDetails, ) -> Result<(), &'static str> { let cancel_request_id = cancel_resolution_request_details.l2RequestId; let cancel_justified = cancel_resolution_request_details.cancelJustified; - let cancel_update: Cancel = match PENDING_UPDATES::::get(cancel_request_id) { - Some(update) => { + let cancel_update: Cancel = match PENDING_UPDATES::::get(cancel_request_id) + { + Some(update) => if let Update::Cancel(cancel) = update { cancel } else { - return Err("Invalid update type"); - } - } + return Err("Invalid update type") + }, None => return Err("Cancel update not found"), }; let updater = cancel_update.updater; let canceler = cancel_update.canceler; - let to_be_slashed = if cancel_justified { - updater.clone() - } else { - canceler.clone() - }; + let to_be_slashed = if cancel_justified { updater.clone() } else { canceler.clone() }; - // return rights to canceler and updater // only if active sequencer SEQUENCER_RIGHTS::::mutate_exists(updater.clone(), |maybe_sequencer| { - match maybe_sequencer{ - &mut Some(ref mut sequencer) if T::SequencerStakingProvider::is_active_sequencer(updater) => { + match maybe_sequencer { + &mut Some(ref mut sequencer) + if T::SequencerStakingProvider::is_active_sequencer(updater) => + { sequencer.readRights += 1; }, _ => {}, } }); SEQUENCER_RIGHTS::::mutate_exists(canceler.clone(), |maybe_sequencer| { - match maybe_sequencer{ - &mut Some(ref mut sequencer) if T::SequencerStakingProvider::is_active_sequencer(canceler) => { + match maybe_sequencer { + &mut Some(ref mut sequencer) + if T::SequencerStakingProvider::is_active_sequencer(canceler) => + { sequencer.cancelRights += 1; }, _ => {}, @@ -691,47 +735,50 @@ impl Pallet { // slash is after adding rights, since slash can reduce stake below required level and remove all rights Self::slash(&to_be_slashed); - log!(info, + log!( + info, "Cancel resolution processed successfully: {:?}", cancel_resolution_request_details ); - + //additional checks Ok(()) } - + fn process_l2_updates_to_remove( updates_to_remove_request_details: &UpdatesToRemoveRequestDetails, ) -> Result<(), &'static str> { - for requestId in updates_to_remove_request_details.updates.iter() { PENDING_UPDATES::::remove(requestId); } - log!(info, + log!( + info, "Update removal processed successfully, removed: {:?}", updates_to_remove_request_details ); //additional checks - + Ok(()) } fn slash(sequencer: &T::AccountId) -> Result<(), &'static str> { // check if sequencer is active - let is_active_sequencer_before = T::SequencerStakingProvider::is_active_sequencer(sequencer.clone()); + let is_active_sequencer_before = + T::SequencerStakingProvider::is_active_sequencer(sequencer.clone()); // slash sequencer T::SequencerStakingProvider::slash_sequencer(sequencer.clone())?; // check if sequencer is active - let is_active_sequencer_after = T::SequencerStakingProvider::is_active_sequencer(sequencer.clone()); + let is_active_sequencer_after = + T::SequencerStakingProvider::is_active_sequencer(sequencer.clone()); // if sequencer was active and is not active anymore, remove rights if is_active_sequencer_before && !is_active_sequencer_after { Self::handle_sequencer_deactivation(sequencer.clone()); } - + log!(info, "SLASH for: {:?}", sequencer); - + Ok(()) } @@ -739,7 +786,7 @@ impl Pallet { let mut hasher = Keccak256::new(); hasher.update(input.as_bytes()); let result = hasher.finalize(); - + U256::from(&result[..]) } @@ -747,15 +794,14 @@ impl Pallet { let mut hasher = Keccak256::new(); hasher.update(input.as_bytes()); let result = hasher.finalize(); - + hex::encode(result) } - + fn calculate_hash_of_pending_requests(json_string_to_hash: &str) -> U256 { - let hash_of_pending_request = Self::calculate_keccak256_hash_u256(json_string_to_hash); log!(info, "Keccak256 Hash of PENDING_REQUESTS at {:#?}", hash_of_pending_request); - + hash_of_pending_request } @@ -772,7 +818,7 @@ impl Pallet { } else { updates.push(0.into()); } - } + }, Update::WithdrawUpdate(success) => { updates.push(2.into()); updates.push(request_id.into()); @@ -781,14 +827,14 @@ impl Pallet { } else { updates.push(0.into()); } - } + }, Update::Cancel(cancel) => { updates.push(3.into()); updates.push(request_id.into()); updates.push(cancel.lastProccessedRequestOnL1.into()); updates.push(cancel.lastAcceptedRequestOnL1.into()); updates.push(cancel.hash); - } + }, Update::ProcessedOnlyInfoUpdate(success) => { updates.push(4.into()); updates.push(request_id.into()); @@ -797,9 +843,8 @@ impl Pallet { } else { updates.push(0.into()); } - } - _ => { - } + }, + _ => {}, } } @@ -826,7 +871,7 @@ impl Pallet { fn calculate_hash_of_u256_array(u256_vec: Vec) -> U256 { let mut hasher = Keccak256::new(); - let mut byte_array: [u8; 32] = Default::default(); + let mut byte_array: [u8; 32] = Default::default(); for u in u256_vec.iter() { u.to_big_endian(&mut byte_array[..]); hasher.update(&byte_array[..]); @@ -835,12 +880,12 @@ impl Pallet { U256::from(&result[..]) } fn eth_to_dot_address(eth_addr: String) -> Result { - T::AddressConverter::try_convert(eth_addr).or(Err("Cannot convert address")) + T::AddressConverter::try_convert(eth_addr).or(Err("Cannot convert address")) } } impl RolldownProviderTrait> for Pallet { - fn new_sequencer_active(sequencer: AccountIdOf){ + fn new_sequencer_active(sequencer: AccountIdOf) { // raise sequencer count sequencer_count::::put(Self::get_sequencer_count() + 1); // add rights to new sequencer @@ -862,4 +907,4 @@ impl RolldownProviderTrait> for Pallet { } } } -} \ No newline at end of file +}