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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{Addr, Coin, StdError, StdResult, Uint128};
use croncat_sdk_core::types::GasPrice;
use cw20::Cw20CoinVerified;

use crate::error::SdkError;

#[cw_serde]
pub struct TaskBalanceResponse {
    pub balance: Option<TaskBalance>,
}
#[cw_serde]
pub struct TaskBalance {
    pub native_balance: Uint128,
    pub cw20_balance: Option<Cw20CoinVerified>,
    pub ibc_balance: Option<Coin>,
}

impl TaskBalance {
    pub fn verify_enough_attached(
        &self,
        native_required: Uint128,
        cw20_required: Option<Cw20CoinVerified>,
        ibc_required: Option<Coin>,
        recurring: bool,
        native_denom: &str,
    ) -> Result<(), SdkError> {
        let multiplier = if recurring {
            Uint128::new(2)
        } else {
            Uint128::new(1)
        };
        if self.native_balance < native_required * multiplier {
            return Err(SdkError::NotEnoughNative {
                denom: native_denom.to_owned(),
                lack: native_required * multiplier - self.native_balance,
            });
        }
        self.verify_enough_cw20(cw20_required, multiplier)?;
        match (ibc_required, &self.ibc_balance) {
            (Some(req), Some(attached)) => {
                if req.denom != attached.denom {
                    return Err(SdkError::NotEnoughNative {
                        denom: req.denom,
                        lack: req.amount * multiplier,
                    });
                }
                if attached.amount < req.amount * multiplier {
                    return Err(SdkError::NotEnoughNative {
                        denom: req.denom,
                        lack: req.amount * multiplier - attached.amount,
                    });
                }
            }
            (Some(req), None) => {
                return Err(SdkError::NotEnoughNative {
                    denom: req.denom,
                    lack: req.amount * multiplier,
                })
            }
            // Dont want untracked or differing CW20s from required
            (None, Some(_)) => {
                return Err(SdkError::NonRequiredDenom {});
            }
            // nothing attached, nothing required
            (None, None) => (),
        }
        Ok(())
    }

    pub fn verify_enough_cw20(
        &self,
        cw20_required: Option<Cw20CoinVerified>,
        multiplier: Uint128,
    ) -> Result<(), SdkError> {
        match (cw20_required, &self.cw20_balance) {
            (Some(req), Some(attached)) => {
                if req.address != attached.address {
                    return Err(SdkError::NotEnoughCw20 {
                        addr: req.address.into_string(),
                        lack: req.amount * multiplier,
                    });
                }
                if attached.amount < req.amount * multiplier {
                    return Err(SdkError::NotEnoughCw20 {
                        addr: req.address.into_string(),
                        lack: req.amount * multiplier - attached.amount,
                    });
                }
                Ok(())
            }
            (Some(req), None) => Err(SdkError::NotEnoughCw20 {
                addr: req.address.into_string(),
                lack: req.amount * multiplier,
            }),
            // Dont want untracked or differing CW20s from required
            (None, Some(_)) => Err(SdkError::NonRequiredDenom {}),
            // nothing attached, nothing required
            (None, None) => Ok(()),
        }
    }

    pub fn sub_coin(&mut self, coin: &Coin, native_denom: &str) -> StdResult<()> {
        if coin.denom == native_denom {
            self.native_balance = self
                .native_balance
                .checked_sub(coin.amount)
                .map_err(|_| StdError::generic_err("Not enough native balance for operation"))?;
        } else {
            match &mut self.ibc_balance {
                Some(task_coin) if task_coin.denom == coin.denom => {
                    task_coin.amount = task_coin.amount.checked_sub(coin.amount).map_err(|_| {
                        StdError::generic_err("Not enough ibc balance for operation")
                    })?;
                }
                _ => {
                    return Err(StdError::generic_err("No balance found for operation"));
                }
            }
        }
        Ok(())
    }

    pub fn sub_cw20(&mut self, cw20: &Cw20CoinVerified) -> StdResult<()> {
        match &mut self.cw20_balance {
            Some(task_cw20) if task_cw20.address == cw20.address => {
                // task_cw20.amount = task_cw20.amount.checked_sub(cw20.amount)?;
                task_cw20.amount = task_cw20
                    .amount
                    .checked_sub(cw20.amount)
                    .map_err(|_| StdError::generic_err("Not enough cw20 balance for operation"))?;
            }
            _ => {
                // If addresses doesn't match it means we have zero coins
                // Uint128::zero().checked_sub(cw20.amount)?;
                return Err(StdError::GenericErr {
                    msg: "Not enough cw20 balance for operation".to_string(),
                });
            }
        }
        Ok(())
    }
}

#[cw_serde]
pub struct Config {
    // Runtime
    pub owner_addr: Addr,

    /// A multisig admin whose sole responsibility is to pause the contract in event of emergency.
    /// Must be a different contract address than DAO, cannot be a regular keypair
    /// Does not have the ability to unpause, must rely on the DAO to assess the situation and act accordingly
    pub pause_admin: Addr,

    /// Address of the croncat_factory
    pub croncat_factory_addr: Addr,

    /// Key to query address of the tasks
    pub croncat_tasks_key: (String, [u8; 2]),
    /// Key to query address of the agents
    pub croncat_agents_key: (String, [u8; 2]),

    // Economics
    pub agent_fee: u16,
    pub treasury_fee: u16,
    pub gas_price: GasPrice,

    // Treasury
    pub treasury_addr: Option<Addr>,
    pub cw20_whitelist: Vec<Addr>,
    pub native_denom: String,

    // The default query limit
    pub limit: u64,
}

#[cw_serde]
pub struct UpdateConfig {
    pub agent_fee: Option<u16>,
    pub treasury_fee: Option<u16>,
    pub gas_price: Option<GasPrice>,
    pub croncat_tasks_key: Option<(String, [u8; 2])>,
    pub croncat_agents_key: Option<(String, [u8; 2])>,
    pub treasury_addr: Option<String>,
    /// Add supported cw20s
    /// That's seems unfair to undo support of cw20's after user already created a task with it
    pub cw20_whitelist: Option<Vec<String>>,
}

#[cfg(test)]
mod test {
    use cosmwasm_std::{coin, Addr, Coin, Uint128};
    use cw20::Cw20CoinVerified;

    use crate::SdkError;

    use super::{GasPrice, TaskBalance};

    #[test]
    fn gas_price_validation() {
        assert!(!GasPrice {
            numerator: 0,
            denominator: 1,
            gas_adjustment_numerator: 1
        }
        .is_valid());

        assert!(!GasPrice {
            numerator: 1,
            denominator: 0,
            gas_adjustment_numerator: 1
        }
        .is_valid());

        assert!(!GasPrice {
            numerator: 1,
            denominator: 1,
            gas_adjustment_numerator: 0
        }
        .is_valid());

        assert!(GasPrice {
            numerator: 1,
            denominator: 1,
            gas_adjustment_numerator: 1
        }
        .is_valid());
    }

    #[test]
    fn gas_price_calculate_test() {
        // Test with default values
        let gas_price_wrapper = GasPrice::default();
        let gas_price = 0.04;
        let gas_adjustments = 1.5;

        let gas = 200_000;
        let expected = gas as f64 * gas_adjustments * gas_price;
        assert_eq!(expected as u128, gas_price_wrapper.calculate(gas).unwrap());

        let gas = 160_000;
        let expected = gas as f64 * gas_adjustments * gas_price;
        assert_eq!(expected as u128, gas_price_wrapper.calculate(gas).unwrap());

        let gas = 1_234_000;
        let expected = gas as f64 * gas_adjustments * gas_price;
        assert_eq!(expected as u128, gas_price_wrapper.calculate(gas).unwrap());

        // Check custom works
        let gas_price_wrapper = GasPrice {
            numerator: 25,
            denominator: 100,
            gas_adjustment_numerator: 120,
        };
        let gas_price = 0.25;
        let gas_adjustments = 1.2;

        let gas = 200_000;
        let expected = gas as f64 * gas_adjustments * gas_price;
        assert_eq!(expected as u128, gas_price_wrapper.calculate(gas).unwrap());

        let gas = 160_000;
        let expected = gas as f64 * gas_adjustments * gas_price;
        assert_eq!(expected as u128, gas_price_wrapper.calculate(gas).unwrap());

        let gas = 1_234_000;
        let expected = gas as f64 * gas_adjustments * gas_price;
        assert_eq!(expected as u128, gas_price_wrapper.calculate(gas).unwrap());
    }

    #[test]
    fn verify_enough_attached_ok_test() {
        let native_balance = Uint128::from(100u64);
        let cw20 = Cw20CoinVerified {
            address: Addr::unchecked("addr"),
            amount: Uint128::from(100u64),
        };
        let ibc_coin = coin(100, "ibc");

        // Test when cw20_balance and ibc_balance are None
        let task_balance = TaskBalance {
            native_balance,
            cw20_balance: None,
            ibc_balance: None,
        };
        assert!(task_balance
            .verify_enough_attached(Uint128::from(100u64), None, None, false, "denom")
            .is_ok());
        assert!(task_balance
            .verify_enough_attached(Uint128::from(50u64), None, None, true, "denom")
            .is_ok());

        // Test with cw20_balance and ibc_balance
        let task_balance = TaskBalance {
            native_balance,
            cw20_balance: Some(cw20.clone()),
            ibc_balance: Some(ibc_coin.clone()),
        };
        // We're now validating you're not adding tokens that never get used, #noMoreBlackHoles
        assert!(task_balance
            .verify_enough_attached(Uint128::from(100u64), None, None, false, "denom")
            .is_err());
        assert!(task_balance
            .verify_enough_attached(Uint128::from(50u64), None, None, true, "denom")
            .is_err());
        assert!(task_balance
            .verify_enough_attached(
                Uint128::from(100u64),
                Some(cw20),
                Some(ibc_coin),
                false,
                "denom"
            )
            .is_ok());
        assert!(task_balance
            .verify_enough_attached(
                Uint128::from(50u64),
                Some(Cw20CoinVerified {
                    address: Addr::unchecked("addr"),
                    amount: Uint128::from(50u64),
                }),
                Some(coin(50, "ibc")),
                true,
                "denom"
            )
            .is_ok());
    }

    #[test]
    fn verify_enough_attached_err_test() {
        let native_balance = Uint128::from(100u64);
        let cw20 = Cw20CoinVerified {
            address: Addr::unchecked("addr"),
            amount: Uint128::from(100u64),
        };
        let ibc_coin = coin(100, "ibc");

        // Test when cw20_balance and ibc_balance are None, native_balance is not sufficient
        let task_balance = TaskBalance {
            native_balance,
            cw20_balance: None,
            ibc_balance: None,
        };
        assert_eq!(
            task_balance
                .verify_enough_attached(Uint128::from(101u64), None, None, false, "denom")
                .unwrap_err(),
            SdkError::NotEnoughNative {
                denom: "denom".to_owned(),
                lack: 1u64.into(),
            }
        );
        assert_eq!(
            task_balance
                .verify_enough_attached(native_balance, Some(cw20.clone()), None, false, "denom")
                .unwrap_err(),
            SdkError::NotEnoughCw20 {
                addr: "addr".to_owned(),
                lack: 100u64.into(),
            }
        );
        assert_eq!(
            task_balance
                .verify_enough_attached(
                    native_balance,
                    None,
                    Some(ibc_coin.clone()),
                    false,
                    "denom"
                )
                .unwrap_err(),
            SdkError::NotEnoughNative {
                denom: "ibc".to_owned(),
                lack: 100u64.into(),
            }
        );

        // Test when cw20_balance or ibc_balance are not sufficient
        let task_balance = TaskBalance {
            native_balance,
            cw20_balance: Some(cw20.clone()),
            ibc_balance: Some(ibc_coin.clone()),
        };
        // cw20_balance is not sufficient
        assert_eq!(
            task_balance
                .verify_enough_attached(
                    Uint128::from(100u64),
                    Some(Cw20CoinVerified {
                        address: Addr::unchecked("addr"),
                        amount: Uint128::from(101u64),
                    }),
                    Some(ibc_coin.clone()),
                    false,
                    "denom"
                )
                .unwrap_err(),
            SdkError::NotEnoughCw20 {
                addr: "addr".to_owned(),
                lack: 1u64.into(),
            }
        );
        // cw20_balance has another address
        assert_eq!(
            task_balance
                .verify_enough_attached(
                    Uint128::from(100u64),
                    Some(Cw20CoinVerified {
                        address: Addr::unchecked("addr2"),
                        amount: Uint128::from(100u64),
                    }),
                    Some(ibc_coin),
                    false,
                    "denom"
                )
                .unwrap_err(),
            SdkError::NotEnoughCw20 {
                addr: "addr2".to_owned(),
                lack: 100u64.into(),
            }
        );
        // ibc_balance is not sufficient
        assert_eq!(
            task_balance
                .verify_enough_attached(
                    Uint128::from(100u64),
                    Some(cw20.clone()),
                    Some(coin(101, "ibc")),
                    false,
                    "denom"
                )
                .unwrap_err(),
            SdkError::NotEnoughNative {
                denom: "ibc".to_owned(),
                lack: 1u64.into(),
            }
        );
        // ibc_balance has another denom
        assert_eq!(
            task_balance
                .verify_enough_attached(
                    Uint128::from(100u64),
                    Some(cw20),
                    Some(coin(100, "ibc2")),
                    false,
                    "denom"
                )
                .unwrap_err(),
            SdkError::NotEnoughNative {
                denom: "ibc2".to_owned(),
                lack: 100u64.into(),
            }
        );
    }

    #[test]
    fn sub_coin_test() {
        let native_balance = Uint128::from(100u64);
        let ibc_coin = coin(100, "ibc");

        let mut task_balance = TaskBalance {
            native_balance,
            cw20_balance: None,
            ibc_balance: Some(ibc_coin.clone()),
        };

        task_balance
            .sub_coin(&coin(10, "native"), "native")
            .unwrap();
        assert_eq!(
            task_balance,
            TaskBalance {
                native_balance: Uint128::from(90u64),
                cw20_balance: None,
                ibc_balance: Some(ibc_coin),
            }
        );

        task_balance.sub_coin(&coin(1, "ibc"), "native").unwrap();
        assert_eq!(
            task_balance,
            TaskBalance {
                native_balance: Uint128::from(90u64),
                cw20_balance: None,
                ibc_balance: Some(coin(99, "ibc")),
            }
        );

        assert!(task_balance
            .sub_coin(&coin(91, "native"), "native")
            .is_err());

        assert!(task_balance.sub_coin(&coin(100, "ibc"), "native").is_err());

        assert!(task_balance
            .sub_coin(&coin(100, "wrong"), "native")
            .is_err());
    }

    #[test]
    fn sub_cw20_test() {
        let native_balance = Uint128::from(100u64);
        let cw20 = Cw20CoinVerified {
            address: Addr::unchecked("addr"),
            amount: Uint128::from(100u64),
        };

        let mut task_balance = TaskBalance {
            native_balance,
            cw20_balance: Some(cw20),
            ibc_balance: None,
        };

        task_balance
            .sub_cw20(&Cw20CoinVerified {
                address: Addr::unchecked("addr"),
                amount: Uint128::from(10u64),
            })
            .unwrap();
        assert_eq!(
            task_balance,
            TaskBalance {
                native_balance,
                cw20_balance: Some(Cw20CoinVerified {
                    address: Addr::unchecked("addr"),
                    amount: Uint128::from(90u64),
                }),
                ibc_balance: None,
            }
        );

        assert!(task_balance
            .sub_cw20(&Cw20CoinVerified {
                address: Addr::unchecked("addr"),
                amount: Uint128::from(91u64),
            })
            .is_err());

        assert!(task_balance
            .sub_cw20(&Cw20CoinVerified {
                address: Addr::unchecked("addr2"),
                amount: Uint128::from(1u64),
            })
            .is_err());
    }

    #[test]
    fn test_sub_coin_success() {
        let native_denom = "native";
        let ibc_denom = "ibc";

        let mut task_balance = TaskBalance {
            native_balance: Uint128::new(100),
            cw20_balance: None,
            ibc_balance: Some(Coin {
                denom: ibc_denom.to_string(),
                amount: Uint128::new(200),
            }),
        };

        let coin_native = Coin {
            denom: native_denom.to_string(),
            amount: Uint128::new(50),
        };

        let coin_ibc = Coin {
            denom: ibc_denom.to_string(),
            amount: Uint128::new(100),
        };

        task_balance.sub_coin(&coin_native, native_denom).unwrap();
        task_balance.sub_coin(&coin_ibc, native_denom).unwrap();

        assert_eq!(task_balance.native_balance, Uint128::new(50));
        assert_eq!(task_balance.ibc_balance.unwrap().amount, Uint128::new(100));
    }

    #[test]
    fn test_sub_coin_overflow() {
        let native_denom = "native";
        let ibc_denom = "ibc";

        let mut task_balance = TaskBalance {
            native_balance: Uint128::new(100),
            cw20_balance: None,
            ibc_balance: Some(Coin {
                denom: ibc_denom.to_string(),
                amount: Uint128::new(200),
            }),
        };

        let coin_native_overflow = Coin {
            denom: native_denom.to_string(),
            amount: Uint128::new(150),
        };

        let coin_ibc_overflow = Coin {
            denom: ibc_denom.to_string(),
            amount: Uint128::new(300),
        };

        let coin_nonexistent = Coin {
            denom: "nonexistent".to_string(),
            amount: Uint128::new(100),
        };

        assert!(task_balance
            .sub_coin(&coin_native_overflow, native_denom)
            .is_err());
        assert!(task_balance
            .sub_coin(&coin_ibc_overflow, native_denom)
            .is_err());
        assert!(task_balance
            .sub_coin(&coin_nonexistent, native_denom)
            .is_err());
    }

    #[test]
    fn test_sub_cw20_success() {
        let cw20_address = Addr::unchecked("cw20_address");
        let mut task_balance = TaskBalance {
            cw20_balance: Some(Cw20CoinVerified {
                address: cw20_address.clone(),
                amount: Uint128::from(100u128),
            }),
            native_balance: Uint128::zero(),
            ibc_balance: None,
        };

        let cw20 = Cw20CoinVerified {
            address: cw20_address,
            amount: Uint128::from(50u128),
        };

        assert!(task_balance.sub_cw20(&cw20).is_ok());
        assert_eq!(
            task_balance.cw20_balance.unwrap().amount,
            Uint128::from(50u128)
        );
    }

    #[test]
    fn test_sub_cw20_insufficient_balance() {
        let cw20_address = Addr::unchecked("cw20_address");
        let mut task_balance = TaskBalance {
            cw20_balance: Some(Cw20CoinVerified {
                address: cw20_address.clone(),
                amount: Uint128::from(100u128),
            }),
            native_balance: Uint128::zero(),
            ibc_balance: None,
        };

        let cw20 = Cw20CoinVerified {
            address: cw20_address,
            amount: Uint128::from(200u128),
        };

        assert!(task_balance.sub_cw20(&cw20).is_err());
    }

    #[test]
    fn test_sub_cw20_address_not_found() {
        let cw20_address = Addr::unchecked("cw20_address");
        let cw20_address_2 = Addr::unchecked("cw20_address_2");
        let mut task_balance = TaskBalance {
            cw20_balance: Some(Cw20CoinVerified {
                address: cw20_address,
                amount: Uint128::from(100u128),
            }),
            native_balance: Uint128::zero(),
            ibc_balance: None,
        };

        let cw20 = Cw20CoinVerified {
            address: cw20_address_2,
            amount: Uint128::from(50u128),
        };

        assert!(task_balance.sub_cw20(&cw20).is_err());
    }
}