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
// This file is part of hydradx-traits.

// Copyright (C) 2020-2022  Intergalactic, Limited (GIB).
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::upper_case_acronyms)]

pub mod liquidity_mining;
pub mod nft;
pub mod pools;
pub mod registry;
pub mod router;

pub use registry::*;
pub mod oracle;
pub use oracle::*;

use codec::{Decode, Encode};
use frame_support::dispatch::{self, DispatchError};
use frame_support::sp_runtime::traits::Zero;
use frame_support::sp_runtime::RuntimeDebug;
use frame_support::traits::LockIdentifier;
use frame_support::weights::Weight;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_std::vec::Vec;

/// Hold information to perform amm transfer
/// Contains also exact amount which will be sold/bought
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
#[derive(RuntimeDebug, Encode, Decode, Copy, Clone, PartialEq, Eq, Default)]
pub struct AMMTransfer<AccountId, AssetId, AssetPair, Balance> {
    pub origin: AccountId,
    pub assets: AssetPair,
    pub amount: Balance,
    pub amount_b: Balance,
    pub discount: bool,
    pub discount_amount: Balance,
    pub fee: (AssetId, Balance),
}

/// Traits for handling AMM Pool trades.
pub trait AMM<AccountId, AssetId, AssetPair, Amount: Zero> {
    /// Check if both assets exist in a pool.
    fn exists(assets: AssetPair) -> bool;

    /// Return pair account.
    fn get_pair_id(assets: AssetPair) -> AccountId;

    /// Return share token for assets.
    fn get_share_token(assets: AssetPair) -> AssetId;

    /// Return list of active assets in a given pool.
    fn get_pool_assets(pool_account_id: &AccountId) -> Option<Vec<AssetId>>;

    /// Calculate spot price for asset a and b.
    fn get_spot_price_unchecked(asset_a: AssetId, asset_b: AssetId, amount: Amount) -> Amount;

    /// Sell trade validation
    /// Perform all necessary checks to validate an intended sale.
    fn validate_sell(
        origin: &AccountId,
        assets: AssetPair,
        amount: Amount,
        min_bought: Amount,
        discount: bool,
    ) -> Result<AMMTransfer<AccountId, AssetId, AssetPair, Amount>, frame_support::sp_runtime::DispatchError>;

    /// Execute buy for given validated transfer.
    fn execute_sell(transfer: &AMMTransfer<AccountId, AssetId, AssetPair, Amount>) -> dispatch::DispatchResult;

    /// Perform asset swap.
    /// Call execute following the validation.
    fn sell(
        origin: &AccountId,
        assets: AssetPair,
        amount: Amount,
        min_bought: Amount,
        discount: bool,
    ) -> dispatch::DispatchResult {
        Self::execute_sell(&Self::validate_sell(origin, assets, amount, min_bought, discount)?)?;
        Ok(())
    }

    /// Buy trade validation
    /// Perform all necessary checks to validate an intended buy.
    fn validate_buy(
        origin: &AccountId,
        assets: AssetPair,
        amount: Amount,
        max_limit: Amount,
        discount: bool,
    ) -> Result<AMMTransfer<AccountId, AssetId, AssetPair, Amount>, frame_support::sp_runtime::DispatchError>;

    /// Execute buy for given validated transfer.
    fn execute_buy(transfer: &AMMTransfer<AccountId, AssetId, AssetPair, Amount>) -> dispatch::DispatchResult;

    /// Perform asset swap.
    fn buy(
        origin: &AccountId,
        assets: AssetPair,
        amount: Amount,
        max_limit: Amount,
        discount: bool,
    ) -> dispatch::DispatchResult {
        Self::execute_buy(&Self::validate_buy(origin, assets, amount, max_limit, discount)?)?;
        Ok(())
    }

    fn get_min_trading_limit() -> Amount;

    fn get_min_pool_liquidity() -> Amount;

    fn get_max_in_ratio() -> u128;

    fn get_max_out_ratio() -> u128;

    fn get_fee(pool_account_id: &AccountId) -> (u32, u32);
}

pub trait Resolver<AccountId, Intention, E> {
    /// Resolve an intention directl via AMM pool.
    fn resolve_single_intention(intention: &Intention);

    /// Resolve intentions by either directly trading with each other or via AMM pool.
    /// Intention ```intention``` must be validated prior to call this function.
    fn resolve_matched_intentions(pair_account: &AccountId, intention: &Intention, matched: &[&Intention]);
}

/// Handler used by AMM pools to perform some tasks when a new pool is created.
pub trait OnCreatePoolHandler<AssetId> {
    /// Register an asset to be handled by price-oracle pallet.
    /// If an asset is not registered, calling `on_trade` results in populating the price buffer in the price oracle pallet,
    /// but the entries are ignored and the average price for the asset is not calculated.
    fn on_create_pool(asset_a: AssetId, asset_b: AssetId) -> dispatch::DispatchResult;
}

impl<AssetId> OnCreatePoolHandler<AssetId> for () {
    fn on_create_pool(_asset_a: AssetId, _asset_b: AssetId) -> dispatch::DispatchResult {
        Ok(())
    }
}

/// Handler used by AMM pools to perform some tasks when a trade is executed.
pub trait OnTradeHandler<AssetId, Balance> {
    /// Include a trade in the average price calculation of the price-oracle pallet.
    fn on_trade(
        source: Source,
        asset_a: AssetId,
        asset_b: AssetId,
        amount_a: Balance,
        amount_b: Balance,
        liquidity_a: Balance,
        liquidity_b: Balance,
    ) -> Result<Weight, (Weight, DispatchError)>;
    /// Known overhead for a trade in `on_initialize/on_finalize`.
    /// Needs to be specified here if we don't want to make AMM pools tightly coupled with the price oracle pallet, otherwise we can't access the weight.
    /// Add this weight to an extrinsic from which you call `on_trade`.
    fn on_trade_weight() -> Weight;
}

impl<AssetId, Balance> OnTradeHandler<AssetId, Balance> for () {
    fn on_trade(
        _source: Source,
        _asset_a: AssetId,
        _asset_b: AssetId,
        _amount_a: Balance,
        _amount_b: Balance,
        _liquidity_a: Balance,
        _liquidity_b: Balance,
    ) -> Result<Weight, (Weight, DispatchError)> {
        Ok(Weight::zero())
    }
    fn on_trade_weight() -> Weight {
        Weight::zero()
    }
}

pub trait CanCreatePool<AssetId> {
    fn can_create(asset_a: AssetId, asset_b: AssetId) -> bool;
}

pub trait LockedBalance<AssetId, AccountId, Balance> {
    fn get_by_lock(lock_id: LockIdentifier, currency_id: AssetId, who: AccountId) -> Balance;
}

/// Handler used by AMM pools to perform some tasks when liquidity changes outside of trades.
pub trait OnLiquidityChangedHandler<AssetId, Balance> {
    /// Notify that the liquidity for a pair of assets has changed.
    fn on_liquidity_changed(
        source: Source,
        asset_a: AssetId,
        asset_b: AssetId,
        amount_a: Balance,
        amount_b: Balance,
        liquidity_a: Balance,
        liquidity_b: Balance,
    ) -> Result<Weight, (Weight, DispatchError)>;
    /// Known overhead for a liquidity change in `on_initialize/on_finalize`.
    /// Needs to be specified here if we don't want to make AMM pools tightly coupled with the price oracle pallet, otherwise we can't access the weight.
    /// Add this weight to an extrinsic from which you call `on_liquidity_changed`.
    fn on_liquidity_changed_weight() -> Weight;
}

impl<AssetId, Balance> OnLiquidityChangedHandler<AssetId, Balance> for () {
    fn on_liquidity_changed(
        _source: Source,
        _a: AssetId,
        _b: AssetId,
        _amount_a: Balance,
        _amount_b: Balance,
        _liq_a: Balance,
        _liq_b: Balance,
    ) -> Result<Weight, (Weight, DispatchError)> {
        Ok(Weight::zero())
    }

    fn on_liquidity_changed_weight() -> Weight {
        Weight::zero()
    }
}

/// Implementers of this trait provides information about user's position in the AMM pool.
pub trait AMMPosition<AssetId, Balance> {
    type Error;

    /// This function calculates amount of assets behind the `share_token`s.
    fn get_liquidity_behind_shares(
        asset_a: AssetId,
        asset_b: AssetId,
        shares_amount: Balance,
    ) -> Result<(Balance, Balance), Self::Error>;
}