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

refactor/PRO-1101: rid of swapping minimum swap amount #4419

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
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
1 change: 0 additions & 1 deletion state-chain/cf-integration-tests/src/mock_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,6 @@ impl ExtBuilder {
polkadot_vault: Default::default(),
environment: Default::default(),
liquidity_pools: Default::default(),
swapping: Default::default(),
system: Default::default(),
transaction_payment: Default::default(),
bitcoin_ingress_egress: Default::default(),
Expand Down
31 changes: 3 additions & 28 deletions state-chain/custom-rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,6 @@ pub struct FundingEnvironment {

#[derive(Serialize, Deserialize)]
pub struct SwappingEnvironment {
minimum_swap_amounts: HashMap<ForeignChain, HashMap<Asset, NumberOrHex>>,
maximum_swap_amounts: HashMap<ForeignChain, HashMap<Asset, Option<NumberOrHex>>>,
}

Expand Down Expand Up @@ -461,8 +460,7 @@ pub trait CustomApi {
#[deprecated(note = "Use direct storage access of `CurrentReleaseVersion` instead.")]
#[method(name = "current_compatibility_version")]
fn cf_current_compatibility_version(&self) -> RpcResult<SemVer>;
#[method(name = "min_swap_amount")]
fn cf_min_swap_amount(&self, asset: RpcAsset) -> RpcResult<AssetAmount>;

#[method(name = "max_swap_amount")]
fn cf_max_swap_amount(&self, asset: RpcAsset) -> RpcResult<Option<AssetAmount>>;
#[subscription(name = "subscribe_pool_price", item = PoolPrice)]
Expand Down Expand Up @@ -992,23 +990,18 @@ where
) -> RpcResult<SwappingEnvironment> {
let runtime_api = &self.client.runtime_api();
let hash = self.unwrap_or_best(at);
let mut minimum_swap_amounts = HashMap::new();

let mut maximum_swap_amounts = HashMap::new();

for asset in Asset::all() {
let min_amount = runtime_api.cf_min_swap_amount(hash, asset).map_err(to_rpc_error)?;
let max_amount = runtime_api.cf_max_swap_amount(hash, asset).map_err(to_rpc_error)?;
minimum_swap_amounts
.entry(asset.into())
.or_insert_with(HashMap::new)
.insert(asset, min_amount.into());
maximum_swap_amounts
.entry(asset.into())
.or_insert_with(HashMap::new)
.insert(asset, max_amount.map(|amt| amt.into()));
}

Ok(SwappingEnvironment { minimum_swap_amounts, maximum_swap_amounts })
Ok(SwappingEnvironment { maximum_swap_amounts })
}

fn cf_funding_environment(
Expand Down Expand Up @@ -1060,13 +1053,6 @@ where
.map_err(to_rpc_error)
}

fn cf_min_swap_amount(&self, asset: RpcAsset) -> RpcResult<AssetAmount> {
self.client
.runtime_api()
.cf_min_swap_amount(self.unwrap_or_best(None), asset.try_into()?)
.map_err(to_rpc_error)
}

fn cf_max_swap_amount(&self, asset: RpcAsset) -> RpcResult<Option<AssetAmount>> {
self.client
.runtime_api()
Expand Down Expand Up @@ -1320,17 +1306,6 @@ mod test {
fn test_environment_serialization() {
let env = RpcEnvironment {
swapping: SwappingEnvironment {
minimum_swap_amounts: HashMap::from([
(ForeignChain::Bitcoin, HashMap::from([(Asset::Btc, 0u32.into())])),
(
ForeignChain::Ethereum,
HashMap::from([
(Asset::Flip, u64::MAX.into()),
(Asset::Usdc, (u64::MAX / 2 - 1).into()),
(Asset::Eth, 0u32.into()),
]),
),
]),
maximum_swap_amounts: HashMap::from([
(ForeignChain::Bitcoin, HashMap::from([(Asset::Btc, Some(0u32.into()))])),
(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
source: state-chain/custom-rpc/src/lib.rs
expression: "serde_json::to_value(env).unwrap()"
---
{"funding":{"minimum_funding_amount":0,"redemption_tax":0},"ingress_egress":{"egress_fees":{"Bitcoin":{"BTC":0},"Ethereum":{"ETH":0,"FLIP":"0xffffffffffffffffffffffffffffffff","USDC":"0x7ffffffffffffffe"}},"ingress_fees":{"Bitcoin":{"BTC":0},"Ethereum":{"ETH":0,"FLIP":"0xffffffffffffffffffffffffffffffff","USDC":"0x7ffffffffffffffe"}},"minimum_deposit_amounts":{"Bitcoin":{"BTC":0},"Ethereum":{"ETH":0,"FLIP":"0xffffffffffffffff","USDC":"0x7ffffffffffffffe"}}},"pools":{"fees":{"Ethereum":{"FLIP":{"limit_order_fee_hundredth_pips":0,"quote_asset":{"asset":"USDC","chain":"Ethereum"},"range_order_fee_hundredth_pips":100}}}},"swapping":{"maximum_swap_amounts":{"Bitcoin":{"BTC":0},"Ethereum":{"ETH":0,"FLIP":null,"USDC":"0x7ffffffffffffffe"}},"minimum_swap_amounts":{"Bitcoin":{"BTC":0},"Ethereum":{"ETH":0,"FLIP":"0xffffffffffffffff","USDC":"0x7ffffffffffffffe"}}}}
{"funding":{"minimum_funding_amount":0,"redemption_tax":0},"ingress_egress":{"egress_fees":{"Bitcoin":{"BTC":0},"Ethereum":{"ETH":0,"FLIP":"0xffffffffffffffffffffffffffffffff","USDC":"0x7ffffffffffffffe"}},"ingress_fees":{"Bitcoin":{"BTC":0},"Ethereum":{"ETH":0,"FLIP":"0xffffffffffffffffffffffffffffffff","USDC":"0x7ffffffffffffffe"}},"minimum_deposit_amounts":{"Bitcoin":{"BTC":0},"Ethereum":{"ETH":0,"FLIP":"0xffffffffffffffff","USDC":"0x7ffffffffffffffe"}}},"pools":{"fees":{"Ethereum":{"FLIP":{"limit_order_fee_hundredth_pips":0,"quote_asset":{"asset":"USDC","chain":"Ethereum"},"range_order_fee_hundredth_pips":100}}}},"swapping":{"maximum_swap_amounts":{"Bitcoin":{"BTC":0},"Ethereum":{"ETH":0,"FLIP":null,"USDC":"0x7ffffffffffffffe"}}}}
9 changes: 2 additions & 7 deletions state-chain/node/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ use cf_chains::{
ChainState,
};
use cf_primitives::{
chains::assets, AccountRole, AssetAmount, AuthorityCount, NetworkEnvironment,
DEFAULT_MAX_AUTHORITY_SET_CONTRACTION,
AccountRole, AuthorityCount, NetworkEnvironment, DEFAULT_MAX_AUTHORITY_SET_CONTRACTION,
};

use cf_chains::{
Expand All @@ -31,7 +30,7 @@ use state_chain_runtime::{
EthereumVaultConfig, FlipBalance, FlipConfig, FundingConfig, GovernanceConfig, GrandpaConfig,
PolkadotChainTrackingConfig, PolkadotIngressEgressConfig, PolkadotThresholdSignerConfig,
PolkadotVaultConfig, ReputationConfig, RuntimeGenesisConfig, SessionConfig, SetSizeParameters,
Signature, SwappingConfig, SystemConfig, ValidatorConfig, WASM_BINARY,
Signature, SystemConfig, ValidatorConfig, WASM_BINARY,
};

use std::{
Expand Down Expand Up @@ -266,7 +265,6 @@ pub fn inner_cf_development_config(
devnet::PENALTIES.to_vec(),
devnet::KEYGEN_CEREMONY_TIMEOUT_BLOCKS,
devnet::THRESHOLD_SIGNATURE_CEREMONY_TIMEOUT_BLOCKS,
devnet::MINIMUM_SWAP_AMOUNTS.to_vec(),
dot_runtime_version,
// Bitcoin block times on localnets are much faster, so we account for that here.
devnet::BITCOIN_EXPIRY_BLOCKS,
Expand Down Expand Up @@ -397,7 +395,6 @@ macro_rules! network_spec {
PENALTIES.to_vec(),
KEYGEN_CEREMONY_TIMEOUT_BLOCKS,
THRESHOLD_SIGNATURE_CEREMONY_TIMEOUT_BLOCKS,
MINIMUM_SWAP_AMOUNTS.to_vec(),
dot_runtime_version,
BITCOIN_EXPIRY_BLOCKS,
ETHEREUM_EXPIRY_BLOCKS,
Expand Down Expand Up @@ -459,7 +456,6 @@ fn testnet_genesis(
penalties: Vec<(Offence, (i32, BlockNumber))>,
keygen_ceremony_timeout_blocks: BlockNumber,
threshold_signature_ceremony_timeout_blocks: BlockNumber,
minimum_swap_amounts: Vec<(assets::any::Asset, AssetAmount)>,
dot_runtime_version: RuntimeVersion,
bitcoin_deposit_channel_lifetime: u32,
ethereum_deposit_channel_lifetime: u32,
Expand Down Expand Up @@ -672,7 +668,6 @@ fn testnet_genesis(
},
transaction_payment: Default::default(),
liquidity_pools: Default::default(),
swapping: SwappingConfig { minimum_swap_amounts, _phantom: PhantomData },
// Channel lifetimes are set to ~2 hours at average block times.
bitcoin_ingress_egress: BitcoinIngressEgressConfig {
deposit_channel_lifetime: bitcoin_deposit_channel_lifetime.into(),
Expand Down
12 changes: 1 addition & 11 deletions state-chain/node/src/chain_spec/berghain.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
pub use super::common::*;
use super::StateChainEnvironment;
use cf_chains::{dot::RuntimeVersion, eth::CHAIN_ID_MAINNET};
use cf_primitives::{
AccountId, AccountRole, Asset, AssetAmount, BlockNumber, FlipBalance, NetworkEnvironment,
};
use cf_primitives::{AccountId, AccountRole, BlockNumber, FlipBalance, NetworkEnvironment};
use sc_service::ChainType;
use sp_core::H256;
use state_chain_runtime::SetSizeParameters;
Expand Down Expand Up @@ -72,14 +70,6 @@ pub const BACKUP_NODE_EMISSION_INFLATION_PERBILL: u32 = 0;

pub const SUPPLY_UPDATE_INTERVAL: u32 = 30 * 24 * HOURS;

pub const MINIMUM_SWAP_AMOUNTS: &[(Asset, AssetAmount)] = &[
(Asset::Eth, 0u128),
(Asset::Flip, 0u128),
(Asset::Usdc, 0u128),
(Asset::Dot, 0u128),
(Asset::Btc, 0u128),
];

pub const MIN_FUNDING: FlipBalance = 6 * FLIPPERINOS_PER_FLIP;
pub const GENESIS_AUTHORITY_FUNDING: FlipBalance = 1_000 * FLIPPERINOS_PER_FLIP;
pub const REDEMPTION_TAX: FlipBalance = 5 * FLIPPERINOS_PER_FLIP;
Expand Down
10 changes: 1 addition & 9 deletions state-chain/node/src/chain_spec/common.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use cf_primitives::{Asset, AssetAmount, AuthorityCount};
use cf_primitives::AuthorityCount;
use sp_runtime::{Percent, Permill};
pub use state_chain_runtime::constants::common::*;
use state_chain_runtime::{chainflip::Offence, BlockNumber, FlipBalance, SetSizeParameters};
Expand Down Expand Up @@ -63,14 +63,6 @@ pub const PENALTIES: &[(Offence, (i32, BlockNumber))] = &[
(Offence::GrandpaEquivocation, (REPUTATION_PENALTY_LARGE, HEARTBEAT_BLOCK_INTERVAL * 5)),
];

pub const MINIMUM_SWAP_AMOUNTS: &[(Asset, AssetAmount)] = &[
(Asset::Eth, 580_000_000_000_000u128), // 1usd worth of Eth = 0.00058 * 18 d.p
(Asset::Flip, FLIPPERINOS_PER_FLIP), // 1 Flip
(Asset::Usdc, 1_000_000u128), // USDC = 6 d.p
(Asset::Dot, 2_000_000_000u128), // 1 USD worth of DOT = 0.2 * 10 d.p
(Asset::Btc, 390_000u128), // 1 USD worth of BTC = 0.000039 * 10 d.p
];

/// Daily slashing rate 0.1% (of the bond) for offline authority
pub const DAILY_SLASHING_RATE: Permill = Permill::from_perthousand(1);

Expand Down
8 changes: 0 additions & 8 deletions state-chain/pallets/cf-swapping/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,6 @@ Swap operations use a lot of system resources and are expensive to execute, and

Since Swap and CCM deposit functions are called by Witnessers, they do not return errors on failure, but will instead emit RuntimeEvents: `SwapAmountTooLow` and `CcmFailed`. `CcmFailed` also contains the reason for failure for diagnostic. All the deposited funds are confiscated and stored in the `CollectedRejectedFunds` storage.

### Minimum Swap Threshold

Swaps deposits are required to be above a certain threshold if they are to be processed by the pallet. This threshold is set by the `set_minimum_swap_amount` extrinsic call, and requires governance.

This check is done for both `schedule_swap_from_contract`, `schedule_swap_from_channel` pathways, which includes the principal swap component of a CCM. If the principal amount does not need to be swapped (if the output asset == input asset, or if the principal amount is 0), then a principal amount lower than the `MinimumSwapAmount` is allowed.

The Gas budgets are exempt from this threshold (as gas budgets are expected to be smaller in value), but has its own threshold as safeguards.

### Minimum Ccm Gas Budget

Ccm messages' Gas budget must be higher than this threshold, or the message will be rejected. This check is done regardless if the Gas needs to be swapped.
Expand Down
30 changes: 0 additions & 30 deletions state-chain/pallets/cf-swapping/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,6 @@ benchmarks! {
schedule_swap_from_contract {
let deposit_amount = 1_000;

// reduce minimum swap amount
let gov_origin = T::EnsureGovernance::try_successful_origin().unwrap();
let call = Call::<T>::set_minimum_swap_amount{
asset: Asset::Usdc,
amount: 1u128,
};
call.dispatch_bypass_filter(gov_origin)?;

let witness_origin = T::EnsureWitnessed::try_successful_origin().unwrap();
let call = Call::<T>::schedule_swap_from_contract{
from: Asset::Usdc,
Expand All @@ -77,14 +69,6 @@ benchmarks! {
}

ccm_deposit {
// reduce minimum swap amount
let gov_origin = T::EnsureGovernance::try_successful_origin().unwrap();
let call = Call::<T>::set_minimum_swap_amount{
asset: Asset::Usdc,
amount: 1u128,
};
call.dispatch_bypass_filter(gov_origin)?;

let origin = T::EnsureWitnessed::try_successful_origin().unwrap();
let deposit_metadata = CcmDepositMetadata {
source_chain: ForeignChain::Ethereum,
Expand Down Expand Up @@ -122,20 +106,6 @@ benchmarks! {
SwapType::CcmGas(1)
)]);
}

set_minimum_swap_amount {
let asset = Asset::Eth;
let amount = 1_000;
let call = Call::<T>::set_minimum_swap_amount {
asset,
amount,
};
}: {
let _ = call.dispatch_bypass_filter(<T as Chainflip>::EnsureGovernance::try_successful_origin().unwrap());
} verify {
assert_eq!(crate::MinimumSwapAmount::<T>::get(asset), amount);
}

set_maximum_swap_amount {
let asset = Asset::Eth;
let amount = 1_000;
Expand Down
Loading
Loading