-
Notifications
You must be signed in to change notification settings - Fork 653
/
Copy pathmock.rs
422 lines (372 loc) · 12.4 KB
/
mock.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// This file is part of Acala.
// Copyright (C) 2020-2022 Acala Foundation.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Mocks for the cdp engine module.
#![cfg(test)]
use super::*;
use frame_support::{
construct_runtime, ord_parameter_types, parameter_types,
traits::{ConstU128, ConstU32, ConstU64, Everything, Nothing},
PalletId,
};
use frame_system::EnsureSignedBy;
use orml_traits::parameter_type_with_key;
use primitives::{DexShare, Moment, TokenSymbol, TradingPair};
use sp_core::H256;
use sp_runtime::{
testing::{Header, TestXt},
traits::{AccountIdConversion, IdentityLookup, One as OneT},
};
use sp_std::cell::RefCell;
use support::mocks::MockStableAsset;
use support::{AuctionManager, EmergencyShutdown, SpecificJointsSwap};
pub type AccountId = u128;
pub type BlockNumber = u64;
pub type AuctionId = u32;
pub const ALICE: AccountId = 1;
pub const BOB: AccountId = 2;
pub const CAROL: AccountId = 3;
pub const ACA: CurrencyId = CurrencyId::Token(TokenSymbol::ACA);
pub const AUSD: CurrencyId = CurrencyId::Token(TokenSymbol::AUSD);
pub const BTC: CurrencyId = CurrencyId::Token(TokenSymbol::RENBTC);
pub const DOT: CurrencyId = CurrencyId::Token(TokenSymbol::DOT);
pub const LP_AUSD_DOT: CurrencyId =
CurrencyId::DexShare(DexShare::Token(TokenSymbol::AUSD), DexShare::Token(TokenSymbol::DOT));
pub const LP_DOT_BTC: CurrencyId =
CurrencyId::DexShare(DexShare::Token(TokenSymbol::RENBTC), DexShare::Token(TokenSymbol::DOT));
mod cdp_engine {
pub use super::super::*;
}
impl frame_system::Config for Runtime {
type Origin = Origin;
type Index = u64;
type BlockNumber = BlockNumber;
type Call = Call;
type Hash = H256;
type Hashing = ::sp_runtime::traits::BlakeTwo256;
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type BlockHashCount = ConstU64<250>;
type BlockWeights = ();
type BlockLength = ();
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
type DbWeight = ();
type BaseCallFilter = Everything;
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = ConstU32<16>;
}
parameter_type_with_key! {
pub ExistentialDeposits: |_currency_id: CurrencyId| -> Balance {
Default::default()
};
}
impl orml_tokens::Config for Runtime {
type Event = Event;
type Balance = Balance;
type Amount = Amount;
type CurrencyId = CurrencyId;
type WeightInfo = ();
type ExistentialDeposits = ExistentialDeposits;
type OnDust = ();
type MaxLocks = ();
type MaxReserves = ();
type ReserveIdentifier = [u8; 8];
type DustRemovalWhitelist = Nothing;
type OnNewTokenAccount = ();
type OnKilledTokenAccount = ();
}
impl pallet_balances::Config for Runtime {
type Balance = Balance;
type DustRemoval = ();
type Event = Event;
type ExistentialDeposit = ConstU128<1>;
type AccountStore = frame_system::Pallet<Runtime>;
type MaxLocks = ();
type MaxReserves = ();
type ReserveIdentifier = [u8; 8];
type WeightInfo = ();
}
pub type AdaptedBasicCurrency = orml_currencies::BasicCurrencyAdapter<Runtime, PalletBalances, Amount, BlockNumber>;
parameter_types! {
pub const GetNativeCurrencyId: CurrencyId = ACA;
}
impl orml_currencies::Config for Runtime {
type MultiCurrency = Tokens;
type NativeCurrency = AdaptedBasicCurrency;
type GetNativeCurrencyId = GetNativeCurrencyId;
type WeightInfo = ();
}
parameter_types! {
pub const LoansPalletId: PalletId = PalletId(*b"aca/loan");
}
impl loans::Config for Runtime {
type Event = Event;
type Currency = Currencies;
type RiskManager = CDPEngineModule;
type CDPTreasury = CDPTreasuryModule;
type PalletId = LoansPalletId;
type OnUpdateLoan = ();
}
thread_local! {
static BTC_PRICE: RefCell<Option<Price>> = RefCell::new(Some(Price::one()));
static DOT_PRICE: RefCell<Option<Price>> = RefCell::new(Some(Price::one()));
static LP_AUSD_DOT_PRICE: RefCell<Option<Price>> = RefCell::new(Some(Price::one()));
static LP_DOT_BTC_PRICE: RefCell<Option<Price>> = RefCell::new(Some(Price::one()));
}
pub struct MockPriceSource;
impl MockPriceSource {
pub fn set_price(currency_id: CurrencyId, price: Option<Price>) {
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),
_ => {}
}
}
}
impl PriceProvider<CurrencyId> for MockPriceSource {
fn get_price(currency_id: CurrencyId) -> Option<Price> {
match currency_id {
BTC => BTC_PRICE.with(|v| *v.borrow()),
DOT => DOT_PRICE.with(|v| *v.borrow()),
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()),
_ => None,
}
}
}
thread_local! {
pub static AUCTION: RefCell<Option<(AccountId, CurrencyId, Balance, Balance)>> = RefCell::new(None);
}
pub struct MockAuctionManager;
impl AuctionManager<AccountId> for MockAuctionManager {
type Balance = Balance;
type CurrencyId = CurrencyId;
type AuctionId = AuctionId;
fn new_collateral_auction(
refund_recipient: &AccountId,
currency_id: Self::CurrencyId,
amount: Self::Balance,
target: Self::Balance,
) -> DispatchResult {
AUCTION.with(|v| *v.borrow_mut() = Some((*refund_recipient, currency_id, amount, target)));
Ok(())
}
fn cancel_auction(_id: Self::AuctionId) -> DispatchResult {
AUCTION.with(|v| *v.borrow_mut() = None);
Ok(())
}
fn get_total_target_in_auction() -> Self::Balance {
AUCTION
.with(|v| *v.borrow())
.map(|auction| auction.3)
.unwrap_or_default()
}
fn get_total_collateral_in_auction(_id: Self::CurrencyId) -> Self::Balance {
AUCTION
.with(|v| *v.borrow())
.map(|auction| auction.2)
.unwrap_or_default()
}
}
parameter_types! {
pub const GetStableCurrencyId: CurrencyId = AUSD;
pub const CDPTreasuryPalletId: PalletId = PalletId(*b"aca/cdpt");
pub TreasuryAccount: AccountId = PalletId(*b"aca/hztr").into_account_truncating();
pub AlternativeSwapPathJointList: Vec<Vec<CurrencyId>> = vec![
vec![ACA],
];
}
impl cdp_treasury::Config for Runtime {
type Event = Event;
type Currency = Currencies;
type GetStableCurrencyId = GetStableCurrencyId;
type AuctionManagerHandler = MockAuctionManager;
type UpdateOrigin = EnsureSignedBy<One, AccountId>;
type DEX = DEXModule;
type Swap = SpecificJointsSwap<DEXModule, AlternativeSwapPathJointList>;
type MaxAuctionsCount = ConstU32<10_000>;
type PalletId = CDPTreasuryPalletId;
type TreasuryAccount = TreasuryAccount;
type WeightInfo = ();
type StableAsset = MockStableAsset<CurrencyId, Balance, AccountId, BlockNumber>;
}
parameter_types! {
pub const DEXPalletId: PalletId = PalletId(*b"aca/dexm");
pub const TreasuryPalletId: PalletId = PalletId(*b"aca/trea");
pub const GetExchangeFee: (u32, u32) = (0, 100);
pub EnabledTradingPairs: Vec<TradingPair> = vec![
TradingPair::from_currency_ids(AUSD, BTC).unwrap(),
TradingPair::from_currency_ids(AUSD, DOT).unwrap(),
TradingPair::from_currency_ids(ACA, BTC).unwrap(),
TradingPair::from_currency_ids(ACA, DOT).unwrap(),
TradingPair::from_currency_ids(ACA, AUSD).unwrap(),
];
}
impl dex::Config for Runtime {
type Event = Event;
type Currency = Currencies;
type GetExchangeFee = GetExchangeFee;
type TradingPathLimit = ConstU32<4>;
type SingleTokenTradingLimit = ConstU32<10>;
type TradingKeysUpdateFrequency = ConstU64<1>;
type PalletId = DEXPalletId;
type TreasuryPallet = TreasuryPalletId;
type Erc20InfoMapping = ();
type DEXIncentives = ();
type WeightInfo = ();
type ListingOrigin = EnsureSignedBy<One, AccountId>;
type ExtendedProvisioningBlocks = ConstU64<0>;
type OnLiquidityPoolUpdated = ();
}
impl pallet_timestamp::Config for Runtime {
type Moment = Moment;
type OnTimestampSet = ();
type MinimumPeriod = ConstU64<1_000>;
type WeightInfo = ();
}
thread_local! {
static IS_SHUTDOWN: RefCell<bool> = RefCell::new(false);
}
pub fn mock_shutdown() {
IS_SHUTDOWN.with(|v| *v.borrow_mut() = true)
}
pub struct MockEmergencyShutdown;
impl EmergencyShutdown for MockEmergencyShutdown {
fn is_shutdown() -> bool {
IS_SHUTDOWN.with(|v| *v.borrow_mut())
}
}
ord_parameter_types! {
pub const One: AccountId = 1;
}
parameter_type_with_key! {
pub MinimumCollateralAmount: |_currency_id: CurrencyId| -> Balance {
10
};
}
parameter_types! {
pub DefaultLiquidationRatio: Ratio = Ratio::saturating_from_rational(3, 2);
pub DefaultDebitExchangeRate: ExchangeRate = ExchangeRate::saturating_from_rational(1, 10);
pub DefaultLiquidationPenalty: Rate = Rate::saturating_from_rational(10, 100);
pub MaxSwapSlippageCompareToOracle: Ratio = Ratio::saturating_from_rational(50, 100);
}
impl Config for Runtime {
type Event = Event;
type PriceSource = MockPriceSource;
type DefaultLiquidationRatio = DefaultLiquidationRatio;
type DefaultDebitExchangeRate = DefaultDebitExchangeRate;
type DefaultLiquidationPenalty = DefaultLiquidationPenalty;
type MinimumDebitValue = ConstU128<2>;
type MinimumCollateralAmount = MinimumCollateralAmount;
type GetStableCurrencyId = GetStableCurrencyId;
type CDPTreasury = CDPTreasuryModule;
type UpdateOrigin = EnsureSignedBy<One, AccountId>;
type MaxSwapSlippageCompareToOracle = MaxSwapSlippageCompareToOracle;
type UnsignedPriority = ConstU64<1048576>; // 1 << 20
type EmergencyShutdown = MockEmergencyShutdown;
type UnixTime = Timestamp;
type Currency = Currencies;
type DEX = DEXModule;
type Swap = SpecificJointsSwap<DEXModule, AlternativeSwapPathJointList>;
type WeightInfo = ();
}
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Runtime>;
type Block = frame_system::mocking::MockBlock<Runtime>;
construct_runtime!(
pub enum Runtime where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Storage, Config, Event<T>},
CDPEngineModule: cdp_engine::{Pallet, Storage, Call, Event<T>, Config, ValidateUnsigned},
CDPTreasuryModule: cdp_treasury::{Pallet, Storage, Call, Config, Event<T>},
Currencies: orml_currencies::{Pallet, Call},
Tokens: orml_tokens::{Pallet, Storage, Event<T>, Config<T>},
LoansModule: loans::{Pallet, Storage, Call, Event<T>},
PalletBalances: pallet_balances::{Pallet, Call, Storage, Event<T>},
DEXModule: dex::{Pallet, Storage, Call, Event<T>, Config<T>},
Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
}
);
/// An extrinsic type used for tests.
pub type Extrinsic = TestXt<Call, ()>;
impl<LocalCall> SendTransactionTypes<LocalCall> for Runtime
where
Call: From<LocalCall>,
{
type OverarchingCall = Call;
type Extrinsic = Extrinsic;
}
pub struct ExtBuilder {
balances: Vec<(AccountId, CurrencyId, Balance)>,
}
impl Default for ExtBuilder {
fn default() -> Self {
Self {
balances: vec![
(ALICE, BTC, 1000),
(BOB, BTC, 1000),
(CAROL, BTC, 10000),
(ALICE, DOT, 1000),
(BOB, DOT, 1000),
(CAROL, DOT, 10000),
(CAROL, AUSD, 10000),
],
}
}
}
impl ExtBuilder {
pub fn build(self) -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default()
.build_storage::<Runtime>()
.unwrap();
pallet_balances::GenesisConfig::<Runtime> {
balances: vec![(CAROL, 10000)],
}
.assimilate_storage(&mut t)
.unwrap();
orml_tokens::GenesisConfig::<Runtime> {
balances: self.balances,
}
.assimilate_storage(&mut t)
.unwrap();
dex::GenesisConfig::<Runtime> {
initial_listing_trading_pairs: vec![],
initial_enabled_trading_pairs: EnabledTradingPairs::get(),
initial_added_liquidity_pools: vec![],
}
.assimilate_storage(&mut t)
.unwrap();
t.into()
}
pub fn lots_of_accounts() -> Self {
let mut balances = Vec::new();
for i in 0..1001 {
let account_id: AccountId = i;
balances.push((account_id, BTC, 1000));
}
Self { balances }
}
}