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

Merged
merged 21 commits into from
Feb 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
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
38 changes: 17 additions & 21 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_000 * EIGHTEEN_DECIMALS; // 100k tokens with 18 decimals
const MOCK_DEPOSIT: u128 = 10_000 * 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 @@ -936,32 +936,27 @@ fn mad_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);

// Setup a LRT Vault for Alice.
let lrt_address = deploy_tangle_lrt(
alice_provider.clone(),
t.weth,
t.usdc,
alice.account_id().0,
"Liquid Restaked Ether",
"lrtETH",
"Liquid Restaked USDC",
"lrtUSDC",
)
.await?;

// 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(MOCK_DEPOSIT * 100);
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);
Expand All @@ -977,7 +972,7 @@ fn mad_rewards() {

// Delegate assets
let precompile = MultiAssetDelegation::new(MULTI_ASSET_DELEGATION, &bob_provider);
let deposit_amount = U256::from(100_000_000u128);
let deposit_amount = U256::from(MOCK_DEPOSIT);

// Deposit and delegate using asset ID
let deposit_result = precompile
Expand All @@ -998,12 +993,13 @@ fn mad_rewards() {

let rewards_addr = api::apis().rewards_api().query_user_rewards(
lrt_address.to_account_id(),
Asset::Erc20((<[u8; 20]>::from(t.weth)).into()),
Asset::Erc20((<[u8; 20]>::from(t.usdc)).into()),
);

let user_rewards = t.subxt.runtime_api().at_latest().await?.call(rewards_addr).await?;
match user_rewards {
Ok(rewards) => {
info!("User rewards: {} TNT", format_ether(U256::from(rewards)));
info!("User rewards: {} USDC", format_ether(U256::from(rewards)));
assert!(rewards > 0);
},
Err(e) => {
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<Perbill>;

/// 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
12 changes: 12 additions & 0 deletions pallets/rewards/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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: Perbill = Perbill::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
39 changes: 20 additions & 19 deletions precompiles/verify-schnorr-signatures/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
// along with Tangle. If not, see <http://www.gnu.org/licenses/>.

#![cfg_attr(not(feature = "std"), no_std)]

use fp_evm::PrecompileHandle;
use fp_evm::{ExitError, PrecompileFailure};
use precompile_utils::prelude::*;
use sp_core::{sr25519, ConstU32};
use sp_io::{crypto::sr25519_verify, hashing::keccak_256};
Expand All @@ -42,12 +42,21 @@ mod tests;
macro_rules! verify_signature {
($impl_type:ty, $key:expr, $signature:expr, $msg:expr, $key_default:expr, $sig_default:expr) => {{
let verifying_key: VerifyingKey<$impl_type> =
VerifyingKey::deserialize($key.try_into().unwrap_or($key_default))
.map_err(|_| revert("InvalidVerifyingKeyDeserialization"))?;
let sig: Signature<$impl_type> =
Signature::deserialize($signature.try_into().unwrap_or($sig_default))
.map_err(|_| revert("InvalidSignatureDeserialization"))?;
verifying_key.verify($msg, &sig).map_err(|_| revert("InvalidSignature"))?
VerifyingKey::deserialize($key.try_into().unwrap_or($key_default)).map_err(|_| {
PrecompileFailure::Error {
exit_status: ExitError::Other("InvalidVerifyingKeyDeserialization".into()),
}
})?;
let sig: Signature<$impl_type> = Signature::deserialize(
$signature.try_into().unwrap_or($sig_default),
)
.map_err(|_| PrecompileFailure::Error {
exit_status: ExitError::Other("InvalidSignatureDeserialization".into()),
})?;
verifying_key.verify($msg, &sig).map_err(|_| PrecompileFailure::Error {
exit_status: ExitError::Other("InvalidSignature".into()),
})?;
Ok(false)
}};
}

Expand Down Expand Up @@ -135,9 +144,7 @@ impl<Runtime: pallet_evm::Config> SchnorrSecp256k1Precompile<Runtime> {
&message,
&[0u8; 33],
&[0u8; 65]
);

Ok(false)
)
}
}

Expand Down Expand Up @@ -166,9 +173,7 @@ impl<Runtime: pallet_evm::Config> SchnorrEd25519Precompile<Runtime> {
&message,
&[0u8; 32],
&[0u8; 64]
);

Ok(false)
)
}
}

Expand Down Expand Up @@ -197,9 +202,7 @@ impl<Runtime: pallet_evm::Config> SchnorrP256Precompile<Runtime> {
&message,
&[0u8; 33],
&[0u8; 65]
);

Ok(false)
)
}
}

Expand Down Expand Up @@ -228,9 +231,7 @@ impl<Runtime: pallet_evm::Config> SchnorrRistretto255Precompile<Runtime> {
&message,
&[0u8; 32],
&[0u8; 64]
);

Ok(false)
)
}
}

Expand Down
Loading
Loading