Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: cf_pool_swap_rate_v3 with broker fee and DCA support #5386

Merged
merged 4 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 89 additions & 10 deletions state-chain/custom-rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ use cf_chains::{
};
use cf_primitives::{
chains::assets::any::{self, AssetMap},
AccountRole, Asset, AssetAmount, BlockNumber, BroadcastId, EpochIndex, ForeignChain,
NetworkEnvironment, SemVer, SwapId, SwapRequestId,
AccountRole, Affiliates, Asset, AssetAmount, BasisPoints, BlockNumber, BroadcastId,
DcaParameters, EpochIndex, ForeignChain, NetworkEnvironment, SemVer, SwapId, SwapRequestId,
};
use cf_utilities::rpc::NumberOrHex;
use core::ops::Range;
Expand Down Expand Up @@ -421,6 +421,32 @@ pub struct RpcSwapOutputV2 {
pub egress_fee: RpcFee,
}

impl From<RpcSwapOutputV3> for RpcSwapOutputV2 {
fn from(swap_output: RpcSwapOutputV3) -> Self {
Self {
intermediary: swap_output.intermediary.map(Into::into),
output: swap_output.output,
network_fee: swap_output.network_fee,
ingress_fee: swap_output.ingress_fee,
egress_fee: swap_output.egress_fee,
}
}
}

#[derive(Serialize, Deserialize, Clone)]
pub struct RpcSwapOutputV3 {
// Intermediary amount, if there's any
pub intermediary: Option<U256>,
// Final output of the swap
pub output: U256,
pub network_fee: RpcFee,
pub ingress_fee: RpcFee,
pub egress_fee: RpcFee,
// Fees for broker and affiliates
pub broker_commission: RpcFee,
pub affiliate_fees: Vec<(sp_runtime::AccountId32, RpcFee)>,
syan095 marked this conversation as resolved.
Show resolved Hide resolved
}

#[derive(Serialize, Deserialize, Clone)]
pub enum SwapRateV2AdditionalOrder {
LimitOrder { base_asset: Asset, quote_asset: Asset, side: Side, tick: Tick, sell_amount: U256 },
Expand Down Expand Up @@ -746,6 +772,18 @@ pub trait CustomApi {
additional_orders: Option<Vec<SwapRateV2AdditionalOrder>>,
at: Option<state_chain_runtime::Hash>,
) -> RpcResult<RpcSwapOutputV2>;
#[method(name = "swap_rate_v3")]
fn cf_pool_swap_rate_v3(
&self,
from_asset: Asset,
to_asset: Asset,
amount: U256,
additional_orders: Option<Vec<SwapRateV2AdditionalOrder>>,
syan095 marked this conversation as resolved.
Show resolved Hide resolved
broker_commission: BasisPoints,
affiliate_fees: Option<Affiliates<state_chain_runtime::AccountId>>,
dca_parameters: Option<DcaParameters>,
at: Option<state_chain_runtime::Hash>,
) -> RpcResult<RpcSwapOutputV3>;
#[method(name = "required_asset_ratio_for_range_order")]
fn cf_required_asset_ratio_for_range_order(
&self,
Expand Down Expand Up @@ -1356,16 +1394,40 @@ where
additional_orders: Option<Vec<SwapRateV2AdditionalOrder>>,
at: Option<state_chain_runtime::Hash>,
) -> RpcResult<RpcSwapOutputV2> {
self.cf_pool_swap_rate_v3(
from_asset,
to_asset,
amount,
additional_orders,
0u16,
None,
None,
at,
)
.map(Into::into)
}

fn cf_pool_swap_rate_v3(
&self,
from_asset: Asset,
to_asset: Asset,
amount: U256,
additional_orders: Option<Vec<SwapRateV2AdditionalOrder>>,
broker_commission: BasisPoints,
affiliate_fees: Option<Affiliates<state_chain_runtime::AccountId>>,
dca_parameters: Option<DcaParameters>,
at: Option<state_chain_runtime::Hash>,
) -> RpcResult<RpcSwapOutputV3> {
self.with_runtime_api(at, |api, hash| {
Ok::<_, CfApiError>(
api.cf_pool_simulate_swap(
api.cf_pool_simulate_swap_v2(
hash,
from_asset,
to_asset,
amount
.try_into()
.map_err(|_| "Swap input amount too large.")
.and_then(|amount| {
.and_then(|amount: u128| {
if amount == 0 {
Err("Swap input amount cannot be zero.")
} else {
Expand Down Expand Up @@ -1397,22 +1459,39 @@ where
})
.collect()
}),
broker_commission,
affiliate_fees,
dca_parameters,
)?
.map(|simulated_swap_info| RpcSwapOutputV2 {
intermediary: simulated_swap_info.intermediary.map(Into::into),
output: simulated_swap_info.output.into(),
.map(|simulated_swap_info_v2| RpcSwapOutputV3 {
intermediary: simulated_swap_info_v2.intermediary.map(Into::into),
output: simulated_swap_info_v2.output.into(),
network_fee: RpcFee {
asset: cf_primitives::STABLE_ASSET,
amount: simulated_swap_info.network_fee.into(),
amount: simulated_swap_info_v2.network_fee.into(),
},
ingress_fee: RpcFee {
asset: from_asset,
amount: simulated_swap_info.ingress_fee.into(),
amount: simulated_swap_info_v2.ingress_fee.into(),
},
egress_fee: RpcFee {
asset: to_asset,
amount: simulated_swap_info.egress_fee.into(),
amount: simulated_swap_info_v2.egress_fee.into(),
},
broker_commission: RpcFee {
asset: cf_primitives::STABLE_ASSET,
amount: simulated_swap_info_v2.broker_fee.into(),
},
affiliate_fees: simulated_swap_info_v2
.affiliate_fees
.into_iter()
.map(|(account, fees)| {
(
account,
RpcFee { asset: cf_primitives::STABLE_ASSET, amount: fees.into() },
)
})
.collect(),
})?,
)
})
Expand Down
13 changes: 13 additions & 0 deletions state-chain/pallets/cf-swapping/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2010,6 +2010,19 @@ pub mod pallet {
},
};
}

/// Swap some amount of an asset into the STABLE_ASSET with no fee deductions.
/// Used for fee estimation ONLY.
#[transactional]
pub fn swap_into_stable_without_fees(
from: Asset,
input_amount: AssetAmount,
) -> Result<AssetAmount, DispatchError> {
match from {
STABLE_ASSET => Ok(input_amount),
_ => T::SwappingApi::swap_single_leg(from, STABLE_ASSET, input_amount),
}
}
}

impl<T: Config> SwapRequestHandler for Pallet<T> {
Expand Down
18 changes: 18 additions & 0 deletions state-chain/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,18 @@ pub struct SwapOutput {
pub network_fee: AssetAmount,
}

impl SwapOutput {
// Multiply each field by x.
// Uses Saturating arithmetics.
pub fn saturating_mul(self, x: AssetAmount) -> Self {
SwapOutput {
intermediary: self.intermediary.map(|intermediary| intermediary.saturating_mul(x)),
output: self.output.saturating_mul(x),
network_fee: self.network_fee.saturating_mul(x),
}
}
}

#[derive(PartialEq, Eq, Copy, Clone, Debug, Encode, Decode, TypeInfo)]
pub enum SwapLeg {
FromStable,
Expand Down Expand Up @@ -425,3 +437,9 @@ pub struct DcaParameters {
/// The interval in blocks between each swap.
pub chunk_interval: u32,
}

/// Utility multiply an AssetAmount by a BasisPoint.
/// Only support up to 10_000 bps or 100%.
pub fn mul_bps(amount: AssetAmount, bps: BasisPoints) -> AssetAmount {
sp_arithmetic::Permill::from_rational(bps as u32, 10_000u32) * amount
}
58 changes: 50 additions & 8 deletions state-chain/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ use crate::{
runtime_decl_for_custom_runtime_api::CustomRuntimeApiV1, AuctionState, BoostPoolDepth,
BoostPoolDetails, BrokerInfo, DispatchErrorWithMessage, FailingWitnessValidators,
LiquidityProviderBoostPoolInfo, LiquidityProviderInfo, RuntimeApiPenalty,
SimulateSwapAdditionalOrder, SimulatedSwapInformation, ValidatorInfo,
SimulateSwapAdditionalOrder, SimulatedSwapInformation, SimulatedSwapInformationV2,
ValidatorInfo,
},
};
use cf_amm::{
Expand All @@ -49,7 +50,10 @@ use cf_chains::{
sol::{SolAddress, SolanaCrypto},
Arbitrum, Bitcoin, DefaultRetryPolicy, ForeignChain, Polkadot, Solana, TransactionBuilder,
};
use cf_primitives::{BroadcastId, EpochIndex, NetworkEnvironment, STABLE_ASSET};
use cf_primitives::{
Affiliates, BasisPoints, Beneficiary, BroadcastId, DcaParameters, EpochIndex,
NetworkEnvironment, STABLE_ASSET,
};
use cf_runtime_utilities::NoopRuntimeUpgrade;
use cf_traits::{
AdjustedFeeEstimationApi, AssetConverter, BalanceApi, DummyEgressSuccessWitnesser,
Expand Down Expand Up @@ -1541,6 +1545,15 @@ impl_runtime_apis! {
LiquidityPools::pool_price(base_asset, quote_asset).map_err(Into::into)
}

fn cf_pool_simulate_swap(
from: Asset,
to: Asset,
amount: AssetAmount,
additional_orders: Option<Vec<SimulateSwapAdditionalOrder>>,
) -> Result<SimulatedSwapInformation, DispatchErrorWithMessage> {
Self::cf_pool_simulate_swap_v2(from, to, amount, additional_orders, Default::default(), None, None).map(Into::into)
}

/// Simulates a swap and return the intermediate (if any) and final output.
///
/// If no swap rate can be calculated, returns None. This can happen if the pools are not
Expand All @@ -1549,12 +1562,15 @@ impl_runtime_apis! {
///
/// Note: This function must only be called through RPC, because RPC has its own storage buffer
/// layer and would not affect on-chain storage.
fn cf_pool_simulate_swap(
fn cf_pool_simulate_swap_v2(
from: Asset,
to: Asset,
amount: AssetAmount,
additional_orders: Option<Vec<SimulateSwapAdditionalOrder>>,
) -> Result<SimulatedSwapInformation, DispatchErrorWithMessage> {
broker_commission: BasisPoints,
affiliate_fees: Option<Affiliates<AccountId>>,
dca_parameters: Option<DcaParameters>,
) -> Result<SimulatedSwapInformationV2, DispatchErrorWithMessage> {
if let Some(additional_orders) = additional_orders {
for (index, additional_order) in additional_orders.into_iter().enumerate() {
match additional_order {
Expand Down Expand Up @@ -1628,20 +1644,46 @@ impl_runtime_apis! {

let (amount_to_swap, ingress_fee) = remove_fees(IngressOrEgress::Ingress, from, amount);

fn accumulate_and_swap_fees_into_stable(asset: Asset, amount: AssetAmount, fees: BasisPoints, total_fees: &mut AssetAmount) -> Result<AssetAmount, DispatchErrorWithMessage> {
let input = cf_primitives::mul_bps(amount, fees);
*total_fees += input;
Swapping::swap_into_stable_without_fees(asset, amount).map_err(Into::into)
}

// Take broker and affiliate fees from the swap amount
let mut total_fees = 0;

// Calculate broker fee
let broker_fee = accumulate_and_swap_fees_into_stable(from, amount_to_swap, broker_commission, &mut total_fees)?;

// Calculate affiliate fees
let affiliate_fees = affiliate_fees.unwrap_or_default().into_iter().map(|Beneficiary {account, bps}|{
let affiliate_fee = accumulate_and_swap_fees_into_stable(from, amount_to_swap, bps, &mut total_fees)?;
Ok((account, affiliate_fee))
}).collect::<Result<Vec<(AccountId, AssetAmount)>, DispatchErrorWithMessage>>()?;

let amount_to_swap_without_fees = amount_to_swap.saturating_sub(total_fees);

// Estimate swap result for a chunk, then extrapolate the result.
// If no DCA parameter is given, swap the entire amount with 1 chunk.
let number_of_chunks: u128 = dca_parameters.map(|dca|dca.number_of_chunks).unwrap_or(1u32).into();
dandanlen marked this conversation as resolved.
Show resolved Hide resolved
let amount_per_chunk = amount_to_swap_without_fees / number_of_chunks;
let swap_output = Swapping::swap_with_network_fee(
from,
to,
amount_to_swap,
)?;
amount_per_chunk,
)?.saturating_mul(number_of_chunks);

let (output, egress_fee) = remove_fees(IngressOrEgress::Egress, to, swap_output.output);

Ok(SimulatedSwapInformation {
Ok(SimulatedSwapInformationV2 {
intermediary: swap_output.intermediary,
output,
network_fee: swap_output.network_fee,
ingress_fee,
egress_fee,
broker_fee,
affiliate_fees,
})
}

Expand Down Expand Up @@ -2095,7 +2137,7 @@ impl_runtime_apis! {
}

fn cf_validate_dca_params(number_of_chunks: u32, chunk_interval: u32) -> Result<(), DispatchErrorWithMessage> {
pallet_cf_swapping::Pallet::<Runtime>::validate_dca_params(&cf_primitives::DcaParameters{number_of_chunks, chunk_interval}).map_err(Into::into)
pallet_cf_swapping::Pallet::<Runtime>::validate_dca_params(&DcaParameters{number_of_chunks, chunk_interval}).map_err(Into::into)
}

fn cf_validate_refund_params(retry_duration: u32) -> Result<(), DispatchErrorWithMessage> {
Expand Down
39 changes: 37 additions & 2 deletions state-chain/runtime/src/runtime_apis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ use cf_chains::{
assets::any::AssetMap, eth::Address as EthereumAddress, Chain, ForeignChainAddress,
};
use cf_primitives::{
AccountRole, Asset, AssetAmount, BlockNumber, BroadcastId, EpochIndex, FlipBalance,
ForeignChain, NetworkEnvironment, PrewitnessedDepositId, SemVer,
AccountRole, Affiliates, Asset, AssetAmount, BasisPoints, BlockNumber, BroadcastId,
DcaParameters, EpochIndex, FlipBalance, ForeignChain, NetworkEnvironment,
PrewitnessedDepositId, SemVer,
};
use cf_traits::SwapLimits;
use codec::{Decode, Encode};
Expand Down Expand Up @@ -147,6 +148,31 @@ pub struct SimulatedSwapInformation {
pub egress_fee: AssetAmount,
}

impl From<SimulatedSwapInformationV2> for SimulatedSwapInformation {
fn from(swap_into: SimulatedSwapInformationV2) -> Self {
Self {
intermediary: swap_into.intermediary,
output: swap_into.output,
network_fee: swap_into.network_fee,
ingress_fee: swap_into.ingress_fee,
egress_fee: swap_into.egress_fee,
}
}
}

/// Struct that represents the estimated output of a Swap V2.
/// Adds additional output for Broker and affiliate fees.
#[derive(Encode, Decode, TypeInfo)]
pub struct SimulatedSwapInformationV2 {
pub intermediary: Option<AssetAmount>,
pub output: AssetAmount,
pub network_fee: AssetAmount,
pub ingress_fee: AssetAmount,
pub egress_fee: AssetAmount,
pub broker_fee: AssetAmount,
pub affiliate_fees: Vec<(AccountId32, AssetAmount)>,
}

#[derive(Debug, Decode, Encode, TypeInfo)]
pub enum DispatchErrorWithMessage {
Module(Vec<u8>),
Expand Down Expand Up @@ -224,6 +250,15 @@ decl_runtime_apis!(
amount: AssetAmount,
additional_limit_orders: Option<Vec<SimulateSwapAdditionalOrder>>,
) -> Result<SimulatedSwapInformation, DispatchErrorWithMessage>;
fn cf_pool_simulate_swap_v2(
from: Asset,
to: Asset,
amount: AssetAmount,
additional_limit_orders: Option<Vec<SimulateSwapAdditionalOrder>>,
broker_commission: BasisPoints,
affiliate_fees: Option<Affiliates<sp_runtime::AccountId32>>,
dca_parameters: Option<DcaParameters>,
) -> Result<SimulatedSwapInformationV2, DispatchErrorWithMessage>;
fn cf_pool_info(
base_asset: Asset,
quote_asset: Asset,
Expand Down
Loading