Skip to content

Commit

Permalink
cleanup clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
1xstj committed Dec 17, 2024
1 parent 99c6b08 commit eeb5487
Show file tree
Hide file tree
Showing 16 changed files with 464 additions and 71 deletions.
15 changes: 11 additions & 4 deletions pallets/multi-asset-delegation/src/functions/delegate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use sp_runtime::{
DispatchError, Percent,
};
use sp_std::vec::Vec;
use tangle_primitives::services::EvmAddressMapping;
use tangle_primitives::{services::Asset, BlueprintId};

impl<T: Config> Pallet<T> {
Expand Down Expand Up @@ -403,10 +404,16 @@ impl<T: Config> Pallet<T> {
);
},
Asset::Erc20(address) => {
// TODO : Handle it
// let (success, _weight) =
// Self::erc20_transfer(address, &caller, Self::address(), value)?;
// ensure!(success, Error::<T>::ERC20TransferFailed);
let slashed_amount_recipient_evm =
T::EvmAddressMapping::into_address(T::SlashedAmountRecipient::get());
let (success, _weight) = Self::erc20_transfer(
address,
&Self::pallet_evm_account(),
slashed_amount_recipient_evm,
slash_amount,
)
.map_err(|e| Error::<T>::ERC20TransferFailed)?;
ensure!(success, Error::<T>::ERC20TransferFailed);
},
}

Expand Down
18 changes: 14 additions & 4 deletions pallets/multi-asset-delegation/src/functions/deposit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,11 @@ impl<T: Config> Pallet<T> {
let delay = T::LeaveDelegatorsDelay::get();

// Process all ready withdraw requests
metadata.withdraw_requests.retain(|request| {
let mut i = 0;
while i < metadata.withdraw_requests.len() {
let request = &metadata.withdraw_requests[i];
if current_round >= delay + request.requested_round {
match request.asset_id {
let transfer_success = match request.asset_id {
Asset::Custom(asset_id) => T::Fungibles::transfer(
asset_id,
&Self::pallet_account(),
Expand All @@ -206,11 +208,19 @@ impl<T: Config> Pallet<T> {
false
}
},
};

if transfer_success {
// Remove the completed request
metadata.withdraw_requests.remove(i);
} else {
// Only increment if we didn't remove the request
i += 1;
}
} else {
true
i += 1;
}
});
}

Ok(())
})
Expand Down
7 changes: 3 additions & 4 deletions pallets/multi-asset-delegation/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ use frame_support::{
traits::{AsEnsureOriginWithArg, ConstU128, ConstU32, OneSessionHandler},
PalletId,
};
use frame_system::EnsureRoot;
use mock_evm::MockedEvmRunner;
use pallet_evm::GasWeightMapping;
use pallet_session::historical as pallet_session_historical;
Expand All @@ -40,10 +39,10 @@ use sp_keyring::AccountKeyring;
use sp_keystore::{testing::MemoryKeystore, KeystoreExt, KeystorePtr};
use sp_runtime::{
testing::UintAuthorityId,
traits::{ConstU64, ConvertInto, IdentityLookup},
traits::{ConvertInto, IdentityLookup},
AccountId32, BuildStorage, Perbill,
};
use tangle_primitives::services::{EvmAddressMapping, EvmGasWeightMapping, EvmRunner, RunnerError};
use tangle_primitives::services::{EvmAddressMapping, EvmGasWeightMapping, EvmRunner};

use core::ops::Mul;
use std::{collections::BTreeMap, sync::Arc};
Expand Down Expand Up @@ -428,7 +427,7 @@ pub fn new_test_ext_raw_authorities() -> sp_io::TestExternalities {

let mut evm_accounts = BTreeMap::new();

let mut create_contract = |bytecode: &str, address: H160| {
let create_contract = |bytecode: &str, address: H160| {
let mut raw_hex = bytecode.replace("0x", "").replace("\n", "");
// fix odd length
if raw_hex.len() % 2 != 0 {
Expand Down
1 change: 0 additions & 1 deletion pallets/multi-asset-delegation/src/mock_evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ use sp_runtime::{
transaction_validity::{TransactionValidity, TransactionValidityError},
ConsensusEngineId,
};
use tangle_primitives::services::{EvmRunner, RunnerError};

use pallet_evm_precompile_blake2::Blake2F;
use pallet_evm_precompile_bn128::{Bn128Add, Bn128Mul, Bn128Pairing};
Expand Down
6 changes: 2 additions & 4 deletions pallets/multi-asset-delegation/src/tests/delegate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,9 @@
// along with Tangle. If not, see <http://www.gnu.org/licenses/>.
#![allow(clippy::all)]
use super::*;
use crate::{types::*, CurrentRound, Error};
use crate::{CurrentRound, Error};
use frame_support::{assert_noop, assert_ok};
use sp_keyring::AccountKeyring::{Alice, Bob, Charlie, Dave, Eve, Ferdie, One, Two};
use sp_runtime::Percent;
use std::collections::BTreeMap;
use sp_keyring::AccountKeyring::{Alice, Bob};
use tangle_primitives::services::Asset;

#[test]
Expand Down
2 changes: 1 addition & 1 deletion pallets/multi-asset-delegation/src/tests/deposit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
use super::*;
use crate::{types::DelegatorStatus, CurrentRound, Error};
use frame_support::{assert_noop, assert_ok};
use sp_keyring::AccountKeyring::{Alice, Bob, Charlie, Dave, Eve, Ferdie, One, Two};
use sp_keyring::AccountKeyring::Bob;
use sp_runtime::ArithmeticError;
use tangle_primitives::services::Asset;

Expand Down
37 changes: 6 additions & 31 deletions pallets/multi-asset-delegation/src/tests/operator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use crate::{
CurrentRound, Error,
};
use frame_support::{assert_noop, assert_ok};
use sp_keyring::AccountKeyring::{Alice, Bob, Charlie, Dave, Eve};
use sp_keyring::AccountKeyring::{Alice, Bob, Eve};
use sp_runtime::Percent;
use tangle_primitives::services::Asset;

Expand Down Expand Up @@ -259,7 +259,7 @@ fn operator_bond_more_not_an_operator() {
fn operator_bond_more_insufficient_balance() {
new_test_ext().execute_with(|| {
let bond_amount = 10_000;
let additional_bond = 1150_000; // Exceeds available balance
let additional_bond = 1_150_000; // Exceeds available balance

// Join operator first
assert_ok!(MultiAssetDelegation::join_operators(
Expand Down Expand Up @@ -651,22 +651,6 @@ fn slash_operator_success() {
Fixed(vec![blueprint_id].try_into().unwrap()),
));

// Setup delegator with all blueprints
assert_ok!(MultiAssetDelegation::deposit(
RuntimeOrigin::signed(Bob.to_account_id()),
asset_id,
delegator_stake,
None
));

assert_ok!(MultiAssetDelegation::delegate(
RuntimeOrigin::signed(Bob.to_account_id()),
Alice.to_account_id(),
asset_id,
delegator_stake,
Fixed(vec![blueprint_id].try_into().unwrap()),
));

// Slash 50% of stakes
let slash_percentage = Percent::from_percent(50);
assert_ok!(MultiAssetDelegation::slash_operator(
Expand All @@ -679,23 +663,14 @@ fn slash_operator_success() {
let operator_info = MultiAssetDelegation::operator_info(Alice.to_account_id()).unwrap();
assert_eq!(operator_info.stake, operator_stake / 2);

// Verify fixed delegator stake was slashed
let delegator_2 = MultiAssetDelegation::delegators(Charlie.to_account_id()).unwrap();
let delegation_2 = delegator_2
.delegations
.iter()
.find(|d| d.operator == Alice.to_account_id())
.unwrap();
assert_eq!(delegation_2.amount, delegator_stake / 2);

// Verify all-blueprints delegator stake was slashed
let delegator_3 = MultiAssetDelegation::delegators(Charlie.to_account_id()).unwrap();
let delegation_3 = delegator_3
// Verify delegator stake was slashed
let delegator = MultiAssetDelegation::delegators(Bob.to_account_id()).unwrap();
let delegation = delegator
.delegations
.iter()
.find(|d| d.operator == Alice.to_account_id())
.unwrap();
assert_eq!(delegation_3.amount, delegator_stake / 2);
assert_eq!(delegation.amount, delegator_stake / 2);

// Verify event
System::assert_has_event(RuntimeEvent::MultiAssetDelegation(Event::OperatorSlashed {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
use super::*;
use crate::CurrentRound;
use frame_support::assert_ok;
use sp_keyring::AccountKeyring::{Alice, Bob, Charlie, Dave, Eve};
use sp_keyring::AccountKeyring::{Alice, Bob, Charlie, Dave};
use tangle_primitives::services::Asset;

#[test]
Expand Down
6 changes: 4 additions & 2 deletions pallets/services/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ use sp_runtime::{
traits::{ConvertInto, IdentityLookup},
AccountId32, BuildStorage, Perbill,
};
use tangle_primitives::services::Asset;
use tangle_primitives::services::{EvmAddressMapping, EvmGasWeightMapping};

use core::ops::Mul;
use std::{collections::BTreeMap, sync::Arc};
Expand Down Expand Up @@ -290,14 +292,14 @@ impl tangle_primitives::traits::MultiAssetDelegationInfo<AccountId, Balance>

fn get_total_delegation_by_asset_id(
_operator: &AccountId,
_asset_id: &Self::AssetId,
_asset_id: &Asset<Self::AssetId>,
) -> Balance {
Default::default()
}

fn get_delegators_for_operator(
_operator: &AccountId,
) -> Vec<(AccountId, Balance, Self::AssetId)> {
) -> Vec<(AccountId, Balance, Asset<Self::AssetId>)> {
Default::default()
}

Expand Down
4 changes: 2 additions & 2 deletions pallets/services/src/mock_evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ impl pallet_services::EvmRunner<Runtime> for MockedEvmRunner {
gas_limit: u64,
is_transactional: bool,
validate: bool,
) -> Result<fp_evm::CallInfo, pallet_services::traits::RunnerError<Self::Error>> {
) -> Result<fp_evm::CallInfo, tangle_primitives::services::RunnerError<Self::Error>> {
let max_fee_per_gas = FixedGasPrice::min_gas_price().0;
let max_priority_fee_per_gas = max_fee_per_gas.saturating_mul(U256::from(2));
let nonce = None;
Expand All @@ -322,7 +322,7 @@ impl pallet_services::EvmRunner<Runtime> for MockedEvmRunner {
proof_size_base_cost,
<Runtime as pallet_evm::Config>::config(),
)
.map_err(|o| pallet_services::traits::RunnerError { error: o.error, weight: o.weight })
.map_err(|o| tangle_primitives::services::RunnerError { error: o.error, weight: o.weight })
}
}

Expand Down
81 changes: 79 additions & 2 deletions precompiles/multi-asset-delegation/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ derive_more = { workspace = true, features = ["full"] }
hex-literal = { workspace = true }
serde = { workspace = true }
sha3 = { workspace = true }
ethereum = { workspace = true, features = ["with-codec"] }
ethers = "2.0"
hex = { workspace = true }
num_enum = { workspace = true }
libsecp256k1 = { workspace = true }
serde_json = { workspace = true }
smallvec = { workspace = true }
sp-keystore = { workspace = true }

# Moonbeam
precompile-utils = { workspace = true, features = ["std", "testing"] }
Expand All @@ -42,6 +50,37 @@ pallet-timestamp = { workspace = true, features = ["std"] }
scale-info = { workspace = true, features = ["derive", "std"] }
sp-io = { workspace = true, features = ["std"] }

# Frontier Primitive
fp-account = { workspace = true }
fp-consensus = { workspace = true }
fp-dynamic-fee = { workspace = true }
fp-ethereum = { workspace = true }
fp-rpc = { workspace = true }
fp-self-contained = { workspace = true }
fp-storage = { workspace = true }

# Frontier FRAME
pallet-base-fee = { workspace = true }
pallet-dynamic-fee = { workspace = true }
pallet-ethereum = { workspace = true }
pallet-evm = { workspace = true }
pallet-evm-chain-id = { workspace = true }

pallet-evm-precompile-blake2 = { workspace = true }
pallet-evm-precompile-bn128 = { workspace = true }
pallet-evm-precompile-curve25519 = { workspace = true }
pallet-evm-precompile-ed25519 = { workspace = true }
pallet-evm-precompile-modexp = { workspace = true }
pallet-evm-precompile-sha3fips = { workspace = true }
pallet-evm-precompile-simple = { workspace = true }

pallet-session = { workspace = true }
pallet-staking = { workspace = true }
sp-staking = { workspace = true }
frame-election-provider-support = { workspace = true }

ethabi = { workspace = true }

[features]
default = ["std"]
std = [
Expand All @@ -57,5 +96,43 @@ std = [
"sp-runtime/std",
"sp-std/std",
"tangle-primitives/std",
"pallet-assets/std"
]
"pallet-assets/std",
"hex/std",
"scale-info/std",
"sp-runtime/std",
"frame-support/std",
"frame-system/std",
"sp-core/std",
"sp-std/std",
"sp-io/std",
"tangle-primitives/std",
"pallet-balances/std",
"pallet-timestamp/std",
"fp-account/std",
"fp-consensus/std",
"fp-dynamic-fee/std",
"fp-ethereum/std",
"fp-evm/std",
"fp-rpc/std",
"fp-self-contained/std",
"fp-storage/std",
"pallet-base-fee/std",
"pallet-dynamic-fee/std",
"pallet-ethereum/std",
"pallet-evm/std",
"pallet-evm-chain-id/std",

"pallet-evm-precompile-modexp/std",
"pallet-evm-precompile-sha3fips/std",
"pallet-evm-precompile-simple/std",
"pallet-evm-precompile-blake2/std",
"pallet-evm-precompile-bn128/std",
"pallet-evm-precompile-curve25519/std",
"pallet-evm-precompile-ed25519/std",
"precompile-utils/std",
"serde/std",
"pallet-session/std",
"pallet-staking/std",
"sp-staking/std",
"frame-election-provider-support/std",
]
8 changes: 2 additions & 6 deletions precompiles/multi-asset-delegation/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
#[cfg(test)]
mod mock;
#[cfg(test)]
mod mock_evm;
#[cfg(test)]
mod tests;

use fp_evm::{PrecompileFailure, PrecompileHandle};
Expand Down Expand Up @@ -122,12 +124,6 @@ where
{
// Errors for the `MultiAssetDelegation` precompile.

/// Found an invalid amount / value.
const INVALID_AMOUNT: [u8; 32] = keccak256!("InvalidAmount()");
/// Value must be zero for ERC20 payment asset.
const VALUE_NOT_ZERO_FOR_ERC20: [u8; 32] = keccak256!("ValueMustBeZeroForERC20()");
/// Value must be zero for custom payment asset.
const VALUE_NOT_ZERO_FOR_CUSTOM_ASSET: [u8; 32] = keccak256!("ValueMustBeZeroForCustomAsset()");
/// Payment asset should be either custom or ERC20.
const PAYMENT_ASSET_SHOULD_BE_CUSTOM_OR_ERC20: [u8; 32] =
keccak256!("PaymentAssetShouldBeCustomOrERC20()");
Expand Down
Loading

0 comments on commit eeb5487

Please sign in to comment.