From bee5207671f895f4464886a29b4a2c42b4c1fae8 Mon Sep 17 00:00:00 2001 From: zjb0807 Date: Tue, 27 Feb 2024 16:49:54 +0800 Subject: [PATCH] use parameter_types instead of thread_local --- .github/workflows/coverage.yml | 1 - modules/auction-manager/src/mock.rs | 17 +++-- modules/cdp-engine/src/mock.rs | 85 ++++++++++++------------ modules/cdp-treasury/src/mock.rs | 15 ++--- modules/dex-oracle/src/mock.rs | 15 ++--- modules/dex/src/mock.rs | 7 +- modules/homa-validator-list/src/mock.rs | 21 +++--- modules/honzon/src/mock.rs | 10 +-- modules/incentives/src/mock.rs | 9 ++- modules/liquid-crowdloan/src/mock.rs | 15 ++--- modules/loans/src/mock.rs | 11 ++- modules/prices/src/mock.rs | 9 ++- modules/transaction-payment/src/mock.rs | 37 +++++------ modules/transaction-payment/src/tests.rs | 32 ++++----- 14 files changed, 128 insertions(+), 156 deletions(-) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 97d9085c9..893387c3d 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -20,7 +20,6 @@ concurrency: env: TARPAULIN_VERSION: 0.27.3 CARGO_INCREMENTAL: 0 - RUST_TEST_THREADS: 1 jobs: test: name: Coverage Report diff --git a/modules/auction-manager/src/mock.rs b/modules/auction-manager/src/mock.rs index 597b5cec1..5c0fc2d1b 100644 --- a/modules/auction-manager/src/mock.rs +++ b/modules/auction-manager/src/mock.rs @@ -36,7 +36,6 @@ use sp_runtime::{ traits::{AccountIdConversion, IdentityLookup, One as OneT}, BuildStorage, }; -use sp_std::cell::RefCell; pub type AccountId = u128; pub type BlockNumber = u64; @@ -119,19 +118,19 @@ impl module_cdp_treasury::Config for Runtime { type StableAsset = MockStableAsset; } -thread_local! { - static RELATIVE_PRICE: RefCell> = RefCell::new(Some(Price::one())); +parameter_types! { + static RelativePrice: Option = Some(Price::one()); } pub struct MockPriceSource; impl MockPriceSource { pub fn set_relative_price(price: Option) { - RELATIVE_PRICE.with(|v| *v.borrow_mut() = price); + RelativePrice::mutate(|v| *v = price); } } impl PriceProvider for MockPriceSource { fn get_relative_price(_base: CurrencyId, _quote: CurrencyId) -> Option { - RELATIVE_PRICE.with(|v| *v.borrow_mut()) + RelativePrice::get() } fn get_price(_currency_id: CurrencyId) -> Option { @@ -163,18 +162,18 @@ impl module_dex::Config for Runtime { type OnLiquidityPoolUpdated = (); } -thread_local! { - static IS_SHUTDOWN: RefCell = RefCell::new(false); +parameter_types! { + static IsShutdown: bool = false; } pub fn mock_shutdown() { - IS_SHUTDOWN.with(|v| *v.borrow_mut() = true) + IsShutdown::mutate(|v| *v = true) } pub struct MockEmergencyShutdown; impl EmergencyShutdown for MockEmergencyShutdown { fn is_shutdown() -> bool { - IS_SHUTDOWN.with(|v| *v.borrow_mut()) + IsShutdown::get() } } diff --git a/modules/cdp-engine/src/mock.rs b/modules/cdp-engine/src/mock.rs index cc8ed7906..9d1af9672 100644 --- a/modules/cdp-engine/src/mock.rs +++ b/modules/cdp-engine/src/mock.rs @@ -36,7 +36,7 @@ use sp_runtime::{ traits::{AccountIdConversion, IdentityLookup, One as OneT}, BuildStorage, }; -use sp_std::{cell::RefCell, str::FromStr}; +use sp_std::str::FromStr; pub type AccountId = AccountId32; pub type BlockNumber = u64; @@ -127,21 +127,21 @@ impl module_loans::Config for Runtime { type OnUpdateLoan = (); } -thread_local! { - static BTC_PRICE: RefCell> = RefCell::new(Some(Price::one())); - static DOT_PRICE: RefCell> = RefCell::new(Some(Price::one())); - static LP_AUSD_DOT_PRICE: RefCell> = RefCell::new(Some(Price::one())); - static LP_DOT_BTC_PRICE: RefCell> = RefCell::new(Some(Price::one())); +parameter_types! { + static BtcPrice: Option = Some(Price::one()); + static DotPrice: Option = Some(Price::one()); + static LpAusdDotPrice: Option = Some(Price::one()); + static LpDotBtcPrice: Option = Some(Price::one()); } pub struct MockPriceSource; impl MockPriceSource { pub fn set_price(currency_id: CurrencyId, price: Option) { match currency_id { - BTC => BTC_PRICE.with(|v| *v.borrow_mut() = price), - DOT => DOT_PRICE.with(|v| *v.borrow_mut() = price), - LP_AUSD_DOT => LP_AUSD_DOT_PRICE.with(|v| *v.borrow_mut() = price), - LP_DOT_BTC => LP_DOT_BTC_PRICE.with(|v| *v.borrow_mut() = price), + BTC => BtcPrice::mutate(|v| *v = price), + DOT => DotPrice::mutate(|v| *v = price), + LP_AUSD_DOT => LpAusdDotPrice::mutate(|v| *v = price), + LP_DOT_BTC => LpDotBtcPrice::mutate(|v| *v = price), _ => {} } } @@ -149,27 +149,24 @@ impl MockPriceSource { impl PriceProvider for MockPriceSource { fn get_price(currency_id: CurrencyId) -> Option { match currency_id { - BTC => BTC_PRICE.with(|v| *v.borrow()), - DOT => DOT_PRICE.with(|v| *v.borrow()), + BTC => BtcPrice::get(), + DOT => DotPrice::get(), AUSD => Some(Price::one()), - LP_AUSD_DOT => LP_AUSD_DOT_PRICE.with(|v| *v.borrow()), - LP_DOT_BTC => LP_DOT_BTC_PRICE.with(|v| *v.borrow()), + LP_AUSD_DOT => LpAusdDotPrice::get(), + LP_DOT_BTC => LpDotBtcPrice::get(), _ => None, } } } -thread_local! { - pub static AUCTION: RefCell> = RefCell::new(None); +parameter_types! { + pub static Auction: Option<(AccountId, CurrencyId, Balance, Balance)> = None; } pub struct MockAuctionManager; impl MockAuctionManager { pub fn auction() -> Option<(AccountId, CurrencyId, Balance, Balance)> { - AUCTION.with(|v| { - let cloned = v.borrow().clone(); - cloned - }) + Auction::get() } } impl AuctionManager for MockAuctionManager { @@ -183,12 +180,12 @@ impl AuctionManager for MockAuctionManager { amount: Self::Balance, target: Self::Balance, ) -> DispatchResult { - AUCTION.with(|v| *v.borrow_mut() = Some((refund_recipient.clone(), currency_id, amount, target))); + Auction::mutate(|v| *v = Some((refund_recipient.clone(), currency_id, amount, target))); Ok(()) } fn cancel_auction(_id: Self::AuctionId) -> DispatchResult { - AUCTION.with(|v| *v.borrow_mut() = None); + Auction::mutate(|v| *v = None); Ok(()) } @@ -308,12 +305,12 @@ impl module_evm_bridge::Config for Runtime { type EVM = EVM; } -thread_local! { - static IS_SHUTDOWN: RefCell = RefCell::new(false); +parameter_types! { + static IsShutdown: bool = false; } pub fn mock_shutdown() { - IS_SHUTDOWN.with(|v| *v.borrow_mut() = true) + IsShutdown::mutate(|v| *v = true) } pub fn liquidation_contract_addr() -> EvmAddress { @@ -323,38 +320,38 @@ pub fn liquidation_contract_addr() -> EvmAddress { pub struct MockEmergencyShutdown; impl EmergencyShutdown for MockEmergencyShutdown { fn is_shutdown() -> bool { - IS_SHUTDOWN.with(|v| *v.borrow_mut()) + IsShutdown::get() } } -thread_local! { - static LIQUIDATED: RefCell<(EvmAddress, EvmAddress, Balance, Balance)> = RefCell::new((EvmAddress::default(), EvmAddress::default(), 0, 0)); - static TRANSFERRED: RefCell<(EvmAddress, Balance)> = RefCell::new((EvmAddress::default(), 0)); - static REFUNDED: RefCell<(EvmAddress, Balance)> = RefCell::new((EvmAddress::default(), 0)); - static LIQUIDATION_RESULT: RefCell = RefCell::new(Err(Error::::LiquidationFailed.into())); - static REPAYMENT: RefCell> = RefCell::new(None); +parameter_types! { + static LIQUIDATED: (EvmAddress, EvmAddress, Balance, Balance) = (EvmAddress::default(), EvmAddress::default(), 0, 0); + static TRANSFERRED: (EvmAddress, Balance) = (EvmAddress::default(), 0); + static REFUNDED: (EvmAddress, Balance) = (EvmAddress::default(), 0); + static LiquidationResult: DispatchResult = Err(Error::::LiquidationFailed.into()); + static REPAYMENT: Option = None; } pub struct MockLiquidationEvmBridge; impl MockLiquidationEvmBridge { pub fn liquidated() -> (EvmAddress, EvmAddress, Balance, Balance) { - LIQUIDATED.with(|v| v.borrow().clone()) + LIQUIDATED::get() } pub fn transferred() -> (EvmAddress, Balance) { - TRANSFERRED.with(|v| v.borrow().clone()) + TRANSFERRED::get() } pub fn refunded() -> (EvmAddress, Balance) { - REFUNDED.with(|v| v.borrow().clone()) + REFUNDED::get() } pub fn reset() { - LIQUIDATION_RESULT.with(|v| *v.borrow_mut() = Err(Error::::LiquidationFailed.into())); - REPAYMENT.with(|v| *v.borrow_mut() = None); + LiquidationResult::mutate(|v| *v = Err(Error::::LiquidationFailed.into())); + REPAYMENT::mutate(|v| *v = None); } pub fn set_liquidation_result(r: DispatchResult) { - LIQUIDATION_RESULT.with(|v| *v.borrow_mut() = r); + LiquidationResult::mutate(|v| *v = r); } pub fn set_repayment(repayment: Balance) { - REPAYMENT.with(|v| *v.borrow_mut() = Some(repayment)); + REPAYMENT::mutate(|v| *v = Some(repayment)); } } impl LiquidationEvmBridge for MockLiquidationEvmBridge { @@ -365,23 +362,23 @@ impl LiquidationEvmBridge for MockLiquidationEvmBridge { amount: Balance, min_repayment: Balance, ) -> DispatchResult { - let result = LIQUIDATION_RESULT.with(|v| v.borrow().clone()); + let result = LiquidationResult::get(); if result.is_ok() { - let repayment = if let Some(r) = REPAYMENT.with(|v| v.borrow().clone()) { + let repayment = if let Some(r) = REPAYMENT::get() { r } else { min_repayment }; let _ = Currencies::deposit(GetStableCurrencyId::get(), &CDPEngineModule::account_id(), repayment); } - LIQUIDATED.with(|v| *v.borrow_mut() = (collateral, repay_dest, amount, min_repayment)); + LIQUIDATED::mutate(|v| *v = (collateral, repay_dest, amount, min_repayment)); result } fn on_collateral_transfer(_context: InvokeContext, collateral: EvmAddress, amount: Balance) { - TRANSFERRED.with(|v| *v.borrow_mut() = (collateral, amount)); + TRANSFERRED::mutate(|v| *v = (collateral, amount)); } fn on_repayment_refund(_context: InvokeContext, collateral: EvmAddress, repayment: Balance) { - REFUNDED.with(|v| *v.borrow_mut() = (collateral, repayment)); + REFUNDED::mutate(|v| *v = (collateral, repayment)); } } diff --git a/modules/cdp-treasury/src/mock.rs b/modules/cdp-treasury/src/mock.rs index a32c43f93..0ca479970 100644 --- a/modules/cdp-treasury/src/mock.rs +++ b/modules/cdp-treasury/src/mock.rs @@ -34,7 +34,6 @@ use nutsfinance_stable_asset::{ use orml_traits::parameter_type_with_key; use primitives::{DexShare, TokenSymbol, TradingPair}; use sp_runtime::{traits::IdentityLookup, BuildStorage}; -use sp_std::cell::RefCell; pub type AccountId = u128; pub type BlockNumber = u64; @@ -138,9 +137,9 @@ impl module_dex::Config for Runtime { type OnLiquidityPoolUpdated = (); } -thread_local! { - pub static TOTAL_COLLATERAL_AUCTION: RefCell = RefCell::new(0); - pub static TOTAL_COLLATERAL_IN_AUCTION: RefCell = RefCell::new(0); +parameter_types! { + pub static TotalCollateralAuction: u32 = 0; + pub static TotalCollateralInAuction: Balance = 0; } pub struct MockAuctionManager; @@ -155,8 +154,8 @@ impl AuctionManager for MockAuctionManager { amount: Self::Balance, _target: Self::Balance, ) -> DispatchResult { - TOTAL_COLLATERAL_AUCTION.with(|v| *v.borrow_mut() += 1); - TOTAL_COLLATERAL_IN_AUCTION.with(|v| *v.borrow_mut() += amount); + TotalCollateralAuction::mutate(|v| *v += 1); + TotalCollateralInAuction::mutate(|v| *v += amount); Ok(()) } @@ -185,10 +184,6 @@ parameter_types! { ]; } -thread_local! { - static IS_SHUTDOWN: RefCell = RefCell::new(false); -} - impl Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Currencies; diff --git a/modules/dex-oracle/src/mock.rs b/modules/dex-oracle/src/mock.rs index b4dbea012..6463d9766 100644 --- a/modules/dex-oracle/src/mock.rs +++ b/modules/dex-oracle/src/mock.rs @@ -30,7 +30,6 @@ use sp_runtime::{ traits::{IdentityLookup, Zero}, BuildStorage, DispatchError, }; -use sp_std::cell::RefCell; pub type AccountId = u128; @@ -64,16 +63,16 @@ impl pallet_timestamp::Config for Runtime { type WeightInfo = (); } -thread_local! { - static AUSD_DOT_POOL: RefCell<(Balance, Balance)> = RefCell::new((Zero::zero(), Zero::zero())); - static ACA_DOT_POOL: RefCell<(Balance, Balance)> = RefCell::new((Zero::zero(), Zero::zero())); +parameter_types! { + static AusdDotPool: (Balance, Balance) = (Zero::zero(), Zero::zero()); + static AcaDotPool: (Balance, Balance) = (Zero::zero(), Zero::zero()); } pub fn set_pool(trading_pair: &TradingPair, pool_0: Balance, pool_1: Balance) { if *trading_pair == AUSDDOTPair::get() { - AUSD_DOT_POOL.with(|v| *v.borrow_mut() = (pool_0, pool_1)); + AusdDotPool::mutate(|v| *v = (pool_0, pool_1)); } else if *trading_pair == ACADOTPair::get() { - ACA_DOT_POOL.with(|v| *v.borrow_mut() = (pool_0, pool_1)); + AcaDotPool::mutate(|v| *v = (pool_0, pool_1)); } } @@ -83,9 +82,9 @@ impl DEXManager for MockDEX { TradingPair::from_currency_ids(currency_id_0, currency_id_1) .map(|trading_pair| { if trading_pair == AUSDDOTPair::get() { - AUSD_DOT_POOL.with(|v| *v.borrow()) + AusdDotPool::get() } else if trading_pair == ACADOTPair::get() { - ACA_DOT_POOL.with(|v| *v.borrow()) + AcaDotPool::get() } else { (0, 0) } diff --git a/modules/dex/src/mock.rs b/modules/dex/src/mock.rs index 5baca06d1..2e686063e 100644 --- a/modules/dex/src/mock.rs +++ b/modules/dex/src/mock.rs @@ -30,7 +30,6 @@ use module_support::{mocks::MockErc20InfoMapping, SpecificJointsSwap}; use orml_traits::{parameter_type_with_key, MultiReservableCurrency}; use primitives::{Amount, TokenSymbol}; use sp_runtime::{traits::IdentityLookup, BuildStorage}; -use sp_std::cell::RefCell; pub type BlockNumber = u64; pub type AccountId = u128; @@ -105,8 +104,8 @@ parameter_types! { ]; } -thread_local! { - pub static AUSD_DOT_POOL_RECORD: RefCell<(Balance, Balance)> = RefCell::new((0, 0)); +parameter_types! { + pub static AusdDotPoolRecord: (Balance, Balance) = (0, 0); } pub struct MockOnLiquidityPoolUpdated; @@ -114,7 +113,7 @@ impl Happened<(TradingPair, Balance, Balance)> for MockOnLiquidityPoolUpdated { fn happened(info: &(TradingPair, Balance, Balance)) { let (trading_pair, new_pool_0, new_pool_1) = info; if *trading_pair == AUSDDOTPair::get() { - AUSD_DOT_POOL_RECORD.with(|v| *v.borrow_mut() = (*new_pool_0, *new_pool_1)); + AusdDotPoolRecord::mutate(|v| *v = (*new_pool_0, *new_pool_1)); } } } diff --git a/modules/homa-validator-list/src/mock.rs b/modules/homa-validator-list/src/mock.rs index 65792b063..802d506ba 100644 --- a/modules/homa-validator-list/src/mock.rs +++ b/modules/homa-validator-list/src/mock.rs @@ -30,7 +30,6 @@ use module_support::ExchangeRate; use orml_traits::parameter_type_with_key; use primitives::{Amount, Balance, CurrencyId, TokenSymbol}; use sp_runtime::{traits::IdentityLookup, BuildStorage}; -use sp_std::cell::RefCell; use std::collections::HashMap; pub type AccountId = u128; @@ -108,15 +107,15 @@ impl orml_currencies::Config for Runtime { type WeightInfo = (); } -thread_local! { - pub static SHARES: RefCell> = RefCell::new(HashMap::new()); - pub static ACCUMULATED_SLASH: RefCell = RefCell::new(0); +parameter_types! { + pub static Shares: HashMap<(AccountId, AccountId), Balance> = HashMap::new(); + pub static AccumulatedSlash: Balance = 0; } pub struct MockOnSlash; impl Happened for MockOnSlash { fn happened(amount: &Balance) { - ACCUMULATED_SLASH.with(|v| *v.borrow_mut() += amount); + AccumulatedSlash::mutate(|v| *v += amount); } } @@ -124,15 +123,15 @@ pub struct MockOnIncreaseGuarantee; impl Happened<(AccountId, AccountId, Balance)> for MockOnIncreaseGuarantee { fn happened(info: &(AccountId, AccountId, Balance)) { let (account_id, relaychain_id, amount) = info; - SHARES.with(|v| { - let mut old_map = v.borrow().clone(); + Shares::mutate(|v| { + let mut old_map = v.clone(); if let Some(share) = old_map.get_mut(&(*account_id, *relaychain_id)) { *share = share.saturating_add(*amount); } else { old_map.insert((*account_id, *relaychain_id), *amount); }; - *v.borrow_mut() = old_map; + *v = old_map; }); } } @@ -141,15 +140,15 @@ pub struct MockOnDecreaseGuarantee; impl Happened<(AccountId, AccountId, Balance)> for MockOnDecreaseGuarantee { fn happened(info: &(AccountId, AccountId, Balance)) { let (account_id, relaychain_id, amount) = info; - SHARES.with(|v| { - let mut old_map = v.borrow().clone(); + Shares::mutate(|v| { + let mut old_map = v.clone(); if let Some(share) = old_map.get_mut(&(*account_id, *relaychain_id)) { *share = share.saturating_sub(*amount); } else { old_map.insert((*account_id, *relaychain_id), Default::default()); }; - *v.borrow_mut() = old_map; + *v = old_map; }); } } diff --git a/modules/honzon/src/mock.rs b/modules/honzon/src/mock.rs index 51d509166..dc5c1595d 100644 --- a/modules/honzon/src/mock.rs +++ b/modules/honzon/src/mock.rs @@ -43,7 +43,7 @@ use sp_runtime::{ traits::{AccountIdConversion, IdentityLookup, One as OneT}, BuildStorage, FixedPointNumber, }; -use sp_std::{cell::RefCell, str::FromStr}; +use sp_std::str::FromStr; mod honzon { pub use super::super::*; @@ -170,18 +170,18 @@ impl AuctionManager for MockAuctionManager { } } -thread_local! { - static IS_SHUTDOWN: RefCell = RefCell::new(false); +parameter_types! { + static IsShutdown: bool = false; } pub fn mock_shutdown() { - IS_SHUTDOWN.with(|v| *v.borrow_mut() = true) + IsShutdown::mutate(|v| *v = true) } pub struct MockEmergencyShutdown; impl EmergencyShutdown for MockEmergencyShutdown { fn is_shutdown() -> bool { - IS_SHUTDOWN.with(|v| *v.borrow_mut()) + IsShutdown::get() } } diff --git a/modules/incentives/src/mock.rs b/modules/incentives/src/mock.rs index 252493508..2c9243cf2 100644 --- a/modules/incentives/src/mock.rs +++ b/modules/incentives/src/mock.rs @@ -30,7 +30,6 @@ pub use module_support::{Price, Ratio, SwapLimit}; use orml_traits::parameter_type_with_key; use primitives::{DexShare, TokenSymbol}; use sp_runtime::{traits::IdentityLookup, AccountId32, BuildStorage}; -use sp_std::cell::RefCell; pub type AccountId = AccountId32; @@ -88,18 +87,18 @@ impl orml_tokens::Config for Runtime { type DustRemovalWhitelist = Nothing; } -thread_local! { - static IS_SHUTDOWN: RefCell = RefCell::new(false); +parameter_types! { + static IsShutdown: bool = false; } pub fn mock_shutdown() { - IS_SHUTDOWN.with(|v| *v.borrow_mut() = true) + IsShutdown::mutate(|v| *v = true) } pub struct MockEmergencyShutdown; impl EmergencyShutdown for MockEmergencyShutdown { fn is_shutdown() -> bool { - IS_SHUTDOWN.with(|v| *v.borrow_mut()) + IsShutdown::get() } } diff --git a/modules/liquid-crowdloan/src/mock.rs b/modules/liquid-crowdloan/src/mock.rs index 827b073be..f984e0e08 100644 --- a/modules/liquid-crowdloan/src/mock.rs +++ b/modules/liquid-crowdloan/src/mock.rs @@ -33,7 +33,6 @@ use orml_traits::parameter_type_with_key; use primitives::{Amount, TokenSymbol}; use sp_core::H160; use sp_runtime::{traits::IdentityLookup, AccountId32, BuildStorage}; -use std::cell::RefCell; pub type AccountId = AccountId32; pub type BlockNumber = u64; @@ -118,9 +117,9 @@ impl module_currencies::Config for Runtime { type OnDust = (); } -thread_local! { - pub static TRANSFER_RECORD: RefCell> = RefCell::new(None); - pub static TRANSFER_OK: RefCell = RefCell::new(true); +parameter_types! { + pub static TransferRecord: Option<(AccountId, AccountId, Balance)> = None; + pub static TransferOk: bool = true; } pub struct MockXcmTransfer; @@ -130,8 +129,8 @@ impl CrowdloanVaultXcm for MockXcmTransfer { recipient: AccountId, amount: Balance, ) -> DispatchResult { - if TRANSFER_OK.with(|v| *v.borrow()) { - TRANSFER_RECORD.with(|v| *v.borrow_mut() = Some((vault, recipient, amount))); + if TransferOk::get() { + TransferRecord::mutate(|v| *v = Some((vault, recipient, amount))); Ok(()) } else { Err(DispatchError::Other("transfer failed")) @@ -193,8 +192,8 @@ impl ExtBuilder { } pub fn build(self) -> sp_io::TestExternalities { - TRANSFER_RECORD.with(|v| *v.borrow_mut() = None); - TRANSFER_OK.with(|v| *v.borrow_mut() = self.transfer_ok); + TransferRecord::mutate(|v| *v = None); + TransferOk::mutate(|v| *v = self.transfer_ok); let mut t = frame_system::GenesisConfig::::default() .build_storage() diff --git a/modules/loans/src/mock.rs b/modules/loans/src/mock.rs index 2e334ea00..4bcdc81ab 100644 --- a/modules/loans/src/mock.rs +++ b/modules/loans/src/mock.rs @@ -34,7 +34,6 @@ use sp_runtime::{ traits::{AccountIdConversion, IdentityLookup}, BuildStorage, }; -use sp_std::cell::RefCell; use std::collections::HashMap; pub type AccountId = u128; @@ -200,8 +199,8 @@ impl RiskManager for MockRiskManager { } } -thread_local! { - pub static DOT_SHARES: RefCell> = RefCell::new(HashMap::new()); +parameter_types! { + pub static DotShares: HashMap = HashMap::new(); } pub struct MockOnUpdateLoan; @@ -216,10 +215,10 @@ impl Happened<(AccountId, CurrencyId, Amount, Balance)> for MockOnUpdateLoan { }; if *currency_id == DOT { - DOT_SHARES.with(|v| { - let mut old_map = v.borrow().clone(); + DotShares::mutate(|v| { + let mut old_map = v.clone(); old_map.insert(*who, new_share_amount); - *v.borrow_mut() = old_map; + *v = old_map; }); } } diff --git a/modules/prices/src/mock.rs b/modules/prices/src/mock.rs index d54fb0ab9..0eed4a52f 100644 --- a/modules/prices/src/mock.rs +++ b/modules/prices/src/mock.rs @@ -31,7 +31,6 @@ use sp_runtime::{ traits::{IdentityLookup, One as OneT, Zero}, BuildStorage, DispatchError, FixedPointNumber, }; -use sp_std::cell::RefCell; pub type AccountId = u128; pub type BlockNumber = u64; @@ -61,18 +60,18 @@ impl frame_system::Config for Runtime { type AccountData = (); } -thread_local! { - static CHANGED: RefCell = RefCell::new(false); +parameter_types! { + static Changed: bool = false; } pub fn mock_oracle_update() { - CHANGED.with(|v| *v.borrow_mut() = true) + Changed::mutate(|v| *v = true) } pub struct MockDataProvider; impl DataProvider for MockDataProvider { fn get(currency_id: &CurrencyId) -> Option { - if CHANGED.with(|v| *v.borrow_mut()) { + if Changed::get() { match *currency_id { AUSD => None, TAI => Some(Price::saturating_from_integer(40000)), diff --git a/modules/transaction-payment/src/mock.rs b/modules/transaction-payment/src/mock.rs index 01af4cbd2..aecfcff61 100644 --- a/modules/transaction-payment/src/mock.rs +++ b/modules/transaction-payment/src/mock.rs @@ -41,7 +41,6 @@ use sp_runtime::{ traits::{AccountIdConversion, IdentityLookup, One}, BuildStorage, Perbill, }; -use sp_std::cell::RefCell; pub type AccountId = AccountId32; pub type BlockNumber = u64; @@ -145,10 +144,6 @@ impl module_currencies::Config for Runtime { type OnDust = (); } -thread_local! { - static IS_SHUTDOWN: RefCell = RefCell::new(false); -} - ord_parameter_types! { pub const Zero: AccountId = AccountId::new([0u8; 32]); } @@ -196,36 +191,36 @@ parameter_types! { pub DotFeeSwapPath: Vec = vec![DOT, AUSD, ACA]; } -thread_local! { - pub static TIP_UNBALANCED_AMOUNT: RefCell = RefCell::new(0); - pub static FEE_UNBALANCED_AMOUNT: RefCell = RefCell::new(0); +parameter_types! { + pub static TipUnbalancedAmount: u128 = 0; + pub static FeeUnbalancedAmount: u128 = 0; } pub struct DealWithFees; impl OnUnbalanced> for DealWithFees { fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { if let Some(fees) = fees_then_tips.next() { - FEE_UNBALANCED_AMOUNT.with(|a| *a.borrow_mut() += fees.peek()); + FeeUnbalancedAmount::mutate(|a| *a += fees.peek()); if let Some(tips) = fees_then_tips.next() { - TIP_UNBALANCED_AMOUNT.with(|a| *a.borrow_mut() += tips.peek()); + TipUnbalancedAmount::mutate(|a| *a += tips.peek()); } } } } -thread_local! { - static RELATIVE_PRICE: RefCell> = RefCell::new(Some(Price::one())); +parameter_types! { + static RelativePrice: Option = Some(Price::one()); } pub struct MockPriceSource; impl MockPriceSource { pub fn set_relative_price(price: Option) { - RELATIVE_PRICE.with(|v| *v.borrow_mut() = price); + RelativePrice::mutate(|v| *v = price); } } impl PriceProvider for MockPriceSource { fn get_relative_price(_base: CurrencyId, _quote: CurrencyId) -> Option { - RELATIVE_PRICE.with(|v| *v.borrow_mut()) + RelativePrice::get() } fn get_price(_currency_id: CurrencyId) -> Option { @@ -256,7 +251,7 @@ impl WeightToFeeT for TransactionByteFee { type Balance = Balance; fn weight_to_fee(weight: &Weight) -> Self::Balance { - Self::Balance::saturated_from(weight.ref_time()).saturating_mul(TRANSACTION_BYTE_FEE.with(|v| *v.borrow())) + Self::Balance::saturated_from(weight.ref_time()).saturating_mul(TransactionByteFee::get()) } } @@ -287,8 +282,8 @@ impl Config for Runtime { type DefaultFeeTokens = DefaultFeeTokens; } -thread_local! { - static WEIGHT_TO_FEE: RefCell = RefCell::new(1); +parameter_types! { + static WeightToFeeStep: u128 = 1; } pub struct WeightToFee; @@ -299,7 +294,7 @@ impl WeightToFeePolynomial for WeightToFee { smallvec![frame_support::weights::WeightToFeeCoefficient { degree: 1, coeff_frac: Perbill::zero(), - coeff_integer: WEIGHT_TO_FEE.with(|v| *v.borrow()), + coeff_integer: WeightToFeeStep::get(), negative: false, }] } @@ -363,9 +358,9 @@ impl ExtBuilder { } fn set_constants(&self) { ExtrinsicBaseWeight::mutate(|v| *v = self.base_weight); - TRANSACTION_BYTE_FEE.with(|v| *v.borrow_mut() = self.byte_fee); - WEIGHT_TO_FEE.with(|v| *v.borrow_mut() = self.weight_to_fee); - TIP_PER_WEIGHT_STEP.with(|v| *v.borrow_mut() = self.tip_per_weight_step); + TransactionByteFee::mutate(|v| *v = self.byte_fee); + WeightToFeeStep::mutate(|v| *v = self.weight_to_fee); + TipPerWeightStep::mutate(|v| *v = self.tip_per_weight_step); } pub fn build(self) -> sp_io::TestExternalities { self.set_constants(); diff --git a/modules/transaction-payment/src/tests.rs b/modules/transaction-payment/src/tests.rs index 93c27798b..2db98a6bd 100644 --- a/modules/transaction-payment/src/tests.rs +++ b/modules/transaction-payment/src/tests.rs @@ -27,9 +27,9 @@ use frame_support::{ dispatch::{DispatchClass, DispatchInfo, Pays}, }; use mock::{ - AccountId, BlockWeights, Currencies, DEXModule, ExtBuilder, FeePoolSize, MockPriceSource, Runtime, RuntimeCall, - RuntimeOrigin, System, TransactionPayment, ACA, ALICE, AUSD, BOB, CHARLIE, DAVE, DOT, FEE_UNBALANCED_AMOUNT, LDOT, - TIP_UNBALANCED_AMOUNT, + AccountId, BlockWeights, Currencies, DEXModule, ExtBuilder, FeePoolSize, FeeUnbalancedAmount, MockPriceSource, + Runtime, RuntimeCall, RuntimeOrigin, System, TipUnbalancedAmount, TransactionPayment, ACA, ALICE, AUSD, BOB, + CHARLIE, DAVE, DOT, LDOT, }; use module_support::{BuyWeightRate, DEXManager, Price, TransactionPayment as TransactionPaymentT}; use orml_traits::{MultiCurrency, MultiLockableCurrency}; @@ -310,8 +310,8 @@ fn pre_post_dispatch_and_refund_native_is_enough() { let refund = 200; // 1000 - 800 assert_eq!(Currencies::free_balance(ACA, &ALICE), 100000 - fee + refund); - assert_eq!(FEE_UNBALANCED_AMOUNT.with(|a| *a.borrow()), fee - refund); - assert_eq!(TIP_UNBALANCED_AMOUNT.with(|a| *a.borrow()), 0); + assert_eq!(FeeUnbalancedAmount::get(), fee - refund); + assert_eq!(TipUnbalancedAmount::get(), 0); System::assert_has_event(crate::mock::RuntimeEvent::TransactionPayment( crate::Event::TransactionFeePaid { @@ -323,7 +323,7 @@ fn pre_post_dispatch_and_refund_native_is_enough() { )); // reset and test refund with tip - FEE_UNBALANCED_AMOUNT.with(|a| *a.borrow_mut() = 0); + FeeUnbalancedAmount::mutate(|a| *a = 0); let tip: Balance = 5; let pre = ChargeTransactionPayment::::from(tip) @@ -340,8 +340,8 @@ fn pre_post_dispatch_and_refund_native_is_enough() { &Ok(()) )); assert_eq!(Currencies::free_balance(ACA, &CHARLIE), 100000 - fee - tip + refund); - assert_eq!(FEE_UNBALANCED_AMOUNT.with(|a| *a.borrow()), fee - refund); - assert_eq!(TIP_UNBALANCED_AMOUNT.with(|a| *a.borrow()), tip); + assert_eq!(FeeUnbalancedAmount::get(), fee - refund); + assert_eq!(TipUnbalancedAmount::get(), tip); System::assert_has_event(crate::mock::RuntimeEvent::TransactionPayment( crate::Event::TransactionFeePaid { @@ -438,11 +438,8 @@ fn pre_post_dispatch_and_refund_with_fee_currency_call(token: CurrencyId, surplu Currencies::free_balance(ACA, &ALICE), aca_init + refund + refund_surplus ); - assert_eq!( - FEE_UNBALANCED_AMOUNT.with(|a| *a.borrow()), - fee - refund + actual_surplus - ); - assert_eq!(TIP_UNBALANCED_AMOUNT.with(|a| *a.borrow()), 0); + assert_eq!(FeeUnbalancedAmount::get(), fee - refund + actual_surplus); + assert_eq!(TipUnbalancedAmount::get(), 0); System::assert_has_event(crate::mock::RuntimeEvent::TransactionPayment( crate::Event::TransactionFeePaid { @@ -454,7 +451,7 @@ fn pre_post_dispatch_and_refund_with_fee_currency_call(token: CurrencyId, surplu )); // reset and test refund with tip - FEE_UNBALANCED_AMOUNT.with(|a| *a.borrow_mut() = 0); + FeeUnbalancedAmount::mutate(|a| *a = 0); assert_ok!(Currencies::update_balance( RuntimeOrigin::root(), @@ -513,11 +510,8 @@ fn pre_post_dispatch_and_refund_with_fee_currency_call(token: CurrencyId, surplu Currencies::free_balance(ACA, &CHARLIE), aca_init + refund + refund_surplus ); - assert_eq!( - FEE_UNBALANCED_AMOUNT.with(|a| *a.borrow()), - fee - refund + surplus - refund_surplus - ); - assert_eq!(TIP_UNBALANCED_AMOUNT.with(|a| *a.borrow()), tip); + assert_eq!(FeeUnbalancedAmount::get(), fee - refund + surplus - refund_surplus); + assert_eq!(TipUnbalancedAmount::get(), tip); System::assert_has_event(crate::mock::RuntimeEvent::TransactionPayment( crate::Event::TransactionFeePaid {