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

code cleanup v3 #909

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
2 changes: 1 addition & 1 deletion frost/frost-ed448/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl Decode for WrappedScalar {
let mut bytes = [0u8; 56];
input.read(&mut bytes)?;
let buffer = ScalarBytes::from_slice(&bytes);
Ok(WrappedScalar(Scalar::from_canonical_bytes(buffer).unwrap_or(Scalar::ZERO)))
WrappedScalar(Scalar::from_canonical_bytes(buffer))
}
}

Expand Down
60 changes: 40 additions & 20 deletions node/tests/evm_restaking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,8 @@ async fn deploy_tangle_lrt(

// Mock values for consistent testing
const EIGHTEEN_DECIMALS: u128 = 1_000_000_000_000_000_000_000;
const MOCK_DEPOSIT_CAP: u128 = 1_000_000 * EIGHTEEN_DECIMALS; // 1M tokens with 18 decimals
const MOCK_DEPOSIT: u128 = 100_000 * EIGHTEEN_DECIMALS; // 100k tokens with 18 decimals
const MOCK_DEPOSIT_CAP: u128 = 100_000 * EIGHTEEN_DECIMALS; // 100k tokens with 18 decimals
const MOCK_DEPOSIT: u128 = 1000 * EIGHTEEN_DECIMALS; // 100k tokens with 18 decimals
const MOCK_APY: u8 = 10; // 10% APY

/// Setup the E2E test environment.
Expand Down Expand Up @@ -461,7 +461,7 @@ fn operator_join_delegator_delegate_erc20() {
let usdc = MockERC20::new(t.usdc, &bob_provider);

// Mint USDC for Bob
let mint_amount = U256::from(100_000_000u128);
let mint_amount = U256::from(100_000u128);
usdc.mint(bob.address(), mint_amount).send().await?.get_receipt().await?;

let bob_balance = usdc.balanceOf(bob.address()).call().await?;
Expand Down Expand Up @@ -924,7 +924,7 @@ fn lrt_deposit_withdraw_erc20() {
}

#[test]
fn lrt_rewards() {
fn mad_rewards() {
run_mad_test(|t| async move {
let alice = TestAccount::Alice;
let alice_provider = alloy_provider_with_wallet(&t.provider, alice.evm_wallet());
Expand All @@ -936,7 +936,7 @@ fn lrt_rewards() {
let cfg_addr = api::storage().rewards().reward_config_storage(vault_id);
let cfg = t.subxt.storage().at_latest().await?.fetch(&cfg_addr).await?.unwrap();

let deposit = U256::from(MOCK_DEPOSIT);
let deposit_amount = U256::from(MOCK_DEPOSIT);

// Setup a LRT Vault for Alice.
let lrt_address = deploy_tangle_lrt(
Expand All @@ -951,29 +951,49 @@ fn lrt_rewards() {
// Bob as delegator
let bob = TestAccount::Bob;
let bob_provider = alloy_provider_with_wallet(&t.provider, bob.evm_wallet());
// Mint WETH for Bob
let weth_amount = deposit;
let weth = MockERC20::new(t.weth, &bob_provider);
weth.mint(bob.address(), weth_amount).send().await?.get_receipt().await?;

// Approve LRT contract to spend WETH
let deposit_amount = weth_amount;
let approve_result =
weth.approve(lrt_address, deposit_amount).send().await?.get_receipt().await?;
assert!(approve_result.status());
info!("Approved {} WETH for deposit in LRT", format_ether(deposit_amount));
// Mint USDC for Bob
let mint_amount = U256::from(100_000_000u128);
let mint_call = api::tx().assets().mint(
t.usdc_asset_id,
bob.address().to_account_id().into(),
mint_amount.to::<u128>(),
);

// Deposit WETH to LRT
let lrt = TangleLiquidRestakingVault::new(lrt_address, &bob_provider);
let deposit_result = lrt
.deposit(deposit_amount, bob.address())
let mut result = t
.subxt
.tx()
.sign_and_submit_then_watch_default(&mint_call, &alice.substrate_signer())
.await?;

while let Some(Ok(s)) = result.next().await {
if let TxStatus::InBestBlock(b) = s {
let evs = match b.wait_for_success().await {
Ok(evs) => evs,
Err(e) => {
error!("Error: {:?}", e);
break;
},
};
evs.find_first::<api::assets::events::Issued>()?
.expect("Issued event to be emitted");
break;
}
}

// Delegate assets
let precompile = MultiAssetDelegation::new(MULTI_ASSET_DELEGATION, &bob_provider);

// Deposit and delegate using asset ID
let deposit_result = precompile
.deposit(U256::from(t.usdc_asset_id), Address::ZERO, U256::from(deposit_amount), 0)
.from(bob.address())
.send()
.await?
.with_timeout(Some(Duration::from_secs(5)))
.get_receipt()
.await?;
assert!(deposit_result.status());
info!("Deposited {} WETH in LRT", format_ether(deposit_amount));

// Wait for one year to pass
wait_for_more_blocks(&t.provider, 51).await;
Expand Down
4 changes: 4 additions & 0 deletions pallets/claims/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,10 @@ pub mod pallet {
) -> DispatchResultWithPostInfo {
T::MoveClaimOrigin::try_origin(origin).map(|_| ()).or_else(ensure_root)?;

if old == new {
return Ok(().into());
}

Claims::<T>::take(&old).map(|c| Claims::<T>::insert(&new, c));
Vesting::<T>::take(&old).map(|c| Vesting::<T>::insert(&new, c));
Signing::<T>::take(&old).map(|c| Signing::<T>::insert(&new, c));
Expand Down
4 changes: 2 additions & 2 deletions pallets/multi-asset-delegation/src/functions/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ impl<T: Config> Pallet<T> {

log::debug!(target: "evm", "Dispatching EVM call(0x{}): {}", hex::encode(transfer_fn.short_signature()), transfer_fn.signature());
let data = transfer_fn.encode_input(&args).map_err(|_| Error::<T>::EVMAbiEncode)?;
let gas_limit = 300_000;
let gas_limit = 500_000;
let call_result = Self::evm_call(*from, erc20, U256::zero(), data, gas_limit);
let info = match call_result {
Ok(info) => info,
Expand Down Expand Up @@ -105,7 +105,7 @@ impl<T: Config> Pallet<T> {

log::debug!(target: "evm", "Dispatching EVM call(0x{}): {}", hex::encode(transfer_fn.short_signature()), transfer_fn.signature());
let data = transfer_fn.encode_input(&args).map_err(|_| Error::<T>::EVMAbiEncode)?;
let gas_limit = 300_000;
let gas_limit = 500_000;
let info =
Self::evm_call(Self::pallet_evm_account(), erc20, U256::zero(), data, gas_limit)?;
let weight = Self::weight_from_call_info(&info);
Expand Down
12 changes: 9 additions & 3 deletions pallets/multi-asset-delegation/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ pub mod traits;
pub mod types;
pub use functions::*;

/// The log target of this pallet.
pub const LOG_TARGET: &str = "runtime::multi-asset-delegation";

#[frame_support::pallet]
pub mod pallet {
use super::functions::*;
Expand Down Expand Up @@ -410,6 +413,8 @@ pub mod pallet {
DepositExceedsCapForAsset,
/// Overflow from math
OverflowRisk,
/// The asset config is not found
AssetConfigNotFound,
}

/// Hooks for the pallet.
Expand Down Expand Up @@ -702,9 +707,10 @@ pub mod pallet {
},
};
// ensure the caps have not been exceeded
let remaning = T::RewardsManager::get_asset_deposit_cap_remaining(asset_id)
.map_err(|_| Error::<T>::DepositExceedsCapForAsset)?;
ensure!(amount <= remaning, Error::<T>::DepositExceedsCapForAsset);
let remaining = T::RewardsManager::get_asset_deposit_cap_remaining(asset_id)
.map_err(|_| Error::<T>::AssetConfigNotFound)?;
log::info!(target: crate::LOG_TARGET, "RewardsManager remaining: {:?}", remaining);
ensure!(amount <= remaining, Error::<T>::DepositExceedsCapForAsset);
Self::process_deposit(who.clone(), asset_id, amount, lock_multiplier)?;
Self::deposit_event(Event::Deposited { who, amount, asset_id });
Ok(())
Expand Down
25 changes: 24 additions & 1 deletion pallets/rewards/src/functions/rewards.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ use crate::{
Event, Pallet, RewardConfigForAssetVault, RewardConfigStorage, RewardVaultsPotAccount,
TotalRewardVaultDeposit, TotalRewardVaultScore, UserClaimedReward,
};
use frame_support::{ensure, traits::Currency};
use frame_support::{
ensure,
traits::{Currency, Get},
};
use frame_system::pallet_prelude::BlockNumberFor;
use scale_info::prelude::vec;
use sp_runtime::{
Expand Down Expand Up @@ -153,6 +156,26 @@ impl<T: Config> Pallet<T> {
Error::<T>::IncentiveCapGreaterThanDepositCap
);

ensure!(
config.incentive_cap <= T::MaxIncentiveCap::get(),
Error::<T>::IncentiveCapGreaterThanMaxIncentiveCap
);

ensure!(
config.deposit_cap <= T::MaxDepositCap::get(),
Error::<T>::DepositCapGreaterThanMaxDepositCap
);

ensure!(
config.incentive_cap >= T::MinIncentiveCap::get(),
Error::<T>::IncentiveCapLessThanMinIncentiveCap
);

ensure!(
config.deposit_cap >= T::MinDepositCap::get(),
Error::<T>::DepositCapLessThanMinDepositCap
);

if let Some(boost_multiplier) = config.boost_multiplier {
// boost multipliers are handled by locks, this ensures the multiplier is 1
// we can change the multiplier to be customisable in the future, but for now we
Expand Down
23 changes: 23 additions & 0 deletions pallets/rewards/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,21 @@ pub mod pallet {

/// The origin that can manage reward assets
type ForceOrigin: EnsureOrigin<Self::RuntimeOrigin>;

/// The max possible apy
type MaxApy: Get<Percent>;

/// The max possible deposit cap
type MaxDepositCap: Get<BalanceOf<Self>>;

/// The max possible incentive cap
type MaxIncentiveCap: Get<BalanceOf<Self>>;

/// The min possible deposit cap
type MinDepositCap: Get<BalanceOf<Self>>;

/// The min possible incentive cap
type MinIncentiveCap: Get<BalanceOf<Self>>;
}

#[pallet::pallet]
Expand Down Expand Up @@ -305,6 +320,14 @@ pub mod pallet {
PotAccountNotFound,
/// Decay rate is too high
InvalidDecayRate,
/// Incentive cap is greater than max incentive cap
IncentiveCapGreaterThanMaxIncentiveCap,
/// Deposit cap is greater than max deposit cap
DepositCapGreaterThanMaxDepositCap,
/// Incentive cap is less than min incentive cap
IncentiveCapLessThanMinIncentiveCap,
/// Deposit cap is less than min deposit cap
DepositCapLessThanMinDepositCap,
}

#[pallet::genesis_config]
Expand Down
14 changes: 13 additions & 1 deletion pallets/rewards/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use sp_keystore::{testing::MemoryKeystore, KeystoreExt, KeystorePtr};
use sp_runtime::{
testing::UintAuthorityId,
traits::{ConvertInto, IdentityLookup},
AccountId32, BuildStorage, Perbill,
AccountId32, BuildStorage, Perbill, Percent,
};
use tangle_primitives::{services::Asset, types::rewards::UserDepositWithLocks};

Expand All @@ -47,6 +47,8 @@ type Nonce = u32;
pub type AssetId = u128;
pub type BlockNumber = u64;

const EIGHTEEN_DECIMALS: u128 = 1_000_000_000_000_000_000_000;

#[frame_support::derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)]
impl frame_system::Config for Runtime {
type BaseCallFilter = frame_support::traits::Everything;
Expand Down Expand Up @@ -235,6 +237,11 @@ impl pallet_assets::Config for Runtime {

parameter_types! {
pub RewardsPID: PalletId = PalletId(*b"PotStake");
pub const MaxDepositCap: u128 = EIGHTEEN_DECIMALS * 100_000_000;
pub const MaxIncentiveCap: u128 = EIGHTEEN_DECIMALS * 100_000;
pub const MaxApy: Percent = Percent::from_percent(20);
pub const MinDepositCap: u128 = 0;
pub const MinIncentiveCap: u128 = 0;
}

impl pallet_rewards::Config for Runtime {
Expand All @@ -245,6 +252,11 @@ impl pallet_rewards::Config for Runtime {
type VaultId = u32;
type DelegationManager = MockDelegationManager;
type ForceOrigin = frame_system::EnsureRoot<AccountId>;
type MaxApy = MaxApy;
type MaxDepositCap = MaxDepositCap;
type MaxIncentiveCap = MaxIncentiveCap;
type MinIncentiveCap = MinIncentiveCap;
type MinDepositCap = MinDepositCap;
}

thread_local! {
Expand Down
8 changes: 4 additions & 4 deletions pallets/services/src/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ impl<T: Config> Pallet<T> {
Token::Address(mbsm),
];
let data = f.encode_input(args).map_err(|_| Error::<T>::EVMAbiEncode)?;
let gas_limit = 300_000;
let gas_limit = 500_000;
let value = U256::zero();
let info = Self::evm_call(Self::address(), bsm, value, data, gas_limit)?;
let weight = Self::weight_from_call_info(&info);
Expand Down Expand Up @@ -1003,7 +1003,7 @@ impl<T: Config> Pallet<T> {

log::debug!(target: "evm", "Dispatching EVM call(0x{}): {}", hex::encode(transfer_fn.short_signature()), transfer_fn.signature());
let data = transfer_fn.encode_input(&args).map_err(|_| Error::<T>::EVMAbiEncode)?;
let gas_limit = 300_000;
let gas_limit = 500_000;
let info = Self::evm_call(from, erc20, U256::zero(), data, gas_limit)?;
let weight = Self::weight_from_call_info(&info);

Expand Down Expand Up @@ -1050,7 +1050,7 @@ impl<T: Config> Pallet<T> {

log::debug!(target: "evm", "Dispatching EVM call(0x{}): {}", hex::encode(transfer_fn.short_signature()), transfer_fn.signature());
let data = transfer_fn.encode_input(&args).map_err(|_| Error::<T>::EVMAbiEncode)?;
let gas_limit = 300_000;
let gas_limit = 500_000;
let info = Self::evm_call(Self::address(), erc20, U256::zero(), data, gas_limit)?;
let weight = Self::weight_from_call_info(&info);

Expand Down Expand Up @@ -1092,7 +1092,7 @@ impl<T: Config> Pallet<T> {
) -> Result<(fp_evm::CallInfo, Weight), DispatchErrorWithPostInfo> {
log::debug!(target: "evm", "Dispatching EVM call(0x{}): {}", hex::encode(f.short_signature()), f.signature());
let data = f.encode_input(args).map_err(|_| Error::<T>::EVMAbiEncode)?;
let gas_limit = 300_000;
let gas_limit = 500_000;
let value = value.using_encoded(U256::from_little_endian);
let info = Self::evm_call(Self::address(), contract, value, data, gas_limit)?;
let weight = Self::weight_from_call_info(&info);
Expand Down
1 change: 1 addition & 0 deletions pallets/tangle-lst/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ use sp_std::{collections::btree_map::BTreeMap, fmt::Debug, ops::Div, vec::Vec};

/// The log target of this pallet.
pub const LOG_TARGET: &str = "runtime::nomination-pools";

// syntactic sugar for logging.
#[macro_export]
macro_rules! log {
Expand Down
Loading
Loading