Skip to content

Commit

Permalink
Merge branch 'main' into fix-unsafe-arithmetic
Browse files Browse the repository at this point in the history
  • Loading branch information
clostao authored Nov 16, 2023
2 parents c47cd3a + 301733b commit 06c7926
Show file tree
Hide file tree
Showing 10 changed files with 737 additions and 661 deletions.
1,234 changes: 628 additions & 606 deletions Cargo.lock

Large diffs are not rendered by default.

16 changes: 11 additions & 5 deletions pallets/dnt-fee-controller/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ pub mod pallet {
conversion_rate: (U256, U256),
amount: U256,
) -> Result<(), Self::Error> {
if amount.is_zero() {
return Ok(());
}
let fee_vault = FeeVaultPrecompileAddressStorage::<T>::get().unwrap();
let mapped_amount = amount
.checked_mul(conversion_rate.0)
Expand All @@ -129,12 +132,11 @@ pub mod pallet {
paid_amount: U256,
actual_amount: U256,
) -> Result<(), Self::Error> {
let over_fee = paid_amount.checked_sub(actual_amount);
let over_fee = paid_amount.saturating_sub(actual_amount);

let over_fee = match over_fee {
Some(amount) => amount,
None => return Err(Error::ArithmeticError),
};
if over_fee.is_zero() {
return Ok(());
}

let mapped_amount = over_fee
.checked_mul(conversion_rate.0)
Expand All @@ -161,6 +163,10 @@ pub mod pallet {
validator: H160,
to: Option<H160>,
) -> Result<(U256, U256), Self::Error> {
if actual_amount.is_zero() {
return Ok((0.into(), 0.into()));
}

let fee_in_user_token = actual_amount
.checked_mul(conversion_rate.0)
.map(|v| v.div_mod(conversion_rate.1).0);
Expand Down
45 changes: 26 additions & 19 deletions pallets/fee-rewards-vault/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,28 +22,19 @@ pub mod pallet {
pub struct Pallet<T>(_);

#[pallet::config]
pub trait Config: frame_system::Config {
}
pub trait Config: frame_system::Config {}

// double map
#[pallet::storage]
#[pallet::getter(fn claimable_reward)]
pub(super) type ClaimableReward<T: Config> = StorageDoubleMap<
_,
Twox64Concat,
H160,
Twox64Concat,
H160,
U256,
ValueQuery,
>;
pub(super) type ClaimableReward<T: Config> =
StorageDoubleMap<_, Twox64Concat, H160, Twox64Concat, H160, U256, ValueQuery>;

// map
#[pallet::storage]
#[pallet::getter(fn whitelist)]
pub(super) type Whitelist<T: Config> = StorageMap<_, Twox64Concat, H160, bool, ValueQuery>;


impl<T: Config> Pallet<T> {
pub fn is_whitelisted(address: H160) -> bool {
Self::whitelist(address)
Expand All @@ -57,24 +48,40 @@ pub mod pallet {
Self::claimable_reward(address, token)
}

pub fn add_claimable_reward(address: H160, token: H160, amount: U256) -> Result<(), &'static str> {
pub fn add_claimable_reward(
address: H160,
token: H160,
amount: U256,
) -> Result<(), &'static str> {
if amount.is_zero() {
return Ok(());
}
let current_amount = Self::claimable_reward(address, token);

let new_amount = current_amount.checked_add(amount)
let new_amount = current_amount
.checked_add(amount)
.ok_or("Overflow adding a new claimable reward")?;

ClaimableReward::<T>::insert(address, token, new_amount);
Ok(())
}

pub fn sub_claimable_reward(address: H160, token: H160, amount: U256)-> Result<(), &'static str> {

pub fn sub_claimable_reward(
address: H160,
token: H160,
amount: U256,
) -> Result<(), &'static str> {
if amount.is_zero() {
return Ok(());
}
let current_amount = Self::claimable_reward(address, token);

let new_amount = current_amount.checked_sub(amount)
let new_amount = current_amount
.checked_sub(amount)
.ok_or("Insufficient balance")?;

ClaimableReward::<T>::insert(address, token, new_amount);
Ok(())
}
}
}
}
10 changes: 9 additions & 1 deletion pallets/root-controller/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,18 @@ pub mod pallet {
DispatchAsRootOccurred { dispatch_result: DispatchResult },
}

impl<T: Config> Pallet<T> {
pub fn dispatch_as_root_weight() -> Weight {
Weight::from_parts(7_984_000, 0)
.saturating_add(Weight::from_parts(0, 1505))
.saturating_add(T::DbWeight::get().reads(1))
}
}

#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight({0})]
#[pallet::weight(Pallet::<T>::dispatch_as_root_weight())]
pub fn dispatch_as_root(
origin: OriginFor<T>,
call: Box<<T as Config>::RuntimeCall>,
Expand Down
22 changes: 13 additions & 9 deletions pallets/sponsored-transactions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ pub mod pallet {
},
transaction_data.into(),
None,
None
None,
)
.validate_in_block_for(&who)
.and_then(|v| v.with_chain_id())
Expand Down Expand Up @@ -273,7 +273,7 @@ pub mod pallet {
},
transaction_data.into(),
None,
None
None,
)
.validate_in_pool_for(&who)
.and_then(|v| v.with_chain_id())
Expand Down Expand Up @@ -326,6 +326,10 @@ pub mod pallet {
}

fn ensure_sponsor_balance(sponsor: H160, token: H160, amount: U256) -> Result<(), ()> {
if amount.is_zero() {
return Ok(());
}

let balance = T::ERC20Manager::balance_of(token.clone(), sponsor.clone());
if balance >= amount {
Ok(())
Expand All @@ -341,14 +345,14 @@ pub mod pallet {
payee: &H160,
amount: U256,
) -> Result<(), ()> {
let actual_amount = match amount
.checked_mul(conversion_rate.0)
.map(|v| v.div_mod(conversion_rate.1).0)
{
Some(v) => v,
None => return Err(()),
};
if amount.is_zero() {
return Ok(());
}

let actual_amount = amount
.saturating_mul(conversion_rate.0)
.div_mod(conversion_rate.1)
.0;
T::ERC20Manager::withdraw_amount(token.clone(), payer.clone(), actual_amount)
.map_err(|_| {})?;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,7 @@ pub mod pallet {
impl Default for GenesisConfig {
fn default() -> Self {
Self {
initial_default_conversion_rate_controller: <H160 as core::str::FromStr>::from_str(
"0x444212d6E4827893A70d19921E383130281Cda4a",
)
.expect("invalid address"),
initial_default_conversion_rate_controller: H160::zero(),
}
}
}
Expand Down
16 changes: 12 additions & 4 deletions pallets/upgrade-runtime-proposal/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,24 +119,32 @@ pub mod pallet {
}
}

impl<T: Config> Pallet<T> {
fn weight_for_read_writes(reads: u64, writes: u64) -> Weight {
Weight::from_parts(21_330_000, 1602)
.saturating_add(T::DbWeight::get().reads(reads))
.saturating_add(T::DbWeight::get().writes(writes))
}
}

#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_initialize(n: T::BlockNumber) -> Weight {
let code_saved_option = <ProposedCode<T>>::get();
let application_block_number_option = <ApplicationBlockNumber<T>>::get();

if code_saved_option.is_none() {
return Weight::zero();
return Pallet::<T>::weight_for_read_writes(2, 0);
}
let code = code_saved_option.unwrap().to_vec();

if application_block_number_option.is_none() {
return Weight::zero();
return Pallet::<T>::weight_for_read_writes(2, 0);
}
let application_block_number = application_block_number_option.unwrap();

if n != application_block_number {
return Weight::zero();
return Pallet::<T>::weight_for_read_writes(2, 0);
}

let call = frame_system::Call::<T>::set_code { code: code.into() };
Expand All @@ -152,7 +160,7 @@ pub mod pallet {
Pallet::<T>::clear_proposed_code();
Pallet::<T>::clear_application_block_number();

Weight::zero()
return Pallet::<T>::weight_for_read_writes(2, 2);
}
}

Expand Down
32 changes: 28 additions & 4 deletions pallets/validator-set/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,30 @@ pub mod pallet {
pub authority_index: u32,
}

impl<T: Config> Pallet<T> {
fn add_validator_weight() -> Weight {
Weight::from_parts(21_330_000, 1602)
.saturating_add(T::DbWeight::get().reads(1_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}

fn remove_validator_weight() -> Weight {
Weight::from_parts(19_840_000, 1602)
.saturating_add(T::DbWeight::get().reads(2_u64))
.saturating_add(T::DbWeight::get().writes(2_u64))
}

fn add_validator_again_weight() -> Weight {
Weight::from_parts(21_330_000, 1602)
.saturating_add(T::DbWeight::get().reads(2_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}

fn update_max_missed_epochs_weight() -> Weight {
Weight::from_parts(21_330_000, 1602).saturating_add(T::DbWeight::get().writes(1_u64))
}
}

#[pallet::call]
impl<T: Config> Pallet<T> {
/// Add a new validator.
Expand All @@ -374,7 +398,7 @@ pub mod pallet {
/// The origin can be configured using the `AddRemoveOrigin` type in the
/// host runtime. Can also be set to sudo/root.
#[pallet::call_index(0)]
#[pallet::weight({0})]
#[pallet::weight(Pallet::<T>::add_validator_weight())]
pub fn add_validator(origin: OriginFor<T>, validator_id: T::AccountId) -> DispatchResult {
T::AddRemoveOrigin::ensure_origin(origin)?;

Expand All @@ -388,7 +412,7 @@ pub mod pallet {
/// The origin can be configured using the `AddRemoveOrigin` type in the
/// host runtime. Can also be set to sudo/root.
#[pallet::call_index(1)]
#[pallet::weight({0})]
#[pallet::weight(Pallet::<T>::remove_validator_weight())]
pub fn remove_validator(
origin: OriginFor<T>,
validator_id: T::AccountId,
Expand All @@ -406,7 +430,7 @@ pub mod pallet {
/// The origin can be configured using the `AddRemoveOrigin` type in the
/// host runtime. Can also be set to sudo/root.
#[pallet::call_index(2)]
#[pallet::weight({0})]
#[pallet::weight(Pallet::<T>::update_max_missed_epochs_weight())]
pub fn update_max_missed_epochs(
origin: OriginFor<T>,
max_missed_epochs: U256,
Expand All @@ -422,7 +446,7 @@ pub mod pallet {
///
/// For this call, the dispatch origin must be the validator itself.
#[pallet::call_index(3)]
#[pallet::weight({0})]
#[pallet::weight(Pallet::<T>::add_validator_again_weight())]
pub fn add_validator_again(
origin: OriginFor<T>,
heartbeat: Heartbeat<T::BlockNumber, T::AuthorityId>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,9 @@ impl pallet_validator_fee_selector::Config for Runtime {

parameter_types! {
pub DefaultOwner : H160 = H160::from_str("0x2dEA828C816cC4D7CF195E0D220CB75354f47F2F").unwrap();
pub InitialDefaultConversionRateController: H160 = H160::from_str(
"0x444212d6E4827893A70d19921E383130281Cda4a",
).unwrap();
}

pub type Precompiles<R> = PrecompileSetBuilder<
Expand Down Expand Up @@ -347,10 +350,8 @@ impl ExtBuilder {
.expect("Pallet balances storage can be assimilated");

let config = pallet_validator_fee_selector::GenesisConfig {
initial_default_conversion_rate_controller: H160::from_str(
"0x444212d6E4827893A70d19921E383130281Cda4a",
)
.expect("invalid address"),
initial_default_conversion_rate_controller: InitialDefaultConversionRateController::get(
),
};

let custom_controller = MeaninglessTokenAddress::get();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ use precompile_utils::prelude::*;

use crate::{
mock::{
DefaultOwner, ExtBuilder, MeaninglessTokenAddress, NonCryptoAlith, PCall, Precompiles,
PrecompilesValue, Runtime, UnpermissionedAccount, UnpermissionedAccount2,
DefaultOwner, ExtBuilder, InitialDefaultConversionRateController, MeaninglessTokenAddress,
NonCryptoAlith, PCall, Precompiles, PrecompilesValue, Runtime, UnpermissionedAccount,
UnpermissionedAccount2,
},
DefaultAcceptance, SELECTOR_LOG_NEW_OWNER, SELECTOR_LOG_VALIDATOR_CONTROLLER_CHANGED,
SELECTOR_LOG_VALIDATOR_TOKEN_ACCEPTANCE_CHANGED,
Expand Down Expand Up @@ -342,9 +343,7 @@ fn accept_token_and_revoke() {

#[test]
fn default_conversion_rate() {
let default: Address = pallet_validator_fee_selector::GenesisConfig::default()
.initial_default_conversion_rate_controller
.into();
let default: Address = InitialDefaultConversionRateController::get().into();
ExtBuilder::default().build().execute_with(|| {
precompiles()
.prepare_test(
Expand Down

0 comments on commit 06c7926

Please sign in to comment.