cw-it 0.4.0

A crate of utils for integration testing CosmWasm smart contracts
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use std::ops::Range;

use apollo_utils::iterators::IntoElementwise;
use cosmwasm_std::{Coin, Uint128};
use osmosis_test_tube::osmosis_std::types::osmosis::gamm::{
    poolmodels::{
        balancer::v1beta1::MsgCreateBalancerPool,
        stableswap::v1beta1::{MsgCreateStableswapPool, PoolParams as StableSwapPoolParams},
    },
    v1beta1::{PoolAsset, PoolParams},
};
use osmosis_test_tube::{Account, Gamm, Module, Runner, SigningAccount};
use prop::collection::vec;
use proptest::prelude::*;
use proptest::strategy::{Just, Strategy};
use proptest::{option, prop_compose, proptest};

use crate::const_coin::ConstCoin;

const MAX_SCALE_FACTOR: u64 = 0x7FFF_FFFF_FFFF_FFFF; // 2^63 - 1
const MAX_POOL_WEIGHT: u64 = 1048575; //2^20 - 1

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OsmosisPoolType {
    Basic,
    Balancer {
        pool_weights: Vec<u64>,
        pool_params: Option<PoolParams>,
    },
    StableSwap {
        scaling_factors: Vec<u64>,
        pool_params: Option<StableSwapPoolParams>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConstOsmosisTestPool {
    pub liquidity: &'static [ConstCoin],
    pub pool_type: OsmosisPoolType,
}

impl ConstOsmosisTestPool {
    pub const fn new(liquidity: &'static [ConstCoin], pool_type: OsmosisPoolType) -> Self {
        Self {
            liquidity,
            pool_type,
        }
    }
}

impl From<ConstOsmosisTestPool> for OsmosisTestPool {
    fn from(pool: ConstOsmosisTestPool) -> Self {
        Self {
            liquidity: pool.liquidity.into_elementwise(),
            pool_type: pool.pool_type,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OsmosisTestPool {
    pub liquidity: Vec<Coin>,
    pub pool_type: OsmosisPoolType,
}

impl OsmosisTestPool {
    /// Create a new Osmosis pool with the given initial liquidity and pool type.
    pub fn new(liquidity: Vec<Coin>, pool_type: OsmosisPoolType) -> Self {
        Self {
            liquidity,
            pool_type,
        }
    }

    pub fn default_pool_params() -> PoolParams {
        PoolParams {
            swap_fee: "200000000000000000".to_string(),
            exit_fee: "0".to_string(),
            smooth_weight_change_params: None,
        }
    }

    pub fn default_stableswap_pool_params() -> StableSwapPoolParams {
        StableSwapPoolParams {
            swap_fee: "200000000000000000".to_string(),
            exit_fee: "0".to_string(),
        }
    }

    /// Create an Osmosis pool with the given initial liquidity.
    ///
    /// Returns the `u64` pool ID.
    pub fn create<'a, R: Runner<'a>>(&self, runner: &'a R, signer: &SigningAccount) -> u64 {
        let gamm = Gamm::new(runner);
        match &self.pool_type {
            OsmosisPoolType::Basic => {
                gamm.create_basic_pool(&self.liquidity, signer)
                    .unwrap()
                    .data
                    .pool_id
            }
            OsmosisPoolType::Balancer {
                pool_weights,
                pool_params,
            } => {
                gamm.create_balancer_pool(
                    MsgCreateBalancerPool {
                        sender: signer.address(),
                        pool_params: Some(
                            pool_params
                                .clone()
                                .unwrap_or_else(Self::default_pool_params),
                        ),
                        pool_assets: self
                            .liquidity
                            .iter()
                            .zip(pool_weights.iter())
                            .map(|(c, weight)| PoolAsset {
                                token: Some(c.clone().into()),
                                weight: weight.to_string(),
                            })
                            .collect(),
                        future_pool_governor: "".to_string(),
                    },
                    signer,
                )
                .unwrap()
                .data
                .pool_id
            }
            OsmosisPoolType::StableSwap {
                scaling_factors,
                pool_params,
            } => {
                gamm.create_stable_swap_pool(
                    MsgCreateStableswapPool {
                        sender: signer.address(),
                        pool_params: Some(
                            pool_params
                                .clone()
                                .unwrap_or_else(Self::default_stableswap_pool_params),
                        ),
                        initial_pool_liquidity: self
                            .liquidity
                            .iter()
                            .map(|c| c.clone().into())
                            .collect(),
                        scaling_factors: scaling_factors.clone(),
                        future_pool_governor: "".to_string(),
                        scaling_factor_controller: "".to_string(),
                    },
                    signer,
                )
                .unwrap()
                .data
                .pool_id
            }
        }
    }
}

/// Generates a vector of random denoms of the specified size
pub fn pool_denoms(count: usize) -> impl Strategy<Value = Vec<String>> {
    Just(Vec::from_iter(0..8))
        .prop_shuffle()
        .prop_flat_map(move |x| {
            let mut denoms = x
                .iter()
                .take(count)
                .map(|i| format!("denom{}", i))
                .collect::<Vec<String>>();
            denoms.sort(); // Osmosis requires denoms to be sorted...
            Just(denoms)
        })
}

/// Generates a vector of random denoms with at least one denom in common with
/// the given denoms.
pub fn pool_denoms_with_one_common(
    count: usize,
    input_denoms: Vec<String>,
) -> impl Strategy<Value = Vec<String>> {
    pool_denoms(count).prop_flat_map(move |mut denoms| {
        if denoms.iter().any(|x| input_denoms.contains(x)) {
            Just(denoms)
        } else {
            let common_denom = input_denoms[0].clone();
            denoms[0] = common_denom;
            denoms.sort(); // Osmosis requires denoms to be sorted...
            Just(denoms)
        }
    })
}

/// Generates a vector of random denoms with one of them being the given
/// specific_denom
pub fn pool_denoms_with_one_specific(
    count: usize,
    specific_denom: String,
) -> impl Strategy<Value = Vec<String>> {
    pool_denoms(count).prop_flat_map(move |mut denoms| {
        if denoms.iter().any(|x| x == &specific_denom) {
            Just(denoms)
        } else {
            denoms[0].clone_from(&specific_denom);
            denoms.sort(); // Osmosis requires denoms to be sorted...
            Just(denoms)
        }
    })
}

/// Generates a vector of size 2..8 with random amounts in the given range,
/// or 0..u128::MAX if no range is given.
pub fn pool_liquidity_amounts(
    liquidity_range: Option<Range<u128>>,
) -> impl Strategy<Value = Vec<u128>> {
    let liquidity_range = liquidity_range.unwrap_or(0..u64::MAX as u128);
    vec(liquidity_range, 2..8)
}

prop_compose! {
    /// Generates a randomly sized vector (size 2-8) of Coins with random amounts and denoms
    pub fn pool_liquidity(liquidity_range: Option<Range<u128>>)(amounts in pool_liquidity_amounts(liquidity_range))(denoms in pool_denoms(amounts.len()), amounts in Just(amounts)) -> Vec<Coin> {
        amounts.into_iter().zip(denoms).map(|(amount, denom)| Coin { amount: Uint128::from(amount), denom }).collect()
    }
}

prop_compose! {
    /// Generates a randomly sized vector (size 2-8) of Coins with random amounts
    /// and denoms, where one denom is in common with the given base_liquidity
    pub fn pool_liquidity_with_one_common_denom(base_liquidity: Vec<Coin>, liquidity_range: Option<Range<u128>>)
        (amounts in  pool_liquidity_amounts(liquidity_range))
        (
            denoms in pool_denoms_with_one_common(amounts.len(),
            base_liquidity.iter().map(|x| x.denom.clone()).collect()),
            amounts in Just(amounts)
        ) -> Vec<Coin> {
            amounts.into_iter().zip(denoms).map(|(amount, denom)|
                Coin { amount: Uint128::from(amount), denom
            }).collect()
        }
}

prop_compose! {
    /// Generates a randomly sized vector (size 2-8) of Coins with random amounts
    /// and denoms, where one denom is the given specific_denom
    pub fn pool_liquidity_with_one_specific_denom(specific_denom: String, liquidity_range: Option<Range<u128>>)
        (amounts in  pool_liquidity_amounts(liquidity_range))
        (
            denoms in pool_denoms_with_one_specific(amounts.len(), specific_denom.clone()),
            amounts in Just(amounts)
        ) -> Vec<Coin> {
            amounts.into_iter().zip(denoms).map(|(amount, denom)|
                Coin { amount: Uint128::from(amount), denom
            }).collect()
        }
}

/// Generates scaling factors for an Osmosis StableSwap pool for the given liquidity
pub fn scaling_factors(pool_liquidity: &[Coin]) -> impl Strategy<Value = Vec<u64>> {
    pool_liquidity
        .iter()
        .map(|x| {
            let max_scale_factor = if x.amount.u128() > MAX_SCALE_FACTOR.into() {
                MAX_SCALE_FACTOR
            } else {
                x.amount.u128() as u64
            };
            1..max_scale_factor
        })
        .collect::<Vec<Range<u64>>>()
}

prop_compose! {
    /// Generates a tuple of vectors with (pool_liquidity, scaling_factors)
    pub fn pool_params()(pool_liq in pool_liquidity(None))(scaling_factors in scaling_factors(&pool_liq), pool_liquidity in Just(pool_liq)) -> (Vec<Coin>,Vec<u64>) {
        (pool_liquidity, scaling_factors)
    }
}

/// Generates a random OsmosisPoolType
pub fn pool_type(pool_liquidity: &[Coin]) -> impl Strategy<Value = OsmosisPoolType> {
    prop_oneof![
        Just(OsmosisPoolType::Basic),
        vec(1..MAX_POOL_WEIGHT, pool_liquidity.len()).prop_map(|pool_weights| {
            OsmosisPoolType::Balancer {
                pool_weights,
                pool_params: None,
            }
        }),
        scaling_factors(pool_liquidity).prop_map(|scaling_factors| {
            OsmosisPoolType::StableSwap {
                scaling_factors,
                pool_params: None,
            }
        }),
    ]
    .no_shrink()
}

prop_compose! {
    /// Generates a random OsmosisTestPool with the given liquidity
    pub fn test_pool_from_liquidity(pool_liquidity: Vec<Coin>)(pool_type in pool_type(&pool_liquidity), liquidity in Just(pool_liquidity)) -> OsmosisTestPool {
        OsmosisTestPool {
            liquidity,
            pool_type,
        }
    }
}

prop_compose! {
    /// Generates a random OsmosisTestPool with 2..8 assets
    pub fn test_pool(liq_range: Option<Range<u128>>)(pool_liquidity in pool_liquidity(liq_range))(
        test_pool in test_pool_from_liquidity(pool_liquidity)
    ) -> OsmosisTestPool {
        test_pool
    }
}

prop_compose! {
    /// Generates a random OsmosisTestPool with one denom in common with the given base pool
    pub fn reward_pool(base_pool: OsmosisTestPool)(pool_liquidity in pool_liquidity_with_one_common_denom(base_pool.liquidity, None))(
        pool_type in pool_type(&pool_liquidity), liquidity in Just(pool_liquidity)
    ) -> OsmosisTestPool {
        OsmosisTestPool {
            liquidity,
            pool_type,
        }
    }
}

prop_compose! {
    /// Generates a random OsmosisTestPool with one denom being the given specific denom
    pub fn pool_with_denom(specific_denom: String, liq_range: Option<Range<u128>>)(pool_liquidity in pool_liquidity_with_one_specific_denom(specific_denom, liq_range))(
        pool_type in pool_type(&pool_liquidity), liquidity in Just(pool_liquidity)
    ) -> OsmosisTestPool {
        OsmosisTestPool {
            liquidity,
            pool_type,
        }
    }
}

prop_compose! {
    /// Generates a tuple of OsmosisTestPools with the given base pool and one or two reward pools
    /// with one denom in common with the base pool
    pub fn test_pools(liq_range: Option<Range<u128>>)
    ((liquidation_target, base_pool) in test_pool(liq_range.clone()).prop_flat_map(|pool| {
        (Just(pool.liquidity[0].denom.clone()),Just(pool))
    }))
    (
        reward1_pool in pool_with_denom(liquidation_target.clone(), liq_range.clone()),
        reward2_pool in option::of(pool_with_denom(liquidation_target, liq_range.clone())),
        base_pool in Just(base_pool)
    ) -> (OsmosisTestPool, OsmosisTestPool, Option<OsmosisTestPool>) {
        (base_pool, reward1_pool, reward2_pool)
    }
}

/// Asserts that all pool properties are valid.
#[cfg(test)]
fn assert_test_pool_properties(pool: OsmosisTestPool) {
    let OsmosisTestPool {
        liquidity,
        pool_type,
    } = pool;
    assert!(liquidity.len() >= 2);
    assert!(liquidity.len() <= 8);
    assert!(liquidity.iter().all(|liq| liq.amount.u128() > 0));
    assert!(liquidity.iter().all(|liq| liq.amount.u128() < u128::MAX));
    match pool_type {
        OsmosisPoolType::Basic => {}
        OsmosisPoolType::Balancer {
            pool_weights,
            pool_params,
        } => {
            assert_eq!(pool_weights.len(), liquidity.len());
            assert!(pool_weights.iter().all(|weight| weight > &0));
            assert!(pool_weights.iter().all(|weight| weight < &MAX_POOL_WEIGHT));
            if let Some(params) = pool_params {
                assert!(params.exit_fee == *"0");
            }
        }
        OsmosisPoolType::StableSwap {
            scaling_factors,
            pool_params,
        } => {
            assert_eq!(scaling_factors.len(), liquidity.len());
            assert!(scaling_factors.iter().all(|scale| scale > &0));
            assert!(scaling_factors
                .iter()
                .all(|scale| scale < &MAX_SCALE_FACTOR));
            assert!(liquidity
                .iter()
                .zip(scaling_factors.iter())
                .all(|(liq, scale)| (*scale as u128) < liq.amount.u128()));
            if let Some(params) = pool_params {
                assert!(params.exit_fee == *"0");
            }
        }
    }
}

proptest! {
    #![proptest_config(ProptestConfig {
        cases: 10000,
        max_local_rejects: 0,
        ..ProptestConfig::default()
    })]

    #[test]
    fn test_pool_params(params in pool_params()) {
        let (pool_liquidity, scaling_factors): (Vec<Coin>,Vec<u64>) = params;
        assert_eq!(pool_liquidity.len(), scaling_factors.len());
        assert!(pool_liquidity.iter().all(|liq| liq.amount.u128() > 0));
        assert!(scaling_factors.iter().all(|scale| scale > &0));
        assert!(scaling_factors.iter().all(|scale| scale < &MAX_SCALE_FACTOR));
        assert!(pool_liquidity.iter().all(|liq| liq.amount.u128() < u128::MAX));
        assert!(pool_liquidity.iter().zip(scaling_factors.iter()).all(|(liq, scale)| (*scale as u128) < liq.amount.u128()));
    }

    #[test]
    fn test_denoms(mut denoms in pool_denoms(8)) {
        assert!(denoms.len() == 8);
        denoms.sort();
        assert_eq!(denoms, Vec::from_iter(0..8).iter().map(|i| format!("denom{}", i)).collect::<Vec<String>>());
    }

    #[test]
    fn test_denoms_one_common(denoms in vec(2..8usize,2).prop_flat_map(|counts| pool_denoms(counts[0]).prop_flat_map(move |base_denoms| {
        (Just(base_denoms.clone()), pool_denoms_with_one_common(counts[1], base_denoms))
    }))) {
        let (base_denoms, other_denoms) = denoms;
        assert!(base_denoms.iter().any(|denom| other_denoms.contains(denom)));
        if base_denoms.len() != other_denoms.len() {
            assert_ne!(base_denoms, other_denoms);
        }
    }

    #[test]
    fn test_denoms_one_specific(denoms in vec(2..8usize,2).prop_flat_map(|counts| pool_denoms(counts[0]).prop_flat_map(move |base_denoms| {
        (Just(base_denoms.clone()), pool_denoms_with_one_specific(counts[1], base_denoms[0].clone()))
    }))) {
        let (base_denoms, other_denoms) = denoms;
        let common_denom = &base_denoms[0];
        assert!(other_denoms.contains(common_denom));
    }

    #[test]
    fn test_test_pool(pool in test_pool(None)) {
        assert_test_pool_properties(pool);
    }

    #[test]
    fn test_pool_with_denom(pool in pool_with_denom(String::from("requested_denom"), None)) {
        assert!(pool.liquidity.iter().any(|liq| liq.denom == "requested_denom"));
        assert_test_pool_properties(pool);
    }

    #[test]
    fn test_reward_pool((pool, reward_pool) in test_pool(None).prop_flat_map(|base_pool| (Just(base_pool.clone()), reward_pool(base_pool)))) {
        let reward_denoms = reward_pool.liquidity.iter().map(|liq| liq.denom.clone()).collect::<Vec<String>>();
        let base_denoms = pool.liquidity.iter().map(|liq| liq.denom.clone()).collect::<Vec<String>>();
        // Assert that reward denoms has at least one denom in common with base denoms
        assert!(reward_denoms.iter().any(|denom| base_denoms.contains(denom)));

        assert_test_pool_properties(pool);
        assert_test_pool_properties(reward_pool);
    }
}