#![deny(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
#[cfg(test)]
mod mock;
mod swap;
#[cfg(test)]
mod tests;
mod types;
pub mod weights;
#[cfg(feature = "runtime-benchmarks")]
pub use benchmarking::{BenchmarkHelper, NativeOrWithIdFactory};
pub use pallet::*;
pub use swap::*;
pub use types::*;
pub use weights::WeightInfo;
extern crate alloc;
use alloc::{boxed::Box, collections::btree_set::BTreeSet, vec::Vec};
use codec::Codec;
use frame_support::{
storage::{with_storage_layer, with_transaction},
traits::{
fungibles::{Balanced, Create, Credit, Inspect, Mutate},
tokens::{
AssetId, Balance,
Fortitude::Polite,
Precision::Exact,
Preservation::{Expendable, Preserve},
},
AccountTouch, Incrementable, OnUnbalanced,
},
PalletId,
};
use sp_core::Get;
use sp_runtime::{
traits::{
CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, Ensure, IntegerSquareRoot, MaybeDisplay,
One, TrailingZeroInput, Zero,
},
DispatchError, Saturating, TokenError, TransactionOutcome,
};
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::{
pallet_prelude::{DispatchResult, *},
traits::fungibles::Refund,
};
use frame_system::pallet_prelude::*;
use sp_arithmetic::{traits::Unsigned, Permill};
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type Balance: Balance;
type HigherPrecisionBalance: IntegerSquareRoot
+ One
+ Ensure
+ Unsigned
+ From<u32>
+ From<Self::Balance>
+ TryInto<Self::Balance>;
type AssetKind: Parameter + MaxEncodedLen;
type Assets: Inspect<Self::AccountId, AssetId = Self::AssetKind, Balance = Self::Balance>
+ Mutate<Self::AccountId>
+ AccountTouch<Self::AssetKind, Self::AccountId, Balance = Self::Balance>
+ Balanced<Self::AccountId>
+ Refund<Self::AccountId, AssetId = Self::AssetKind>;
type PoolId: Parameter + MaxEncodedLen + Ord;
type PoolLocator: PoolLocator<Self::AccountId, Self::AssetKind, Self::PoolId>;
type PoolAssetId: AssetId + PartialOrd + Incrementable + From<u32>;
type PoolAssets: Inspect<Self::AccountId, AssetId = Self::PoolAssetId, Balance = Self::Balance>
+ Create<Self::AccountId>
+ Mutate<Self::AccountId>
+ AccountTouch<Self::PoolAssetId, Self::AccountId, Balance = Self::Balance>
+ Refund<Self::AccountId, AssetId = Self::PoolAssetId>;
#[pallet::constant]
type LPFee: Get<u32>;
#[pallet::constant]
type PoolSetupFee: Get<Self::Balance>;
#[pallet::constant]
type PoolSetupFeeAsset: Get<Self::AssetKind>;
type PoolSetupFeeTarget: OnUnbalanced<CreditOf<Self>>;
#[pallet::constant]
type LiquidityWithdrawalFee: Get<Permill>;
#[pallet::constant]
type MintMinLiquidity: Get<Self::Balance>;
#[pallet::constant]
type MaxSwapPathLength: Get<u32>;
#[pallet::constant]
type PalletId: Get<PalletId>;
type WeightInfo: WeightInfo;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper: BenchmarkHelper<Self::AssetKind>;
}
#[pallet::storage]
pub type Pools<T: Config> =
StorageMap<_, Blake2_128Concat, T::PoolId, PoolInfo<T::PoolAssetId>, OptionQuery>;
#[pallet::storage]
pub type NextPoolAssetId<T: Config> = StorageValue<_, T::PoolAssetId, OptionQuery>;
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
PoolCreated {
creator: T::AccountId,
pool_id: T::PoolId,
pool_account: T::AccountId,
lp_token: T::PoolAssetId,
},
LiquidityAdded {
who: T::AccountId,
mint_to: T::AccountId,
pool_id: T::PoolId,
amount1_provided: T::Balance,
amount2_provided: T::Balance,
lp_token: T::PoolAssetId,
lp_token_minted: T::Balance,
},
LiquidityRemoved {
who: T::AccountId,
withdraw_to: T::AccountId,
pool_id: T::PoolId,
amount1: T::Balance,
amount2: T::Balance,
lp_token: T::PoolAssetId,
lp_token_burned: T::Balance,
withdrawal_fee: Permill,
},
SwapExecuted {
who: T::AccountId,
send_to: T::AccountId,
amount_in: T::Balance,
amount_out: T::Balance,
path: BalancePath<T>,
},
SwapCreditExecuted {
amount_in: T::Balance,
amount_out: T::Balance,
path: BalancePath<T>,
},
Touched {
pool_id: T::PoolId,
who: T::AccountId,
},
}
#[pallet::error]
pub enum Error<T> {
InvalidAssetPair,
PoolExists,
WrongDesiredAmount,
AmountOneLessThanMinimal,
AmountTwoLessThanMinimal,
ReserveLeftLessThanMinimal,
AmountOutTooHigh,
PoolNotFound,
Overflow,
AssetOneDepositDidNotMeetMinimum,
AssetTwoDepositDidNotMeetMinimum,
AssetOneWithdrawalDidNotMeetMinimum,
AssetTwoWithdrawalDidNotMeetMinimum,
OptimalAmountLessThanDesired,
InsufficientLiquidityMinted,
ZeroLiquidity,
ZeroAmount,
ProvidedMinimumNotSufficientForSwap,
ProvidedMaximumNotSufficientForSwap,
InvalidPath,
NonUniquePath,
IncorrectPoolAssetId,
BelowMinimum,
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn integrity_test() {
assert!(
T::MaxSwapPathLength::get() > 1,
"the `MaxSwapPathLength` should be greater than 1",
);
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::create_pool())]
pub fn create_pool(
origin: OriginFor<T>,
asset1: Box<T::AssetKind>,
asset2: Box<T::AssetKind>,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
ensure!(asset1 != asset2, Error::<T>::InvalidAssetPair);
let pool_id = T::PoolLocator::pool_id(&asset1, &asset2)
.map_err(|_| Error::<T>::InvalidAssetPair)?;
ensure!(!Pools::<T>::contains_key(&pool_id), Error::<T>::PoolExists);
let pool_account =
T::PoolLocator::address(&pool_id).map_err(|_| Error::<T>::InvalidAssetPair)?;
let fee =
Self::withdraw(T::PoolSetupFeeAsset::get(), &sender, T::PoolSetupFee::get(), true)?;
T::PoolSetupFeeTarget::on_unbalanced(fee);
if T::Assets::should_touch(*asset1.clone(), &pool_account) {
T::Assets::touch(*asset1, &pool_account, &sender)?
};
if T::Assets::should_touch(*asset2.clone(), &pool_account) {
T::Assets::touch(*asset2, &pool_account, &sender)?
};
let lp_token = NextPoolAssetId::<T>::get()
.or(T::PoolAssetId::initial_value())
.ok_or(Error::<T>::IncorrectPoolAssetId)?;
let next_lp_token_id = lp_token.increment().ok_or(Error::<T>::IncorrectPoolAssetId)?;
NextPoolAssetId::<T>::set(Some(next_lp_token_id));
T::PoolAssets::create(lp_token.clone(), pool_account.clone(), false, 1u32.into())?;
if T::PoolAssets::should_touch(lp_token.clone(), &pool_account) {
T::PoolAssets::touch(lp_token.clone(), &pool_account, &sender)?
};
let pool_info = PoolInfo { lp_token: lp_token.clone() };
Pools::<T>::insert(pool_id.clone(), pool_info);
Self::deposit_event(Event::PoolCreated {
creator: sender,
pool_id,
pool_account,
lp_token,
});
Ok(())
}
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::add_liquidity())]
pub fn add_liquidity(
origin: OriginFor<T>,
asset1: Box<T::AssetKind>,
asset2: Box<T::AssetKind>,
amount1_desired: T::Balance,
amount2_desired: T::Balance,
amount1_min: T::Balance,
amount2_min: T::Balance,
mint_to: T::AccountId,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
let pool_id = T::PoolLocator::pool_id(&asset1, &asset2)
.map_err(|_| Error::<T>::InvalidAssetPair)?;
ensure!(
amount1_desired > Zero::zero() && amount2_desired > Zero::zero(),
Error::<T>::WrongDesiredAmount
);
let pool = Pools::<T>::get(&pool_id).ok_or(Error::<T>::PoolNotFound)?;
let pool_account =
T::PoolLocator::address(&pool_id).map_err(|_| Error::<T>::InvalidAssetPair)?;
let reserve1 = Self::get_balance(&pool_account, *asset1.clone());
let reserve2 = Self::get_balance(&pool_account, *asset2.clone());
let amount1: T::Balance;
let amount2: T::Balance;
if reserve1.is_zero() || reserve2.is_zero() {
amount1 = amount1_desired;
amount2 = amount2_desired;
} else {
let amount2_optimal = Self::quote(&amount1_desired, &reserve1, &reserve2)?;
if amount2_optimal <= amount2_desired {
ensure!(
amount2_optimal >= amount2_min,
Error::<T>::AssetTwoDepositDidNotMeetMinimum
);
amount1 = amount1_desired;
amount2 = amount2_optimal;
} else {
let amount1_optimal = Self::quote(&amount2_desired, &reserve2, &reserve1)?;
ensure!(
amount1_optimal <= amount1_desired,
Error::<T>::OptimalAmountLessThanDesired
);
ensure!(
amount1_optimal >= amount1_min,
Error::<T>::AssetOneDepositDidNotMeetMinimum
);
amount1 = amount1_optimal;
amount2 = amount2_desired;
}
}
ensure!(
amount1.saturating_add(reserve1) >= T::Assets::minimum_balance(*asset1.clone()),
Error::<T>::AmountOneLessThanMinimal
);
ensure!(
amount2.saturating_add(reserve2) >= T::Assets::minimum_balance(*asset2.clone()),
Error::<T>::AmountTwoLessThanMinimal
);
T::Assets::transfer(*asset1, &sender, &pool_account, amount1, Preserve)?;
T::Assets::transfer(*asset2, &sender, &pool_account, amount2, Preserve)?;
let total_supply = T::PoolAssets::total_issuance(pool.lp_token.clone());
let lp_token_amount: T::Balance;
if total_supply.is_zero() {
lp_token_amount = Self::calc_lp_amount_for_zero_supply(&amount1, &amount2)?;
T::PoolAssets::mint_into(
pool.lp_token.clone(),
&pool_account,
T::MintMinLiquidity::get(),
)?;
} else {
let side1 = Self::mul_div(&amount1, &total_supply, &reserve1)?;
let side2 = Self::mul_div(&amount2, &total_supply, &reserve2)?;
lp_token_amount = side1.min(side2);
}
ensure!(
lp_token_amount > T::MintMinLiquidity::get(),
Error::<T>::InsufficientLiquidityMinted
);
T::PoolAssets::mint_into(pool.lp_token.clone(), &mint_to, lp_token_amount)?;
Self::deposit_event(Event::LiquidityAdded {
who: sender,
mint_to,
pool_id,
amount1_provided: amount1,
amount2_provided: amount2,
lp_token: pool.lp_token,
lp_token_minted: lp_token_amount,
});
Ok(())
}
#[pallet::call_index(2)]
#[pallet::weight(T::WeightInfo::remove_liquidity())]
pub fn remove_liquidity(
origin: OriginFor<T>,
asset1: Box<T::AssetKind>,
asset2: Box<T::AssetKind>,
lp_token_burn: T::Balance,
amount1_min_receive: T::Balance,
amount2_min_receive: T::Balance,
withdraw_to: T::AccountId,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
let pool_id = T::PoolLocator::pool_id(&asset1, &asset2)
.map_err(|_| Error::<T>::InvalidAssetPair)?;
ensure!(lp_token_burn > Zero::zero(), Error::<T>::ZeroLiquidity);
let pool = Pools::<T>::get(&pool_id).ok_or(Error::<T>::PoolNotFound)?;
let pool_account =
T::PoolLocator::address(&pool_id).map_err(|_| Error::<T>::InvalidAssetPair)?;
let reserve1 = Self::get_balance(&pool_account, *asset1.clone());
let reserve2 = Self::get_balance(&pool_account, *asset2.clone());
let total_supply = T::PoolAssets::total_issuance(pool.lp_token.clone());
let withdrawal_fee_amount = T::LiquidityWithdrawalFee::get() * lp_token_burn;
let lp_redeem_amount = lp_token_burn.saturating_sub(withdrawal_fee_amount);
let amount1 = Self::mul_div(&lp_redeem_amount, &reserve1, &total_supply)?;
let amount2 = Self::mul_div(&lp_redeem_amount, &reserve2, &total_supply)?;
ensure!(
!amount1.is_zero() && amount1 >= amount1_min_receive,
Error::<T>::AssetOneWithdrawalDidNotMeetMinimum
);
ensure!(
!amount2.is_zero() && amount2 >= amount2_min_receive,
Error::<T>::AssetTwoWithdrawalDidNotMeetMinimum
);
let reserve1_left = reserve1.saturating_sub(amount1);
let reserve2_left = reserve2.saturating_sub(amount2);
ensure!(
reserve1_left >= T::Assets::minimum_balance(*asset1.clone()),
Error::<T>::ReserveLeftLessThanMinimal
);
ensure!(
reserve2_left >= T::Assets::minimum_balance(*asset2.clone()),
Error::<T>::ReserveLeftLessThanMinimal
);
T::PoolAssets::burn_from(
pool.lp_token.clone(),
&sender,
lp_token_burn,
Expendable,
Exact,
Polite,
)?;
T::Assets::transfer(*asset1, &pool_account, &withdraw_to, amount1, Expendable)?;
T::Assets::transfer(*asset2, &pool_account, &withdraw_to, amount2, Expendable)?;
Self::deposit_event(Event::LiquidityRemoved {
who: sender,
withdraw_to,
pool_id,
amount1,
amount2,
lp_token: pool.lp_token,
lp_token_burned: lp_token_burn,
withdrawal_fee: T::LiquidityWithdrawalFee::get(),
});
Ok(())
}
#[pallet::call_index(3)]
#[pallet::weight(T::WeightInfo::swap_exact_tokens_for_tokens(path.len() as u32))]
pub fn swap_exact_tokens_for_tokens(
origin: OriginFor<T>,
path: Vec<Box<T::AssetKind>>,
amount_in: T::Balance,
amount_out_min: T::Balance,
send_to: T::AccountId,
keep_alive: bool,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
Self::do_swap_exact_tokens_for_tokens(
sender,
path.into_iter().map(|a| *a).collect(),
amount_in,
Some(amount_out_min),
send_to,
keep_alive,
)?;
Ok(())
}
#[pallet::call_index(4)]
#[pallet::weight(T::WeightInfo::swap_tokens_for_exact_tokens(path.len() as u32))]
pub fn swap_tokens_for_exact_tokens(
origin: OriginFor<T>,
path: Vec<Box<T::AssetKind>>,
amount_out: T::Balance,
amount_in_max: T::Balance,
send_to: T::AccountId,
keep_alive: bool,
) -> DispatchResult {
let sender = ensure_signed(origin)?;
Self::do_swap_tokens_for_exact_tokens(
sender,
path.into_iter().map(|a| *a).collect(),
amount_out,
Some(amount_in_max),
send_to,
keep_alive,
)?;
Ok(())
}
#[pallet::call_index(5)]
#[pallet::weight(T::WeightInfo::touch(3))]
pub fn touch(
origin: OriginFor<T>,
asset1: Box<T::AssetKind>,
asset2: Box<T::AssetKind>,
) -> DispatchResultWithPostInfo {
let who = ensure_signed(origin)?;
let pool_id = T::PoolLocator::pool_id(&asset1, &asset2)
.map_err(|_| Error::<T>::InvalidAssetPair)?;
let pool = Pools::<T>::get(&pool_id).ok_or(Error::<T>::PoolNotFound)?;
let pool_account =
T::PoolLocator::address(&pool_id).map_err(|_| Error::<T>::InvalidAssetPair)?;
let mut refunds_number: u32 = 0;
if T::Assets::should_touch(*asset1.clone(), &pool_account) {
T::Assets::touch(*asset1, &pool_account, &who)?;
refunds_number += 1;
}
if T::Assets::should_touch(*asset2.clone(), &pool_account) {
T::Assets::touch(*asset2, &pool_account, &who)?;
refunds_number += 1;
}
if T::PoolAssets::should_touch(pool.lp_token.clone(), &pool_account) {
T::PoolAssets::touch(pool.lp_token, &pool_account, &who)?;
refunds_number += 1;
}
Self::deposit_event(Event::Touched { pool_id, who });
Ok(Some(T::WeightInfo::touch(refunds_number)).into())
}
}
impl<T: Config> Pallet<T> {
pub(crate) fn do_swap_exact_tokens_for_tokens(
sender: T::AccountId,
path: Vec<T::AssetKind>,
amount_in: T::Balance,
amount_out_min: Option<T::Balance>,
send_to: T::AccountId,
keep_alive: bool,
) -> Result<T::Balance, DispatchError> {
ensure!(amount_in > Zero::zero(), Error::<T>::ZeroAmount);
if let Some(amount_out_min) = amount_out_min {
ensure!(amount_out_min > Zero::zero(), Error::<T>::ZeroAmount);
}
Self::validate_swap_path(&path)?;
let path = Self::balance_path_from_amount_in(amount_in, path)?;
let amount_out = path.last().map(|(_, a)| *a).ok_or(Error::<T>::InvalidPath)?;
if let Some(amount_out_min) = amount_out_min {
ensure!(
amount_out >= amount_out_min,
Error::<T>::ProvidedMinimumNotSufficientForSwap
);
}
Self::swap(&sender, &path, &send_to, keep_alive)?;
Self::deposit_event(Event::SwapExecuted {
who: sender,
send_to,
amount_in,
amount_out,
path,
});
Ok(amount_out)
}
pub(crate) fn do_swap_tokens_for_exact_tokens(
sender: T::AccountId,
path: Vec<T::AssetKind>,
amount_out: T::Balance,
amount_in_max: Option<T::Balance>,
send_to: T::AccountId,
keep_alive: bool,
) -> Result<T::Balance, DispatchError> {
ensure!(amount_out > Zero::zero(), Error::<T>::ZeroAmount);
if let Some(amount_in_max) = amount_in_max {
ensure!(amount_in_max > Zero::zero(), Error::<T>::ZeroAmount);
}
Self::validate_swap_path(&path)?;
let path = Self::balance_path_from_amount_out(amount_out, path)?;
let amount_in = path.first().map(|(_, a)| *a).ok_or(Error::<T>::InvalidPath)?;
if let Some(amount_in_max) = amount_in_max {
ensure!(
amount_in <= amount_in_max,
Error::<T>::ProvidedMaximumNotSufficientForSwap
);
}
Self::swap(&sender, &path, &send_to, keep_alive)?;
Self::deposit_event(Event::SwapExecuted {
who: sender,
send_to,
amount_in,
amount_out,
path,
});
Ok(amount_in)
}
pub(crate) fn do_swap_exact_credit_tokens_for_tokens(
path: Vec<T::AssetKind>,
credit_in: CreditOf<T>,
amount_out_min: Option<T::Balance>,
) -> Result<CreditOf<T>, (CreditOf<T>, DispatchError)> {
let amount_in = credit_in.peek();
let inspect_path = |credit_asset| {
ensure!(
path.first().map_or(false, |a| *a == credit_asset),
Error::<T>::InvalidPath
);
ensure!(!amount_in.is_zero(), Error::<T>::ZeroAmount);
ensure!(amount_out_min.map_or(true, |a| !a.is_zero()), Error::<T>::ZeroAmount);
Self::validate_swap_path(&path)?;
let path = Self::balance_path_from_amount_in(amount_in, path)?;
let amount_out = path.last().map(|(_, a)| *a).ok_or(Error::<T>::InvalidPath)?;
ensure!(
amount_out_min.map_or(true, |a| amount_out >= a),
Error::<T>::ProvidedMinimumNotSufficientForSwap
);
Ok((path, amount_out))
};
let (path, amount_out) = match inspect_path(credit_in.asset()) {
Ok((p, a)) => (p, a),
Err(e) => return Err((credit_in, e)),
};
let credit_out = Self::credit_swap(credit_in, &path)?;
Self::deposit_event(Event::SwapCreditExecuted { amount_in, amount_out, path });
Ok(credit_out)
}
pub(crate) fn do_swap_credit_tokens_for_exact_tokens(
path: Vec<T::AssetKind>,
credit_in: CreditOf<T>,
amount_out: T::Balance,
) -> Result<(CreditOf<T>, CreditOf<T>), (CreditOf<T>, DispatchError)> {
let amount_in_max = credit_in.peek();
let inspect_path = |credit_asset| {
ensure!(
path.first().map_or(false, |a| a == &credit_asset),
Error::<T>::InvalidPath
);
ensure!(amount_in_max > Zero::zero(), Error::<T>::ZeroAmount);
ensure!(amount_out > Zero::zero(), Error::<T>::ZeroAmount);
Self::validate_swap_path(&path)?;
let path = Self::balance_path_from_amount_out(amount_out, path)?;
let amount_in = path.first().map(|(_, a)| *a).ok_or(Error::<T>::InvalidPath)?;
ensure!(
amount_in <= amount_in_max,
Error::<T>::ProvidedMaximumNotSufficientForSwap
);
Ok((path, amount_in))
};
let (path, amount_in) = match inspect_path(credit_in.asset()) {
Ok((p, a)) => (p, a),
Err(e) => return Err((credit_in, e)),
};
let (credit_in, credit_change) = credit_in.split(amount_in);
let credit_out = Self::credit_swap(credit_in, &path)?;
Self::deposit_event(Event::SwapCreditExecuted { amount_in, amount_out, path });
Ok((credit_out, credit_change))
}
fn swap(
sender: &T::AccountId,
path: &BalancePath<T>,
send_to: &T::AccountId,
keep_alive: bool,
) -> Result<(), DispatchError> {
let (asset_in, amount_in) = path.first().ok_or(Error::<T>::InvalidPath)?;
let credit_in = Self::withdraw(asset_in.clone(), sender, *amount_in, keep_alive)?;
let credit_out = Self::credit_swap(credit_in, path).map_err(|(_, e)| e)?;
T::Assets::resolve(send_to, credit_out).map_err(|_| Error::<T>::BelowMinimum)?;
Ok(())
}
fn credit_swap(
credit_in: CreditOf<T>,
path: &BalancePath<T>,
) -> Result<CreditOf<T>, (CreditOf<T>, DispatchError)> {
let resolve_path = || -> Result<CreditOf<T>, DispatchError> {
for pos in 0..=path.len() {
if let Some([(asset1, _), (asset2, amount_out)]) = path.get(pos..=pos + 1) {
let pool_from = T::PoolLocator::pool_address(asset1, asset2)
.map_err(|_| Error::<T>::InvalidAssetPair)?;
if let Some((asset3, _)) = path.get(pos + 2) {
let pool_to = T::PoolLocator::pool_address(asset2, asset3)
.map_err(|_| Error::<T>::InvalidAssetPair)?;
T::Assets::transfer(
asset2.clone(),
&pool_from,
&pool_to,
*amount_out,
Preserve,
)?;
} else {
let credit_out =
Self::withdraw(asset2.clone(), &pool_from, *amount_out, true)?;
return Ok(credit_out)
}
}
}
Err(Error::<T>::InvalidPath.into())
};
let credit_out = match resolve_path() {
Ok(c) => c,
Err(e) => return Err((credit_in, e)),
};
let pool_to = if let Some([(asset1, _), (asset2, _)]) = path.get(0..2) {
match T::PoolLocator::pool_address(asset1, asset2) {
Ok(address) => address,
Err(_) => return Err((credit_in, Error::<T>::InvalidAssetPair.into())),
}
} else {
return Err((credit_in, Error::<T>::InvalidPath.into()))
};
T::Assets::resolve(&pool_to, credit_in)
.map_err(|c| (c, Error::<T>::BelowMinimum.into()))?;
Ok(credit_out)
}
fn withdraw(
asset: T::AssetKind,
who: &T::AccountId,
value: T::Balance,
keep_alive: bool,
) -> Result<CreditOf<T>, DispatchError> {
let preservation = match keep_alive {
true => Preserve,
false => Expendable,
};
if preservation == Preserve {
let free = T::Assets::reducible_balance(asset.clone(), who, preservation, Polite);
ensure!(free >= value, TokenError::NotExpendable);
}
T::Assets::withdraw(asset, who, value, Exact, preservation, Polite)
}
fn get_balance(owner: &T::AccountId, asset: T::AssetKind) -> T::Balance {
T::Assets::reducible_balance(asset, owner, Expendable, Polite)
}
pub fn get_reserves(
asset1: T::AssetKind,
asset2: T::AssetKind,
) -> Result<(T::Balance, T::Balance), Error<T>> {
let pool_account = T::PoolLocator::pool_address(&asset1, &asset2)
.map_err(|_| Error::<T>::InvalidAssetPair)?;
let balance1 = Self::get_balance(&pool_account, asset1);
let balance2 = Self::get_balance(&pool_account, asset2);
if balance1.is_zero() || balance2.is_zero() {
Err(Error::<T>::PoolNotFound)?;
}
Ok((balance1, balance2))
}
pub(crate) fn balance_path_from_amount_out(
amount_out: T::Balance,
path: Vec<T::AssetKind>,
) -> Result<BalancePath<T>, DispatchError> {
let mut balance_path: BalancePath<T> = Vec::with_capacity(path.len());
let mut amount_in: T::Balance = amount_out;
let mut iter = path.into_iter().rev().peekable();
while let Some(asset2) = iter.next() {
let asset1 = match iter.peek() {
Some(a) => a,
None => {
balance_path.push((asset2, amount_in));
break
},
};
let (reserve_in, reserve_out) = Self::get_reserves(asset1.clone(), asset2.clone())?;
balance_path.push((asset2, amount_in));
amount_in = Self::get_amount_in(&amount_in, &reserve_in, &reserve_out)?;
}
balance_path.reverse();
Ok(balance_path)
}
pub(crate) fn balance_path_from_amount_in(
amount_in: T::Balance,
path: Vec<T::AssetKind>,
) -> Result<BalancePath<T>, DispatchError> {
let mut balance_path: BalancePath<T> = Vec::with_capacity(path.len());
let mut amount_out: T::Balance = amount_in;
let mut iter = path.into_iter().peekable();
while let Some(asset1) = iter.next() {
let asset2 = match iter.peek() {
Some(a) => a,
None => {
balance_path.push((asset1, amount_out));
break
},
};
let (reserve_in, reserve_out) = Self::get_reserves(asset1.clone(), asset2.clone())?;
balance_path.push((asset1, amount_out));
amount_out = Self::get_amount_out(&amount_out, &reserve_in, &reserve_out)?;
}
Ok(balance_path)
}
pub fn quote_price_exact_tokens_for_tokens(
asset1: T::AssetKind,
asset2: T::AssetKind,
amount: T::Balance,
include_fee: bool,
) -> Option<T::Balance> {
let pool_account = T::PoolLocator::pool_address(&asset1, &asset2).ok()?;
let balance1 = Self::get_balance(&pool_account, asset1);
let balance2 = Self::get_balance(&pool_account, asset2);
if !balance1.is_zero() {
if include_fee {
Self::get_amount_out(&amount, &balance1, &balance2).ok()
} else {
Self::quote(&amount, &balance1, &balance2).ok()
}
} else {
None
}
}
pub fn quote_price_tokens_for_exact_tokens(
asset1: T::AssetKind,
asset2: T::AssetKind,
amount: T::Balance,
include_fee: bool,
) -> Option<T::Balance> {
let pool_account = T::PoolLocator::pool_address(&asset1, &asset2).ok()?;
let balance1 = Self::get_balance(&pool_account, asset1);
let balance2 = Self::get_balance(&pool_account, asset2);
if !balance1.is_zero() {
if include_fee {
Self::get_amount_in(&amount, &balance1, &balance2).ok()
} else {
Self::quote(&amount, &balance2, &balance1).ok()
}
} else {
None
}
}
pub fn quote(
amount: &T::Balance,
reserve1: &T::Balance,
reserve2: &T::Balance,
) -> Result<T::Balance, Error<T>> {
Self::mul_div(amount, reserve2, reserve1)
}
pub(super) fn calc_lp_amount_for_zero_supply(
amount1: &T::Balance,
amount2: &T::Balance,
) -> Result<T::Balance, Error<T>> {
let amount1 = T::HigherPrecisionBalance::from(*amount1);
let amount2 = T::HigherPrecisionBalance::from(*amount2);
let result = amount1
.checked_mul(&amount2)
.ok_or(Error::<T>::Overflow)?
.integer_sqrt()
.checked_sub(&T::MintMinLiquidity::get().into())
.ok_or(Error::<T>::InsufficientLiquidityMinted)?;
result.try_into().map_err(|_| Error::<T>::Overflow)
}
fn mul_div(a: &T::Balance, b: &T::Balance, c: &T::Balance) -> Result<T::Balance, Error<T>> {
let a = T::HigherPrecisionBalance::from(*a);
let b = T::HigherPrecisionBalance::from(*b);
let c = T::HigherPrecisionBalance::from(*c);
let result = a
.checked_mul(&b)
.ok_or(Error::<T>::Overflow)?
.checked_div(&c)
.ok_or(Error::<T>::Overflow)?;
result.try_into().map_err(|_| Error::<T>::Overflow)
}
pub fn get_amount_out(
amount_in: &T::Balance,
reserve_in: &T::Balance,
reserve_out: &T::Balance,
) -> Result<T::Balance, Error<T>> {
let amount_in = T::HigherPrecisionBalance::from(*amount_in);
let reserve_in = T::HigherPrecisionBalance::from(*reserve_in);
let reserve_out = T::HigherPrecisionBalance::from(*reserve_out);
if reserve_in.is_zero() || reserve_out.is_zero() {
return Err(Error::<T>::ZeroLiquidity)
}
let amount_in_with_fee = amount_in
.checked_mul(&(T::HigherPrecisionBalance::from(1000u32) - (T::LPFee::get().into())))
.ok_or(Error::<T>::Overflow)?;
let numerator =
amount_in_with_fee.checked_mul(&reserve_out).ok_or(Error::<T>::Overflow)?;
let denominator = reserve_in
.checked_mul(&1000u32.into())
.ok_or(Error::<T>::Overflow)?
.checked_add(&amount_in_with_fee)
.ok_or(Error::<T>::Overflow)?;
let result = numerator.checked_div(&denominator).ok_or(Error::<T>::Overflow)?;
result.try_into().map_err(|_| Error::<T>::Overflow)
}
pub fn get_amount_in(
amount_out: &T::Balance,
reserve_in: &T::Balance,
reserve_out: &T::Balance,
) -> Result<T::Balance, Error<T>> {
let amount_out = T::HigherPrecisionBalance::from(*amount_out);
let reserve_in = T::HigherPrecisionBalance::from(*reserve_in);
let reserve_out = T::HigherPrecisionBalance::from(*reserve_out);
if reserve_in.is_zero() || reserve_out.is_zero() {
Err(Error::<T>::ZeroLiquidity)?
}
if amount_out >= reserve_out {
Err(Error::<T>::AmountOutTooHigh)?
}
let numerator = reserve_in
.checked_mul(&amount_out)
.ok_or(Error::<T>::Overflow)?
.checked_mul(&1000u32.into())
.ok_or(Error::<T>::Overflow)?;
let denominator = reserve_out
.checked_sub(&amount_out)
.ok_or(Error::<T>::Overflow)?
.checked_mul(&(T::HigherPrecisionBalance::from(1000u32) - T::LPFee::get().into()))
.ok_or(Error::<T>::Overflow)?;
let result = numerator
.checked_div(&denominator)
.ok_or(Error::<T>::Overflow)?
.checked_add(&One::one())
.ok_or(Error::<T>::Overflow)?;
result.try_into().map_err(|_| Error::<T>::Overflow)
}
fn validate_swap_path(path: &Vec<T::AssetKind>) -> Result<(), DispatchError> {
ensure!(path.len() >= 2, Error::<T>::InvalidPath);
ensure!(path.len() as u32 <= T::MaxSwapPathLength::get(), Error::<T>::InvalidPath);
let mut pools = BTreeSet::<T::PoolId>::new();
for assets_pair in path.windows(2) {
if let [asset1, asset2] = assets_pair {
let pool_id = T::PoolLocator::pool_id(asset1, asset2)
.map_err(|_| Error::<T>::InvalidAssetPair)?;
let new_element = pools.insert(pool_id);
if !new_element {
return Err(Error::<T>::NonUniquePath.into())
}
}
}
Ok(())
}
#[cfg(any(test, feature = "runtime-benchmarks"))]
pub fn get_next_pool_asset_id() -> T::PoolAssetId {
NextPoolAssetId::<T>::get()
.or(T::PoolAssetId::initial_value())
.expect("Next pool asset ID can not be None")
}
}
}
sp_api::decl_runtime_apis! {
pub trait AssetConversionApi<Balance, AssetId>
where
Balance: frame_support::traits::tokens::Balance + MaybeDisplay,
AssetId: Codec,
{
fn quote_price_tokens_for_exact_tokens(
asset1: AssetId,
asset2: AssetId,
amount: Balance,
include_fee: bool,
) -> Option<Balance>;
fn quote_price_exact_tokens_for_tokens(
asset1: AssetId,
asset2: AssetId,
amount: Balance,
include_fee: bool,
) -> Option<Balance>;
fn get_reserves(asset1: AssetId, asset2: AssetId) -> Option<(Balance, Balance)>;
}
}
sp_core::generate_feature_enabled_macro!(runtime_benchmarks_enabled, feature = "runtime-benchmarks", $);