Skip to content

Commit aa6555d

Browse files
Ad96elrflechtner
andauthored
chore: mocks for bonding curve pallet (#780)
## Adding some mocks for testing + benchmarking --------- Co-authored-by: Raphael <[email protected]>
1 parent 969a25b commit aa6555d

File tree

4 files changed

+379
-7
lines changed

4 files changed

+379
-7
lines changed

pallets/pallet-bonded-coins/Cargo.toml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ scale-info = { workspace = true, features = ["derive"] }
2020
frame-benchmarking = { workspace = true }
2121
frame-support = { workspace = true }
2222
frame-system = { workspace = true }
23+
pallet-assets = { workspace = true }
2324
sp-arithmetic = { workspace = true }
2425
sp-core = { workspace = true }
2526
sp-runtime = { workspace = true }
@@ -30,7 +31,6 @@ log = { workspace = true }
3031
substrate-fixed = { workspace = true }
3132

3233
[dev-dependencies]
33-
pallet-assets = { workspace = true, features = ["std"] }
3434
pallet-balances = { workspace = true, features = ["std"] }
3535
serde = { workspace = true }
3636
sp-keystore = { workspace = true, features = ["std"] }
@@ -44,12 +44,14 @@ runtime-benchmarks = [
4444
"frame-benchmarking/runtime-benchmarks",
4545
"frame-support/runtime-benchmarks",
4646
"frame-system/runtime-benchmarks",
47+
"pallet-assets/runtime-benchmarks",
4748
"pallet-balances/runtime-benchmarks",
4849
]
4950
std = [
5051
"frame-benchmarking/std",
5152
"frame-support/std",
5253
"frame-system/std",
54+
"pallet-assets/std",
5355
"parity-scale-codec/std",
5456
"scale-info/std",
5557
"substrate-fixed/std",

pallets/pallet-bonded-coins/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ pub use pallet::*;
77

88
#[cfg(feature = "runtime-benchmarks")]
99
mod benchmarking;
10-
#[cfg(test)]
10+
#[cfg(any(test, feature = "runtime-benchmarks"))]
1111
mod mock;
1212
#[cfg(test)]
1313
mod tests;
@@ -62,7 +62,7 @@ pub mod pallet {
6262

6363
type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as sp_runtime::traits::StaticLookup>::Source;
6464

65-
type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
65+
pub(crate) type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
6666

6767
pub(crate) type DepositCurrencyBalanceOf<T> =
6868
<<T as Config>::DepositCurrency as InspectFungible<<T as frame_system::Config>::AccountId>>::Balance;

pallets/pallet-bonded-coins/src/mock.rs

Lines changed: 322 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,47 @@
1-
use substrate_fixed::types::I75F53;
1+
use frame_support::{
2+
parameter_types,
3+
traits::{ConstU128, ConstU32},
4+
weights::constants::RocksDbWeight,
5+
Hashable,
6+
};
7+
use frame_system::{EnsureRoot, EnsureSigned};
8+
use sp_runtime::{
9+
traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify},
10+
BoundedVec, BuildStorage, MultiSignature,
11+
};
12+
use substrate_fixed::{
13+
traits::{FixedSigned, FixedUnsigned},
14+
types::{I75F53, U75F53},
15+
};
16+
17+
use crate::{
18+
self as pallet_bonded_coins,
19+
curves::{
20+
polynomial::{PolynomialParameters, PolynomialParametersInput},
21+
Curve, CurveInput,
22+
},
23+
types::{Locks, PoolStatus},
24+
DepositCurrencyBalanceOf, PoolDetailsOf,
25+
};
226

327
pub type Float = I75F53;
28+
pub(crate) type FloatInput = U75F53;
29+
pub type Hash = sp_core::H256;
30+
pub type Balance = u128;
31+
pub type AssetId = u32;
32+
pub type Signature = MultiSignature;
33+
pub type AccountPublic = <Signature as Verify>::Signer;
34+
pub type AccountId = <AccountPublic as IdentifyAccount>::AccountId;
35+
36+
// accounts
37+
pub(crate) const ACCOUNT_00: AccountId = AccountId::new([0u8; 32]);
38+
pub(crate) const ACCOUNT_01: AccountId = AccountId::new([1u8; 32]);
39+
const ACCOUNT_99: AccountId = AccountId::new([99u8; 32]);
40+
// assets
41+
pub(crate) const DEFAULT_BONDED_CURRENCY_ID: AssetId = 0;
42+
pub(crate) const DEFAULT_COLLATERAL_CURRENCY_ID: AssetId = AssetId::MAX;
43+
pub(crate) const DEFAULT_COLLATERAL_DENOMINATION: u8 = 10;
44+
pub(crate) const DEFAULT_BONDED_DENOMINATION: u8 = 10;
445

546
// helper functions
647
pub fn assert_relative_eq(target: Float, expected: Float, epsilon: Float) {
@@ -11,3 +52,283 @@ pub fn assert_relative_eq(target: Float, expected: Float, epsilon: Float) {
1152
target
1253
);
1354
}
55+
56+
pub(crate) fn get_linear_bonding_curve<Float: FixedSigned>() -> Curve<Float> {
57+
let m = Float::from_num(0);
58+
let n = Float::from_num(2);
59+
let o = Float::from_num(3);
60+
Curve::Polynomial(PolynomialParameters { m, n, o })
61+
}
62+
63+
pub(crate) fn get_linear_bonding_curve_input<Float: FixedUnsigned>() -> CurveInput<Float> {
64+
let m = Float::from_num(0);
65+
let n = Float::from_num(2);
66+
let o = Float::from_num(3);
67+
CurveInput::Polynomial(PolynomialParametersInput { m, n, o })
68+
}
69+
70+
pub(crate) fn calculate_pool_id(currencies: &[AssetId]) -> AccountId {
71+
AccountId::from(currencies.to_vec().blake2_256())
72+
}
73+
74+
#[cfg(test)]
75+
pub mod runtime {
76+
77+
use super::*;
78+
79+
pub type Block = frame_system::mocking::MockBlock<Test>;
80+
81+
pub fn generate_pool_details(
82+
currencies: Vec<AssetId>,
83+
curve: Curve<Float>,
84+
transferable: bool,
85+
state: Option<PoolStatus<Locks>>,
86+
manager: Option<AccountId>,
87+
collateral_id: Option<AssetId>,
88+
owner: Option<AccountId>,
89+
) -> PoolDetailsOf<Test> {
90+
let bonded_currencies = BoundedVec::truncate_from(currencies);
91+
let state = state.unwrap_or(PoolStatus::Active);
92+
let owner = owner.unwrap_or(ACCOUNT_99);
93+
let collateral_id = collateral_id.unwrap_or(DEFAULT_COLLATERAL_CURRENCY_ID);
94+
PoolDetailsOf::<Test> {
95+
curve,
96+
manager,
97+
transferable,
98+
bonded_currencies,
99+
state,
100+
collateral_id,
101+
denomination: 10,
102+
owner,
103+
}
104+
}
105+
106+
pub(crate) fn events() -> Vec<crate::Event<Test>> {
107+
System::events()
108+
.into_iter()
109+
.map(|r| r.event)
110+
.filter_map(|e| {
111+
if let RuntimeEvent::BondingPallet(e) = e {
112+
Some(e)
113+
} else {
114+
None
115+
}
116+
})
117+
.collect::<Vec<_>>()
118+
}
119+
120+
frame_support::construct_runtime!(
121+
pub enum Test
122+
{
123+
System: frame_system,
124+
Balances: pallet_balances,
125+
Assets: pallet_assets,
126+
BondingPallet: crate,
127+
}
128+
);
129+
130+
parameter_types! {
131+
pub const SS58Prefix: u8 = 38;
132+
pub const BlockHashCount: u64 = 250;
133+
}
134+
135+
impl frame_system::Config for Test {
136+
type AccountData = pallet_balances::AccountData<Balance>;
137+
type AccountId = AccountId;
138+
type BaseCallFilter = frame_support::traits::Everything;
139+
type Block = Block;
140+
type BlockHashCount = BlockHashCount;
141+
type BlockLength = ();
142+
type BlockWeights = ();
143+
type DbWeight = RocksDbWeight;
144+
type Hash = Hash;
145+
type Hashing = BlakeTwo256;
146+
type Lookup = IdentityLookup<Self::AccountId>;
147+
type MaxConsumers = ConstU32<16>;
148+
type Nonce = u64;
149+
type OnKilledAccount = ();
150+
type OnNewAccount = ();
151+
type OnSetCode = ();
152+
type PalletInfo = PalletInfo;
153+
type RuntimeCall = RuntimeCall;
154+
type RuntimeEvent = RuntimeEvent;
155+
type RuntimeOrigin = RuntimeOrigin;
156+
type RuntimeTask = ();
157+
type SS58Prefix = SS58Prefix;
158+
type SystemWeightInfo = ();
159+
type Version = ();
160+
}
161+
162+
parameter_types! {
163+
pub const ExistentialDeposit: Balance = 500;
164+
pub const MaxLocks: u32 = 50;
165+
pub const MaxReserves: u32 = 50;
166+
}
167+
168+
impl pallet_balances::Config for Test {
169+
type AccountStore = System;
170+
type Balance = Balance;
171+
type DustRemoval = ();
172+
type ExistentialDeposit = ExistentialDeposit;
173+
type FreezeIdentifier = ();
174+
type MaxFreezes = ();
175+
type MaxLocks = MaxLocks;
176+
type MaxReserves = MaxReserves;
177+
type ReserveIdentifier = [u8; 8];
178+
type RuntimeEvent = RuntimeEvent;
179+
type RuntimeFreezeReason = ();
180+
type RuntimeHoldReason = RuntimeHoldReason;
181+
type WeightInfo = ();
182+
}
183+
184+
parameter_types! {
185+
pub const StringLimit: u32 = 50;
186+
187+
}
188+
impl pallet_assets::Config for Test {
189+
type ApprovalDeposit = ConstU128<0>;
190+
type AssetAccountDeposit = ConstU128<0>;
191+
type AssetDeposit = ConstU128<0>;
192+
type AssetId = AssetId;
193+
type AssetIdParameter = AssetId;
194+
type Balance = Balance;
195+
type CallbackHandle = ();
196+
type CreateOrigin = EnsureSigned<AccountId>;
197+
type Currency = Balances;
198+
type Extra = ();
199+
type ForceOrigin = EnsureRoot<AccountId>;
200+
type Freezer = ();
201+
type MetadataDepositBase = ConstU128<0>;
202+
type MetadataDepositPerByte = ConstU128<0>;
203+
type RemoveItemsLimit = ConstU32<5>;
204+
type RuntimeEvent = RuntimeEvent;
205+
type StringLimit = StringLimit;
206+
type WeightInfo = ();
207+
208+
#[cfg(feature = "runtime-benchmarks")]
209+
type BenchmarkHelper = ();
210+
}
211+
parameter_types! {
212+
pub const CurrencyDeposit: Balance = 500;
213+
pub const MaxCurrencies: u32 = 50;
214+
pub const CollateralAssetId: u32 = u32::MAX;
215+
}
216+
217+
impl pallet_bonded_coins::Config for Test {
218+
type AssetId = AssetId;
219+
type BaseDeposit = ExistentialDeposit;
220+
type CollateralCurrencies = Assets;
221+
type CurveParameterInput = FloatInput;
222+
type CurveParameterType = Float;
223+
type DefaultOrigin = EnsureSigned<AccountId>;
224+
type DepositCurrency = Balances;
225+
type DepositPerCurrency = CurrencyDeposit;
226+
type ForceOrigin = EnsureRoot<AccountId>;
227+
type Fungibles = Assets;
228+
type MaxCurrencies = MaxCurrencies;
229+
type MaxStringLength = StringLimit;
230+
type PoolCreateOrigin = EnsureSigned<AccountId>;
231+
type PoolId = AccountId;
232+
type RuntimeEvent = RuntimeEvent;
233+
type RuntimeHoldReason = RuntimeHoldReason;
234+
}
235+
236+
#[derive(Clone, Default)]
237+
pub(crate) struct ExtBuilder {
238+
native_assets: Vec<(AccountId, DepositCurrencyBalanceOf<Test>)>,
239+
bonded_balance: Vec<(AssetId, AccountId, Balance)>,
240+
// pool_id, PoolDetails
241+
pools: Vec<(AccountId, PoolDetailsOf<Test>)>,
242+
collaterals: Vec<AssetId>,
243+
}
244+
245+
impl ExtBuilder {
246+
pub(crate) fn with_native_balances(
247+
mut self,
248+
native_assets: Vec<(AccountId, DepositCurrencyBalanceOf<Test>)>,
249+
) -> Self {
250+
self.native_assets = native_assets;
251+
self
252+
}
253+
254+
pub(crate) fn with_collaterals(mut self, collaterals: Vec<AssetId>) -> Self {
255+
self.collaterals = collaterals;
256+
self
257+
}
258+
259+
pub(crate) fn with_pools(mut self, pools: Vec<(AccountId, PoolDetailsOf<Test>)>) -> Self {
260+
self.pools = pools;
261+
self
262+
}
263+
264+
pub(crate) fn with_bonded_balance(mut self, bonded_balance: Vec<(AssetId, AccountId, Balance)>) -> Self {
265+
self.bonded_balance = bonded_balance;
266+
self
267+
}
268+
269+
pub(crate) fn build(self) -> sp_io::TestExternalities {
270+
let mut storage = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
271+
pallet_balances::GenesisConfig::<Test> {
272+
balances: self.native_assets.clone(),
273+
}
274+
.assimilate_storage(&mut storage)
275+
.expect("assimilate should not fail");
276+
277+
let collateral_assets = self.collaterals.into_iter().map(|id| (id, ACCOUNT_99, false, 1));
278+
279+
pallet_assets::GenesisConfig::<Test> {
280+
assets: self
281+
.pools
282+
.iter()
283+
.flat_map(|(owner, pool)| {
284+
pool.bonded_currencies
285+
.iter()
286+
.map(|id| (*id, owner.to_owned(), false, 1u128))
287+
.collect::<Vec<(AssetId, AccountId, bool, Balance)>>()
288+
})
289+
.chain(collateral_assets)
290+
.collect(),
291+
292+
accounts: self.bonded_balance,
293+
metadata: self
294+
.pools
295+
.iter()
296+
.flat_map(|(_, pool_details)| {
297+
pool_details
298+
.bonded_currencies
299+
.iter()
300+
.map(|id| (*id, vec![], vec![], pool_details.denomination))
301+
.collect::<Vec<(u32, Vec<u8>, Vec<u8>, u8)>>()
302+
})
303+
.collect(),
304+
}
305+
.assimilate_storage(&mut storage)
306+
.expect("assimilate should not fail");
307+
308+
let mut ext = sp_io::TestExternalities::new(storage);
309+
310+
ext.execute_with(|| {
311+
System::set_block_number(System::block_number() + 1);
312+
313+
self.pools.into_iter().for_each(|(pool_id, pool)| {
314+
crate::Pools::<Test>::insert(pool_id, pool);
315+
});
316+
});
317+
318+
ext
319+
}
320+
321+
#[cfg(feature = "runtime-benchmarks")]
322+
pub(crate) fn build_with_keystore(self) -> sp_io::TestExternalities {
323+
use sp_keystore::{testing::MemoryKeystore, KeystoreExt};
324+
use sp_std::sync::Arc;
325+
326+
let mut ext = self.build();
327+
328+
let keystore = MemoryKeystore::new();
329+
ext.register_extension(KeystoreExt(Arc::new(keystore)));
330+
331+
ext
332+
}
333+
}
334+
}

0 commit comments

Comments
 (0)