Skip to content

Commit

Permalink
Change as_u128 to try_from (#1072)
Browse files Browse the repository at this point in the history
* fix: 🐛 rm as_u128

* fix: 🐛 rpc of stable-pool

* fix: 🐛 test-all

* fix: 🐛 clippy

* fix: 🐛 clippy

* fix: 🐛 token_to_vtoken

* fix: 🐛 clippy
  • Loading branch information
yooml authored Dec 5, 2023
1 parent 11e4d46 commit 19fb365
Show file tree
Hide file tree
Showing 15 changed files with 133 additions and 96 deletions.
27 changes: 15 additions & 12 deletions pallets/farming/src/gauge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,15 +322,16 @@ where
let gauge_reward = gauge_rate * reward;
// reward_to_claim = farming rate * gauge rate * gauge rewards *
// existing rewards in the gauge pool
let reward_to_claim: BalanceOf<T> =
let reward_to_claim: BalanceOf<T> = u128::try_from(
U256::from(share_info.share.to_owned().saturated_into::<u128>())
.saturating_mul(U256::from(
gauge_reward.to_owned().saturated_into::<u128>(),
))
.checked_div(total_shares)
.unwrap_or_default()
.as_u128()
.unique_saturated_into();
.unwrap_or_default(),
)
.map_err(|_| ArithmeticError::Overflow)?
.unique_saturated_into();
*total_gauged_reward = total_gauged_reward
.checked_add(&gauge_reward)
.ok_or(ArithmeticError::Overflow)?;
Expand Down Expand Up @@ -416,15 +417,16 @@ where
let withdrawn_reward =
share_info.withdrawn_rewards.get(reward_currency).copied().unwrap_or_default();

let total_reward_proportion: BalanceOf<T> =
let total_reward_proportion: BalanceOf<T> = u128::try_from(
U256::from(share_info.share.to_owned().saturated_into::<u128>())
.saturating_mul(U256::from(
total_reward.to_owned().saturated_into::<u128>(),
))
.checked_div(total_shares)
.unwrap_or_default()
.as_u128()
.unique_saturated_into();
.unwrap_or_default(),
)
.map_err(|_| ArithmeticError::Overflow)?
.unique_saturated_into();

let reward_to_withdraw = total_reward_proportion
.saturating_sub(withdrawn_reward)
Expand Down Expand Up @@ -498,15 +500,16 @@ where
let gauge_reward = gauge_rate * reward;
// reward_to_claim = farming rate * gauge rate * gauge rewards *
// existing rewards in the gauge pool
let reward_to_claim: BalanceOf<T> =
let reward_to_claim: BalanceOf<T> = u128::try_from(
U256::from(share_info.share.to_owned().saturated_into::<u128>())
.saturating_mul(U256::from(
gauge_reward.to_owned().saturated_into::<u128>(),
))
.checked_div(total_shares)
.unwrap_or_default()
.as_u128()
.unique_saturated_into();
.unwrap_or_default(),
)
.map_err(|_| ArithmeticError::Overflow)?
.unique_saturated_into();
result_vec.push((*reward_currency, reward_to_claim));
Ok(())
},
Expand Down
56 changes: 31 additions & 25 deletions pallets/farming/src/rewards.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,14 +168,19 @@ impl<T: Config> Pallet<T> {
let reward_inflation = if initial_total_shares.is_zero() {
Zero::zero()
} else {
U256::from(add_amount.to_owned().saturated_into::<u128>())
.saturating_mul(total_reward.to_owned().saturated_into::<u128>().into())
.checked_div(
initial_total_shares.to_owned().saturated_into::<u128>().into(),
)
.unwrap_or_default()
.as_u128()
.saturated_into()
// If the total shares is zero or reward amount overflow, the reward inflation
// is zero.
u128::try_from(
U256::from(add_amount.to_owned().saturated_into::<u128>())
.saturating_mul(total_reward.to_owned().saturated_into::<u128>().into())
.checked_div(
initial_total_shares.to_owned().saturated_into::<u128>().into(),
)
.unwrap_or_default(),
)
.ok()
.unwrap_or_default()
.saturated_into()
};
*total_reward = total_reward.saturating_add(reward_inflation);
*total_withdrawn_reward = total_withdrawn_reward.saturating_add(reward_inflation);
Expand Down Expand Up @@ -246,15 +251,16 @@ impl<T: Config> Pallet<T> {
// update withdrawn rewards for each reward currency
share_info.withdrawn_rewards.iter_mut().try_for_each(
|(reward_currency, withdrawn_reward)| -> DispatchResult {
let withdrawn_reward_to_remove: BalanceOf<T> = removing_share
.saturating_mul(
withdrawn_reward.to_owned().saturated_into::<u128>().into(),
)
.checked_div(share_info.share.saturated_into::<u128>().into())
.unwrap_or_default()
.as_u128()
.saturated_into();

let withdrawn_reward_to_remove: BalanceOf<T> = u128::try_from(
removing_share
.saturating_mul(
withdrawn_reward.to_owned().saturated_into::<u128>().into(),
)
.checked_div(share_info.share.saturated_into::<u128>().into())
.unwrap_or_default(),
)
.map_err(|_| ArithmeticError::Overflow)?
.unique_saturated_into();
if let Some((total_reward, total_withdrawn_reward)) =
pool_info.rewards.get_mut(reward_currency)
{
Expand Down Expand Up @@ -310,15 +316,15 @@ impl<T: Config> Pallet<T> {
.copied()
.unwrap_or_default();

let total_reward_proportion: BalanceOf<T> = U256::from(
share_info.share.to_owned().saturated_into::<u128>(),
let total_reward_proportion: BalanceOf<T> = u128::try_from(
U256::from(share_info.share.to_owned().saturated_into::<u128>())
.saturating_mul(U256::from(
total_reward.to_owned().saturated_into::<u128>(),
))
.checked_div(total_shares)
.unwrap_or_default(),
)
.saturating_mul(U256::from(
total_reward.to_owned().saturated_into::<u128>(),
))
.checked_div(total_shares)
.unwrap_or_default()
.as_u128()
.map_err(|_| ArithmeticError::Overflow)?
.unique_saturated_into();

let reward_to_withdraw = total_reward_proportion
Expand Down
1 change: 0 additions & 1 deletion pallets/farming/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ fn asset_registry() {
#[test]
fn boost() {
ExtBuilder::default().one_hundred_for_alice_n_bob().build().execute_with(|| {
env_logger::try_init().unwrap_or(());
asset_registry();
System::set_block_number(System::block_number() + 20);
assert_ok!(VeMinting::set_config(
Expand Down
2 changes: 1 addition & 1 deletion pallets/salp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1270,7 +1270,7 @@ pub mod pallet {
relay_currency_id,
relay_vtoken_id,
value,
);
)?;
T::StablePool::swap(
&T::BuybackPalletId::get().into_account_truncating(),
pool_id,
Expand Down
2 changes: 1 addition & 1 deletion pallets/salp/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1448,7 +1448,7 @@ fn refund_meanwhile_issue_should_work() {
orml_tokens::Error::<Test>::BalanceTooLow
);
let token_value = VtokenMinting::token_to_vtoken(KSM, VKSM, 100);
assert_eq!(token_value, 100);
assert_eq!(token_value, Ok(100));
assert_eq!(Tokens::free_balance(KSM, &ALICE), 95000);
assert_ok!(Tokens::set_balance(RuntimeOrigin::root(), buyback_account, KSM, 100, 0));

Expand Down
4 changes: 2 additions & 2 deletions pallets/slp/src/agents/phala_agent/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -886,9 +886,9 @@ impl<T: Config> PhalaAgent<T> {
let shares: u128 = U256::from((*total_shares).saturated_into::<u128>())
.saturating_mul(amount.saturated_into::<u128>().into())
.checked_div((*total_value).saturated_into::<u128>().into())
.map(|x| u128::try_from(x))
.ok_or(Error::<T>::OverFlow)?
.as_u128()
.saturated_into();
.map_err(|_| Error::<T>::OverFlow)?;

Ok(BalanceOf::<T>::unique_saturated_from(shares))
}
Expand Down
6 changes: 2 additions & 4 deletions pallets/stable-pool/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -785,9 +785,8 @@ impl<T: Config> Pallet<T> {
currency_id_out: PoolTokenIndex,
amount: T::Balance,
) -> Result<T::Balance, DispatchError> {
let mut pool_info =
let pool_info =
T::StableAsset::pool(pool_id).ok_or(bifrost_stable_asset::Error::<T>::PoolNotFound)?;
T::StableAsset::collect_yield(pool_id, &mut pool_info)?;
let dx = Self::upscale(
amount,
pool_id,
Expand Down Expand Up @@ -854,7 +853,7 @@ impl<T: Config> Pallet<T> {
pool_id: StableAssetPoolId,
mut amounts: Vec<T::Balance>,
) -> Result<T::Balance, DispatchError> {
let mut pool_info =
let pool_info =
T::StableAsset::pool(pool_id).ok_or(bifrost_stable_asset::Error::<T>::PoolNotFound)?;
for (i, amount) in amounts.iter_mut().enumerate() {
*amount = Self::upscale(
Expand All @@ -866,7 +865,6 @@ impl<T: Config> Pallet<T> {
.ok_or(bifrost_stable_asset::Error::<T>::ArgumentsMismatch)?,
)?;
}
T::StableAsset::collect_yield(pool_id, &mut pool_info)?;
let MintResult { mint_amount, .. } =
bifrost_stable_asset::Pallet::<T>::get_mint_amount(&pool_info, &amounts)?;

Expand Down
29 changes: 22 additions & 7 deletions pallets/stable-pool/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,8 @@ fn swap_successful() {
#[test]
fn get_swap_output_amount() {
ExtBuilder::default().new_test_ext().build().execute_with(|| {
env_logger::try_init().unwrap_or(());
System::set_block_number(2);
assert_ok!(VtokenMinting::set_minimum_mint(RuntimeOrigin::signed(1), DOT, 0));
assert_ok!(VtokenMinting::mint(Some(3).into(), DOT, 100_000_000, BoundedVec::default()));

Expand All @@ -263,7 +265,24 @@ fn get_swap_output_amount() {
));
let amounts = vec![10000000u128, 20000000u128];
assert_ok!(StablePool::mint_inner(&3, 0, amounts, 0));
assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 0));
assert_eq!(StablePool::get_swap_output(0, 0, 1, 5000000u128).ok(), Some(4999301));
assert_noop!(
StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 4999302),
Error::<Test>::SwapUnderMin
);
assert_ok!(StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 4999301));
assert_ok!(StablePool::edit_token_rate(
RuntimeOrigin::root(),
0,
vec![(DOT, (1, 1)), (VDOT, (90_000_000, 100_000_000))]
));
assert_eq!(StablePool::get_swap_output(0, 0, 1, 5000000u128).ok(), Some(4485945));
assert_ok!(StablePool::edit_token_rate(
RuntimeOrigin::root(),
0,
vec![(coin0, (1, 1)), (coin1, (1, 1))]
));
assert_eq!(StablePool::get_swap_output(0, 0, 1, 5000000u128).ok(), Some(4980724));
assert_noop!(
StablePool::on_swap(&3u128, 0, 1, 1, 5000000u128, 0),
bifrost_stable_asset::Error::<Test>::ArgumentsError
Expand All @@ -284,10 +303,6 @@ fn get_swap_output_amount() {
StablePool::on_swap(&3u128, 0, 0, 1, 0u128, 0),
bifrost_stable_asset::Error::<Test>::ArgumentsError
);
assert_noop!(
StablePool::on_swap(&3u128, 0, 0, 1, 5000000u128, 50000000000000000u128),
Error::<Test>::SwapUnderMin
);
assert_noop!(
StablePool::on_swap(&3u128, 0, 0, 1, 500000000u128, 0u128),
orml_tokens::Error::<Test>::BalanceTooLow
Expand All @@ -304,9 +319,9 @@ fn get_swap_output_amount() {
redeem_fee: 50000000u128,
total_supply: 300006989999594867u128,
a: 10000u128,
a_block: 0,
a_block: 2,
future_a: 10000u128,
future_a_block: 0,
future_a_block: 2,
balances: vec![150000000000000000u128, 150006990000000000u128],
fee_recipient: 2,
account_id: swap_id,
Expand Down
3 changes: 2 additions & 1 deletion pallets/system-maker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,8 +249,9 @@ pub mod pallet {
let amount_out_min: u128 = U256::from(info.granularity.saturated_into::<u128>())
.saturating_mul(U256::from(1_000_000u32))
.checked_div(denominator)
.map(|x| u128::try_from(x))
.ok_or(ArithmeticError::Overflow)?
.as_u128();
.map_err(|_| ArithmeticError::Overflow)?;

T::DexOperator::inner_swap_exact_assets_for_assets(
system_maker,
Expand Down
3 changes: 3 additions & 0 deletions pallets/system-staking/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@ benchmarks! {
Some(vec![1 as PoolId]),
Some(vec![Perbill::from_percent(100)]),
));
let caller: T::AccountId = whitelisted_caller();
assert_ok!(T::MultiCurrency::deposit(KSM, &caller, BalanceOf::<T>::unique_saturated_from(1000u128)));
assert_ok!(T::VtokenMintingInterface::mint(caller, KSM, BalanceOf::<T>::unique_saturated_from(1000u128), BoundedVec::default(),));
}: _(RawOrigin::Root,KSM)

on_redeem_success {
Expand Down
6 changes: 3 additions & 3 deletions pallets/system-staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -455,12 +455,12 @@ pub mod pallet {
// Calculate the revenue generated by vtoken
let vfree_amount = T::MultiCurrency::free_balance(vtoken_id, &pallet_account);
let free_amount =
T::VtokenMintingInterface::vtoken_to_token(token, vtoken_id, vfree_amount);
T::VtokenMintingInterface::vtoken_to_token(token, vtoken_id, vfree_amount)?;
let token_amount = free_amount.saturating_sub(token_info.system_shadow_amount);

// Calculate the number of benefits converted to vtoken
let vtoken_amount =
T::VtokenMintingInterface::token_to_vtoken(token, vtoken_id, token_amount);
T::VtokenMintingInterface::token_to_vtoken(token, vtoken_id, token_amount)?;

// Transfer vtoken(benefits) to TreasuryAccount
T::MultiCurrency::transfer(
Expand Down Expand Up @@ -581,7 +581,7 @@ impl<T: Config> Pallet<T> {
// Calculate how many ksm can be received by vksm through VtokenMintingInterface
// ===> vredeem_amount(vksm amount)
let vredeem_amount =
T::VtokenMintingInterface::token_to_vtoken(token_id, vtoken_id, redeem_amount);
T::VtokenMintingInterface::token_to_vtoken(token_id, vtoken_id, redeem_amount)?;
if vredeem_amount != BalanceOf::<T>::zero() {
// redeem vksm ===> vTokenMinting redeem_inner on_redeemed , update
// pending_redeem_amount += token_amount
Expand Down
22 changes: 12 additions & 10 deletions pallets/ve-minting/src/incentive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,23 +45,24 @@ impl<T: Config> Pallet<T> {
pub fn reward_per_token() -> Result<BTreeMap<CurrencyIdOf<T>, BalanceOf<T>>, DispatchError> {
let mut conf = Self::incentive_configs();
let current_block_number: BlockNumberFor<T> = frame_system::Pallet::<T>::block_number();
let _total_supply = Self::total_supply(current_block_number)?;
if _total_supply == BalanceOf::<T>::zero() {
let total_supply = Self::total_supply(current_block_number)?;
if total_supply == BalanceOf::<T>::zero() {
return Ok(conf.reward_per_token_stored);
}
conf.reward_rate.iter().try_for_each(|(currency, &reward)| -> DispatchResult {
let increment: BalanceOf<T> = U256::from(
let increment: BalanceOf<T> = U512::from(
Self::last_time_reward_applicable()
.saturating_sub(conf.last_update_time)
.saturated_into::<u128>(),
)
.checked_mul(U256::from(reward.saturated_into::<u128>()))
.checked_mul(U512::from(reward.saturated_into::<u128>()))
.ok_or(ArithmeticError::Overflow)?
.checked_mul(U256::from(T::Multiplier::get().saturated_into::<u128>()))
.checked_mul(U512::from(T::Multiplier::get().saturated_into::<u128>()))
.ok_or(ArithmeticError::Overflow)?
.checked_div(U256::from(_total_supply.saturated_into::<u128>()))
.unwrap_or_default()
.as_u128()
.checked_div(U512::from(total_supply.saturated_into::<u128>()))
.map(|x| u128::try_from(x))
.ok_or(ArithmeticError::Overflow)?
.map_err(|_| ArithmeticError::Overflow)?
.unique_saturated_into();
conf.reward_per_token_stored
.entry(*currency)
Expand Down Expand Up @@ -97,8 +98,9 @@ impl<T: Config> Pallet<T> {
))
.ok_or(ArithmeticError::Overflow)?
.checked_div(U256::from(T::Multiplier::get().saturated_into::<u128>()))
.unwrap_or_default()
.as_u128()
.map(|x| u128::try_from(x))
.ok_or(ArithmeticError::Overflow)?
.map_err(|_| ArithmeticError::Overflow)?
.unique_saturated_into();
rewards
.entry(*currency)
Expand Down
12 changes: 7 additions & 5 deletions pallets/ve-minting/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ use frame_system::pallet_prelude::*;
pub use incentive::*;
use orml_traits::{MultiCurrency, MultiLockableCurrency};
pub use pallet::*;
use sp_core::U256;
use sp_core::{U256, U512};
use sp_std::{borrow::ToOwned, collections::btree_map::BTreeMap, vec, vec::Vec};
pub use traits::VeMintingInterface;
pub use weights::WeightInfo;
Expand Down Expand Up @@ -354,8 +354,9 @@ pub mod pallet {
if old_locked.end > current_block_number && old_locked.amount > BalanceOf::<T>::zero() {
u_old.slope = U256::from(old_locked.amount.saturated_into::<u128>())
.checked_div(U256::from(T::MaxBlock::get().saturated_into::<u128>()))
.unwrap_or_default()
.as_u128()
.map(|x| u128::try_from(x))
.ok_or(ArithmeticError::Overflow)?
.map_err(|_| ArithmeticError::Overflow)?
.unique_saturated_into();
u_old.bias = u_old
.slope
Expand All @@ -368,8 +369,9 @@ pub mod pallet {
if new_locked.end > current_block_number && new_locked.amount > BalanceOf::<T>::zero() {
u_new.slope = U256::from(new_locked.amount.saturated_into::<u128>())
.checked_div(U256::from(T::MaxBlock::get().saturated_into::<u128>()))
.unwrap_or_default()
.as_u128()
.map(|x| u128::try_from(x))
.ok_or(ArithmeticError::Overflow)?
.map_err(|_| ArithmeticError::Overflow)?
.unique_saturated_into();
u_new.bias = u_new
.slope
Expand Down
Loading

0 comments on commit 19fb365

Please sign in to comment.