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
// This file is part of the SORA network and Polkaswap app.

// Copyright (c) 2020, 2021, Polka Biome Ltd. All rights reserved.
// SPDX-License-Identifier: BSD-4-Clause

// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:

// Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// All advertising materials mentioning features or use of this software must display
// the following acknowledgement: This product includes software developed by Polka Biome
// Ltd., SORA, and Polkaswap.
//
// Neither the name of the Polka Biome Ltd. nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific prior written permission.

// THIS SOFTWARE IS PROVIDED BY Polka Biome Ltd. AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Polka Biome Ltd. BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use frame_support::dispatch::DispatchResult;
use frame_support::ensure;
use frame_support::weights::Weight;
use sp_runtime::traits::Zero;

use common::prelude::FixedWrapper;
use common::AssetInfoProvider;

use crate::{to_balance, AccountPools, PoolProviders, TotalIssuances};

use crate::aliases::{AccountIdOf, AssetIdOf, TechAccountIdOf};
use crate::{Config, Error, Pallet, MIN_LIQUIDITY};

use crate::bounds::*;
use crate::operations::*;

impl<T: Config> common::SwapRulesValidation<AccountIdOf<T>, TechAccountIdOf<T>, AssetIdOf<T>, T>
    for WithdrawLiquidityAction<AssetIdOf<T>, AccountIdOf<T>, TechAccountIdOf<T>>
{
    fn is_abstract_checking(&self) -> bool {
        self.destination.0.amount == Bounds::Dummy || self.destination.1.amount == Bounds::Dummy
    }

    fn prepare_and_validate(
        &mut self,
        source_opt: Option<&AccountIdOf<T>>,
        _base_asset_id: &AssetIdOf<T>,
    ) -> DispatchResult {
        //TODO: replace unwrap.
        let source = source_opt.unwrap();
        // Check that client account is same as source, because signature is checked for source.
        // Signature checking is used in extrinsics for example, and source is derived from origin.
        // TODO: In general case it is possible to use different client account, for example if
        // signature of source is legal for some source accounts.
        match &self.client_account {
            // Just use `client_account` as copy of source.
            None => {
                self.client_account = Some(source.clone());
            }
            Some(ca) => {
                if ca != source {
                    Err(Error::<T>::SourceAndClientAccountDoNotMatchAsEqual)?;
                }
            }
        }

        // Dealing with receiver account, for example case then not swapping to self, but to
        // other account.
        match &self.receiver_account_a {
            // Just use `client_account` as same account, swapping to self.
            None => {
                self.receiver_account_a = self.client_account.clone();
            }
            _ => (),
        }
        match &self.receiver_account_b {
            // Just use `client_account` as same account, swapping to self.
            None => {
                self.receiver_account_b = self.client_account.clone();
            }
            _ => (),
        }
        let pool_account_repr_sys =
            technical::Pallet::<T>::tech_account_id_to_account_id(&self.pool_account)?;
        // Check that pool account is valid.
        Pallet::<T>::is_pool_account_valid_for(self.destination.0.asset, &self.pool_account)?;

        // Balance of source account for k value.
        let balance_ks = PoolProviders::<T>::get(&pool_account_repr_sys, &source).unwrap_or(0);
        if balance_ks <= 0 {
            Err(Error::<T>::AccountBalanceIsInvalid)?;
        }

        // Balance of pool account for asset pair basic asset.
        let balance_bp =
            <assets::Pallet<T>>::free_balance(&self.destination.0.asset, &pool_account_repr_sys)?;
        // Balance of pool account for asset pair target asset.
        let balance_tp =
            <assets::Pallet<T>>::free_balance(&self.destination.1.asset, &pool_account_repr_sys)?;

        if balance_bp == 0 && balance_tp == 0 {
            Err(Error::<T>::PoolIsEmpty)?;
        } else if balance_bp <= 0 {
            Err(Error::<T>::PoolIsInvalid)?;
        } else if balance_tp <= 0 {
            Err(Error::<T>::PoolIsInvalid)?;
        }

        let fxw_balance_bp = FixedWrapper::from(balance_bp);
        let fxw_balance_tp = FixedWrapper::from(balance_tp);

        let total_iss =
            TotalIssuances::<T>::get(&pool_account_repr_sys).ok_or(Error::<T>::PoolIsInvalid)?;
        // Adding min liquidity to pretend that initial provider has locked amount, which actually is not reflected in total supply.
        let fxw_total_iss = FixedWrapper::from(total_iss) + MIN_LIQUIDITY;

        let has_enough_unlocked_liquidity =
            ceres_liquidity_locker::Pallet::<T>::check_if_has_enough_unlocked_liquidity(
                &source,
                self.destination.0.asset,
                self.destination.1.asset,
                self.pool_tokens,
            );
        ensure!(
            has_enough_unlocked_liquidity == true,
            Error::<T>::NotEnoughUnlockedLiquidity
        );

        let has_enough_liquidity_out_of_farming =
            demeter_farming_platform::Pallet::<T>::check_if_has_enough_liquidity_out_of_farming(
                source,
                self.destination.0.asset,
                self.destination.1.asset,
                self.pool_tokens,
            );
        ensure!(
            has_enough_liquidity_out_of_farming == true,
            Error::<T>::NotEnoughLiquidityOutOfFarming
        );

        ensure!(self.pool_tokens > 0, Error::<T>::ZeroValueInAmountParameter);

        if balance_ks < self.pool_tokens {
            Err(Error::<T>::SourceBalanceOfLiquidityTokensIsNotLargeEnough)?;
        }

        let (recom_x, recom_y) = if self.pool_tokens != total_iss {
            let fxw_source_k = FixedWrapper::from(self.pool_tokens);
            let fxw_recom_x = fxw_balance_bp * fxw_source_k.clone() / fxw_total_iss.clone();
            let fxw_recom_y = fxw_balance_tp * fxw_source_k / fxw_total_iss;
            (to_balance!(fxw_recom_x), to_balance!(fxw_recom_y))
        } else {
            (balance_bp, balance_tp)
        };
        match self.destination.0.amount {
            Bounds::Desired(x) => {
                if x != recom_x {
                    Err(Error::<T>::InvalidWithdrawLiquidityBasicAssetAmount)?;
                }
            }
            bounds => {
                let calc = Bounds::Calculated(recom_x);
                ensure!(
                    bounds.meets_the_boundaries(&calc),
                    Error::<T>::CalculatedValueIsNotMeetsRequiredBoundaries
                );
                self.destination.0.amount = calc;
            }
        }

        match self.destination.1.amount {
            Bounds::Desired(y) => {
                if y != recom_y {
                    Err(Error::<T>::InvalidWithdrawLiquidityTargetAssetAmount)?;
                }
            }
            bounds => {
                let calc = Bounds::Calculated(recom_y);
                ensure!(
                    bounds.meets_the_boundaries(&calc),
                    Error::<T>::CalculatedValueIsNotMeetsRequiredBoundaries
                );
                self.destination.1.amount = calc;
            }
        }

        // Get required values, now it is always Some, it is safe to unwrap().
        let _base_amount = self.destination.1.amount.unwrap();
        let _target_amount = self.destination.0.amount.unwrap();

        //TODO: Debug why in this place checking is failed, but in transfer checks is success.
        /*
        // Checking that balances if correct and large enough for amounts.
        if balance_bp < base_amount {
            Err(Error::<T>::DestinationBaseBalanceIsNotLargeEnough)?;
        }
        if balance_tp < target_amount {
            Err(Error::<T>::DestinationTargetBalanceIsNotLargeEnough)?;
        }
        */
        Ok(())
    }
    fn instant_auto_claim_used(&self) -> bool {
        true
    }
    fn triggered_auto_claim_used(&self) -> bool {
        false
    }
    fn is_able_to_claim(&self) -> bool {
        true
    }
}

impl<T: Config> common::SwapAction<AccountIdOf<T>, TechAccountIdOf<T>, AssetIdOf<T>, T>
    for WithdrawLiquidityAction<AssetIdOf<T>, AccountIdOf<T>, TechAccountIdOf<T>>
{
    fn reserve(&self, source: &AccountIdOf<T>, base_asset_id: &AssetIdOf<T>) -> DispatchResult {
        ensure!(
            Some(source) == self.client_account.as_ref(),
            Error::<T>::SourceAndClientAccountDoNotMatchAsEqual
        );
        let pool_account_repr_sys =
            technical::Pallet::<T>::tech_account_id_to_account_id(&self.pool_account)?;
        technical::Pallet::<T>::transfer_out(
            &self.destination.0.asset,
            &self.pool_account,
            self.receiver_account_a.as_ref().unwrap(),
            self.destination.0.amount.unwrap(),
        )?;
        technical::Pallet::<T>::transfer_out(
            &self.destination.1.asset,
            &self.pool_account,
            self.receiver_account_b.as_ref().unwrap(),
            self.destination.1.amount.unwrap(),
        )?;
        Pallet::<T>::burn(&pool_account_repr_sys, source, self.pool_tokens)?;
        // Pool tokens balance became zero while burned amount was actually non-zero.
        if Pallet::<T>::pool_providers(&pool_account_repr_sys, source)
            .unwrap_or(0)
            .is_zero()
            && !self.pool_tokens.is_zero()
        {
            let pair = Pallet::<T>::strict_sort_pair(
                base_asset_id,
                &self.destination.0.asset,
                &self.destination.1.asset,
            )?;
            AccountPools::<T>::mutate(source, &pair.base_asset_id, |set| {
                set.remove(&pair.target_asset_id)
            });
        }
        let balance_a =
            <assets::Pallet<T>>::free_balance(&self.destination.0.asset, &pool_account_repr_sys)?;
        let balance_b =
            <assets::Pallet<T>>::free_balance(&self.destination.1.asset, &pool_account_repr_sys)?;
        Pallet::<T>::update_reserves(
            base_asset_id,
            &self.destination.0.asset,
            &self.destination.1.asset,
            (&balance_a, &balance_b),
        );
        Ok(())
    }
    fn claim(&self, _source: &AccountIdOf<T>) -> bool {
        true
    }
    fn weight(&self) -> Weight {
        unimplemented!()
    }
    fn cancel(&self, _source: &AccountIdOf<T>) {
        unimplemented!()
    }
}