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
use sp_std::marker::PhantomData;

use frame_support::{
    pallet_prelude::*,
    traits::{
        tokens::{fungibles::Unbalanced, WithdrawConsequence},
        ExistenceRequirement, ReservableCurrency, WithdrawReasons,
    },
};

use frame_support::traits::tokens::{
    Fortitude::Polite, Precision::Exact, Preservation::Expendable,
};
use sp_runtime::traits::Convert;

pub struct Monetary<AccountId, Assets, NativeCurrency, AssetBalanceOf>(
    PhantomData<(AccountId, Assets, NativeCurrency, AssetBalanceOf)>,
);
impl<
        AccountId,
        Assets: Unbalanced<AccountId>,
        NativeCurrency: ReservableCurrency<AccountId>,
        AssetBalanceOf: Convert<NativeCurrency::Balance, Assets::Balance>,
    > Monetary<AccountId, Assets, NativeCurrency, AssetBalanceOf>
{
    pub fn deposit(
        beneficiary: &AccountId,
        asset_id: Option<Assets::AssetId>,
        amount: NativeCurrency::Balance,
    ) {
        match asset_id {
            None => {
                NativeCurrency::deposit_creating(beneficiary, amount);
            },
            Some(asset_id) => {
                Assets::increase_balance(
                    asset_id,
                    beneficiary,
                    AssetBalanceOf::convert(amount),
                    Exact,
                );
            },
        }
    }

    pub fn can_withdraw(
        beneficiary: &AccountId,
        asset_id: Option<Assets::AssetId>,
        amount: NativeCurrency::Balance,
    ) -> bool {
        match asset_id {
            None =>
                NativeCurrency::free_balance(beneficiary) + NativeCurrency::minimum_balance()
                    >= amount,
            Some(asset_id) => {
                match Assets::can_withdraw(asset_id, beneficiary, AssetBalanceOf::convert(amount)) {
                    WithdrawConsequence::Success => true,
                    _ => false,
                }
            },
        }
    }

    pub fn withdraw(
        source: &AccountId,
        amount: NativeCurrency::Balance,
        maybe_asset_id: Option<Assets::AssetId>,
    ) -> DispatchResult {
        match maybe_asset_id {
            None => match NativeCurrency::withdraw(
                source,
                amount,
                WithdrawReasons::RESERVE,
                ExistenceRequirement::KeepAlive,
            ) {
                Err(e) => Err(e),
                Ok(_imbalance) => Ok(()),
            },
            Some(asset_id) => {
                match Assets::decrease_balance(
                    asset_id,
                    source,
                    AssetBalanceOf::convert(amount),
                    Exact,
                    Expendable,
                    Polite,
                ) {
                    Err(e) => Err(e),
                    Ok(_imbalance) => Ok(()),
                }
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use circuit_mock_runtime::*;
    use frame_support::traits::fungibles::Mutate;

    use frame_support::{assert_noop, assert_ok, traits::Currency};
    use sp_runtime::{traits::ConvertInto, ModuleError};

    use circuit_runtime_types::{AccountId, Balance};

    const DEFAULT_BALANCE: Balance = 1_000_000;

    #[test]
    fn given_native_assets_monetary_deposits_correctly() {
        ExtBuilder::default().build().execute_with(|| {
            let _ = Balances::deposit_creating(&ALICE, DEFAULT_BALANCE);

            const DEPOSIT_AMOUNT: Balance = DEFAULT_BALANCE / 10;
            assert_eq!(Balances::free_balance(&ALICE), DEFAULT_BALANCE);

            Monetary::<AccountId, Assets, Balances, ConvertInto>::deposit(
                &ALICE,
                None,
                DEFAULT_BALANCE / 10,
            );
            assert_eq!(
                Balances::free_balance(ALICE),
                DEFAULT_BALANCE + DEPOSIT_AMOUNT
            );
        });
    }

    #[test]
    fn given_foreign_assets_monetary_deposits_correctly() {
        ExtBuilder::default().build().execute_with(|| {
            const FOREIGN_ASSET_A: AssetId = 1;
            const MIN_BALANCE_ASSET_A: Balance = 1;
            assert_ok!(Assets::force_create(
                RuntimeOrigin::root(),
                FOREIGN_ASSET_A,
                sp_runtime::MultiAddress::Id(BOB), /* owner */
                true,                              /* is_sufficient */
                MIN_BALANCE_ASSET_A
            ));

            const DEPOSIT_AMOUNT: Balance = DEFAULT_BALANCE / 10;

            assert_ok!(Assets::mint_into(FOREIGN_ASSET_A, &ALICE, DEFAULT_BALANCE));
            assert_eq!(Assets::balance(FOREIGN_ASSET_A, ALICE), DEFAULT_BALANCE);

            Monetary::<AccountId, Assets, Balances, ConvertInto>::deposit(
                &ALICE,
                Some(FOREIGN_ASSET_A),
                DEPOSIT_AMOUNT,
            );
            assert_eq!(
                Assets::balance(FOREIGN_ASSET_A, ALICE),
                DEFAULT_BALANCE + DEPOSIT_AMOUNT
            );
        });
    }

    #[test]
    fn given_foreign_assets_monetary_withdraws_correctly() {
        ExtBuilder::default().build().execute_with(|| {
            const FOREIGN_ASSET_A: AssetId = 1;
            const MIN_BALANCE_ASSET_A: Balance = 1;
            assert_ok!(Assets::force_create(
                RuntimeOrigin::root(),
                FOREIGN_ASSET_A,
                sp_runtime::MultiAddress::Id(BOB), /* owner */
                true,                              /* is_sufficient */
                MIN_BALANCE_ASSET_A
            ));

            const DEPOSIT_AMOUNT: Balance = DEFAULT_BALANCE / 10;

            assert_ok!(Assets::mint_into(FOREIGN_ASSET_A, &ALICE, DEFAULT_BALANCE));
            assert_eq!(Assets::balance(FOREIGN_ASSET_A, ALICE), DEFAULT_BALANCE);

            assert_ok!(
                Monetary::<AccountId, Assets, Balances, ConvertInto>::withdraw(
                    &ALICE,
                    DEPOSIT_AMOUNT,
                    Some(FOREIGN_ASSET_A),
                )
            );

            assert_eq!(
                Assets::balance(FOREIGN_ASSET_A, ALICE),
                DEFAULT_BALANCE - DEPOSIT_AMOUNT
            );

            // withdraw again works
            assert_ok!(
                Monetary::<AccountId, Assets, Balances, ConvertInto>::withdraw(
                    &ALICE,
                    DEPOSIT_AMOUNT,
                    Some(FOREIGN_ASSET_A),
                )
            );

            assert_eq!(
                Assets::balance(FOREIGN_ASSET_A, ALICE),
                DEFAULT_BALANCE - 2 * DEPOSIT_AMOUNT
            );

            // withdraw too much fails
            assert_noop!(
                Monetary::<AccountId, Assets, Balances, ConvertInto>::withdraw(
                    &ALICE,
                    DEFAULT_BALANCE,
                    Some(FOREIGN_ASSET_A),
                ),
                DispatchError::Module(ModuleError {
                    index: 12,
                    error: [0, 0, 0, 0],
                    message: Some("BalanceLow")
                })
            );
        });
    }
}