diff --git a/CHANGELOG.md b/CHANGELOG.md index 469ba21a37a..d7e0c3012f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -78,6 +78,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#4868](https://github.com/osmosis-labs/osmosis/pull/4868) Remove wasmEnabledProposals []wasm.ProposalType from NewOsmosisApp * [#4983](https://github.com/osmosis-labs/osmosis/pull/4983) Consume a gas when creating a new token using tokenfactory as a spam deterrence mechanism. * [#4951](https://github.com/osmosis-labs/osmosis/pull/4951) Implement pool liquidity query in pool manager, deprecate the one in gamm +* [#5138](https://github.com/osmosis-labs/osmosis/pull/5138) Rename swap fee to spread factor. Broke PoolI interface. Did not break CLI, message, pool models, queries or events. ## v15.1.0 @@ -209,7 +210,7 @@ This release includes stableswap, and expands the IBC safety & composability fun * Gamm: * Introduction of the stableswap pool type - * Multi-hop swapfee reduction + * Multi-hop spread factor reduction * Filtered queries to help front-ends * Adding a spot price v2 query * spotprice v1beta1 had baseassetdenom and quoteassetdenom backwards. diff --git a/Makefile b/Makefile index ec10c98994a..d03ac729d8d 100644 --- a/Makefile +++ b/Makefile @@ -475,8 +475,9 @@ cl-create-bigbang-config: ### Go Mock ### ############################################################################### -go-mock-update-pool-module: +go-mock-update: mockgen -source=x/poolmanager/types/routes.go -destination=tests/mocks/pool_module.go -package=mocks + mockgen -source=x/poolmanager/types/pool.go -destination=tests/mocks/pool.go -package=mocks .PHONY: all build-linux install format lint \ go-mod-cache draw-deps clean build build-contract-tests-hooks \ diff --git a/README.md b/README.md index e988e1e7173..3d7e8d39dea 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ swap-type use cases. Bonding curves, while have found its primary use case in decentralized exchange mechanisms, its potential use case can be further extended through the customizability that Osmosis offers. Through the customizability offered by Osmosis such as custom-curve AMMs, -dynamic adjustments of swap fees, multi-token liquidity pools--the AMM +dynamic adjustments of spread factors, multi-token liquidity pools--the AMM can offer decentralized formation of token fundraisers, interchain staking, options market, and more for the Cosmos ecosystem. diff --git a/app/apptesting/concentrated_liquidity.go b/app/apptesting/concentrated_liquidity.go index 17b010a6fb4..4055d0b0575 100644 --- a/app/apptesting/concentrated_liquidity.go +++ b/app/apptesting/concentrated_liquidity.go @@ -21,7 +21,7 @@ var ( ) // PrepareConcentratedPool sets up an eth usdc concentrated liquidity pool with pool ID 1, tick spacing of 100, -// no liquidity and zero swap fee. +// no liquidity and zero spread factor. func (s *KeeperTestHelper) PrepareConcentratedPool() types.ConcentratedPoolExtension { return s.PrepareCustomConcentratedPool(s.TestAccs[0], ETH, USDC, DefaultTickSpacing, sdk.ZeroDec()) } @@ -41,19 +41,19 @@ func (s *KeeperTestHelper) PrepareConcentratedPoolWithCoinsAndFullRangePosition( return clPool } -// createConcentratedPoolsFromCoinsWithSwapFee creates CL pools from given sets of coins and respective swap fees. +// createConcentratedPoolsFromCoinsWithSpreadFactor creates CL pools from given sets of coins and respective swap fees. // Where element 1 of the input corresponds to the first pool created, element 2 to the second pool created etc. -func (s *KeeperTestHelper) CreateConcentratedPoolsAndFullRangePositionWithSwapFee(poolDenoms [][]string, swapFee []sdk.Dec) { +func (s *KeeperTestHelper) CreateConcentratedPoolsAndFullRangePositionWithSpreadFactor(poolDenoms [][]string, spreadFactor []sdk.Dec) { for i, curPoolDenoms := range poolDenoms { s.Require().Equal(2, len(curPoolDenoms)) - var curSwapFee sdk.Dec - if len(swapFee) > i { - curSwapFee = swapFee[i] + var curSpreadFactor sdk.Dec + if len(spreadFactor) > i { + curSpreadFactor = spreadFactor[i] } else { - curSwapFee = sdk.ZeroDec() + curSpreadFactor = sdk.ZeroDec() } - clPool := s.PrepareCustomConcentratedPool(s.TestAccs[0], curPoolDenoms[0], curPoolDenoms[1], DefaultTickSpacing, curSwapFee) + clPool := s.PrepareCustomConcentratedPool(s.TestAccs[0], curPoolDenoms[0], curPoolDenoms[1], DefaultTickSpacing, curSpreadFactor) fundCoins := sdk.NewCoins(sdk.NewCoin(curPoolDenoms[0], DefaultCoinAmount), sdk.NewCoin(curPoolDenoms[1], DefaultCoinAmount)) s.FundAcc(s.TestAccs[0], fundCoins) s.CreateFullRangePosition(clPool, fundCoins) @@ -63,7 +63,7 @@ func (s *KeeperTestHelper) CreateConcentratedPoolsAndFullRangePositionWithSwapFe // createConcentratedPoolsFromCoins creates CL pools from given sets of coins (with zero swap fees). // Where element 1 of the input corresponds to the first pool created, element 2 to the second pool created etc. func (s *KeeperTestHelper) CreateConcentratedPoolsAndFullRangePosition(poolDenoms [][]string) { - s.CreateConcentratedPoolsAndFullRangePositionWithSwapFee(poolDenoms, []sdk.Dec{sdk.ZeroDec()}) + s.CreateConcentratedPoolsAndFullRangePositionWithSpreadFactor(poolDenoms, []sdk.Dec{sdk.ZeroDec()}) } // PrepareConcentratedPoolWithCoinsAndLockedFullRangePosition sets up a concentrated liquidity pool with custom denoms. @@ -80,12 +80,12 @@ func (s *KeeperTestHelper) PrepareConcentratedPoolWithCoinsAndLockedFullRangePos } // PrepareCustomConcentratedPool sets up a concentrated liquidity pool with the custom parameters. -func (s *KeeperTestHelper) PrepareCustomConcentratedPool(owner sdk.AccAddress, denom0, denom1 string, tickSpacing uint64, swapFee sdk.Dec) types.ConcentratedPoolExtension { +func (s *KeeperTestHelper) PrepareCustomConcentratedPool(owner sdk.AccAddress, denom0, denom1 string, tickSpacing uint64, spreadFactor sdk.Dec) types.ConcentratedPoolExtension { // Mint some assets to the account. s.FundAcc(s.TestAccs[0], DefaultAcctFunds) // Create a concentrated pool via the poolmanager - poolID, err := s.App.PoolManagerKeeper.CreatePool(s.Ctx, clmodel.NewMsgCreateConcentratedPool(owner, denom0, denom1, tickSpacing, swapFee)) + poolID, err := s.App.PoolManagerKeeper.CreatePool(s.Ctx, clmodel.NewMsgCreateConcentratedPool(owner, denom0, denom1, tickSpacing, spreadFactor)) s.Require().NoError(err) // Retrieve the poolInterface via the poolID diff --git a/app/apptesting/gamm.go b/app/apptesting/gamm.go index d9f0fbb3947..7f209c43df6 100644 --- a/app/apptesting/gamm.go +++ b/app/apptesting/gamm.go @@ -218,8 +218,8 @@ func (s *KeeperTestHelper) ModifySpotPrice(poolID uint64, targetSpotPrice sdk.De s.Require().NoError(err) } else { swapOut := sdk.NewCoins(sdk.NewCoin(quoteDenom, sdk.NewInt(amountTrade.RoundInt64()).Abs())) - swapFee := pool.GetSwapFee(s.Ctx) - tokenIn, err := pool.CalcInAmtGivenOut(s.Ctx, swapOut, baseDenom, swapFee) + spreadFactor := pool.GetSpreadFactor(s.Ctx) + tokenIn, err := pool.CalcInAmtGivenOut(s.Ctx, swapOut, baseDenom, spreadFactor) s.Require().NoError(err) s.FundAcc(s.TestAccs[0], sdk.NewCoins(tokenIn)) msg := gammtypes.MsgSwapExactAmountOut{ diff --git a/app/upgrades/v15/upgrade_test.go b/app/upgrades/v15/upgrade_test.go index bf02bf4bc4e..57b785761a4 100644 --- a/app/upgrades/v15/upgrade_test.go +++ b/app/upgrades/v15/upgrade_test.go @@ -98,13 +98,13 @@ func (suite *UpgradeTestSuite) TestMigrateBalancerToStablePools() { suite.FundAcc(testAccount, DefaultAcctFunds) // Create the balancer pool - swapFee := sdk.MustNewDecFromStr("0.003") + spreadFactor := sdk.MustNewDecFromStr("0.003") exitFee := sdk.ZeroDec() poolID, err := suite.App.PoolManagerKeeper.CreatePool( suite.Ctx, balancer.NewMsgCreateBalancerPool(suite.TestAccs[0], balancer.PoolParams{ - SwapFee: swapFee, + SwapFee: spreadFactor, ExitFee: exitFee, }, []balancer.PoolAsset{ diff --git a/app/upgrades/v15/upgrades.go b/app/upgrades/v15/upgrades.go index e5a0f82d04c..3c4e5944314 100644 --- a/app/upgrades/v15/upgrades.go +++ b/app/upgrades/v15/upgrades.go @@ -102,7 +102,7 @@ func migrateBalancerPoolToSolidlyStable(ctx sdk.Context, gammKeeper *gammkeeper. // initialize the stableswap pool stableswapPool, err := stableswap.NewStableswapPool( poolId, - stableswap.PoolParams{SwapFee: balancerPool.GetSwapFee(ctx), ExitFee: balancerPool.GetExitFee(ctx)}, + stableswap.PoolParams{SwapFee: balancerPool.GetSpreadFactor(ctx), ExitFee: balancerPool.GetExitFee(ctx)}, balancerPoolLiquidity, []uint64{1, 1}, "osmo1k8c2m5cn322akk5wy8lpt87dd2f4yh9afcd7af", // Stride Foundation 2/3 multisig diff --git a/app/upgrades/v16/concentrated_pool.go b/app/upgrades/v16/concentrated_pool.go index 7e29d98dfd9..0017255973c 100644 --- a/app/upgrades/v16/concentrated_pool.go +++ b/app/upgrades/v16/concentrated_pool.go @@ -46,10 +46,10 @@ func createConcentratedPoolFromCFMM(ctx sdk.Context, cfmmPoolIdToLinkWith uint64 return nil, NoDesiredDenomInPoolError{desiredDenom0} } - // Swap fee is 0.2%, which is an authorized swap fee. - swapFee := cfmmPool.GetSwapFee(ctx) + // Swap fee is 0.2%, which is an authorized spread factor. + spreadFactor := cfmmPool.GetSpreadFactor(ctx) - createPoolMsg := clmodel.NewMsgCreateConcentratedPool(poolCreatorAddress, desiredDenom0, denom1, TickSpacing, swapFee) + createPoolMsg := clmodel.NewMsgCreateConcentratedPool(poolCreatorAddress, desiredDenom0, denom1, TickSpacing, spreadFactor) concentratedPool, err := poolmanagerKeeper.CreateConcentratedPoolAsPoolManager(ctx, createPoolMsg) if err != nil { return nil, err diff --git a/app/upgrades/v16/concentrated_pool_test.go b/app/upgrades/v16/concentrated_pool_test.go index d4a2bbf1b05..74b8667648f 100644 --- a/app/upgrades/v16/concentrated_pool_test.go +++ b/app/upgrades/v16/concentrated_pool_test.go @@ -91,8 +91,8 @@ func (suite *ConcentratedUpgradeTestSuite) TestCreateConcentratedPoolFromCFMM() suite.Require().NoError(err) suite.Require().Equal(clPoolReturned, clPoolInState) - // Validate CL and balancer pools have the same swap fee. - suite.Require().Equal(balancerPool.GetSwapFee(suite.Ctx), clPoolReturned.GetSwapFee(suite.Ctx)) + // Validate CL and balancer pools have the same spread factor. + suite.Require().Equal(balancerPool.GetSpreadFactor(suite.Ctx), clPoolReturned.GetSpreadFactor(suite.Ctx)) // Validate that CL and balancer pools have the same denoms balancerDenoms, err := suite.App.PoolManagerKeeper.RouteGetPoolDenoms(suite.Ctx, balancerPool.GetId()) diff --git a/app/upgrades/v16/upgrades.go b/app/upgrades/v16/upgrades.go index a79753a5aa5..c974be55567 100644 --- a/app/upgrades/v16/upgrades.go +++ b/app/upgrades/v16/upgrades.go @@ -22,7 +22,7 @@ const ( // DAI/OSMO pool ID // https://app.osmosis.zone/pool/674 // Note, new concentrated liquidity pool - // swap fee is initialized to be the same as the balancers pool swap fee of 0.2%. + // spread factor is initialized to be the same as the balancers pool spread factor of 0.2%. DaiOsmoPoolId = uint64(674) // Denom0 translates to a base asset while denom1 to a quote asset // We want quote asset to be DAI so that when the limit orders on ticks diff --git a/app/upgrades/v9/prop214.go b/app/upgrades/v9/prop214.go index 8d0c311dd9d..3b7f27bfd85 100644 --- a/app/upgrades/v9/prop214.go +++ b/app/upgrades/v9/prop214.go @@ -10,7 +10,7 @@ import ( // Executes prop214, https://www.mintscan.io/osmosis/proposals/214 // Run `osmosisd q gov proposal 214` to see the text. // It was voted in, and it has update instructions: -// Voting YES for this proposal would reduce the Pool 1 (OSMO/ATOM) swap fee from 0.3% to 0.2% +// Voting YES for this proposal would reduce the Pool 1 (OSMO/ATOM) spread factor from 0.3% to 0.2% func ExecuteProp214(ctx sdk.Context, gamm *gammkeeper.Keeper) { poolId := 1 pool, err := gamm.GetPoolAndPoke(ctx, uint64(poolId)) diff --git a/app/upgrades/v9/prop214_test.go b/app/upgrades/v9/prop214_test.go index 645d3a1044e..ee9275484d2 100644 --- a/app/upgrades/v9/prop214_test.go +++ b/app/upgrades/v9/prop214_test.go @@ -29,8 +29,8 @@ func (suite *UpgradeTestSuite) TestProp214() { suite.Require().NoError(err) // Kept as comments for recordkeeping. Since SetPool is now private, the changes being tested for can no longer be made: - // swapFee := pool.GetSwapFee(suite.Ctx) - // expectedSwapFee := sdk.MustNewDecFromStr("0.002") + // spreadFactor := pool.GetSpreadFactor(suite.Ctx) + // expectedSpreadFactor := sdk.MustNewDecFromStr("0.002") // - // suite.Require().Equal(expectedSwapFee, swapFee) + // suite.Require().Equal(expectedSpreadFactor, spreadFactor) } diff --git a/proto/osmosis/concentrated-liquidity/gov.proto b/proto/osmosis/concentrated-liquidity/gov.proto index 71ede11723f..6e50a27e7eb 100644 --- a/proto/osmosis/concentrated-liquidity/gov.proto +++ b/proto/osmosis/concentrated-liquidity/gov.proto @@ -24,9 +24,9 @@ message CreateConcentratedLiquidityPoolProposal { (gogoproto.moretags) = "yaml:\"exponent_at_price_one\"", (gogoproto.nullable) = false ]; - string swap_fee = 7 [ + string spread_factor = 7 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.moretags) = "yaml:\"swap_fee\"", + (gogoproto.moretags) = "yaml:\"spread_factor\"", (gogoproto.nullable) = false ]; } diff --git a/proto/osmosis/concentrated-liquidity/incentive_record.proto b/proto/osmosis/concentrated-liquidity/incentive_record.proto index 53987456ab9..2a0e127b710 100644 --- a/proto/osmosis/concentrated-liquidity/incentive_record.proto +++ b/proto/osmosis/concentrated-liquidity/incentive_record.proto @@ -51,7 +51,7 @@ message IncentiveRecordBody { // emission_rate is the incentive emission rate per second string emission_rate = 2 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.moretags) = "yaml:\"swap_fee\"", + (gogoproto.moretags) = "yaml:\"emission_rate\"", (gogoproto.nullable) = false ]; diff --git a/proto/osmosis/concentrated-liquidity/params.proto b/proto/osmosis/concentrated-liquidity/params.proto index 1ed58f907e7..4c1144f9139 100644 --- a/proto/osmosis/concentrated-liquidity/params.proto +++ b/proto/osmosis/concentrated-liquidity/params.proto @@ -14,9 +14,9 @@ message Params { // to be created with tick spacing of 1, 10, or 30. repeated uint64 authorized_tick_spacing = 1 [ (gogoproto.moretags) = "yaml:\"authorized_tick_spacing\"" ]; - repeated string authorized_swap_fees = 2 [ + repeated string authorized_spread_factors = 2 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.moretags) = "yaml:\"authorized_swap_fees\"", + (gogoproto.moretags) = "yaml:\"authorized_spread_factors\"", (gogoproto.nullable) = false ]; // balancer_shares_reward_discount is the rate by which incentives flowing diff --git a/proto/osmosis/concentrated-liquidity/pool-model/tx.proto b/proto/osmosis/concentrated-liquidity/pool-model/tx.proto index 757a53cd9ea..1d41d142c7b 100644 --- a/proto/osmosis/concentrated-liquidity/pool-model/tx.proto +++ b/proto/osmosis/concentrated-liquidity/pool-model/tx.proto @@ -17,9 +17,9 @@ message MsgCreateConcentratedPool { string denom0 = 2 [ (gogoproto.moretags) = "yaml:\"denom0\"" ]; string denom1 = 3 [ (gogoproto.moretags) = "yaml:\"denom1\"" ]; uint64 tick_spacing = 4 [ (gogoproto.moretags) = "yaml:\"tick_spacing\"" ]; - string swap_fee = 5 [ + string spread_factor = 5 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.moretags) = "yaml:\"swap_fee\"", + (gogoproto.moretags) = "yaml:\"spread_factor\"", (gogoproto.nullable) = false ]; } diff --git a/proto/osmosis/concentrated-liquidity/pool.proto b/proto/osmosis/concentrated-liquidity/pool.proto index f1eb2a84942..fbc96511e46 100644 --- a/proto/osmosis/concentrated-liquidity/pool.proto +++ b/proto/osmosis/concentrated-liquidity/pool.proto @@ -50,10 +50,10 @@ message Pool { int64 exponent_at_price_one = 11 [ (gogoproto.moretags) = "yaml:\"exponent_at_price_one\"" ]; - // swap_fee is the ratio that is charged on the amount of token in. - string swap_fee = 12 [ + // spread_factor is the ratio that is charged on the amount of token in. + string spread_factor = 12 [ (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.moretags) = "yaml:\"swap_fee\"", + (gogoproto.moretags) = "yaml:\"spread_factor\"", (gogoproto.nullable) = false ]; diff --git a/scripts/cl/in_given_out.py b/scripts/cl/in_given_out.py index 696ff1e025b..69805e9fb7f 100644 --- a/scripts/cl/in_given_out.py +++ b/scripts/cl/in_given_out.py @@ -6,13 +6,13 @@ import zero_for_one as zfo import one_for_zero as ofz -def estimate_test_case_in_given_out(tick_ranges: list[SqrtPriceRange], token_out: Decimal, swap_fee: Decimal, is_zero_for_one: bool) -> Tuple[Decimal, Decimal]: +def estimate_test_case_in_given_out(tick_ranges: list[SqrtPriceRange], token_out: Decimal, spread_factor: Decimal, is_zero_for_one: bool) -> Tuple[Decimal, Decimal]: """ Estimates a calc concentrated liquidity test case when swapping for token in given out. Given - sqrt price range with the start sqrt price, next sqrt price and liquidity - token out - - swap fee + - spread factor - zero for one boolean flag Estimates the token in with fee applied and the fee growth per share and prints it to stdout. Also, estimates these and other values at each range and prints them to stdout. @@ -37,9 +37,9 @@ def estimate_test_case_in_given_out(tick_ranges: list[SqrtPriceRange], token_out if is_with_next_sqrt_price: token_out_consumed, token_in, fee_growth_per_share = sdk_dec.zero, sdk_dec.zero, sdk_dec.zero if is_zero_for_one: - token_out_consumed, token_in, fee_growth_per_share = zfo.calc_test_case_with_next_sqrt_price_in_given_out(tick_range.liquidity, tick_range.sqrt_price_start, tick_range.sqrt_price_next, swap_fee) + token_out_consumed, token_in, fee_growth_per_share = zfo.calc_test_case_with_next_sqrt_price_in_given_out(tick_range.liquidity, tick_range.sqrt_price_start, tick_range.sqrt_price_next, spread_factor) else: - token_out_consumed, token_in, fee_growth_per_share = ofz.calc_test_case_with_next_sqrt_price_in_given_out(tick_range.liquidity, tick_range.sqrt_price_start, tick_range.sqrt_price_next, swap_fee) + token_out_consumed, token_in, fee_growth_per_share = ofz.calc_test_case_with_next_sqrt_price_in_given_out(tick_range.liquidity, tick_range.sqrt_price_start, tick_range.sqrt_price_next, spread_factor) print(F"token_out_consumed {token_out_consumed}") print(F"token_in {token_in}") token_out_consumed_total += token_out_consumed @@ -54,9 +54,9 @@ def estimate_test_case_in_given_out(tick_ranges: list[SqrtPriceRange], token_out token_in, fee_growth_per_share = sdk_dec.zero, sdk_dec.zero if is_zero_for_one: - _, token_in, fee_growth_per_share = zfo.calc_test_case_in_given_out(tick_range.liquidity, tick_range.sqrt_price_start, token_out_remaining, swap_fee) + _, token_in, fee_growth_per_share = zfo.calc_test_case_in_given_out(tick_range.liquidity, tick_range.sqrt_price_start, token_out_remaining, spread_factor) else: - _, token_in, fee_growth_per_share = ofz.calc_test_case_in_given_out(tick_range.liquidity, tick_range.sqrt_price_start, token_out_remaining, swap_fee) + _, token_in, fee_growth_per_share = ofz.calc_test_case_in_given_out(tick_range.liquidity, tick_range.sqrt_price_start, token_out_remaining, spread_factor) token_in_total += token_in fee_growth_per_share_total += fee_growth_per_share @@ -81,14 +81,14 @@ def estimate_single_position_within_one_tick_ofz_in_given_out(): """ is_zero_for_one = False - swap_fee = sdk_dec.new("0.01") + spread_factor = sdk_dec.new("0.01") token_out_initial = sdk_dec.new("42000000") tick_ranges = [ SqrtPriceRange(5000, None, sdk_dec.new("1517882343.751510418088349649")), # last one must be computed based on remaining token in, therefore it is None ] - token_in, fee_growth_per_share_total = estimate_test_case_in_given_out(tick_ranges, token_out_initial, swap_fee, is_zero_for_one) + token_in, fee_growth_per_share_total = estimate_test_case_in_given_out(tick_ranges, token_out_initial, spread_factor, is_zero_for_one) expected_token_in = sdk_dec.new("8481") expected_fee_growth_per_share_total = sdk_dec.new("0.000000055877384518") @@ -103,21 +103,21 @@ def estimate_two_positions_within_one_tick_zfo_in_given_out(): """ is_zero_for_one = True - swap_fee = sdk_dec.new("0.03") + spread_factor = sdk_dec.new("0.03") token_out = sdk_dec.new("13370") tick_ranges = [ SqrtPriceRange(5000, None, sdk_dec.new("3035764687.503020836176699298")), # last one must be computed based on remaining token in, therefore it is None ] - token_in, fee_growth_per_share_total = estimate_test_case_in_given_out(tick_ranges, token_out, swap_fee, is_zero_for_one) + token_in, fee_growth_per_share_total = estimate_test_case_in_given_out(tick_ranges, token_out, spread_factor, is_zero_for_one) expected_token_in = sdk_dec.new("68896070") expected_fee_growth_per_share_total = sdk_dec.new("0.000680843976677818") validate_confirmed_results(token_in, fee_growth_per_share_total, expected_token_in, expected_fee_growth_per_share_total) -def estimate_two_consecutive_positions_zfo_in_given_out(swap_fee: str, expected_token_in: str, expected_fee_growth_per_share_total: str): +def estimate_two_consecutive_positions_zfo_in_given_out(spread_factor: str, expected_token_in: str, expected_fee_growth_per_share_total: str): """Estimates and prints the results of a calc concentrated liquidity test case with two consecutive positions when swapping token zero for one (zfo). @@ -125,7 +125,7 @@ def estimate_two_consecutive_positions_zfo_in_given_out(swap_fee: str, expected_ """ is_zero_for_one = True - swap_fee = sdk_dec.new(swap_fee) + spread_factor = sdk_dec.new(spread_factor) token_out = sdk_dec.new("2000000") tick_ranges = [ @@ -133,7 +133,7 @@ def estimate_two_consecutive_positions_zfo_in_given_out(swap_fee: str, expected_ SqrtPriceRange(4545, None, sdk_dec.new("1198735489.597250295669959398")), # last one must be computed based on remaining token in, therefore it is None ] - token_in, fee_growth_per_share_total = estimate_test_case_in_given_out(tick_ranges, token_out, swap_fee, is_zero_for_one) + token_in, fee_growth_per_share_total = estimate_test_case_in_given_out(tick_ranges, token_out, spread_factor, is_zero_for_one) expected_token_in = sdk_dec.new(expected_token_in) expected_fee_growth_per_share_total = sdk_dec.new(expected_fee_growth_per_share_total) @@ -148,7 +148,7 @@ def estimate_overlapping_price_range_ofz_test_in_given_out(): """ is_zero_for_one = False - swap_fee = sdk_dec.new("0.1") + spread_factor = sdk_dec.new("0.1") token_out_initial = sdk_dec.new("10000000000") tick_ranges = [ @@ -157,14 +157,14 @@ def estimate_overlapping_price_range_ofz_test_in_given_out(): SqrtPriceRange(5500, None, sdk_dec.new("670416088.605668727039240782")), # last one must be computed based on remaining token in, therefore it is None ] - token_in, fee_growth_per_share_total = estimate_test_case_in_given_out(tick_ranges, token_out_initial, swap_fee, is_zero_for_one) + token_in, fee_growth_per_share_total = estimate_test_case_in_given_out(tick_ranges, token_out_initial, spread_factor, is_zero_for_one) expected_token_in = sdk_dec.new("2071290") expected_fee_growth_per_share_total = sdk_dec.new("0.000143548203873862") validate_confirmed_results(token_in, fee_growth_per_share_total, expected_token_in, expected_fee_growth_per_share_total) -def estimate_overlapping_price_range_zfo_test_in_given_out(tokein_in_initial: str, swap_fee: str, expected_token_in: str, expected_fee_growth_per_share_total: str): +def estimate_overlapping_price_range_zfo_test_in_given_out(tokein_in_initial: str, spread_factor: str, expected_token_in: str, expected_fee_growth_per_share_total: str): """Estimates and prints the results of a calc concentrated liquidity test case with overlapping price ranges when swapping token zero for one (zfo) and not consuming full liquidity of the second position. @@ -172,7 +172,7 @@ def estimate_overlapping_price_range_zfo_test_in_given_out(tokein_in_initial: st """ is_zero_for_one = True - swap_fee = sdk_dec.new(swap_fee) + spread_factor = sdk_dec.new(spread_factor) token_in_initial = sdk_dec.new(tokein_in_initial) tick_ranges = [ @@ -181,7 +181,7 @@ def estimate_overlapping_price_range_zfo_test_in_given_out(tokein_in_initial: st SqrtPriceRange(4545, None, sdk_dec.new("670416215.718827443660400594")), # last one must be computed based on remaining token in, therefore it is None ] - token_in, fee_growth_per_share_total = estimate_test_case_in_given_out(tick_ranges, token_in_initial, swap_fee, is_zero_for_one) + token_in, fee_growth_per_share_total = estimate_test_case_in_given_out(tick_ranges, token_in_initial, spread_factor, is_zero_for_one) expected_token_in = sdk_dec.new(expected_token_in) expected_fee_growth_per_share_total = sdk_dec.new(expected_fee_growth_per_share_total) @@ -196,7 +196,7 @@ def estimate_consecutive_positions_gap_ofz_test_in_given_out(): """ is_zero_for_one = False - swap_fee = sdk_dec.new("0.03") + spread_factor = sdk_dec.new("0.03") token_out_initial = sdk_dec.new("10000000000") tick_ranges = [ @@ -204,7 +204,7 @@ def estimate_consecutive_positions_gap_ofz_test_in_given_out(): SqrtPriceRange(5501, None, sdk_dec.new("1199528406.187413669220037261")), # last one must be computed based on remaining token in, therefore it is None ] - token_in, fee_growth_per_share_total = estimate_test_case_in_given_out(tick_ranges, token_out_initial, swap_fee, is_zero_for_one) + token_in, fee_growth_per_share_total = estimate_test_case_in_given_out(tick_ranges, token_out_initial, spread_factor, is_zero_for_one) expected_token_in = sdk_dec.new("1876851") expected_fee_growth_per_share_total = sdk_dec.new("0.000041537584780053") @@ -219,14 +219,14 @@ def estimate_slippage_protection_zfo_test_in_given_out(): """ is_zero_for_one = True - swap_fee = sdk_dec.new("0.01") + spread_factor = sdk_dec.new("0.01") token_in_initial = sdk_dec.new("13370") tick_ranges = [ SqrtPriceRange(5000, 4994, sdk_dec.new("1517882343.751510418088349649")), ] - token_in, fee_growth_per_share_total = estimate_test_case_in_given_out(tick_ranges, token_in_initial, swap_fee, is_zero_for_one) + token_in, fee_growth_per_share_total = estimate_test_case_in_given_out(tick_ranges, token_in_initial, spread_factor, is_zero_for_one) expected_token_in = sdk_dec.new("65068308") expected_fee_growth_per_share_total = sdk_dec.new("0.000428678206421614") diff --git a/scripts/cl/one_for_zero.py b/scripts/cl/one_for_zero.py index 73e8d7f8aeb..3d376c4b9a2 100644 --- a/scripts/cl/one_for_zero.py +++ b/scripts/cl/one_for_zero.py @@ -33,14 +33,14 @@ def calc_amount_one_delta(liquidity: Decimal, sqrt_price_current: Decimal, sqrt_ return result -def calc_test_case_out_given_in(liquidity: Decimal, sqrt_price_current: Decimal, token_in_remaining: Decimal, swap_fee: Decimal) -> Tuple[Decimal, Decimal, Decimal]: +def calc_test_case_out_given_in(liquidity: Decimal, sqrt_price_current: Decimal, token_in_remaining: Decimal, spread_factor: Decimal) -> Tuple[Decimal, Decimal, Decimal]: """ Computes and prints all one for zero test case parameters when swapping for out given in. Next sqrt price is computed from the given parameters. Returns the next square root price, token out and fee amount per share. """ token_in_remaining_after_fee = sdk_dec.mul( - token_in_remaining, (sdk_dec.one - swap_fee)) + token_in_remaining, (sdk_dec.one - spread_factor)) sqrt_price_next = get_next_sqrt_price( liquidity, sqrt_price_current, token_in_remaining_after_fee) @@ -54,7 +54,7 @@ def calc_test_case_out_given_in(liquidity: Decimal, sqrt_price_current: Decimal, token_out = get_token_out(liquidity, sqrt_price_current, sqrt_price_next) fee_charge_total = sdk_dec.zero - if swap_fee > sdk_dec.zero: + if spread_factor > sdk_dec.zero: fee_charge_total = token_in_remaining - token_in_after_fee_rounded_up fee_amount_per_share = sdk_dec.quo(fee_charge_total, liquidity) @@ -67,7 +67,7 @@ def calc_test_case_out_given_in(liquidity: Decimal, sqrt_price_current: Decimal, return sqrt_price_next, token_out, fee_amount_per_share -def calc_test_case_in_given_out(liquidity: Decimal, sqrt_price_current: Decimal, token_in: Decimal, swap_fee: Decimal) -> Tuple[Decimal, Decimal, Decimal]: +def calc_test_case_in_given_out(liquidity: Decimal, sqrt_price_current: Decimal, token_in: Decimal, spread_factor: Decimal) -> Tuple[Decimal, Decimal, Decimal]: """ Computes and prints all one for zero test case parameters when swapping for in given out. Next sqrt price is computed from the given parameters. Returns the next square root price, token in and fee amount per share. @@ -80,7 +80,7 @@ def calc_test_case_in_given_out(liquidity: Decimal, sqrt_price_current: Decimal, liquidity, sqrt_price_current, sqrt_price_next) total_fee = sdk_dec.quo(sdk_dec.mul( - token_in, swap_fee), (sdk_dec.one - swap_fee)) + token_in, spread_factor), (sdk_dec.one - spread_factor)) fee_amount_per_share = sdk_dec.quo(total_fee, liquidity) @@ -95,7 +95,7 @@ def calc_test_case_in_given_out(liquidity: Decimal, sqrt_price_current: Decimal, return sqrt_price_next, token_in_after_fee, fee_amount_per_share -def calc_test_case_with_next_sqrt_price_out_given_in(liquidity: Decimal, sqrt_price_current: Decimal, sqrt_price_next: Decimal, swap_fee: Decimal) -> Tuple[Decimal, Decimal, Decimal]: +def calc_test_case_with_next_sqrt_price_out_given_in(liquidity: Decimal, sqrt_price_current: Decimal, sqrt_price_next: Decimal, spread_factor: Decimal) -> Tuple[Decimal, Decimal, Decimal]: """ Computes and prints one for zero test case parameters when next square root price is known. Assumes swapping for token out given in. Returns the expected token in, token out and fee amount per share. @@ -103,9 +103,9 @@ def calc_test_case_with_next_sqrt_price_out_given_in(liquidity: Decimal, sqrt_pr expected_token_in_before_fee = calc_amount_one_delta( liquidity, sqrt_price_current, sqrt_price_next, True) expected_fee = sdk_dec.zero - if swap_fee > sdk_dec.zero: + if spread_factor > sdk_dec.zero: expected_fee = sdk_dec.quo(sdk_dec.mul( - expected_token_in_before_fee, swap_fee), sdk_dec.one - swap_fee) + expected_token_in_before_fee, spread_factor), sdk_dec.one - spread_factor) expected_token_in = expected_token_in_before_fee + expected_fee @@ -124,7 +124,7 @@ def calc_test_case_with_next_sqrt_price_out_given_in(liquidity: Decimal, sqrt_pr return expected_token_in, token_out, fee_amount_per_share -def calc_test_case_with_next_sqrt_price_in_given_out(liquidity: Decimal, sqrt_price_current: Decimal, sqrt_price_next: Decimal, swap_fee: Decimal) -> Tuple[Decimal, Decimal, Decimal]: +def calc_test_case_with_next_sqrt_price_in_given_out(liquidity: Decimal, sqrt_price_current: Decimal, sqrt_price_next: Decimal, spread_factor: Decimal) -> Tuple[Decimal, Decimal, Decimal]: """ Computes and prints one for zero test case parameters when next square root price is known. Assumes swapping for token in given out. @@ -137,7 +137,7 @@ def calc_test_case_with_next_sqrt_price_in_given_out(liquidity: Decimal, sqrt_pr liquidity, sqrt_price_current, sqrt_price_next) total_fee = sdk_dec.quo(sdk_dec.mul( - token_in, swap_fee), (sdk_dec.one - swap_fee)) + token_in, spread_factor), (sdk_dec.one - spread_factor)) fee_amount_per_share = sdk_dec.quo(total_fee, liquidity) diff --git a/scripts/cl/out_given_in.py b/scripts/cl/out_given_in.py index 1ceac8e686d..0f8cf8055c4 100644 --- a/scripts/cl/out_given_in.py +++ b/scripts/cl/out_given_in.py @@ -5,13 +5,13 @@ import zero_for_one as zfo import one_for_zero as ofz -def estimate_test_case_out_given_in(tick_ranges: list[SqrtPriceRange], token_in_initial: Decimal, swap_fee: Decimal, is_zero_for_one: bool) -> Tuple[Decimal, Decimal]: +def estimate_test_case_out_given_in(tick_ranges: list[SqrtPriceRange], token_in_initial: Decimal, spread_factor: Decimal, is_zero_for_one: bool) -> Tuple[Decimal, Decimal]: """ Estimates a calc concentrated liquidity test case when swapping for token out given in. Given - sqrt price range with the start sqrt price, next sqrt price and liquidity - initial token in - - swap fee + - spread factor - zero for one boolean flag Estimates the final token out and the fee growth per share and prints it to stdout. Also, estimates these and other values at each range and prints them to stdout. @@ -39,9 +39,9 @@ def estimate_test_case_out_given_in(tick_ranges: list[SqrtPriceRange], token_in_ if is_with_next_sqrt_price: token_in_consumed, token_out, fee_growth_per_share = zero, zero, zero if is_zero_for_one: - token_in_consumed, token_out, fee_growth_per_share = zfo.calc_test_case_with_next_sqrt_price_out_given_in(tick_range.liquidity, tick_range.sqrt_price_start, tick_range.sqrt_price_next, swap_fee) + token_in_consumed, token_out, fee_growth_per_share = zfo.calc_test_case_with_next_sqrt_price_out_given_in(tick_range.liquidity, tick_range.sqrt_price_start, tick_range.sqrt_price_next, spread_factor) else: - token_in_consumed, token_out, fee_growth_per_share = ofz.calc_test_case_with_next_sqrt_price_out_given_in(tick_range.liquidity, tick_range.sqrt_price_start, tick_range.sqrt_price_next, swap_fee) + token_in_consumed, token_out, fee_growth_per_share = ofz.calc_test_case_with_next_sqrt_price_out_given_in(tick_range.liquidity, tick_range.sqrt_price_start, tick_range.sqrt_price_next, spread_factor) token_in_consumed_total += token_in_consumed token_out_total += token_out @@ -53,9 +53,9 @@ def estimate_test_case_out_given_in(tick_ranges: list[SqrtPriceRange], token_in_ token_out, fee_growth_per_share = zero, zero if is_zero_for_one: - _, token_out, fee_growth_per_share = zfo.calc_test_case_out_given_in(tick_range.liquidity, tick_range.sqrt_price_start, token_in_remaining, swap_fee) + _, token_out, fee_growth_per_share = zfo.calc_test_case_out_given_in(tick_range.liquidity, tick_range.sqrt_price_start, token_in_remaining, spread_factor) else: - _, token_out, fee_growth_per_share = ofz.calc_test_case_out_given_in(tick_range.liquidity, tick_range.sqrt_price_start, token_in_remaining, swap_fee) + _, token_out, fee_growth_per_share = ofz.calc_test_case_out_given_in(tick_range.liquidity, tick_range.sqrt_price_start, token_in_remaining, spread_factor) token_out_total += token_out fee_growth_per_share_total += fee_growth_per_share @@ -81,7 +81,7 @@ def estimate_single_position_within_one_tick_ofz(): """ is_zero_for_one = False - swap_fee = sdk_dec.new("0.01") + spread_factor = sdk_dec.new("0.01") token_in_initial = sdk_dec.new("42000000") tick_ranges = [ @@ -90,7 +90,7 @@ def estimate_single_position_within_one_tick_ofz(): print(tick_ranges[0].liquidity) - token_out_total, fee_growth_per_share_total = estimate_test_case_out_given_in(tick_ranges, token_in_initial, swap_fee, is_zero_for_one) + token_out_total, fee_growth_per_share_total = estimate_test_case_out_given_in(tick_ranges, token_in_initial, spread_factor, is_zero_for_one) expected_token_out_total = sdk_dec.new("8312") expected_fee_growth_per_share_total = sdk_dec.new("0.000276701288297452") @@ -105,28 +105,28 @@ def estimate_two_positions_within_one_tick_zfo(): """ is_zero_for_one = True - swap_fee = sdk_dec.new("0.03") + spread_factor = sdk_dec.new("0.03") token_in_initial = sdk_dec.new("13370") tick_ranges = [ SqrtPriceRange(5000, None, sdk_dec.new("3035764687.503020836176699298")), # last one must be computed based on remaining token in, therefore it is None ] - token_out_total, fee_growth_per_share_total = estimate_test_case_out_given_in(tick_ranges, token_in_initial, swap_fee, is_zero_for_one) + token_out_total, fee_growth_per_share_total = estimate_test_case_out_given_in(tick_ranges, token_in_initial, spread_factor, is_zero_for_one) expected_token_out_total = sdk_dec.new("64824917") expected_fee_growth_per_share_total = sdk_dec.new("0.000000132091924532") validate_confirmed_results(token_out_total, fee_growth_per_share_total, expected_token_out_total, expected_fee_growth_per_share_total) -def estimate_two_consecutive_positions_zfo(swap_fee: str, expected_token_out_total: str, expected_fee_growth_per_share_total: str): +def estimate_two_consecutive_positions_zfo(spread_factor: str, expected_token_out_total: str, expected_fee_growth_per_share_total: str): """Estimates and prints the results of a calc concentrated liquidity test case with two consecutive positions when swapping token zero for one (zfo). go test -timeout 30s -v -run TestKeeperTestSuite/TestCalcAndSwapOutAmtGivenIn/fee_3 github.com/osmosis-labs/osmosis/v15/x/concentrated-liquidity """ - swap_fee = sdk_dec.new(swap_fee) + spread_factor = sdk_dec.new(spread_factor) expected_token_out_total = sdk_dec.new(expected_token_out_total) expected_fee_growth_per_share_total = sdk_dec.new(expected_fee_growth_per_share_total) @@ -138,14 +138,14 @@ def estimate_two_consecutive_positions_zfo(swap_fee: str, expected_token_out_tot SqrtPriceRange(4545, None, sdk_dec.new("1198735489.597250295669959397")), # last one must be computed based on remaining token in, therefore it is None ] - token_out_total, fee_growth_per_share_total = estimate_test_case_out_given_in(tick_ranges, token_in_initial, swap_fee, is_zero_for_one) + token_out_total, fee_growth_per_share_total = estimate_test_case_out_given_in(tick_ranges, token_in_initial, spread_factor, is_zero_for_one) # TODO: this validation fails due to a different rounding strategy in scripts. # Needs investigation. # Go code should have the right value # validate_confirmed_results(token_out_total, fee_growth_per_share_total, expected_token_out_total, expected_fee_growth_per_share_total) -def estimate_overlapping_price_range_ofz_test(swap_fee: str, expected_token_out_total: str, expected_fee_growth_per_share_total: str): +def estimate_overlapping_price_range_ofz_test(spread_factor: str, expected_token_out_total: str, expected_fee_growth_per_share_total: str): """Estimates and prints the results of a calc concentrated liquidity test case with overlapping price ranges when swapping token one for token zero (ofz). @@ -153,7 +153,7 @@ def estimate_overlapping_price_range_ofz_test(swap_fee: str, expected_token_out_ """ is_zero_for_one = False - swap_fee = sdk_dec.new(swap_fee) + spread_factor = sdk_dec.new(spread_factor) token_in_initial = sdk_dec.new("10000000000") print("token_in_initial", token_in_initial) @@ -165,14 +165,14 @@ def estimate_overlapping_price_range_ofz_test(swap_fee: str, expected_token_out_ SqrtPriceRange(5500, None, sdk_dec.new("670416088.605668727039240782")), # last one must be computed based on remaining token in, therefore it is None ] - token_out_total, fee_growth_per_share_total = estimate_test_case_out_given_in(tick_ranges, token_in_initial, swap_fee, is_zero_for_one) + token_out_total, fee_growth_per_share_total = estimate_test_case_out_given_in(tick_ranges, token_in_initial, spread_factor, is_zero_for_one) expected_token_out_total = sdk_dec.new(expected_token_out_total) expected_fee_growth_per_share_total = sdk_dec.new(expected_fee_growth_per_share_total) validate_confirmed_results(token_out_total, fee_growth_per_share_total, expected_token_out_total, expected_fee_growth_per_share_total) -def estimate_overlapping_price_range_zfo_test(token_in_initial: str, swap_fee: str, expected_token_out_total: str, expected_fee_growth_per_share_total: str): +def estimate_overlapping_price_range_zfo_test(token_in_initial: str, spread_factor: str, expected_token_out_total: str, expected_fee_growth_per_share_total: str): """Estimates and prints the results of a calc concentrated liquidity test case with overlapping price ranges when swapping token zero for one (zfo) and not consuming full liquidity of the second position. @@ -180,7 +180,7 @@ def estimate_overlapping_price_range_zfo_test(token_in_initial: str, swap_fee: s """ is_zero_for_one = True - swap_fee = sdk_dec.new(swap_fee) + spread_factor = sdk_dec.new(spread_factor) token_in_initial = sdk_dec.new(token_in_initial) tick_ranges = [ @@ -189,7 +189,7 @@ def estimate_overlapping_price_range_zfo_test(token_in_initial: str, swap_fee: s SqrtPriceRange(4545, None, sdk_dec.new("670416215.718827443660400593000")), # last one must be computed based on remaining token in, therefore it is None ] - token_out_total, fee_growth_per_share_total = estimate_test_case_out_given_in(tick_ranges, token_in_initial, swap_fee, is_zero_for_one) + token_out_total, fee_growth_per_share_total = estimate_test_case_out_given_in(tick_ranges, token_in_initial, spread_factor, is_zero_for_one) expected_token_out_total = sdk_dec.new(expected_token_out_total) expected_fee_growth_per_share_total = sdk_dec.new(expected_fee_growth_per_share_total) @@ -204,7 +204,7 @@ def estimate_consecutive_positions_gap_ofz_test(): """ is_zero_for_one = False - swap_fee = sdk_dec.new("0.03") + spread_factor = sdk_dec.new("0.03") token_in_initial = sdk_dec.new("10000000000") tick_ranges = [ @@ -212,7 +212,7 @@ def estimate_consecutive_positions_gap_ofz_test(): SqrtPriceRange(5501, None, sdk_dec.new("1199528406.187413669220037261")), # last one must be computed based on remaining token in, therefore it is None ] - token_out_total, fee_growth_per_share_total = estimate_test_case_out_given_in(tick_ranges, token_in_initial, swap_fee, is_zero_for_one) + token_out_total, fee_growth_per_share_total = estimate_test_case_out_given_in(tick_ranges, token_in_initial, spread_factor, is_zero_for_one) expected_token_out_total = sdk_dec.new("1771252") expected_fee_growth_per_share_total = sdk_dec.new("0.221769187794051751") @@ -227,14 +227,14 @@ def estimate_slippage_protection_zfo_test(): """ is_zero_for_one = True - swap_fee = sdk_dec.new("0.01") + spread_factor = sdk_dec.new("0.01") token_in_initial = sdk_dec.new("13370") tick_ranges = [ SqrtPriceRange(5000, 4994, sdk_dec.new("1517882343.751510418088349649")), ] - token_out_total, fee_growth_per_share_total = estimate_test_case_out_given_in(tick_ranges, token_in_initial, swap_fee, is_zero_for_one) + token_out_total, fee_growth_per_share_total = estimate_test_case_out_given_in(tick_ranges, token_in_initial, spread_factor, is_zero_for_one) expected_token_out_total = sdk_dec.new("64417624") expected_fee_growth_per_share_total = sdk_dec.new("0.000000085792039652") diff --git a/scripts/cl/zero_for_one.py b/scripts/cl/zero_for_one.py index edbfb5b2592..38b6bfff459 100644 --- a/scripts/cl/zero_for_one.py +++ b/scripts/cl/zero_for_one.py @@ -36,12 +36,12 @@ def calc_amount_zero_delta(liquidity: Decimal, sqrt_price_current: Decimal, sqrt return result -def calc_test_case_out_given_in(liquidity: Decimal, sqrt_price_current: Decimal, token_in_remaining: Decimal, swap_fee: Decimal) -> Tuple[Decimal, Decimal, Decimal]: +def calc_test_case_out_given_in(liquidity: Decimal, sqrt_price_current: Decimal, token_in_remaining: Decimal, spread_factor: Decimal) -> Tuple[Decimal, Decimal, Decimal]: """ Computes and prints all zero for one test case parameters. Next sqrt price is computed from the given parameters. Returns the next square root price, token out and fee amount per share. """ token_in_remaining_after_fee = sdk_dec.mul( - token_in_remaining, (sdk_dec.one - swap_fee)) + token_in_remaining, (sdk_dec.one - spread_factor)) print(F"token_in_remaining_after_fee: {token_in_remaining_after_fee}") sqrt_price_next = get_next_sqrt_price( @@ -55,7 +55,7 @@ def calc_test_case_out_given_in(liquidity: Decimal, sqrt_price_current: Decimal, token_out = get_token_out(liquidity, sqrt_price_current, sqrt_price_next) fee_charge_total = sdk_dec.zero - if swap_fee > sdk_dec.zero: + if spread_factor > sdk_dec.zero: fee_charge_total = token_in_remaining - token_in_after_fee_rounded_up fee_amount_per_share = sdk_dec.quo(fee_charge_total, liquidity) @@ -69,7 +69,7 @@ def calc_test_case_out_given_in(liquidity: Decimal, sqrt_price_current: Decimal, return sqrt_price_next, token_out, fee_amount_per_share -def calc_test_case_in_given_out(liquidity: Decimal, sqrt_price_current: Decimal, token_out_remaining: Decimal, swap_fee: Decimal) -> Tuple[Decimal, Decimal, Decimal]: +def calc_test_case_in_given_out(liquidity: Decimal, sqrt_price_current: Decimal, token_out_remaining: Decimal, spread_factor: Decimal) -> Tuple[Decimal, Decimal, Decimal]: """ Computes and prints all zero for one test case parameters. Next sqrt price is computed from the given parameters. Returns the next square root price, token out and fee amount per share. """ @@ -80,7 +80,7 @@ def calc_test_case_in_given_out(liquidity: Decimal, sqrt_price_current: Decimal, liquidity, sqrt_price_current, sqrt_price_next) total_fee = sdk_dec.quo(sdk_dec.mul( - token_in, swap_fee), (sdk_dec.one - swap_fee)) + token_in, spread_factor), (sdk_dec.one - spread_factor)) fee_amount_per_share = sdk_dec.quo(total_fee, liquidity) token_in_after_fee = token_in + total_fee @@ -94,7 +94,7 @@ def calc_test_case_in_given_out(liquidity: Decimal, sqrt_price_current: Decimal, return sqrt_price_next, token_in_after_fee, fee_amount_per_share -def calc_test_case_with_next_sqrt_price_out_given_in(liquidity: Decimal, sqrt_price_current: Decimal, sqrt_price_next: Decimal, swap_fee: Decimal) -> Tuple[Decimal, Decimal, Decimal]: +def calc_test_case_with_next_sqrt_price_out_given_in(liquidity: Decimal, sqrt_price_current: Decimal, sqrt_price_next: Decimal, spread_factor: Decimal) -> Tuple[Decimal, Decimal, Decimal]: """ Computes and prints all zero for one test case parameters when next square root price is known. Returns the expected token in, token out and fee amount per share. @@ -102,7 +102,7 @@ def calc_test_case_with_next_sqrt_price_out_given_in(liquidity: Decimal, sqrt_pr expected_token_in_before_fee = calc_amount_zero_delta( liquidity, sqrt_price_current, sqrt_price_next, True) expected_fee = sdk_dec.quo(sdk_dec.mul( - expected_token_in_before_fee, swap_fee), (sdk_dec.one - swap_fee)) + expected_token_in_before_fee, spread_factor), (sdk_dec.one - spread_factor)) expected_token_in = expected_token_in_before_fee + expected_fee token_out = get_token_out(liquidity, sqrt_price_current, sqrt_price_next) @@ -120,7 +120,7 @@ def calc_test_case_with_next_sqrt_price_out_given_in(liquidity: Decimal, sqrt_pr return expected_token_in, token_out, fee_amount_per_share -def calc_test_case_with_next_sqrt_price_in_given_out(liquidity: Decimal, sqrt_price_current: Decimal, sqrt_price_next: Decimal, swap_fee: Decimal) -> Tuple[Decimal, Decimal, Decimal]: +def calc_test_case_with_next_sqrt_price_in_given_out(liquidity: Decimal, sqrt_price_current: Decimal, sqrt_price_next: Decimal, spread_factor: Decimal) -> Tuple[Decimal, Decimal, Decimal]: """ Computes and prints all zero for one test case parameters when next square root price is known. Assems swapping token for token in given out. @@ -133,7 +133,7 @@ def calc_test_case_with_next_sqrt_price_in_given_out(liquidity: Decimal, sqrt_pr liquidity, sqrt_price_current, sqrt_price_next) total_fee = sdk_dec.quo(sdk_dec.mul( - token_in, swap_fee), (sdk_dec.one - swap_fee)) + token_in, spread_factor), (sdk_dec.one - spread_factor)) fee_amount_per_share = sdk_dec.quo(total_fee, liquidity) token_in_after_fee = token_in + total_fee diff --git a/tests/cl-genesis-positions/convert.go b/tests/cl-genesis-positions/convert.go index df6f63aefee..e9c0d3e6f32 100644 --- a/tests/cl-genesis-positions/convert.go +++ b/tests/cl-genesis-positions/convert.go @@ -84,11 +84,11 @@ func ConvertSubgraphToOsmosisGenesis(positionCreatorAddresses []sdk.AccAddress, } msgCreatePool := model.MsgCreateConcentratedPool{ - Sender: osmosis.TestAccs[0].String(), - Denom0: denom0, - Denom1: denom1, - TickSpacing: 100, - SwapFee: sdk.MustNewDecFromStr("0.0005"), + Sender: osmosis.TestAccs[0].String(), + Denom0: denom0, + Denom1: denom1, + TickSpacing: 100, + SpreadFactor: sdk.MustNewDecFromStr("0.0005"), } err := msgCreatePool.ValidateBasic() diff --git a/tests/cl-go-client/main.go b/tests/cl-go-client/main.go index 0cf154b05b0..7cc4a4a9e91 100644 --- a/tests/cl-go-client/main.go +++ b/tests/cl-go-client/main.go @@ -127,11 +127,11 @@ func main() { func createPool(igniteClient cosmosclient.Client, accountName string) uint64 { msg := &model.MsgCreateConcentratedPool{ - Sender: getAccountAddressFromKeyring(igniteClient, accountName), - Denom1: denom0, - Denom0: denom1, - TickSpacing: 1, - SwapFee: sdk.ZeroDec(), + Sender: getAccountAddressFromKeyring(igniteClient, accountName), + Denom1: denom0, + Denom0: denom1, + TickSpacing: 1, + SpreadFactor: sdk.ZeroDec(), } txResp, err := igniteClient.BroadcastTx(accountName, msg) if err != nil { diff --git a/tests/e2e/configurer/chain/commands.go b/tests/e2e/configurer/chain/commands.go index c9b273f5afe..faf3268c720 100644 --- a/tests/e2e/configurer/chain/commands.go +++ b/tests/e2e/configurer/chain/commands.go @@ -69,10 +69,10 @@ func (n *NodeConfig) CollectFees(from, positionIds string) { // CreateConcentratedPool creates a concentrated pool. // Returns pool id of newly created pool on success -func (n *NodeConfig) CreateConcentratedPool(from, denom1, denom2 string, tickSpacing uint64, swapFee string) (uint64, error) { +func (n *NodeConfig) CreateConcentratedPool(from, denom1, denom2 string, tickSpacing uint64, spreadFactor string) (uint64, error) { n.LogActionF("creating concentrated pool") - cmd := []string{"osmosisd", "tx", "concentratedliquidity", "create-pool", denom1, denom2, fmt.Sprintf("%d", tickSpacing), swapFee, fmt.Sprintf("--from=%s", from)} + cmd := []string{"osmosisd", "tx", "concentratedliquidity", "create-pool", denom1, denom2, fmt.Sprintf("%d", tickSpacing), spreadFactor, fmt.Sprintf("--from=%s", from)} _, _, err := n.containerManager.ExecTxCmd(n.t, n.chainId, n.Name, cmd) if err != nil { return 0, err diff --git a/tests/e2e/e2e_test.go b/tests/e2e/e2e_test.go index 9810a4bc1bd..59af706f47d 100644 --- a/tests/e2e/e2e_test.go +++ b/tests/e2e/e2e_test.go @@ -192,11 +192,11 @@ func (s *IntegrationTestSuite) TestConcentratedLiquidity() { s.Require().NoError(err) var ( - denom0 = "uion" - denom1 = "uosmo" - tickSpacing uint64 = 100 - swapFee = "0.001" // 0.1% - swapFeeDec = sdk.MustNewDecFromStr("0.001") + denom0 = "uion" + denom1 = "uosmo" + tickSpacing uint64 = 100 + spreadFactor = "0.001" // 0.1% + spreadFactorDec = sdk.MustNewDecFromStr("0.001") ) // Get the permisionless pool creation parameter. @@ -216,7 +216,7 @@ func (s *IntegrationTestSuite) TestConcentratedLiquidity() { } // Create concentrated liquidity pool when permisionless pool creation is enabled. - poolID, err := chainANode.CreateConcentratedPool(initialization.ValidatorWalletName, denom0, denom1, tickSpacing, swapFee) + poolID, err := chainANode.CreateConcentratedPool(initialization.ValidatorWalletName, denom0, denom1, tickSpacing, spreadFactor) s.Require().NoError(err) concentratedPool := s.updatedConcentratedPool(chainANode, poolID) @@ -232,7 +232,7 @@ func (s *IntegrationTestSuite) TestConcentratedLiquidity() { s.Require().Equal(concentratedPool.GetToken1(), denom1) s.Require().Equal(concentratedPool.GetTickSpacing(), tickSpacing) s.Require().Equal(concentratedPool.GetExponentAtPriceOne(), cltypes.ExponentAtPriceOne) - s.Require().Equal(concentratedPool.GetSwapFee(sdk.Context{}), sdk.MustNewDecFromStr(swapFee)) + s.Require().Equal(concentratedPool.GetSpreadFactor(sdk.Context{}), sdk.MustNewDecFromStr(spreadFactor)) fundTokens := []string{"100000000uosmo", "100000000uion", "100000000stake"} @@ -305,7 +305,7 @@ func (s *IntegrationTestSuite) TestConcentratedLiquidity() { // Perform swap (not crossing initialized ticks) chainANode.SwapExactAmountIn(uosmoIn_Swap1, outMinAmt, fmt.Sprintf("%d", poolID), denom0, initialization.ValidatorWalletName) // Calculate and track global fee growth for swap 1 - feeGrowthGlobal.AddMut(calculateFeeGrowthGlobal(uosmoInDec_Swap1, swapFeeDec, concentratedPool.GetLiquidity())) + feeGrowthGlobal.AddMut(calculateFeeGrowthGlobal(uosmoInDec_Swap1, spreadFactorDec, concentratedPool.GetLiquidity())) // Update pool and track liquidity and sqrt price liquidityBeforeSwap := concentratedPool.GetLiquidity() @@ -320,7 +320,7 @@ func (s *IntegrationTestSuite) TestConcentratedLiquidity() { s.Require().Equal(liquidityAfterSwap.String(), liquidityBeforeSwap.String()) // Assert current sqrt price - inAmountSubFee := uosmoInDec_Swap1.Mul(sdk.OneDec().Sub(swapFeeDec)) + inAmountSubFee := uosmoInDec_Swap1.Mul(sdk.OneDec().Sub(spreadFactorDec)) expectedSqrtPriceDelta := inAmountSubFee.QuoTruncate(concentratedPool.GetLiquidity()) // Δ(sqrtPrice) = Δy / L expectedSqrtPrice := sqrtPriceBeforeSwap.Add(expectedSqrtPriceDelta) @@ -395,7 +395,7 @@ func (s *IntegrationTestSuite) TestConcentratedLiquidity() { // uosmoInDec_Swap2_NoFee is calculated such that swapping this amount (not considering fee) moves the price over the next initialized tick uosmoInDec_Swap2_NoFee = amountInToGetToNextInitTick.Add(amountInToGetToTickAfterInitialized) - uosmoInDec_Swap2 = uosmoInDec_Swap2_NoFee.Quo(sdk.OneDec().Sub(swapFeeDec)).TruncateDec() // account for swap fee of 1% + uosmoInDec_Swap2 = uosmoInDec_Swap2_NoFee.Quo(sdk.OneDec().Sub(spreadFactorDec)).TruncateDec() // account for spread factor of 1% uosmoIn_Swap2 = fmt.Sprintf("%suosmo", uosmoInDec_Swap2.String()) feeGrowthGlobal_Swap1 = feeGrowthGlobal.Clone() @@ -420,8 +420,8 @@ func (s *IntegrationTestSuite) TestConcentratedLiquidity() { // Step1: amountIn is uosmo tokens that are swapped + uosmo tokens that are paid for fee // hasReachedTarget in SwapStep is true, hence, to find fees, calculate: - // feeCharge = amountIn * swapFee / (1 - swapFee) - feeCharge_Swap2_Step1 := amountInToGetToNextInitTick.Mul(swapFeeDec).Quo(sdk.OneDec().Sub(swapFeeDec)) + // feeCharge = amountIn * spreadFactor / (1 - spreadFactor) + feeCharge_Swap2_Step1 := amountInToGetToNextInitTick.Mul(spreadFactorDec).Quo(sdk.OneDec().Sub(spreadFactorDec)) // Step2: hasReachedTarget in SwapStep is false (nextTick is 120000), hence, to find fees, calculate: // feeCharge = amountRemaining - amountOne @@ -536,8 +536,8 @@ func (s *IntegrationTestSuite) TestConcentratedLiquidity() { var ( // Swap parameters - uionInDec_Swap3_NoFee = amountInToGetToNextInitTick.Add(amountInToGetToTickBelowInitialized) // amount of uion to move price from current to desired (not considering swapFee) - uionInDec_Swap3 = uionInDec_Swap3_NoFee.Quo(sdk.OneDec().Sub(swapFeeDec)).TruncateDec() // consider swapFee + uionInDec_Swap3_NoFee = amountInToGetToNextInitTick.Add(amountInToGetToTickBelowInitialized) // amount of uion to move price from current to desired (not considering spreadFactor) + uionInDec_Swap3 = uionInDec_Swap3_NoFee.Quo(sdk.OneDec().Sub(spreadFactorDec)).TruncateDec() // consider spreadFactor uionIn_Swap3 = fmt.Sprintf("%suion", uionInDec_Swap3.String()) // Save variables from previous swaps @@ -568,8 +568,8 @@ func (s *IntegrationTestSuite) TestConcentratedLiquidity() { // Step1: amountIn is uion tokens that are swapped + uion tokens that are paid for fee // hasReachedTarget in SwapStep is true, hence, to find fees, calculate: - // feeCharge = amountIn * swapFee / (1 - swapFee) - feeCharge_Swap3_Step1 := amountInToGetToNextInitTick.Mul(swapFeeDec).Quo(sdk.OneDec().Sub(swapFeeDec)) + // feeCharge = amountIn * spreadFactor / (1 - spreadFactor) + feeCharge_Swap3_Step1 := amountInToGetToNextInitTick.Mul(spreadFactorDec).Quo(sdk.OneDec().Sub(spreadFactorDec)) // Step2: hasReachedTarget in SwapStep is false (next initialized tick is -20000), hence, to find fees, calculate: // feeCharge = amountRemaining - amountZero @@ -905,10 +905,10 @@ func (s *IntegrationTestSuite) TestCreateConcentratedLiquidityPoolVoting() { s.NoError(err) var ( - expectedDenom0 = "stake" - expectedDenom1 = "uosmo" - expectedTickspacing = uint64(100) - expectedSwapFee = "0.001000000000000000" + expectedDenom0 = "stake" + expectedDenom1 = "uosmo" + expectedTickspacing = uint64(100) + expectedSpreadFactor = "0.001000000000000000" ) poolId := chainANode.QueryNumPools() @@ -919,7 +919,7 @@ func (s *IntegrationTestSuite) TestCreateConcentratedLiquidityPoolVoting() { s.Require().Equal(expectedDenom0, concentratedPool.GetToken0()) s.Require().Equal(expectedDenom1, concentratedPool.GetToken1()) s.Require().Equal(expectedTickspacing, concentratedPool.GetTickSpacing()) - s.Require().Equal(expectedSwapFee, concentratedPool.GetSwapFee(sdk.Context{}).String()) + s.Require().Equal(expectedSpreadFactor, concentratedPool.GetSpreadFactor(sdk.Context{}).String()) return true }, @@ -1594,7 +1594,7 @@ func (s *IntegrationTestSuite) TestAConcentratedLiquidity_CanonicalPool_And_Para s.Require().Equal(v16.DesiredDenom0, concentratedPool.GetToken0()) s.Require().Equal(v16.DAIIBCDenom, concentratedPool.GetToken1()) s.Require().Equal(uint64(v16.TickSpacing), concentratedPool.GetTickSpacing()) - s.Require().Equal(expectedFee.String(), concentratedPool.GetSwapFee(sdk.Context{}).String()) + s.Require().Equal(expectedFee.String(), concentratedPool.GetSpreadFactor(sdk.Context{}).String()) // Get the permisionless pool creation parameter. isPermisionlessCreationEnabledStr := chainANode.QueryParams(cltypes.ModuleName, string(cltypes.KeyIsPermisionlessPoolCreationEnabled)) diff --git a/tests/e2e/helpers_e2e_test.go b/tests/e2e/helpers_e2e_test.go index 1ed8fbec3ff..b7d25829222 100644 --- a/tests/e2e/helpers_e2e_test.go +++ b/tests/e2e/helpers_e2e_test.go @@ -13,11 +13,11 @@ var defaultFeePerTx = sdk.NewInt(1000) // calculateFeeGrowthGlobal calculates fee growth global per unit of virtual liquidity based on swap parameters: // amountIn - amount being swapped -// swapFee - pool's swap fee +// spreadFactor - pool's spread factor // poolLiquidity - current pool liquidity -func calculateFeeGrowthGlobal(amountIn, swapFee, poolLiquidity sdk.Dec) sdk.Dec { - // First we get total fee charge for the swap (ΔY * swapFee) - feeChargeTotal := amountIn.Mul(swapFee) +func calculateFeeGrowthGlobal(amountIn, spreadFactor, poolLiquidity sdk.Dec) sdk.Dec { + // First we get total fee charge for the swap (ΔY * spreadFactor) + feeChargeTotal := amountIn.Mul(spreadFactor) // Calculating fee growth global (dividing by pool liquidity to find fee growth per unit of virtual liquidity) feeGrowthGlobal := feeChargeTotal.Quo(poolLiquidity) diff --git a/tests/mocks/cfmm_pool.go b/tests/mocks/cfmm_pool.go index b985649655d..a696d789c0a 100644 --- a/tests/mocks/cfmm_pool.go +++ b/tests/mocks/cfmm_pool.go @@ -52,24 +52,24 @@ func (mr *MockCFMMPoolIMockRecorder) CalcExitPoolCoinsFromShares(ctx, numShares, } // CalcInAmtGivenOut mocks base method. -func (m *MockCFMMPoolI) CalcInAmtGivenOut(ctx types.Context, tokenOut types.Coins, tokenInDenom string, swapFee types.Dec) (types.Coin, error) { +func (m *MockCFMMPoolI) CalcInAmtGivenOut(ctx types.Context, tokenOut types.Coins, tokenInDenom string, spreadFactor types.Dec) (types.Coin, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcInAmtGivenOut", ctx, tokenOut, tokenInDenom, swapFee) + ret := m.ctrl.Call(m, "CalcInAmtGivenOut", ctx, tokenOut, tokenInDenom, spreadFactor) ret0, _ := ret[0].(types.Coin) ret1, _ := ret[1].(error) return ret0, ret1 } // CalcInAmtGivenOut indicates an expected call of CalcInAmtGivenOut. -func (mr *MockCFMMPoolIMockRecorder) CalcInAmtGivenOut(ctx, tokenOut, tokenInDenom, swapFee interface{}) *gomock.Call { +func (mr *MockCFMMPoolIMockRecorder) CalcInAmtGivenOut(ctx, tokenOut, tokenInDenom, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcInAmtGivenOut", reflect.TypeOf((*MockCFMMPoolI)(nil).CalcInAmtGivenOut), ctx, tokenOut, tokenInDenom, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcInAmtGivenOut", reflect.TypeOf((*MockCFMMPoolI)(nil).CalcInAmtGivenOut), ctx, tokenOut, tokenInDenom, spreadFactor) } // CalcJoinPoolNoSwapShares mocks base method. -func (m *MockCFMMPoolI) CalcJoinPoolNoSwapShares(ctx types.Context, tokensIn types.Coins, swapFee types.Dec) (types.Int, types.Coins, error) { +func (m *MockCFMMPoolI) CalcJoinPoolNoSwapShares(ctx types.Context, tokensIn types.Coins, spreadFactor types.Dec) (types.Int, types.Coins, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcJoinPoolNoSwapShares", ctx, tokensIn, swapFee) + ret := m.ctrl.Call(m, "CalcJoinPoolNoSwapShares", ctx, tokensIn, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(types.Coins) ret2, _ := ret[2].(error) @@ -77,15 +77,15 @@ func (m *MockCFMMPoolI) CalcJoinPoolNoSwapShares(ctx types.Context, tokensIn typ } // CalcJoinPoolNoSwapShares indicates an expected call of CalcJoinPoolNoSwapShares. -func (mr *MockCFMMPoolIMockRecorder) CalcJoinPoolNoSwapShares(ctx, tokensIn, swapFee interface{}) *gomock.Call { +func (mr *MockCFMMPoolIMockRecorder) CalcJoinPoolNoSwapShares(ctx, tokensIn, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcJoinPoolNoSwapShares", reflect.TypeOf((*MockCFMMPoolI)(nil).CalcJoinPoolNoSwapShares), ctx, tokensIn, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcJoinPoolNoSwapShares", reflect.TypeOf((*MockCFMMPoolI)(nil).CalcJoinPoolNoSwapShares), ctx, tokensIn, spreadFactor) } // CalcJoinPoolShares mocks base method. -func (m *MockCFMMPoolI) CalcJoinPoolShares(ctx types.Context, tokensIn types.Coins, swapFee types.Dec) (types.Int, types.Coins, error) { +func (m *MockCFMMPoolI) CalcJoinPoolShares(ctx types.Context, tokensIn types.Coins, spreadFactor types.Dec) (types.Int, types.Coins, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcJoinPoolShares", ctx, tokensIn, swapFee) + ret := m.ctrl.Call(m, "CalcJoinPoolShares", ctx, tokensIn, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(types.Coins) ret2, _ := ret[2].(error) @@ -93,24 +93,24 @@ func (m *MockCFMMPoolI) CalcJoinPoolShares(ctx types.Context, tokensIn types.Coi } // CalcJoinPoolShares indicates an expected call of CalcJoinPoolShares. -func (mr *MockCFMMPoolIMockRecorder) CalcJoinPoolShares(ctx, tokensIn, swapFee interface{}) *gomock.Call { +func (mr *MockCFMMPoolIMockRecorder) CalcJoinPoolShares(ctx, tokensIn, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcJoinPoolShares", reflect.TypeOf((*MockCFMMPoolI)(nil).CalcJoinPoolShares), ctx, tokensIn, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcJoinPoolShares", reflect.TypeOf((*MockCFMMPoolI)(nil).CalcJoinPoolShares), ctx, tokensIn, spreadFactor) } // CalcOutAmtGivenIn mocks base method. -func (m *MockCFMMPoolI) CalcOutAmtGivenIn(ctx types.Context, tokenIn types.Coins, tokenOutDenom string, swapFee types.Dec) (types.Coin, error) { +func (m *MockCFMMPoolI) CalcOutAmtGivenIn(ctx types.Context, tokenIn types.Coins, tokenOutDenom string, spreadFactor types.Dec) (types.Coin, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcOutAmtGivenIn", ctx, tokenIn, tokenOutDenom, swapFee) + ret := m.ctrl.Call(m, "CalcOutAmtGivenIn", ctx, tokenIn, tokenOutDenom, spreadFactor) ret0, _ := ret[0].(types.Coin) ret1, _ := ret[1].(error) return ret0, ret1 } // CalcOutAmtGivenIn indicates an expected call of CalcOutAmtGivenIn. -func (mr *MockCFMMPoolIMockRecorder) CalcOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, swapFee interface{}) *gomock.Call { +func (mr *MockCFMMPoolIMockRecorder) CalcOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcOutAmtGivenIn", reflect.TypeOf((*MockCFMMPoolI)(nil).CalcOutAmtGivenIn), ctx, tokenIn, tokenOutDenom, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcOutAmtGivenIn", reflect.TypeOf((*MockCFMMPoolI)(nil).CalcOutAmtGivenIn), ctx, tokenIn, tokenOutDenom, spreadFactor) } // ExitPool mocks base method. @@ -170,18 +170,18 @@ func (mr *MockCFMMPoolIMockRecorder) GetId() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetId", reflect.TypeOf((*MockCFMMPoolI)(nil).GetId)) } -// GetSwapFee mocks base method. -func (m *MockCFMMPoolI) GetSwapFee(ctx types.Context) types.Dec { +// GetSpreadFactor mocks base method. +func (m *MockCFMMPoolI) GetSpreadFactor(ctx types.Context) types.Dec { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSwapFee", ctx) + ret := m.ctrl.Call(m, "GetSpreadFactor", ctx) ret0, _ := ret[0].(types.Dec) return ret0 } -// GetSwapFee indicates an expected call of GetSwapFee. -func (mr *MockCFMMPoolIMockRecorder) GetSwapFee(ctx interface{}) *gomock.Call { +// GetSpreadFactor indicates an expected call of GetSpreadFactor. +func (mr *MockCFMMPoolIMockRecorder) GetSpreadFactor(ctx interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSwapFee", reflect.TypeOf((*MockCFMMPoolI)(nil).GetSwapFee), ctx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSpreadFactor", reflect.TypeOf((*MockCFMMPoolI)(nil).GetSpreadFactor), ctx) } // GetTotalPoolLiquidity mocks base method. @@ -241,33 +241,33 @@ func (mr *MockCFMMPoolIMockRecorder) IsActive(ctx interface{}) *gomock.Call { } // JoinPool mocks base method. -func (m *MockCFMMPoolI) JoinPool(ctx types.Context, tokensIn types.Coins, swapFee types.Dec) (types.Int, error) { +func (m *MockCFMMPoolI) JoinPool(ctx types.Context, tokensIn types.Coins, spreadFactor types.Dec) (types.Int, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "JoinPool", ctx, tokensIn, swapFee) + ret := m.ctrl.Call(m, "JoinPool", ctx, tokensIn, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(error) return ret0, ret1 } // JoinPool indicates an expected call of JoinPool. -func (mr *MockCFMMPoolIMockRecorder) JoinPool(ctx, tokensIn, swapFee interface{}) *gomock.Call { +func (mr *MockCFMMPoolIMockRecorder) JoinPool(ctx, tokensIn, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "JoinPool", reflect.TypeOf((*MockCFMMPoolI)(nil).JoinPool), ctx, tokensIn, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "JoinPool", reflect.TypeOf((*MockCFMMPoolI)(nil).JoinPool), ctx, tokensIn, spreadFactor) } // JoinPoolNoSwap mocks base method. -func (m *MockCFMMPoolI) JoinPoolNoSwap(ctx types.Context, tokensIn types.Coins, swapFee types.Dec) (types.Int, error) { +func (m *MockCFMMPoolI) JoinPoolNoSwap(ctx types.Context, tokensIn types.Coins, spreadFactor types.Dec) (types.Int, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "JoinPoolNoSwap", ctx, tokensIn, swapFee) + ret := m.ctrl.Call(m, "JoinPoolNoSwap", ctx, tokensIn, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(error) return ret0, ret1 } // JoinPoolNoSwap indicates an expected call of JoinPoolNoSwap. -func (mr *MockCFMMPoolIMockRecorder) JoinPoolNoSwap(ctx, tokensIn, swapFee interface{}) *gomock.Call { +func (mr *MockCFMMPoolIMockRecorder) JoinPoolNoSwap(ctx, tokensIn, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "JoinPoolNoSwap", reflect.TypeOf((*MockCFMMPoolI)(nil).JoinPoolNoSwap), ctx, tokensIn, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "JoinPoolNoSwap", reflect.TypeOf((*MockCFMMPoolI)(nil).JoinPoolNoSwap), ctx, tokensIn, spreadFactor) } // ProtoMessage mocks base method. @@ -324,33 +324,33 @@ func (mr *MockCFMMPoolIMockRecorder) String() *gomock.Call { } // SwapInAmtGivenOut mocks base method. -func (m *MockCFMMPoolI) SwapInAmtGivenOut(ctx types.Context, tokenOut types.Coins, tokenInDenom string, swapFee types.Dec) (types.Coin, error) { +func (m *MockCFMMPoolI) SwapInAmtGivenOut(ctx types.Context, tokenOut types.Coins, tokenInDenom string, spreadFactor types.Dec) (types.Coin, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SwapInAmtGivenOut", ctx, tokenOut, tokenInDenom, swapFee) + ret := m.ctrl.Call(m, "SwapInAmtGivenOut", ctx, tokenOut, tokenInDenom, spreadFactor) ret0, _ := ret[0].(types.Coin) ret1, _ := ret[1].(error) return ret0, ret1 } // SwapInAmtGivenOut indicates an expected call of SwapInAmtGivenOut. -func (mr *MockCFMMPoolIMockRecorder) SwapInAmtGivenOut(ctx, tokenOut, tokenInDenom, swapFee interface{}) *gomock.Call { +func (mr *MockCFMMPoolIMockRecorder) SwapInAmtGivenOut(ctx, tokenOut, tokenInDenom, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapInAmtGivenOut", reflect.TypeOf((*MockCFMMPoolI)(nil).SwapInAmtGivenOut), ctx, tokenOut, tokenInDenom, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapInAmtGivenOut", reflect.TypeOf((*MockCFMMPoolI)(nil).SwapInAmtGivenOut), ctx, tokenOut, tokenInDenom, spreadFactor) } // SwapOutAmtGivenIn mocks base method. -func (m *MockCFMMPoolI) SwapOutAmtGivenIn(ctx types.Context, tokenIn types.Coins, tokenOutDenom string, swapFee types.Dec) (types.Coin, error) { +func (m *MockCFMMPoolI) SwapOutAmtGivenIn(ctx types.Context, tokenIn types.Coins, tokenOutDenom string, spreadFactor types.Dec) (types.Coin, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SwapOutAmtGivenIn", ctx, tokenIn, tokenOutDenom, swapFee) + ret := m.ctrl.Call(m, "SwapOutAmtGivenIn", ctx, tokenIn, tokenOutDenom, spreadFactor) ret0, _ := ret[0].(types.Coin) ret1, _ := ret[1].(error) return ret0, ret1 } // SwapOutAmtGivenIn indicates an expected call of SwapOutAmtGivenIn. -func (mr *MockCFMMPoolIMockRecorder) SwapOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, swapFee interface{}) *gomock.Call { +func (mr *MockCFMMPoolIMockRecorder) SwapOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapOutAmtGivenIn", reflect.TypeOf((*MockCFMMPoolI)(nil).SwapOutAmtGivenIn), ctx, tokenIn, tokenOutDenom, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapOutAmtGivenIn", reflect.TypeOf((*MockCFMMPoolI)(nil).SwapOutAmtGivenIn), ctx, tokenIn, tokenOutDenom, spreadFactor) } // MockPoolAmountOutExtension is a mock of PoolAmountOutExtension interface. @@ -392,24 +392,24 @@ func (mr *MockPoolAmountOutExtensionMockRecorder) CalcExitPoolCoinsFromShares(ct } // CalcInAmtGivenOut mocks base method. -func (m *MockPoolAmountOutExtension) CalcInAmtGivenOut(ctx types.Context, tokenOut types.Coins, tokenInDenom string, swapFee types.Dec) (types.Coin, error) { +func (m *MockPoolAmountOutExtension) CalcInAmtGivenOut(ctx types.Context, tokenOut types.Coins, tokenInDenom string, spreadFactor types.Dec) (types.Coin, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcInAmtGivenOut", ctx, tokenOut, tokenInDenom, swapFee) + ret := m.ctrl.Call(m, "CalcInAmtGivenOut", ctx, tokenOut, tokenInDenom, spreadFactor) ret0, _ := ret[0].(types.Coin) ret1, _ := ret[1].(error) return ret0, ret1 } // CalcInAmtGivenOut indicates an expected call of CalcInAmtGivenOut. -func (mr *MockPoolAmountOutExtensionMockRecorder) CalcInAmtGivenOut(ctx, tokenOut, tokenInDenom, swapFee interface{}) *gomock.Call { +func (mr *MockPoolAmountOutExtensionMockRecorder) CalcInAmtGivenOut(ctx, tokenOut, tokenInDenom, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcInAmtGivenOut", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).CalcInAmtGivenOut), ctx, tokenOut, tokenInDenom, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcInAmtGivenOut", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).CalcInAmtGivenOut), ctx, tokenOut, tokenInDenom, spreadFactor) } // CalcJoinPoolNoSwapShares mocks base method. -func (m *MockPoolAmountOutExtension) CalcJoinPoolNoSwapShares(ctx types.Context, tokensIn types.Coins, swapFee types.Dec) (types.Int, types.Coins, error) { +func (m *MockPoolAmountOutExtension) CalcJoinPoolNoSwapShares(ctx types.Context, tokensIn types.Coins, spreadFactor types.Dec) (types.Int, types.Coins, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcJoinPoolNoSwapShares", ctx, tokensIn, swapFee) + ret := m.ctrl.Call(m, "CalcJoinPoolNoSwapShares", ctx, tokensIn, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(types.Coins) ret2, _ := ret[2].(error) @@ -417,15 +417,15 @@ func (m *MockPoolAmountOutExtension) CalcJoinPoolNoSwapShares(ctx types.Context, } // CalcJoinPoolNoSwapShares indicates an expected call of CalcJoinPoolNoSwapShares. -func (mr *MockPoolAmountOutExtensionMockRecorder) CalcJoinPoolNoSwapShares(ctx, tokensIn, swapFee interface{}) *gomock.Call { +func (mr *MockPoolAmountOutExtensionMockRecorder) CalcJoinPoolNoSwapShares(ctx, tokensIn, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcJoinPoolNoSwapShares", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).CalcJoinPoolNoSwapShares), ctx, tokensIn, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcJoinPoolNoSwapShares", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).CalcJoinPoolNoSwapShares), ctx, tokensIn, spreadFactor) } // CalcJoinPoolShares mocks base method. -func (m *MockPoolAmountOutExtension) CalcJoinPoolShares(ctx types.Context, tokensIn types.Coins, swapFee types.Dec) (types.Int, types.Coins, error) { +func (m *MockPoolAmountOutExtension) CalcJoinPoolShares(ctx types.Context, tokensIn types.Coins, spreadFactor types.Dec) (types.Int, types.Coins, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcJoinPoolShares", ctx, tokensIn, swapFee) + ret := m.ctrl.Call(m, "CalcJoinPoolShares", ctx, tokensIn, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(types.Coins) ret2, _ := ret[2].(error) @@ -433,39 +433,39 @@ func (m *MockPoolAmountOutExtension) CalcJoinPoolShares(ctx types.Context, token } // CalcJoinPoolShares indicates an expected call of CalcJoinPoolShares. -func (mr *MockPoolAmountOutExtensionMockRecorder) CalcJoinPoolShares(ctx, tokensIn, swapFee interface{}) *gomock.Call { +func (mr *MockPoolAmountOutExtensionMockRecorder) CalcJoinPoolShares(ctx, tokensIn, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcJoinPoolShares", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).CalcJoinPoolShares), ctx, tokensIn, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcJoinPoolShares", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).CalcJoinPoolShares), ctx, tokensIn, spreadFactor) } // CalcOutAmtGivenIn mocks base method. -func (m *MockPoolAmountOutExtension) CalcOutAmtGivenIn(ctx types.Context, tokenIn types.Coins, tokenOutDenom string, swapFee types.Dec) (types.Coin, error) { +func (m *MockPoolAmountOutExtension) CalcOutAmtGivenIn(ctx types.Context, tokenIn types.Coins, tokenOutDenom string, spreadFactor types.Dec) (types.Coin, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcOutAmtGivenIn", ctx, tokenIn, tokenOutDenom, swapFee) + ret := m.ctrl.Call(m, "CalcOutAmtGivenIn", ctx, tokenIn, tokenOutDenom, spreadFactor) ret0, _ := ret[0].(types.Coin) ret1, _ := ret[1].(error) return ret0, ret1 } // CalcOutAmtGivenIn indicates an expected call of CalcOutAmtGivenIn. -func (mr *MockPoolAmountOutExtensionMockRecorder) CalcOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, swapFee interface{}) *gomock.Call { +func (mr *MockPoolAmountOutExtensionMockRecorder) CalcOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcOutAmtGivenIn", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).CalcOutAmtGivenIn), ctx, tokenIn, tokenOutDenom, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcOutAmtGivenIn", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).CalcOutAmtGivenIn), ctx, tokenIn, tokenOutDenom, spreadFactor) } // CalcTokenInShareAmountOut mocks base method. -func (m *MockPoolAmountOutExtension) CalcTokenInShareAmountOut(ctx types.Context, tokenInDenom string, shareOutAmount types.Int, swapFee types.Dec) (types.Int, error) { +func (m *MockPoolAmountOutExtension) CalcTokenInShareAmountOut(ctx types.Context, tokenInDenom string, shareOutAmount types.Int, spreadFactor types.Dec) (types.Int, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcTokenInShareAmountOut", ctx, tokenInDenom, shareOutAmount, swapFee) + ret := m.ctrl.Call(m, "CalcTokenInShareAmountOut", ctx, tokenInDenom, shareOutAmount, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(error) return ret0, ret1 } // CalcTokenInShareAmountOut indicates an expected call of CalcTokenInShareAmountOut. -func (mr *MockPoolAmountOutExtensionMockRecorder) CalcTokenInShareAmountOut(ctx, tokenInDenom, shareOutAmount, swapFee interface{}) *gomock.Call { +func (mr *MockPoolAmountOutExtensionMockRecorder) CalcTokenInShareAmountOut(ctx, tokenInDenom, shareOutAmount, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcTokenInShareAmountOut", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).CalcTokenInShareAmountOut), ctx, tokenInDenom, shareOutAmount, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcTokenInShareAmountOut", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).CalcTokenInShareAmountOut), ctx, tokenInDenom, shareOutAmount, spreadFactor) } // ExitPool mocks base method. @@ -540,18 +540,18 @@ func (mr *MockPoolAmountOutExtensionMockRecorder) GetId() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetId", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).GetId)) } -// GetSwapFee mocks base method. -func (m *MockPoolAmountOutExtension) GetSwapFee(ctx types.Context) types.Dec { +// GetSpreadFactor mocks base method. +func (m *MockPoolAmountOutExtension) GetSpreadFactor(ctx types.Context) types.Dec { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSwapFee", ctx) + ret := m.ctrl.Call(m, "GetSpreadFactor", ctx) ret0, _ := ret[0].(types.Dec) return ret0 } -// GetSwapFee indicates an expected call of GetSwapFee. -func (mr *MockPoolAmountOutExtensionMockRecorder) GetSwapFee(ctx interface{}) *gomock.Call { +// GetSpreadFactor indicates an expected call of GetSpreadFactor. +func (mr *MockPoolAmountOutExtensionMockRecorder) GetSpreadFactor(ctx interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSwapFee", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).GetSwapFee), ctx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSpreadFactor", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).GetSpreadFactor), ctx) } // GetTotalPoolLiquidity mocks base method. @@ -623,33 +623,33 @@ func (mr *MockPoolAmountOutExtensionMockRecorder) IsActive(ctx interface{}) *gom } // JoinPool mocks base method. -func (m *MockPoolAmountOutExtension) JoinPool(ctx types.Context, tokensIn types.Coins, swapFee types.Dec) (types.Int, error) { +func (m *MockPoolAmountOutExtension) JoinPool(ctx types.Context, tokensIn types.Coins, spreadFactor types.Dec) (types.Int, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "JoinPool", ctx, tokensIn, swapFee) + ret := m.ctrl.Call(m, "JoinPool", ctx, tokensIn, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(error) return ret0, ret1 } // JoinPool indicates an expected call of JoinPool. -func (mr *MockPoolAmountOutExtensionMockRecorder) JoinPool(ctx, tokensIn, swapFee interface{}) *gomock.Call { +func (mr *MockPoolAmountOutExtensionMockRecorder) JoinPool(ctx, tokensIn, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "JoinPool", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).JoinPool), ctx, tokensIn, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "JoinPool", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).JoinPool), ctx, tokensIn, spreadFactor) } // JoinPoolNoSwap mocks base method. -func (m *MockPoolAmountOutExtension) JoinPoolNoSwap(ctx types.Context, tokensIn types.Coins, swapFee types.Dec) (types.Int, error) { +func (m *MockPoolAmountOutExtension) JoinPoolNoSwap(ctx types.Context, tokensIn types.Coins, spreadFactor types.Dec) (types.Int, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "JoinPoolNoSwap", ctx, tokensIn, swapFee) + ret := m.ctrl.Call(m, "JoinPoolNoSwap", ctx, tokensIn, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(error) return ret0, ret1 } // JoinPoolNoSwap indicates an expected call of JoinPoolNoSwap. -func (mr *MockPoolAmountOutExtensionMockRecorder) JoinPoolNoSwap(ctx, tokensIn, swapFee interface{}) *gomock.Call { +func (mr *MockPoolAmountOutExtensionMockRecorder) JoinPoolNoSwap(ctx, tokensIn, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "JoinPoolNoSwap", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).JoinPoolNoSwap), ctx, tokensIn, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "JoinPoolNoSwap", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).JoinPoolNoSwap), ctx, tokensIn, spreadFactor) } // JoinPoolTokenInMaxShareAmountOut mocks base method. @@ -721,33 +721,33 @@ func (mr *MockPoolAmountOutExtensionMockRecorder) String() *gomock.Call { } // SwapInAmtGivenOut mocks base method. -func (m *MockPoolAmountOutExtension) SwapInAmtGivenOut(ctx types.Context, tokenOut types.Coins, tokenInDenom string, swapFee types.Dec) (types.Coin, error) { +func (m *MockPoolAmountOutExtension) SwapInAmtGivenOut(ctx types.Context, tokenOut types.Coins, tokenInDenom string, spreadFactor types.Dec) (types.Coin, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SwapInAmtGivenOut", ctx, tokenOut, tokenInDenom, swapFee) + ret := m.ctrl.Call(m, "SwapInAmtGivenOut", ctx, tokenOut, tokenInDenom, spreadFactor) ret0, _ := ret[0].(types.Coin) ret1, _ := ret[1].(error) return ret0, ret1 } // SwapInAmtGivenOut indicates an expected call of SwapInAmtGivenOut. -func (mr *MockPoolAmountOutExtensionMockRecorder) SwapInAmtGivenOut(ctx, tokenOut, tokenInDenom, swapFee interface{}) *gomock.Call { +func (mr *MockPoolAmountOutExtensionMockRecorder) SwapInAmtGivenOut(ctx, tokenOut, tokenInDenom, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapInAmtGivenOut", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).SwapInAmtGivenOut), ctx, tokenOut, tokenInDenom, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapInAmtGivenOut", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).SwapInAmtGivenOut), ctx, tokenOut, tokenInDenom, spreadFactor) } // SwapOutAmtGivenIn mocks base method. -func (m *MockPoolAmountOutExtension) SwapOutAmtGivenIn(ctx types.Context, tokenIn types.Coins, tokenOutDenom string, swapFee types.Dec) (types.Coin, error) { +func (m *MockPoolAmountOutExtension) SwapOutAmtGivenIn(ctx types.Context, tokenIn types.Coins, tokenOutDenom string, spreadFactor types.Dec) (types.Coin, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SwapOutAmtGivenIn", ctx, tokenIn, tokenOutDenom, swapFee) + ret := m.ctrl.Call(m, "SwapOutAmtGivenIn", ctx, tokenIn, tokenOutDenom, spreadFactor) ret0, _ := ret[0].(types.Coin) ret1, _ := ret[1].(error) return ret0, ret1 } // SwapOutAmtGivenIn indicates an expected call of SwapOutAmtGivenIn. -func (mr *MockPoolAmountOutExtensionMockRecorder) SwapOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, swapFee interface{}) *gomock.Call { +func (mr *MockPoolAmountOutExtensionMockRecorder) SwapOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapOutAmtGivenIn", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).SwapOutAmtGivenIn), ctx, tokenIn, tokenOutDenom, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapOutAmtGivenIn", reflect.TypeOf((*MockPoolAmountOutExtension)(nil).SwapOutAmtGivenIn), ctx, tokenIn, tokenOutDenom, spreadFactor) } // MockWeightedPoolExtension is a mock of WeightedPoolExtension interface. @@ -789,24 +789,24 @@ func (mr *MockWeightedPoolExtensionMockRecorder) CalcExitPoolCoinsFromShares(ctx } // CalcInAmtGivenOut mocks base method. -func (m *MockWeightedPoolExtension) CalcInAmtGivenOut(ctx types.Context, tokenOut types.Coins, tokenInDenom string, swapFee types.Dec) (types.Coin, error) { +func (m *MockWeightedPoolExtension) CalcInAmtGivenOut(ctx types.Context, tokenOut types.Coins, tokenInDenom string, spreadFactor types.Dec) (types.Coin, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcInAmtGivenOut", ctx, tokenOut, tokenInDenom, swapFee) + ret := m.ctrl.Call(m, "CalcInAmtGivenOut", ctx, tokenOut, tokenInDenom, spreadFactor) ret0, _ := ret[0].(types.Coin) ret1, _ := ret[1].(error) return ret0, ret1 } // CalcInAmtGivenOut indicates an expected call of CalcInAmtGivenOut. -func (mr *MockWeightedPoolExtensionMockRecorder) CalcInAmtGivenOut(ctx, tokenOut, tokenInDenom, swapFee interface{}) *gomock.Call { +func (mr *MockWeightedPoolExtensionMockRecorder) CalcInAmtGivenOut(ctx, tokenOut, tokenInDenom, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcInAmtGivenOut", reflect.TypeOf((*MockWeightedPoolExtension)(nil).CalcInAmtGivenOut), ctx, tokenOut, tokenInDenom, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcInAmtGivenOut", reflect.TypeOf((*MockWeightedPoolExtension)(nil).CalcInAmtGivenOut), ctx, tokenOut, tokenInDenom, spreadFactor) } // CalcJoinPoolNoSwapShares mocks base method. -func (m *MockWeightedPoolExtension) CalcJoinPoolNoSwapShares(ctx types.Context, tokensIn types.Coins, swapFee types.Dec) (types.Int, types.Coins, error) { +func (m *MockWeightedPoolExtension) CalcJoinPoolNoSwapShares(ctx types.Context, tokensIn types.Coins, spreadFactor types.Dec) (types.Int, types.Coins, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcJoinPoolNoSwapShares", ctx, tokensIn, swapFee) + ret := m.ctrl.Call(m, "CalcJoinPoolNoSwapShares", ctx, tokensIn, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(types.Coins) ret2, _ := ret[2].(error) @@ -814,15 +814,15 @@ func (m *MockWeightedPoolExtension) CalcJoinPoolNoSwapShares(ctx types.Context, } // CalcJoinPoolNoSwapShares indicates an expected call of CalcJoinPoolNoSwapShares. -func (mr *MockWeightedPoolExtensionMockRecorder) CalcJoinPoolNoSwapShares(ctx, tokensIn, swapFee interface{}) *gomock.Call { +func (mr *MockWeightedPoolExtensionMockRecorder) CalcJoinPoolNoSwapShares(ctx, tokensIn, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcJoinPoolNoSwapShares", reflect.TypeOf((*MockWeightedPoolExtension)(nil).CalcJoinPoolNoSwapShares), ctx, tokensIn, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcJoinPoolNoSwapShares", reflect.TypeOf((*MockWeightedPoolExtension)(nil).CalcJoinPoolNoSwapShares), ctx, tokensIn, spreadFactor) } // CalcJoinPoolShares mocks base method. -func (m *MockWeightedPoolExtension) CalcJoinPoolShares(ctx types.Context, tokensIn types.Coins, swapFee types.Dec) (types.Int, types.Coins, error) { +func (m *MockWeightedPoolExtension) CalcJoinPoolShares(ctx types.Context, tokensIn types.Coins, spreadFactor types.Dec) (types.Int, types.Coins, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcJoinPoolShares", ctx, tokensIn, swapFee) + ret := m.ctrl.Call(m, "CalcJoinPoolShares", ctx, tokensIn, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(types.Coins) ret2, _ := ret[2].(error) @@ -830,24 +830,24 @@ func (m *MockWeightedPoolExtension) CalcJoinPoolShares(ctx types.Context, tokens } // CalcJoinPoolShares indicates an expected call of CalcJoinPoolShares. -func (mr *MockWeightedPoolExtensionMockRecorder) CalcJoinPoolShares(ctx, tokensIn, swapFee interface{}) *gomock.Call { +func (mr *MockWeightedPoolExtensionMockRecorder) CalcJoinPoolShares(ctx, tokensIn, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcJoinPoolShares", reflect.TypeOf((*MockWeightedPoolExtension)(nil).CalcJoinPoolShares), ctx, tokensIn, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcJoinPoolShares", reflect.TypeOf((*MockWeightedPoolExtension)(nil).CalcJoinPoolShares), ctx, tokensIn, spreadFactor) } // CalcOutAmtGivenIn mocks base method. -func (m *MockWeightedPoolExtension) CalcOutAmtGivenIn(ctx types.Context, tokenIn types.Coins, tokenOutDenom string, swapFee types.Dec) (types.Coin, error) { +func (m *MockWeightedPoolExtension) CalcOutAmtGivenIn(ctx types.Context, tokenIn types.Coins, tokenOutDenom string, spreadFactor types.Dec) (types.Coin, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcOutAmtGivenIn", ctx, tokenIn, tokenOutDenom, swapFee) + ret := m.ctrl.Call(m, "CalcOutAmtGivenIn", ctx, tokenIn, tokenOutDenom, spreadFactor) ret0, _ := ret[0].(types.Coin) ret1, _ := ret[1].(error) return ret0, ret1 } // CalcOutAmtGivenIn indicates an expected call of CalcOutAmtGivenIn. -func (mr *MockWeightedPoolExtensionMockRecorder) CalcOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, swapFee interface{}) *gomock.Call { +func (mr *MockWeightedPoolExtensionMockRecorder) CalcOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcOutAmtGivenIn", reflect.TypeOf((*MockWeightedPoolExtension)(nil).CalcOutAmtGivenIn), ctx, tokenIn, tokenOutDenom, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcOutAmtGivenIn", reflect.TypeOf((*MockWeightedPoolExtension)(nil).CalcOutAmtGivenIn), ctx, tokenIn, tokenOutDenom, spreadFactor) } // ExitPool mocks base method. @@ -907,18 +907,18 @@ func (mr *MockWeightedPoolExtensionMockRecorder) GetId() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetId", reflect.TypeOf((*MockWeightedPoolExtension)(nil).GetId)) } -// GetSwapFee mocks base method. -func (m *MockWeightedPoolExtension) GetSwapFee(ctx types.Context) types.Dec { +// GetSpreadFactor mocks base method. +func (m *MockWeightedPoolExtension) GetSpreadFactor(ctx types.Context) types.Dec { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSwapFee", ctx) + ret := m.ctrl.Call(m, "GetSpreadFactor", ctx) ret0, _ := ret[0].(types.Dec) return ret0 } -// GetSwapFee indicates an expected call of GetSwapFee. -func (mr *MockWeightedPoolExtensionMockRecorder) GetSwapFee(ctx interface{}) *gomock.Call { +// GetSpreadFactor indicates an expected call of GetSpreadFactor. +func (mr *MockWeightedPoolExtensionMockRecorder) GetSpreadFactor(ctx interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSwapFee", reflect.TypeOf((*MockWeightedPoolExtension)(nil).GetSwapFee), ctx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSpreadFactor", reflect.TypeOf((*MockWeightedPoolExtension)(nil).GetSpreadFactor), ctx) } // GetTokenWeight mocks base method. @@ -993,33 +993,33 @@ func (mr *MockWeightedPoolExtensionMockRecorder) IsActive(ctx interface{}) *gomo } // JoinPool mocks base method. -func (m *MockWeightedPoolExtension) JoinPool(ctx types.Context, tokensIn types.Coins, swapFee types.Dec) (types.Int, error) { +func (m *MockWeightedPoolExtension) JoinPool(ctx types.Context, tokensIn types.Coins, spreadFactor types.Dec) (types.Int, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "JoinPool", ctx, tokensIn, swapFee) + ret := m.ctrl.Call(m, "JoinPool", ctx, tokensIn, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(error) return ret0, ret1 } // JoinPool indicates an expected call of JoinPool. -func (mr *MockWeightedPoolExtensionMockRecorder) JoinPool(ctx, tokensIn, swapFee interface{}) *gomock.Call { +func (mr *MockWeightedPoolExtensionMockRecorder) JoinPool(ctx, tokensIn, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "JoinPool", reflect.TypeOf((*MockWeightedPoolExtension)(nil).JoinPool), ctx, tokensIn, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "JoinPool", reflect.TypeOf((*MockWeightedPoolExtension)(nil).JoinPool), ctx, tokensIn, spreadFactor) } // JoinPoolNoSwap mocks base method. -func (m *MockWeightedPoolExtension) JoinPoolNoSwap(ctx types.Context, tokensIn types.Coins, swapFee types.Dec) (types.Int, error) { +func (m *MockWeightedPoolExtension) JoinPoolNoSwap(ctx types.Context, tokensIn types.Coins, spreadFactor types.Dec) (types.Int, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "JoinPoolNoSwap", ctx, tokensIn, swapFee) + ret := m.ctrl.Call(m, "JoinPoolNoSwap", ctx, tokensIn, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(error) return ret0, ret1 } // JoinPoolNoSwap indicates an expected call of JoinPoolNoSwap. -func (mr *MockWeightedPoolExtensionMockRecorder) JoinPoolNoSwap(ctx, tokensIn, swapFee interface{}) *gomock.Call { +func (mr *MockWeightedPoolExtensionMockRecorder) JoinPoolNoSwap(ctx, tokensIn, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "JoinPoolNoSwap", reflect.TypeOf((*MockWeightedPoolExtension)(nil).JoinPoolNoSwap), ctx, tokensIn, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "JoinPoolNoSwap", reflect.TypeOf((*MockWeightedPoolExtension)(nil).JoinPoolNoSwap), ctx, tokensIn, spreadFactor) } // PokePool mocks base method. @@ -1088,31 +1088,31 @@ func (mr *MockWeightedPoolExtensionMockRecorder) String() *gomock.Call { } // SwapInAmtGivenOut mocks base method. -func (m *MockWeightedPoolExtension) SwapInAmtGivenOut(ctx types.Context, tokenOut types.Coins, tokenInDenom string, swapFee types.Dec) (types.Coin, error) { +func (m *MockWeightedPoolExtension) SwapInAmtGivenOut(ctx types.Context, tokenOut types.Coins, tokenInDenom string, spreadFactor types.Dec) (types.Coin, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SwapInAmtGivenOut", ctx, tokenOut, tokenInDenom, swapFee) + ret := m.ctrl.Call(m, "SwapInAmtGivenOut", ctx, tokenOut, tokenInDenom, spreadFactor) ret0, _ := ret[0].(types.Coin) ret1, _ := ret[1].(error) return ret0, ret1 } // SwapInAmtGivenOut indicates an expected call of SwapInAmtGivenOut. -func (mr *MockWeightedPoolExtensionMockRecorder) SwapInAmtGivenOut(ctx, tokenOut, tokenInDenom, swapFee interface{}) *gomock.Call { +func (mr *MockWeightedPoolExtensionMockRecorder) SwapInAmtGivenOut(ctx, tokenOut, tokenInDenom, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapInAmtGivenOut", reflect.TypeOf((*MockWeightedPoolExtension)(nil).SwapInAmtGivenOut), ctx, tokenOut, tokenInDenom, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapInAmtGivenOut", reflect.TypeOf((*MockWeightedPoolExtension)(nil).SwapInAmtGivenOut), ctx, tokenOut, tokenInDenom, spreadFactor) } // SwapOutAmtGivenIn mocks base method. -func (m *MockWeightedPoolExtension) SwapOutAmtGivenIn(ctx types.Context, tokenIn types.Coins, tokenOutDenom string, swapFee types.Dec) (types.Coin, error) { +func (m *MockWeightedPoolExtension) SwapOutAmtGivenIn(ctx types.Context, tokenIn types.Coins, tokenOutDenom string, spreadFactor types.Dec) (types.Coin, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SwapOutAmtGivenIn", ctx, tokenIn, tokenOutDenom, swapFee) + ret := m.ctrl.Call(m, "SwapOutAmtGivenIn", ctx, tokenIn, tokenOutDenom, spreadFactor) ret0, _ := ret[0].(types.Coin) ret1, _ := ret[1].(error) return ret0, ret1 } // SwapOutAmtGivenIn indicates an expected call of SwapOutAmtGivenIn. -func (mr *MockWeightedPoolExtensionMockRecorder) SwapOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, swapFee interface{}) *gomock.Call { +func (mr *MockWeightedPoolExtensionMockRecorder) SwapOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapOutAmtGivenIn", reflect.TypeOf((*MockWeightedPoolExtension)(nil).SwapOutAmtGivenIn), ctx, tokenIn, tokenOutDenom, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapOutAmtGivenIn", reflect.TypeOf((*MockWeightedPoolExtension)(nil).SwapOutAmtGivenIn), ctx, tokenIn, tokenOutDenom, spreadFactor) } diff --git a/tests/mocks/cl_pool.go b/tests/mocks/cl_pool.go index 3c3bc3b32a2..4a9e48da4dc 100644 --- a/tests/mocks/cl_pool.go +++ b/tests/mocks/cl_pool.go @@ -162,18 +162,18 @@ func (mr *MockConcentratedPoolExtensionMockRecorder) GetExponentAtPriceOne() *go return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetExponentAtPriceOne", reflect.TypeOf((*MockConcentratedPoolExtension)(nil).GetExponentAtPriceOne)) } -// GetSwapFee mocks base method. -func (m *MockConcentratedPoolExtension) GetSwapFee(ctx types.Context) types.Dec { +// GetSpreadFactor mocks base method. +func (m *MockConcentratedPoolExtension) GetSpreadFactor(ctx types.Context) types.Dec { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSwapFee", ctx) + ret := m.ctrl.Call(m, "GetSpreadFactor", ctx) ret0, _ := ret[0].(types.Dec) return ret0 } -// GetSwapFee indicates an expected call of GetSwapFee. -func (mr *MockConcentratedPoolExtensionMockRecorder) GetSwapFee(ctx interface{}) *gomock.Call { +// GetSpreadFactor indicates an expected call of GetSpreadFactor. +func (mr *MockConcentratedPoolExtensionMockRecorder) GetSpreadFactor(ctx interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSwapFee", reflect.TypeOf((*MockConcentratedPoolExtension)(nil).GetSwapFee), ctx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSpreadFactor", reflect.TypeOf((*MockConcentratedPoolExtension)(nil).GetSpreadFactor), ctx) } // GetTickSpacing mocks base method. diff --git a/tests/mocks/pool.go b/tests/mocks/pool.go new file mode 100644 index 00000000000..41879a11f17 --- /dev/null +++ b/tests/mocks/pool.go @@ -0,0 +1,159 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: x/poolmanager/types/pool.go + +// Package mocks is a generated GoMock package. +package mocks + +import ( + reflect "reflect" + + types "github.com/cosmos/cosmos-sdk/types" + gomock "github.com/golang/mock/gomock" + types0 "github.com/osmosis-labs/osmosis/v15/x/poolmanager/types" +) + +// MockPoolI is a mock of PoolI interface. +type MockPoolI struct { + ctrl *gomock.Controller + recorder *MockPoolIMockRecorder +} + +// MockPoolIMockRecorder is the mock recorder for MockPoolI. +type MockPoolIMockRecorder struct { + mock *MockPoolI +} + +// NewMockPoolI creates a new mock instance. +func NewMockPoolI(ctrl *gomock.Controller) *MockPoolI { + mock := &MockPoolI{ctrl: ctrl} + mock.recorder = &MockPoolIMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockPoolI) EXPECT() *MockPoolIMockRecorder { + return m.recorder +} + +// GetAddress mocks base method. +func (m *MockPoolI) GetAddress() types.AccAddress { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAddress") + ret0, _ := ret[0].(types.AccAddress) + return ret0 +} + +// GetAddress indicates an expected call of GetAddress. +func (mr *MockPoolIMockRecorder) GetAddress() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAddress", reflect.TypeOf((*MockPoolI)(nil).GetAddress)) +} + +// GetId mocks base method. +func (m *MockPoolI) GetId() uint64 { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetId") + ret0, _ := ret[0].(uint64) + return ret0 +} + +// GetId indicates an expected call of GetId. +func (mr *MockPoolIMockRecorder) GetId() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetId", reflect.TypeOf((*MockPoolI)(nil).GetId)) +} + +// GetSpreadFactor mocks base method. +func (m *MockPoolI) GetSpreadFactor(ctx types.Context) types.Dec { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSpreadFactor", ctx) + ret0, _ := ret[0].(types.Dec) + return ret0 +} + +// GetSpreadFactor indicates an expected call of GetSpreadFactor. +func (mr *MockPoolIMockRecorder) GetSpreadFactor(ctx interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSpreadFactor", reflect.TypeOf((*MockPoolI)(nil).GetSpreadFactor), ctx) +} + +// GetType mocks base method. +func (m *MockPoolI) GetType() types0.PoolType { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetType") + ret0, _ := ret[0].(types0.PoolType) + return ret0 +} + +// GetType indicates an expected call of GetType. +func (mr *MockPoolIMockRecorder) GetType() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetType", reflect.TypeOf((*MockPoolI)(nil).GetType)) +} + +// IsActive mocks base method. +func (m *MockPoolI) IsActive(ctx types.Context) bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "IsActive", ctx) + ret0, _ := ret[0].(bool) + return ret0 +} + +// IsActive indicates an expected call of IsActive. +func (mr *MockPoolIMockRecorder) IsActive(ctx interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsActive", reflect.TypeOf((*MockPoolI)(nil).IsActive), ctx) +} + +// ProtoMessage mocks base method. +func (m *MockPoolI) ProtoMessage() { + m.ctrl.T.Helper() + m.ctrl.Call(m, "ProtoMessage") +} + +// ProtoMessage indicates an expected call of ProtoMessage. +func (mr *MockPoolIMockRecorder) ProtoMessage() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProtoMessage", reflect.TypeOf((*MockPoolI)(nil).ProtoMessage)) +} + +// Reset mocks base method. +func (m *MockPoolI) Reset() { + m.ctrl.T.Helper() + m.ctrl.Call(m, "Reset") +} + +// Reset indicates an expected call of Reset. +func (mr *MockPoolIMockRecorder) Reset() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Reset", reflect.TypeOf((*MockPoolI)(nil).Reset)) +} + +// SpotPrice mocks base method. +func (m *MockPoolI) SpotPrice(ctx types.Context, quoteAssetDenom, baseAssetDenom string) (types.Dec, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SpotPrice", ctx, quoteAssetDenom, baseAssetDenom) + ret0, _ := ret[0].(types.Dec) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// SpotPrice indicates an expected call of SpotPrice. +func (mr *MockPoolIMockRecorder) SpotPrice(ctx, quoteAssetDenom, baseAssetDenom interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SpotPrice", reflect.TypeOf((*MockPoolI)(nil).SpotPrice), ctx, quoteAssetDenom, baseAssetDenom) +} + +// String mocks base method. +func (m *MockPoolI) String() string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "String") + ret0, _ := ret[0].(string) + return ret0 +} + +// String indicates an expected call of String. +func (mr *MockPoolIMockRecorder) String() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "String", reflect.TypeOf((*MockPoolI)(nil).String)) +} diff --git a/tests/mocks/pool_module.go b/tests/mocks/pool_module.go index 8badde0452e..e6656fd381b 100644 --- a/tests/mocks/pool_module.go +++ b/tests/mocks/pool_module.go @@ -201,33 +201,33 @@ func (m *MockPoolModuleI) EXPECT() *MockPoolModuleIMockRecorder { } // CalcInAmtGivenOut mocks base method. -func (m *MockPoolModuleI) CalcInAmtGivenOut(ctx types.Context, poolI types2.PoolI, tokenOut types.Coin, tokenInDenom string, swapFee types.Dec) (types.Coin, error) { +func (m *MockPoolModuleI) CalcInAmtGivenOut(ctx types.Context, poolI types2.PoolI, tokenOut types.Coin, tokenInDenom string, spreadFactor types.Dec) (types.Coin, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcInAmtGivenOut", ctx, poolI, tokenOut, tokenInDenom, swapFee) + ret := m.ctrl.Call(m, "CalcInAmtGivenOut", ctx, poolI, tokenOut, tokenInDenom, spreadFactor) ret0, _ := ret[0].(types.Coin) ret1, _ := ret[1].(error) return ret0, ret1 } // CalcInAmtGivenOut indicates an expected call of CalcInAmtGivenOut. -func (mr *MockPoolModuleIMockRecorder) CalcInAmtGivenOut(ctx, poolI, tokenOut, tokenInDenom, swapFee interface{}) *gomock.Call { +func (mr *MockPoolModuleIMockRecorder) CalcInAmtGivenOut(ctx, poolI, tokenOut, tokenInDenom, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcInAmtGivenOut", reflect.TypeOf((*MockPoolModuleI)(nil).CalcInAmtGivenOut), ctx, poolI, tokenOut, tokenInDenom, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcInAmtGivenOut", reflect.TypeOf((*MockPoolModuleI)(nil).CalcInAmtGivenOut), ctx, poolI, tokenOut, tokenInDenom, spreadFactor) } // CalcOutAmtGivenIn mocks base method. -func (m *MockPoolModuleI) CalcOutAmtGivenIn(ctx types.Context, poolI types2.PoolI, tokenIn types.Coin, tokenOutDenom string, swapFee types.Dec) (types.Coin, error) { +func (m *MockPoolModuleI) CalcOutAmtGivenIn(ctx types.Context, poolI types2.PoolI, tokenIn types.Coin, tokenOutDenom string, spreadFactor types.Dec) (types.Coin, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CalcOutAmtGivenIn", ctx, poolI, tokenIn, tokenOutDenom, swapFee) + ret := m.ctrl.Call(m, "CalcOutAmtGivenIn", ctx, poolI, tokenIn, tokenOutDenom, spreadFactor) ret0, _ := ret[0].(types.Coin) ret1, _ := ret[1].(error) return ret0, ret1 } // CalcOutAmtGivenIn indicates an expected call of CalcOutAmtGivenIn. -func (mr *MockPoolModuleIMockRecorder) CalcOutAmtGivenIn(ctx, poolI, tokenIn, tokenOutDenom, swapFee interface{}) *gomock.Call { +func (mr *MockPoolModuleIMockRecorder) CalcOutAmtGivenIn(ctx, poolI, tokenIn, tokenOutDenom, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcOutAmtGivenIn", reflect.TypeOf((*MockPoolModuleI)(nil).CalcOutAmtGivenIn), ctx, poolI, tokenIn, tokenOutDenom, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalcOutAmtGivenIn", reflect.TypeOf((*MockPoolModuleI)(nil).CalcOutAmtGivenIn), ctx, poolI, tokenIn, tokenOutDenom, spreadFactor) } // CalculateSpotPrice mocks base method. @@ -320,33 +320,33 @@ func (mr *MockPoolModuleIMockRecorder) InitializePool(ctx, pool, creatorAddress } // SwapExactAmountIn mocks base method. -func (m *MockPoolModuleI) SwapExactAmountIn(ctx types.Context, sender types.AccAddress, pool types2.PoolI, tokenIn types.Coin, tokenOutDenom string, tokenOutMinAmount types.Int, swapFee types.Dec) (types.Int, error) { +func (m *MockPoolModuleI) SwapExactAmountIn(ctx types.Context, sender types.AccAddress, pool types2.PoolI, tokenIn types.Coin, tokenOutDenom string, tokenOutMinAmount types.Int, spreadFactor types.Dec) (types.Int, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SwapExactAmountIn", ctx, sender, pool, tokenIn, tokenOutDenom, tokenOutMinAmount, swapFee) + ret := m.ctrl.Call(m, "SwapExactAmountIn", ctx, sender, pool, tokenIn, tokenOutDenom, tokenOutMinAmount, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(error) return ret0, ret1 } // SwapExactAmountIn indicates an expected call of SwapExactAmountIn. -func (mr *MockPoolModuleIMockRecorder) SwapExactAmountIn(ctx, sender, pool, tokenIn, tokenOutDenom, tokenOutMinAmount, swapFee interface{}) *gomock.Call { +func (mr *MockPoolModuleIMockRecorder) SwapExactAmountIn(ctx, sender, pool, tokenIn, tokenOutDenom, tokenOutMinAmount, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapExactAmountIn", reflect.TypeOf((*MockPoolModuleI)(nil).SwapExactAmountIn), ctx, sender, pool, tokenIn, tokenOutDenom, tokenOutMinAmount, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapExactAmountIn", reflect.TypeOf((*MockPoolModuleI)(nil).SwapExactAmountIn), ctx, sender, pool, tokenIn, tokenOutDenom, tokenOutMinAmount, spreadFactor) } // SwapExactAmountOut mocks base method. -func (m *MockPoolModuleI) SwapExactAmountOut(ctx types.Context, sender types.AccAddress, pool types2.PoolI, tokenInDenom string, tokenInMaxAmount types.Int, tokenOut types.Coin, swapFee types.Dec) (types.Int, error) { +func (m *MockPoolModuleI) SwapExactAmountOut(ctx types.Context, sender types.AccAddress, pool types2.PoolI, tokenInDenom string, tokenInMaxAmount types.Int, tokenOut types.Coin, spreadFactor types.Dec) (types.Int, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SwapExactAmountOut", ctx, sender, pool, tokenInDenom, tokenInMaxAmount, tokenOut, swapFee) + ret := m.ctrl.Call(m, "SwapExactAmountOut", ctx, sender, pool, tokenInDenom, tokenInMaxAmount, tokenOut, spreadFactor) ret0, _ := ret[0].(types.Int) ret1, _ := ret[1].(error) return ret0, ret1 } // SwapExactAmountOut indicates an expected call of SwapExactAmountOut. -func (mr *MockPoolModuleIMockRecorder) SwapExactAmountOut(ctx, sender, pool, tokenInDenom, tokenInMaxAmount, tokenOut, swapFee interface{}) *gomock.Call { +func (mr *MockPoolModuleIMockRecorder) SwapExactAmountOut(ctx, sender, pool, tokenInDenom, tokenInMaxAmount, tokenOut, spreadFactor interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapExactAmountOut", reflect.TypeOf((*MockPoolModuleI)(nil).SwapExactAmountOut), ctx, sender, pool, tokenInDenom, tokenInMaxAmount, tokenOut, swapFee) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SwapExactAmountOut", reflect.TypeOf((*MockPoolModuleI)(nil).SwapExactAmountOut), ctx, sender, pool, tokenInDenom, tokenInMaxAmount, tokenOut, spreadFactor) } // ValidatePermissionlessPoolCreationEnabled mocks base method. diff --git a/x/concentrated-liquidity/README.md b/x/concentrated-liquidity/README.md index b6927ba7d83..bcf100fe0c0 100644 --- a/x/concentrated-liquidity/README.md +++ b/x/concentrated-liquidity/README.md @@ -452,7 +452,7 @@ type MsgCreateConcentratedPool struct { Denom0 string Denom1 string TickSpacing uint64 - SwapFee github_com_cosmos_cosmos_sdk_types.Dec + SpreadFactor github_com_cosmos_cosmos_sdk_types.Dec } ``` @@ -981,7 +981,7 @@ Note, that the numbers used in this example are not realistic. They are used to illustrate the concepts on the high level. Imagine a tick range from min tick -1000 to max tick 1000 in a pool with a 1% -swap fee. +spread factor. Assume that user A created a full range position from ticks -1000 to 1000 for `10_000` liquidity units. @@ -1049,7 +1049,7 @@ Now, we update the swap state as follows: of the crossed tick 0 (1_000) = 11_000. - `feeGrowthGlobal` is set to 2_500 \* 0.01 / 10_000 = 0.0025 because we assumed -1% swap fee. +1% spread factor. Now, we proceed by getting the next initialized tick in the direction of the swap (100). @@ -1073,7 +1073,7 @@ Now, we update the swap state as follows: - `liquidity` is set kept the same as we did not cross any initialized tick. - `feeGrowthGlobal` is updated to 0.0025 + (2_500 \* 0.01 / 10_000) = 0.005 - because we assumed 1% swap fee. + because we assumed 1% spread factor. As a result, we complete the swap having swapped 5_000 tokens one in for 22_500 tokens zero out. The tick is now at 70 and the current liquidity at the active @@ -1114,11 +1114,11 @@ layers of state: // Note that this is proto-generated. type Pool struct { ... - SwapFee sdk.Dec + SpreadFactor sdk.Dec } ``` -Each pool is initialized with a static fee value `SwapFee` to be paid by swappers. +Each pool is initialized with a static fee value `SpreadFactor` to be paid by swappers. Additionally, each pool's fee accumulator tracks and stores the total fees accrued throughout its lifespan, named `FeeGrowthGlobal`. @@ -1253,15 +1253,15 @@ swapped in. Then, to calculate the fee within a single tick, we perform the following steps: -1. Calculate an updated `tokenInAmtAfterFee` by charging the `pool.SwapFee` on `tokenInAmt`. +1. Calculate an updated `tokenInAmtAfterFee` by charging the `pool.SpreadFactor` on `tokenInAmt`. ```go // Update global fee accumulator tracking fees for denom of tokenInAmt. // TODO: revisit to make sure if truncations need to happen. -pool.FeeGrowthGlobalOutside.TokenX = pool.FeeGrowthGlobalOutside.TokenX.Add(tokenInAmt.Mul(pool.SwapFee)) +pool.FeeGrowthGlobalOutside.TokenX = pool.FeeGrowthGlobalOutside.TokenX.Add(tokenInAmt.Mul(pool.SpreadFactor)) // Update tokenInAmt to account for fees. -fee = tokenInAmt.Mul(pool.SwapFee).Ceil() +fee = tokenInAmt.Mul(pool.SpreadFactor).Ceil() tokenInAmtAfterFee = tokenInAmt.Sub(fee) k.bankKeeper.SendCoins(ctx, swapper, pool.GetAddress(), ...) // send tokenInAmtAfterFee @@ -1306,7 +1306,7 @@ feeChargeTotal = amountSpecifiedRemaining.Sub(amountIn) The fee is charged on the amount actually consumed during a swap step. ```go -feeChargeTotal = amountIn.Mul(swapFee) +feeChargeTotal = amountIn.Mul(spreadFactor) ``` 3. Price impact protection makes it exit before consuming all amount remaining. @@ -1315,7 +1315,7 @@ The fee is charged on the amount in actually consumed before price impact protection got trigerred. ```go -feeChargeTotal = amountIn.Mul(swapFee) +feeChargeTotal = amountIn.Mul(spreadFactor) ``` ## Incentive/Liquidity Mining Mechanism diff --git a/x/concentrated-liquidity/bench_test.go b/x/concentrated-liquidity/bench_test.go index 8fecfe4a05d..1451cebfc7f 100644 --- a/x/concentrated-liquidity/bench_test.go +++ b/x/concentrated-liquidity/bench_test.go @@ -229,7 +229,7 @@ func BenchmarkSwapExactAmountIn(b *testing.B) { b.StartTimer() // System under test - _, err = clKeeper.SwapExactAmountIn(s.Ctx, s.TestAccs[0], pool, largeSwapInCoin, denom1, sdk.NewInt(1), pool.GetSwapFee(s.Ctx)) + _, err = clKeeper.SwapExactAmountIn(s.Ctx, s.TestAccs[0], pool, largeSwapInCoin, denom1, sdk.NewInt(1), pool.GetSpreadFactor(s.Ctx)) noError(err) // Notice that we stop the timer again in case there are multiple iterations. diff --git a/x/concentrated-liquidity/client/cli/tx.go b/x/concentrated-liquidity/client/cli/tx.go index d658d4a48d1..c643db95084 100644 --- a/x/concentrated-liquidity/client/cli/tx.go +++ b/x/concentrated-liquidity/client/cli/tx.go @@ -38,8 +38,8 @@ var poolIdFlagOverride = map[string]string{ func NewCreateConcentratedPoolCmd() (*osmocli.TxCliDesc, *clmodel.MsgCreateConcentratedPool) { return &osmocli.TxCliDesc{ - Use: "create-pool [denom-0] [denom-1] [tick-spacing] [swap-fee]", - Short: "create a concentrated liquidity pool with the given denom pair, tick spacing, and swap fee", + Use: "create-pool [denom-0] [denom-1] [tick-spacing] [spread-factor]", + Short: "create a concentrated liquidity pool with the given denom pair, tick spacing, and spread factor", Long: "denom-1 (the quote denom), tick spacing, and swap fees must all be authorized by the concentrated liquidity module", Example: "create-pool uion uosmo 100 0.01 --from val --chain-id osmosis-1", }, &clmodel.MsgCreateConcentratedPool{} @@ -96,7 +96,7 @@ func NewFungifyChargedPositionsCmd() (*osmocli.TxCliDesc, *types.MsgFungifyCharg // NewCmdCreateConcentratedLiquidityPoolProposal implements a command handler for create concentrated liquidity pool proposal func NewCmdCreateConcentratedLiquidityPoolProposal() *cobra.Command { cmd := &cobra.Command{ - Use: "create-concentratedliquidity-pool-proposal [denom0] [denom1] [tick-spacing] [swap-fee] [flags]", + Use: "create-concentratedliquidity-pool-proposal [denom0] [denom1] [tick-spacing] [spread-factor] [flags]", Args: cobra.ExactArgs(4), Short: "Submit a create concentrated liquidity pool proposal", Long: strings.TrimSpace(`Submit a create concentrated liquidity pool proposal. @@ -113,12 +113,12 @@ func NewCmdCreateConcentratedLiquidityPoolProposal() *cobra.Command { return err } - swapFee, err := sdk.NewDecFromStr(args[3]) + spreadFactor, err := sdk.NewDecFromStr(args[3]) if err != nil { return err } - content, err := parseCreateConcentratedLiquidityPoolArgsToContent(cmd, args[0], args[1], tickSpacing, swapFee) + content, err := parseCreateConcentratedLiquidityPoolArgsToContent(cmd, args[0], args[1], tickSpacing, spreadFactor) if err != nil { return err } @@ -211,7 +211,7 @@ Note: The new tick spacing value must be less than the current tick spacing valu return cmd } -func parseCreateConcentratedLiquidityPoolArgsToContent(cmd *cobra.Command, denom0, denom1 string, tickSpacing uint64, swapFee sdk.Dec) (govtypes.Content, error) { +func parseCreateConcentratedLiquidityPoolArgsToContent(cmd *cobra.Command, denom0, denom1 string, tickSpacing uint64, spreadFactor sdk.Dec) (govtypes.Content, error) { title, err := cmd.Flags().GetString(govcli.FlagTitle) if err != nil { return nil, err @@ -222,12 +222,12 @@ func parseCreateConcentratedLiquidityPoolArgsToContent(cmd *cobra.Command, denom return nil, err } content := &types.CreateConcentratedLiquidityPoolProposal{ - Title: title, - Description: description, - Denom0: denom0, - Denom1: denom1, - TickSpacing: tickSpacing, - SwapFee: swapFee, + Title: title, + Description: description, + Denom0: denom0, + Denom1: denom1, + TickSpacing: tickSpacing, + SpreadFactor: spreadFactor, } return content, nil diff --git a/x/concentrated-liquidity/export_test.go b/x/concentrated-liquidity/export_test.go index d67a6948ea2..f04c0ad2a76 100644 --- a/x/concentrated-liquidity/export_test.go +++ b/x/concentrated-liquidity/export_test.go @@ -57,9 +57,9 @@ func (k Keeper) SwapOutAmtGivenIn( pool types.ConcentratedPoolExtension, tokenIn sdk.Coin, tokenOutDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, priceLimit sdk.Dec) (calcTokenIn, calcTokenOut sdk.Coin, currentTick int64, liquidity, sqrtPrice sdk.Dec, err error) { - return k.swapOutAmtGivenIn(ctx, sender, pool, tokenIn, tokenOutDenom, swapFee, priceLimit) + return k.swapOutAmtGivenIn(ctx, sender, pool, tokenIn, tokenOutDenom, spreadFactor, priceLimit) } func (k Keeper) ComputeOutAmtGivenIn( @@ -67,11 +67,11 @@ func (k Keeper) ComputeOutAmtGivenIn( poolId uint64, tokenInMin sdk.Coin, tokenOutDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, priceLimit sdk.Dec, ) (calcTokenIn, calcTokenOut sdk.Coin, currentTick int64, liquidity, sqrtPrice sdk.Dec, totalFees sdk.Dec, err error) { - return k.computeOutAmtGivenIn(ctx, poolId, tokenInMin, tokenOutDenom, swapFee, priceLimit) + return k.computeOutAmtGivenIn(ctx, poolId, tokenInMin, tokenOutDenom, spreadFactor, priceLimit) } func (k Keeper) SwapInAmtGivenOut( @@ -80,21 +80,21 @@ func (k Keeper) SwapInAmtGivenOut( pool types.ConcentratedPoolExtension, desiredTokenOut sdk.Coin, tokenInDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, priceLimit sdk.Dec) (calcTokenIn, calcTokenOut sdk.Coin, currentTick int64, liquidity, sqrtPrice sdk.Dec, err error) { - return k.swapInAmtGivenOut(ctx, sender, pool, desiredTokenOut, tokenInDenom, swapFee, priceLimit) + return k.swapInAmtGivenOut(ctx, sender, pool, desiredTokenOut, tokenInDenom, spreadFactor, priceLimit) } func (k Keeper) ComputeInAmtGivenOut( ctx sdk.Context, desiredTokenOut sdk.Coin, tokenInDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, priceLimit sdk.Dec, poolId uint64, ) (calcTokenIn, calcTokenOut sdk.Coin, currentTick int64, liquidity, sqrtPrice sdk.Dec, totalFees sdk.Dec, err error) { - return k.computeInAmtGivenOut(ctx, desiredTokenOut, tokenInDenom, swapFee, priceLimit, poolId) + return k.computeInAmtGivenOut(ctx, desiredTokenOut, tokenInDenom, spreadFactor, priceLimit, poolId) } func (k Keeper) InitOrUpdateTick(ctx sdk.Context, poolId uint64, currentTick int64, tickIndex int64, liquidityIn sdk.Dec, upper bool) (err error) { @@ -137,8 +137,8 @@ func ConvertPoolInterfaceToConcentrated(poolI poolmanagertypes.PoolI) (types.Con return convertPoolInterfaceToConcentrated(poolI) } -func (k Keeper) ValidateSwapFee(ctx sdk.Context, params types.Params, swapFee sdk.Dec) bool { - return k.validateSwapFee(ctx, params, swapFee) +func (k Keeper) ValidateSpreadFactor(ctx sdk.Context, params types.Params, spreadFactor sdk.Dec) bool { + return k.validateSpreadFactor(ctx, params, spreadFactor) } func (k Keeper) ValidateTickSpacing(ctx sdk.Context, params types.Params, tickSpacing uint64) bool { diff --git a/x/concentrated-liquidity/fees_test.go b/x/concentrated-liquidity/fees_test.go index 6d10ee94ddb..b7e1107be21 100644 --- a/x/concentrated-liquidity/fees_test.go +++ b/x/concentrated-liquidity/fees_test.go @@ -546,7 +546,7 @@ func (s *KeeperTestSuite) TestGetInitialFeeGrowthOppositeDirectionOfLastTraversa ctx := s.Ctx clKeeper := s.App.ConcentratedLiquidityKeeper - pool, err := clmodel.NewConcentratedLiquidityPool(validPoolId, ETH, USDC, DefaultTickSpacing, DefaultZeroSwapFee) + pool, err := clmodel.NewConcentratedLiquidityPool(validPoolId, ETH, USDC, DefaultTickSpacing, DefaultZeroSpreadFactor) s.Require().NoError(err) // N.B.: we set the listener mock because we would like to avoid @@ -1426,7 +1426,7 @@ func (s *KeeperTestSuite) TestFunctional_Fees_Swaps() { // Default setup only creates 3 accounts, but we need 5 for this test. s.TestAccs = apptesting.CreateRandomAccounts(positions.numAccounts) - // Create a default CL pool, but with a 0.3 percent swap fee. + // Create a default CL pool, but with a 0.3 percent spread factor. clPool := s.PrepareCustomConcentratedPool(s.TestAccs[0], ETH, USDC, DefaultTickSpacing, sdk.MustNewDecFromStr("0.002")) positionIds := make([][]uint64, 4) @@ -1492,13 +1492,13 @@ func (s *KeeperTestSuite) TestFunctional_Fees_LP() { owner = s.TestAccs[0] ) - // Create pool with 0.2% swap fee. + // Create pool with 0.2% spread factor. pool := s.PrepareCustomConcentratedPool(s.TestAccs[0], ETH, USDC, DefaultTickSpacing, sdk.MustNewDecFromStr("0.002")) fundCoins := sdk.NewCoins(sdk.NewCoin(ETH, DefaultAmt0.MulRaw(2)), sdk.NewCoin(USDC, DefaultAmt1.MulRaw(2))) s.FundAcc(owner, fundCoins) // Errors since no position. - _, _, _, _, _, err := s.App.ConcentratedLiquidityKeeper.SwapOutAmtGivenIn(s.Ctx, owner, pool, sdk.NewCoin(ETH, sdk.OneInt()), USDC, pool.GetSwapFee(s.Ctx), types.MaxSpotPrice) + _, _, _, _, _, err := s.App.ConcentratedLiquidityKeeper.SwapOutAmtGivenIn(s.Ctx, owner, pool, sdk.NewCoin(ETH, sdk.OneInt()), USDC, pool.GetSpreadFactor(s.Ctx), types.MaxSpotPrice) s.Require().Error(err) // Create position in the default range 1. @@ -1642,9 +1642,9 @@ func (s *KeeperTestSuite) swapAndTrackXTimesInARow(poolId uint64, coinIn sdk.Coi totalTokenIn = sdk.NewCoin(coinIn.Denom, sdk.ZeroInt()) totalTokenOut = sdk.NewCoin(coinOutDenom, sdk.ZeroInt()) for i := 0; i < numSwaps; i++ { - coinIn, coinOut, _, _, _, err := s.App.ConcentratedLiquidityKeeper.SwapOutAmtGivenIn(s.Ctx, s.TestAccs[4], clPool, coinIn, coinOutDenom, clPool.GetSwapFee(s.Ctx), priceLimit) + coinIn, coinOut, _, _, _, err := s.App.ConcentratedLiquidityKeeper.SwapOutAmtGivenIn(s.Ctx, s.TestAccs[4], clPool, coinIn, coinOutDenom, clPool.GetSpreadFactor(s.Ctx), priceLimit) s.Require().NoError(err) - fee := coinIn.Amount.ToDec().Mul(clPool.GetSwapFee(s.Ctx)) + fee := coinIn.Amount.ToDec().Mul(clPool.GetSpreadFactor(s.Ctx)) totalFees = totalFees.Add(sdk.NewCoin(coinIn.Denom, fee.TruncateInt())) clPool, err = s.App.ConcentratedLiquidityKeeper.GetPoolById(s.Ctx, clPool.GetId()) s.Require().NoError(err) diff --git a/x/concentrated-liquidity/genesis_test.go b/x/concentrated-liquidity/genesis_test.go index 971957e0263..1dd3f4ff5da 100644 --- a/x/concentrated-liquidity/genesis_test.go +++ b/x/concentrated-liquidity/genesis_test.go @@ -32,7 +32,7 @@ var ( baseGenesis = genesis.GenesisState{ Params: types.Params{ AuthorizedTickSpacing: []uint64{1, 10, 100, 1000}, - AuthorizedSwapFees: []sdk.Dec{sdk.MustNewDecFromStr("0.0001"), sdk.MustNewDecFromStr("0.0003"), sdk.MustNewDecFromStr("0.0005")}, + AuthorizedSpreadFactors: []sdk.Dec{sdk.MustNewDecFromStr("0.0001"), sdk.MustNewDecFromStr("0.0003"), sdk.MustNewDecFromStr("0.0005")}, AuthorizedQuoteDenoms: []string{ETH, USDC}, BalancerSharesRewardDiscount: types.DefaultBalancerSharesDiscount, AuthorizedUptimes: types.DefaultAuthorizedUptimes, diff --git a/x/concentrated-liquidity/gov.go b/x/concentrated-liquidity/gov.go index 1d7c19e18f9..a4d2c825624 100644 --- a/x/concentrated-liquidity/gov.go +++ b/x/concentrated-liquidity/gov.go @@ -15,7 +15,7 @@ func handleCreateConcentratedLiquidityPoolProposal(ctx sdk.Context, k Keeper, p func (k Keeper) HandleCreateConcentratedLiquidityPoolProposal(ctx sdk.Context, p *types.CreateConcentratedLiquidityPoolProposal) error { poolmanagerModuleAcc := k.accountKeeper.GetModuleAccount(ctx, poolmanagertypes.ModuleName) poolCreatorAddress := poolmanagerModuleAcc.GetAddress() - createPoolMsg := clmodel.NewMsgCreateConcentratedPool(poolCreatorAddress, p.Denom0, p.Denom1, p.TickSpacing, p.SwapFee) + createPoolMsg := clmodel.NewMsgCreateConcentratedPool(poolCreatorAddress, p.Denom0, p.Denom1, p.TickSpacing, p.SpreadFactor) _, err := k.poolmanagerKeeper.CreateConcentratedPoolAsPoolManager(ctx, createPoolMsg) return err } diff --git a/x/concentrated-liquidity/keeper_test.go b/x/concentrated-liquidity/keeper_test.go index 28381cf19d9..f8b18c65910 100644 --- a/x/concentrated-liquidity/keeper_test.go +++ b/x/concentrated-liquidity/keeper_test.go @@ -29,7 +29,7 @@ var ( DefaultCurrPrice = sdk.NewDec(5000) DefaultCurrTick int64 = 31000000 DefaultCurrSqrtPrice, _ = DefaultCurrPrice.ApproxSqrt() // 70.710678118654752440 - DefaultZeroSwapFee = sdk.ZeroDec() + DefaultZeroSpreadFactor = sdk.ZeroDec() DefaultFeeAccumCoins = sdk.NewDecCoins(sdk.NewDecCoin("foo", sdk.NewInt(50))) DefaultPositionId = uint64(1) DefaultUnderlyingLockId = uint64(0) diff --git a/x/concentrated-liquidity/model/msgs.go b/x/concentrated-liquidity/model/msgs.go index a489e906dff..63b3f7e994d 100644 --- a/x/concentrated-liquidity/model/msgs.go +++ b/x/concentrated-liquidity/model/msgs.go @@ -24,14 +24,14 @@ func NewMsgCreateConcentratedPool( denom0 string, denom1 string, tickSpacing uint64, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) MsgCreateConcentratedPool { return MsgCreateConcentratedPool{ - Sender: sender.String(), - Denom0: denom0, - Denom1: denom1, - TickSpacing: tickSpacing, - SwapFee: swapFee, + Sender: sender.String(), + Denom0: denom0, + Denom1: denom1, + TickSpacing: tickSpacing, + SpreadFactor: spreadFactor, } } @@ -59,9 +59,9 @@ func (msg MsgCreateConcentratedPool) ValidateBasic() error { return fmt.Errorf("denom1 is invalid: %s", sdk.ValidateDenom(msg.Denom1)) } - swapFee := msg.SwapFee - if swapFee.IsNegative() || swapFee.GTE(one) { - return cltypes.InvalidSwapFeeError{ActualFee: swapFee} + spreadFactor := msg.SpreadFactor + if spreadFactor.IsNegative() || spreadFactor.GTE(one) { + return cltypes.InvalidSpreadFactorError{ActualFee: spreadFactor} } return nil @@ -98,7 +98,7 @@ func (msg MsgCreateConcentratedPool) InitialLiquidity() sdk.Coins { } func (msg MsgCreateConcentratedPool) CreatePool(ctx sdk.Context, poolID uint64) (poolmanagertypes.PoolI, error) { - poolI, err := NewConcentratedLiquidityPool(poolID, msg.Denom0, msg.Denom1, msg.TickSpacing, msg.SwapFee) + poolI, err := NewConcentratedLiquidityPool(poolID, msg.Denom0, msg.Denom1, msg.TickSpacing, msg.SpreadFactor) return &poolI, err } diff --git a/x/concentrated-liquidity/model/msgs_test.go b/x/concentrated-liquidity/model/msgs_test.go index aecd374acf9..6d5450d462c 100644 --- a/x/concentrated-liquidity/model/msgs_test.go +++ b/x/concentrated-liquidity/model/msgs_test.go @@ -26,74 +26,74 @@ func TestMsgCreateConcentratedPool(t *testing.T) { { name: "proper msg", msg: clmodel.MsgCreateConcentratedPool{ - Sender: addr1, - Denom0: ETH, - Denom1: USDC, - TickSpacing: DefaultTickSpacing, - SwapFee: DefaultSwapFee, + Sender: addr1, + Denom0: ETH, + Denom1: USDC, + TickSpacing: DefaultTickSpacing, + SpreadFactor: DefaultSpreadFactor, }, expectPass: true, }, { name: "invalid sender", msg: clmodel.MsgCreateConcentratedPool{ - Sender: invalidAddr.String(), - Denom0: ETH, - Denom1: USDC, - TickSpacing: DefaultTickSpacing, - SwapFee: DefaultSwapFee, + Sender: invalidAddr.String(), + Denom0: ETH, + Denom1: USDC, + TickSpacing: DefaultTickSpacing, + SpreadFactor: DefaultSpreadFactor, }, expectPass: false, }, { name: "missing denom1", msg: clmodel.MsgCreateConcentratedPool{ - Sender: invalidAddr.String(), - Denom0: ETH, - TickSpacing: DefaultTickSpacing, - SwapFee: DefaultSwapFee, + Sender: invalidAddr.String(), + Denom0: ETH, + TickSpacing: DefaultTickSpacing, + SpreadFactor: DefaultSpreadFactor, }, expectPass: false, }, { name: "missing denom0", msg: clmodel.MsgCreateConcentratedPool{ - Sender: invalidAddr.String(), - Denom1: USDC, - TickSpacing: DefaultTickSpacing, - SwapFee: DefaultSwapFee, + Sender: invalidAddr.String(), + Denom1: USDC, + TickSpacing: DefaultTickSpacing, + SpreadFactor: DefaultSpreadFactor, }, expectPass: false, }, { name: "missing sender", msg: clmodel.MsgCreateConcentratedPool{ - Denom0: ETH, - Denom1: USDC, - TickSpacing: DefaultTickSpacing, - SwapFee: DefaultSwapFee, + Denom0: ETH, + Denom1: USDC, + TickSpacing: DefaultTickSpacing, + SpreadFactor: DefaultSpreadFactor, }, expectPass: false, }, { - name: "negative swap fee", + name: "negative spread factor", msg: clmodel.MsgCreateConcentratedPool{ - Sender: addr1, - Denom0: ETH, - Denom1: USDC, - TickSpacing: DefaultTickSpacing, - SwapFee: sdk.ZeroDec().Sub(sdk.SmallestDec()), + Sender: addr1, + Denom0: ETH, + Denom1: USDC, + TickSpacing: DefaultTickSpacing, + SpreadFactor: sdk.ZeroDec().Sub(sdk.SmallestDec()), }, expectPass: false, }, { - name: "swap fee == 1", + name: "spread factor == 1", msg: clmodel.MsgCreateConcentratedPool{ - Sender: addr1, - Denom0: ETH, - Denom1: USDC, - TickSpacing: DefaultTickSpacing, - SwapFee: sdk.OneDec(), + Sender: addr1, + Denom0: ETH, + Denom1: USDC, + TickSpacing: DefaultTickSpacing, + SpreadFactor: sdk.OneDec(), }, expectPass: false, }, diff --git a/x/concentrated-liquidity/model/pool.go b/x/concentrated-liquidity/model/pool.go index 927aac9c80b..b9f2b374c16 100644 --- a/x/concentrated-liquidity/model/pool.go +++ b/x/concentrated-liquidity/model/pool.go @@ -25,15 +25,15 @@ var ( // NewConcentratedLiquidityPool creates a new ConcentratedLiquidity pool with the specified parameters. // The two provided denoms are ordered so that denom0 is lexicographically smaller than denom1. -func NewConcentratedLiquidityPool(poolId uint64, denom0, denom1 string, tickSpacing uint64, swapFee sdk.Dec) (Pool, error) { +func NewConcentratedLiquidityPool(poolId uint64, denom0, denom1 string, tickSpacing uint64, spreadFactor sdk.Dec) (Pool, error) { // Ensure that the two denoms are different if denom0 == denom1 { return Pool{}, types.MatchingDenomError{Denom: denom0} } // Swap fee must be [0,1) - if swapFee.IsNegative() || swapFee.GTE(one) { - return Pool{}, types.InvalidSwapFeeError{ActualFee: swapFee} + if spreadFactor.IsNegative() || spreadFactor.GTE(one) { + return Pool{}, types.InvalidSpreadFactorError{ActualFee: spreadFactor} } // Create a new pool struct with the specified parameters @@ -49,7 +49,7 @@ func NewConcentratedLiquidityPool(poolId uint64, denom0, denom1 string, tickSpac Token1: denom1, TickSpacing: tickSpacing, ExponentAtPriceOne: types.ExponentAtPriceOne, - SwapFee: swapFee, + SpreadFactor: spreadFactor, } return pool, nil } @@ -94,9 +94,9 @@ func (p Pool) String() string { return string(out) } -// GetSwapFee returns the swap fee of the pool -func (p Pool) GetSwapFee(ctx sdk.Context) sdk.Dec { - return p.SwapFee +// GetSpreadFactor returns the spread factor of the pool +func (p Pool) GetSpreadFactor(ctx sdk.Context) sdk.Dec { + return p.SpreadFactor } // IsActive returns true if the pool is active diff --git a/x/concentrated-liquidity/model/pool.pb.go b/x/concentrated-liquidity/model/pool.pb.go index c0a4dac8093..1c360bed29b 100644 --- a/x/concentrated-liquidity/model/pool.pb.go +++ b/x/concentrated-liquidity/model/pool.pb.go @@ -52,8 +52,8 @@ type Pool struct { // concentrated-liquidity parameters TickSpacing uint64 `protobuf:"varint,10,opt,name=tick_spacing,json=tickSpacing,proto3" json:"tick_spacing,omitempty" yaml:"tick_spacing"` ExponentAtPriceOne int64 `protobuf:"varint,11,opt,name=exponent_at_price_one,json=exponentAtPriceOne,proto3" json:"exponent_at_price_one,omitempty" yaml:"exponent_at_price_one"` - // swap_fee is the ratio that is charged on the amount of token in. - SwapFee github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,12,opt,name=swap_fee,json=swapFee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"swap_fee" yaml:"swap_fee"` + // spread_factor is the ratio that is charged on the amount of token in. + SpreadFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,12,opt,name=spread_factor,json=spreadFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"spread_factor" yaml:"spread_factor"` // last_liquidity_update is the last time either the pool liquidity or the // active tick changed LastLiquidityUpdate time.Time `protobuf:"bytes,13,opt,name=last_liquidity_update,json=lastLiquidityUpdate,proto3,stdtime" json:"last_liquidity_update" yaml:"last_liquidity_update"` @@ -100,47 +100,47 @@ func init() { } var fileDescriptor_3526ea5373d96c9a = []byte{ - // 633 bytes of a gzipped FileDescriptorProto + // 637 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0xcb, 0x6e, 0xd3, 0x40, - 0x14, 0x8d, 0xfb, 0x4a, 0x3b, 0x29, 0x85, 0x4e, 0x1f, 0xb8, 0x15, 0x8d, 0x23, 0x4b, 0xa0, 0x20, - 0x11, 0x9b, 0x80, 0xd8, 0x74, 0xd7, 0x80, 0x90, 0x90, 0x2a, 0xb5, 0x9a, 0x96, 0x0d, 0xaa, 0x64, - 0x39, 0xf6, 0x34, 0x8c, 0x62, 0x7b, 0x1c, 0xcf, 0xa4, 0xb4, 0x1f, 0x80, 0xc4, 0xb2, 0x4b, 0x96, - 0xfd, 0x05, 0x24, 0x3e, 0xa2, 0x62, 0xd5, 0x25, 0x62, 0x61, 0x50, 0xfb, 0x07, 0xf9, 0x02, 0x34, - 0x0f, 0xa7, 0x96, 0x08, 0x8b, 0xae, 0xe2, 0x7b, 0xee, 0xb9, 0xc7, 0xe7, 0x1e, 0x67, 0x06, 0x3c, - 0xa5, 0x2c, 0xa6, 0x8c, 0x30, 0x37, 0xa0, 0x49, 0x80, 0x13, 0x9e, 0xf9, 0x1c, 0x87, 0xad, 0x88, - 0x0c, 0x86, 0x24, 0x24, 0xfc, 0xcc, 0x4d, 0x29, 0x8d, 0x9c, 0x34, 0xa3, 0x9c, 0xc2, 0xc7, 0x9a, - 0xea, 0x94, 0xa9, 0x63, 0xa6, 0x73, 0xd2, 0xee, 0x62, 0xee, 0xb7, 0x37, 0x37, 0x02, 0xc9, 0xf3, - 0xe4, 0x90, 0xab, 0x0a, 0xa5, 0xb0, 0xb9, 0xda, 0xa3, 0x3d, 0xaa, 0x70, 0xf1, 0xa4, 0x51, 0xab, - 0x47, 0x69, 0x2f, 0xc2, 0xae, 0xac, 0xba, 0xc3, 0x63, 0x97, 0x93, 0x18, 0x33, 0xee, 0xc7, 0xa9, - 0x22, 0xd8, 0xdf, 0xaa, 0x60, 0x66, 0x9f, 0xd2, 0x08, 0x3e, 0x03, 0x55, 0x3f, 0x0c, 0x33, 0xcc, - 0x98, 0x69, 0x34, 0x8c, 0xe6, 0x42, 0x07, 0x8e, 0x72, 0x6b, 0xe9, 0xcc, 0x8f, 0xa3, 0x6d, 0x5b, - 0x37, 0x6c, 0x54, 0x50, 0xe0, 0x2e, 0x80, 0x44, 0x1a, 0x25, 0x27, 0x98, 0x79, 0xc5, 0xe0, 0x94, - 0x1c, 0xdc, 0x1a, 0xe5, 0xd6, 0x86, 0x1a, 0xfc, 0x97, 0x63, 0xa3, 0xe5, 0x5b, 0x70, 0x47, 0xab, - 0x6d, 0x83, 0xc5, 0x63, 0x5c, 0xd2, 0x99, 0x96, 0x3a, 0x0f, 0x47, 0xb9, 0xb5, 0xa2, 0x74, 0xca, - 0x5d, 0x1b, 0xd5, 0x44, 0x59, 0xcc, 0x2e, 0x81, 0x29, 0x12, 0x9a, 0x33, 0x0d, 0xa3, 0x39, 0x83, - 0xa6, 0x48, 0x08, 0x3f, 0x1b, 0x60, 0x3d, 0x18, 0x66, 0x19, 0x4e, 0xb8, 0xc7, 0x49, 0xd0, 0xf7, - 0xc6, 0x29, 0x9a, 0xb3, 0x52, 0x76, 0xef, 0x32, 0xb7, 0x2a, 0xbf, 0x72, 0xeb, 0x49, 0x8f, 0xf0, - 0x8f, 0xc3, 0xae, 0x13, 0xd0, 0x58, 0x27, 0xa9, 0x7f, 0x5a, 0x2c, 0xec, 0xbb, 0xfc, 0x2c, 0xc5, - 0xcc, 0x79, 0x83, 0x83, 0x51, 0x6e, 0x6d, 0x29, 0x13, 0x93, 0x55, 0x6d, 0xb4, 0xaa, 0x1b, 0x87, - 0x24, 0xe8, 0xef, 0x16, 0x30, 0x5c, 0x07, 0x73, 0x9c, 0xf6, 0x71, 0xf2, 0xdc, 0x9c, 0x13, 0xaf, - 0x45, 0xba, 0x1a, 0xe3, 0x6d, 0xb3, 0x5a, 0xc2, 0xdb, 0x70, 0x00, 0x60, 0xf1, 0x02, 0x36, 0xc8, - 0xb8, 0x97, 0x66, 0x24, 0xc0, 0xe6, 0xbc, 0xb4, 0xfc, 0xfa, 0xce, 0x96, 0x97, 0x95, 0x65, 0x96, - 0x52, 0xad, 0x64, 0xa3, 0x07, 0x5a, 0xfe, 0x60, 0x90, 0xf1, 0x7d, 0x01, 0x89, 0xd8, 0xcb, 0x3b, - 0x99, 0x0b, 0x0d, 0xa3, 0x39, 0x5d, 0x8e, 0xbd, 0xdc, 0xb5, 0x51, 0xad, 0xb4, 0xa7, 0x98, 0x95, - 0x39, 0xb0, 0xd4, 0x0f, 0x48, 0xd2, 0x33, 0x81, 0xf8, 0x00, 0xe5, 0xd9, 0x72, 0xd7, 0x46, 0x35, - 0x51, 0x1e, 0xa8, 0x0a, 0x1e, 0x80, 0x35, 0x7c, 0x9a, 0xd2, 0x44, 0x48, 0xfb, 0xda, 0x9f, 0x47, - 0x13, 0x6c, 0xd6, 0xa4, 0x81, 0xc6, 0x28, 0xb7, 0x1e, 0x29, 0x91, 0x89, 0x34, 0x1b, 0xc1, 0x02, - 0xdf, 0x51, 0x9b, 0xec, 0x25, 0x18, 0x1e, 0x81, 0x79, 0xf6, 0xc9, 0x4f, 0xbd, 0x63, 0x8c, 0xcd, - 0x45, 0x99, 0xda, 0xce, 0x9d, 0x53, 0xbb, 0xaf, 0x53, 0xd3, 0x3a, 0x36, 0xaa, 0x8a, 0xc7, 0xb7, - 0x18, 0xc3, 0x53, 0xb0, 0x16, 0xf9, 0x8c, 0xdf, 0x7e, 0x76, 0x6f, 0x98, 0x86, 0x3e, 0xc7, 0xe6, - 0xbd, 0x86, 0xd1, 0xac, 0xbd, 0xd8, 0x74, 0xd4, 0x39, 0x73, 0x8a, 0x73, 0xe6, 0x1c, 0x16, 0xe7, - 0xac, 0xd3, 0x14, 0x36, 0x6e, 0x57, 0x9a, 0x28, 0x63, 0x9f, 0xff, 0xb6, 0x0c, 0xb4, 0x22, 0x7a, - 0xe3, 0x7f, 0xd0, 0x7b, 0xd9, 0xd9, 0x5e, 0xfe, 0x72, 0x61, 0x55, 0xbe, 0x5e, 0x58, 0x95, 0x1f, - 0xdf, 0x5b, 0xb3, 0xe2, 0xa4, 0xbe, 0xeb, 0x1c, 0x5d, 0x5e, 0xd7, 0x8d, 0xab, 0xeb, 0xba, 0xf1, - 0xe7, 0xba, 0x6e, 0x9c, 0xdf, 0xd4, 0x2b, 0x57, 0x37, 0xf5, 0xca, 0xcf, 0x9b, 0x7a, 0xe5, 0x43, - 0xa7, 0xb4, 0xaa, 0xbe, 0x51, 0x5a, 0x91, 0xdf, 0x65, 0x45, 0xe1, 0x9e, 0xb4, 0x5f, 0xb9, 0xa7, - 0xff, 0xbb, 0x8f, 0x62, 0x1a, 0xe2, 0xa8, 0x3b, 0x27, 0x77, 0x78, 0xf9, 0x37, 0x00, 0x00, 0xff, - 0xff, 0xb9, 0x3a, 0x2a, 0xb2, 0xbe, 0x04, 0x00, 0x00, + 0x14, 0x8d, 0xfb, 0xa4, 0x93, 0xb6, 0xa2, 0xd3, 0x07, 0x6e, 0x45, 0xe3, 0xc8, 0x12, 0x28, 0x48, + 0xc4, 0x26, 0x20, 0x36, 0xdd, 0x35, 0xa0, 0x4a, 0x48, 0x95, 0x5a, 0xb9, 0x65, 0x83, 0x90, 0xac, + 0x89, 0x3d, 0x0d, 0xa3, 0x38, 0x1e, 0xc7, 0x33, 0xa9, 0xda, 0x0f, 0x40, 0x62, 0xd9, 0x25, 0xcb, + 0x7e, 0x04, 0x1f, 0xc0, 0xb2, 0x62, 0xd5, 0x25, 0x62, 0x61, 0x50, 0xfb, 0x07, 0xf9, 0x02, 0x34, + 0x0f, 0xa7, 0x23, 0x11, 0x16, 0x5d, 0x25, 0xe7, 0xde, 0x73, 0x8f, 0xcf, 0x3d, 0xf6, 0x0c, 0x78, + 0x46, 0x59, 0x9f, 0x32, 0xc2, 0xfc, 0x88, 0xa6, 0x11, 0x4e, 0x79, 0x8e, 0x38, 0x8e, 0x9b, 0x09, + 0x19, 0x0c, 0x49, 0x4c, 0xf8, 0xb9, 0x9f, 0x51, 0x9a, 0x78, 0x59, 0x4e, 0x39, 0x85, 0x4f, 0x34, + 0xd5, 0x33, 0xa9, 0x63, 0xa6, 0x77, 0xda, 0xea, 0x60, 0x8e, 0x5a, 0x5b, 0x9b, 0x91, 0xe4, 0x85, + 0x72, 0xc8, 0x57, 0x40, 0x29, 0x6c, 0xad, 0x75, 0x69, 0x97, 0xaa, 0xba, 0xf8, 0xa7, 0xab, 0x4e, + 0x97, 0xd2, 0x6e, 0x82, 0x7d, 0x89, 0x3a, 0xc3, 0x13, 0x9f, 0x93, 0x3e, 0x66, 0x1c, 0xf5, 0x33, + 0x45, 0x70, 0xbf, 0xcf, 0x83, 0x99, 0x43, 0x4a, 0x13, 0xf8, 0x1c, 0xcc, 0xa3, 0x38, 0xce, 0x31, + 0x63, 0xb6, 0x55, 0xb7, 0x1a, 0x0b, 0x6d, 0x38, 0x2a, 0x9c, 0xe5, 0x73, 0xd4, 0x4f, 0x76, 0x5c, + 0xdd, 0x70, 0x83, 0x92, 0x02, 0xf7, 0x01, 0x24, 0xd2, 0x28, 0x39, 0xc5, 0x2c, 0x2c, 0x07, 0xa7, + 0xe4, 0xe0, 0xf6, 0xa8, 0x70, 0x36, 0xd5, 0xe0, 0xbf, 0x1c, 0x37, 0x58, 0xb9, 0x2b, 0xee, 0x6a, + 0xb5, 0x1d, 0xb0, 0x78, 0x82, 0x0d, 0x9d, 0x69, 0xa9, 0xf3, 0x68, 0x54, 0x38, 0xab, 0x4a, 0xc7, + 0xec, 0xba, 0x41, 0x55, 0xc0, 0x72, 0x76, 0x19, 0x4c, 0x91, 0xd8, 0x9e, 0xa9, 0x5b, 0x8d, 0x99, + 0x60, 0x8a, 0xc4, 0xf0, 0xb3, 0x05, 0x36, 0xa2, 0x61, 0x9e, 0xe3, 0x94, 0x87, 0x9c, 0x44, 0xbd, + 0x70, 0x9c, 0xa2, 0x3d, 0x2b, 0x65, 0x0f, 0xae, 0x0a, 0xa7, 0xf2, 0xab, 0x70, 0x9e, 0x76, 0x09, + 0xff, 0x34, 0xec, 0x78, 0x11, 0xed, 0xeb, 0x24, 0xf5, 0x4f, 0x93, 0xc5, 0x3d, 0x9f, 0x9f, 0x67, + 0x98, 0x79, 0x6f, 0x71, 0x34, 0x2a, 0x9c, 0x6d, 0x65, 0x62, 0xb2, 0xaa, 0x1b, 0xac, 0xe9, 0xc6, + 0x31, 0x89, 0x7a, 0xfb, 0x65, 0x19, 0x6e, 0x80, 0x39, 0x4e, 0x7b, 0x38, 0x7d, 0x61, 0xcf, 0x89, + 0xc7, 0x06, 0x1a, 0x8d, 0xeb, 0x2d, 0x7b, 0xde, 0xa8, 0xb7, 0xe0, 0x00, 0xc0, 0xf2, 0x01, 0x6c, + 0x90, 0xf3, 0x30, 0xcb, 0x49, 0x84, 0xed, 0x07, 0xd2, 0xf2, 0x9b, 0x7b, 0x5b, 0x5e, 0x51, 0x96, + 0x59, 0x46, 0xb5, 0x92, 0x1b, 0x3c, 0xd4, 0xf2, 0x47, 0x83, 0x9c, 0x1f, 0x8a, 0x92, 0x88, 0xdd, + 0xdc, 0xc9, 0x5e, 0xa8, 0x5b, 0x8d, 0x69, 0x33, 0x76, 0xb3, 0xeb, 0x06, 0x55, 0x63, 0x4f, 0x31, + 0x2b, 0x73, 0x60, 0x19, 0x8a, 0x48, 0xda, 0xb5, 0x81, 0x78, 0x01, 0xe6, 0xac, 0xd9, 0x75, 0x83, + 0xaa, 0x80, 0x47, 0x0a, 0xc1, 0x23, 0xb0, 0x8e, 0xcf, 0x32, 0x9a, 0x0a, 0x69, 0xa4, 0xfd, 0x85, + 0x34, 0xc5, 0x76, 0x55, 0x1a, 0xa8, 0x8f, 0x0a, 0xe7, 0xb1, 0x12, 0x99, 0x48, 0x73, 0x03, 0x58, + 0xd6, 0x77, 0xd5, 0x26, 0x07, 0x29, 0x86, 0x3d, 0xb0, 0xc4, 0xb2, 0x1c, 0xa3, 0x38, 0x3c, 0x41, + 0x11, 0xa7, 0xb9, 0xbd, 0x28, 0xa3, 0xdb, 0xbb, 0x77, 0x74, 0x6b, 0x65, 0x74, 0x86, 0x98, 0x1b, + 0x2c, 0x2a, 0xbc, 0x27, 0x21, 0x3c, 0x03, 0xeb, 0x09, 0x62, 0xfc, 0xee, 0x2b, 0x08, 0x87, 0x59, + 0x8c, 0x38, 0xb6, 0x97, 0xea, 0x56, 0xa3, 0xfa, 0x72, 0xcb, 0x53, 0xc7, 0xce, 0x2b, 0x8f, 0x9d, + 0x77, 0x5c, 0x1e, 0xbb, 0x76, 0x43, 0x18, 0xba, 0xdb, 0x70, 0xa2, 0x8c, 0x7b, 0xf1, 0xdb, 0xb1, + 0x82, 0x55, 0xd1, 0x1b, 0x7f, 0x50, 0xef, 0x65, 0x67, 0x67, 0xe5, 0xcb, 0xa5, 0x53, 0xf9, 0x7a, + 0xe9, 0x54, 0x7e, 0x7c, 0x6b, 0xce, 0x8a, 0x83, 0xfb, 0xae, 0xfd, 0xf1, 0xea, 0xa6, 0x66, 0x5d, + 0xdf, 0xd4, 0xac, 0x3f, 0x37, 0x35, 0xeb, 0xe2, 0xb6, 0x56, 0xb9, 0xbe, 0xad, 0x55, 0x7e, 0xde, + 0xd6, 0x2a, 0x1f, 0xda, 0xc6, 0xd2, 0xfa, 0x82, 0x69, 0x26, 0xa8, 0xc3, 0x4a, 0xe0, 0x9f, 0xb6, + 0x5e, 0xfb, 0x67, 0xff, 0xbb, 0x9e, 0xfa, 0x34, 0xc6, 0x49, 0x67, 0x4e, 0xee, 0xf0, 0xea, 0x6f, + 0x00, 0x00, 0x00, 0xff, 0xff, 0xb3, 0x4b, 0x9b, 0xf7, 0xcd, 0x04, 0x00, 0x00, } func (m *Pool) Marshal() (dAtA []byte, err error) { @@ -172,9 +172,9 @@ func (m *Pool) MarshalToSizedBuffer(dAtA []byte) (int, error) { i-- dAtA[i] = 0x6a { - size := m.SwapFee.Size() + size := m.SpreadFactor.Size() i -= size - if _, err := m.SwapFee.MarshalTo(dAtA[i:]); err != nil { + if _, err := m.SpreadFactor.MarshalTo(dAtA[i:]); err != nil { return 0, err } i = encodeVarintPool(dAtA, i, uint64(size)) @@ -312,7 +312,7 @@ func (m *Pool) Size() (n int) { if m.ExponentAtPriceOne != 0 { n += 1 + sovPool(uint64(m.ExponentAtPriceOne)) } - l = m.SwapFee.Size() + l = m.SpreadFactor.Size() n += 1 + l + sovPool(uint64(l)) l = github_com_gogo_protobuf_types.SizeOfStdTime(m.LastLiquidityUpdate) n += 1 + l + sovPool(uint64(l)) @@ -660,7 +660,7 @@ func (m *Pool) Unmarshal(dAtA []byte) error { } case 12: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapFee", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field SpreadFactor", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -688,7 +688,7 @@ func (m *Pool) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.SwapFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.SpreadFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex diff --git a/x/concentrated-liquidity/model/pool_test.go b/x/concentrated-liquidity/model/pool_test.go index 030c520b46b..1725cb12c37 100644 --- a/x/concentrated-liquidity/model/pool_test.go +++ b/x/concentrated-liquidity/model/pool_test.go @@ -30,7 +30,7 @@ var ( DefaultCurrTick int64 = 310000 DefaultCurrPrice = sdk.NewDec(5000) DefaultCurrSqrtPrice, _ = DefaultCurrPrice.ApproxSqrt() // 70.710678118654752440 - DefaultSwapFee = sdk.MustNewDecFromStr("0.01") + DefaultSpreadFactor = sdk.MustNewDecFromStr("0.01") ) type ConcentratedPoolTestSuite struct { @@ -296,11 +296,11 @@ func (s *ConcentratedPoolTestSuite) TestApplySwap() { // TestNewConcentratedLiquidityPool is a test suite that tests the NewConcentratedLiquidityPool function. func (s *ConcentratedPoolTestSuite) TestNewConcentratedLiquidityPool() { type param struct { - poolId uint64 - denom0 string - denom1 string - tickSpacing uint64 - swapFee sdk.Dec + poolId uint64 + denom0 string + denom1 string + tickSpacing uint64 + spreadFactor sdk.Dec } tests := []struct { @@ -315,11 +315,11 @@ func (s *ConcentratedPoolTestSuite) TestNewConcentratedLiquidityPool() { { name: "Happy path", param: param{ - poolId: DefaultValidPoolID, - denom0: ETH, - denom1: USDC, - tickSpacing: DefaultTickSpacing, - swapFee: DefaultSwapFee, + poolId: DefaultValidPoolID, + denom0: ETH, + denom1: USDC, + tickSpacing: DefaultTickSpacing, + spreadFactor: DefaultSpreadFactor, }, expectedPoolId: DefaultValidPoolID, expectedDenom0: ETH, @@ -329,11 +329,11 @@ func (s *ConcentratedPoolTestSuite) TestNewConcentratedLiquidityPool() { { name: "Non lexicographical order of denoms should not get reordered", param: param{ - poolId: DefaultValidPoolID, - denom0: USDC, - denom1: ETH, - tickSpacing: DefaultTickSpacing, - swapFee: sdk.ZeroDec(), + poolId: DefaultValidPoolID, + denom0: USDC, + denom1: ETH, + tickSpacing: DefaultTickSpacing, + spreadFactor: sdk.ZeroDec(), }, expectedPoolId: DefaultValidPoolID, expectedDenom0: USDC, @@ -344,35 +344,35 @@ func (s *ConcentratedPoolTestSuite) TestNewConcentratedLiquidityPool() { { name: "Error: same denom not allowed", param: param{ - poolId: DefaultValidPoolID, - denom0: USDC, - denom1: USDC, - tickSpacing: DefaultTickSpacing, - swapFee: DefaultSwapFee, + poolId: DefaultValidPoolID, + denom0: USDC, + denom1: USDC, + tickSpacing: DefaultTickSpacing, + spreadFactor: DefaultSpreadFactor, }, expectedErr: types.MatchingDenomError{Denom: USDC}, }, { - name: "Error: negative swap fee", + name: "Error: negative spread factor", param: param{ - poolId: DefaultValidPoolID, - denom0: ETH, - denom1: USDC, - tickSpacing: DefaultTickSpacing, - swapFee: sdk.ZeroDec().Sub(sdk.SmallestDec()), + poolId: DefaultValidPoolID, + denom0: ETH, + denom1: USDC, + tickSpacing: DefaultTickSpacing, + spreadFactor: sdk.ZeroDec().Sub(sdk.SmallestDec()), }, - expectedErr: types.InvalidSwapFeeError{ActualFee: sdk.ZeroDec().Sub(sdk.SmallestDec())}, + expectedErr: types.InvalidSpreadFactorError{ActualFee: sdk.ZeroDec().Sub(sdk.SmallestDec())}, }, { - name: "Error: swap fee == 1", + name: "Error: spread factor == 1", param: param{ - poolId: DefaultValidPoolID, - denom0: ETH, - denom1: USDC, - tickSpacing: DefaultTickSpacing, - swapFee: sdk.OneDec(), + poolId: DefaultValidPoolID, + denom0: ETH, + denom1: USDC, + tickSpacing: DefaultTickSpacing, + spreadFactor: sdk.OneDec(), }, - expectedErr: types.InvalidSwapFeeError{ActualFee: sdk.OneDec()}, + expectedErr: types.InvalidSpreadFactorError{ActualFee: sdk.OneDec()}, }, } @@ -382,7 +382,7 @@ func (s *ConcentratedPoolTestSuite) TestNewConcentratedLiquidityPool() { s.Setup() // Call NewConcentratedLiquidityPool with the parameters from the current test. - pool, err := model.NewConcentratedLiquidityPool(test.param.poolId, test.param.denom0, test.param.denom1, test.param.tickSpacing, test.param.swapFee) + pool, err := model.NewConcentratedLiquidityPool(test.param.poolId, test.param.denom0, test.param.denom1, test.param.tickSpacing, test.param.spreadFactor) if test.expectedErr != nil { // If the test is expected to produce an error, check if it does. @@ -397,7 +397,7 @@ func (s *ConcentratedPoolTestSuite) TestNewConcentratedLiquidityPool() { s.Require().Equal(test.expectedDenom0, pool.Token0) s.Require().Equal(test.expectedDenom1, pool.Token1) s.Require().Equal(test.expectedTickSpacing, pool.TickSpacing) - s.Require().Equal(test.param.swapFee, pool.SwapFee) + s.Require().Equal(test.param.spreadFactor, pool.SpreadFactor) } }) } diff --git a/x/concentrated-liquidity/model/tx.pb.go b/x/concentrated-liquidity/model/tx.pb.go index 5fe52525ec2..2a20e829cde 100644 --- a/x/concentrated-liquidity/model/tx.pb.go +++ b/x/concentrated-liquidity/model/tx.pb.go @@ -32,11 +32,11 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // ===================== MsgCreateConcentratedPool type MsgCreateConcentratedPool struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` - Denom0 string `protobuf:"bytes,2,opt,name=denom0,proto3" json:"denom0,omitempty" yaml:"denom0"` - Denom1 string `protobuf:"bytes,3,opt,name=denom1,proto3" json:"denom1,omitempty" yaml:"denom1"` - TickSpacing uint64 `protobuf:"varint,4,opt,name=tick_spacing,json=tickSpacing,proto3" json:"tick_spacing,omitempty" yaml:"tick_spacing"` - SwapFee github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=swap_fee,json=swapFee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"swap_fee" yaml:"swap_fee"` + Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` + Denom0 string `protobuf:"bytes,2,opt,name=denom0,proto3" json:"denom0,omitempty" yaml:"denom0"` + Denom1 string `protobuf:"bytes,3,opt,name=denom1,proto3" json:"denom1,omitempty" yaml:"denom1"` + TickSpacing uint64 `protobuf:"varint,4,opt,name=tick_spacing,json=tickSpacing,proto3" json:"tick_spacing,omitempty" yaml:"tick_spacing"` + SpreadFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=spread_factor,json=spreadFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"spread_factor" yaml:"spread_factor"` } func (m *MsgCreateConcentratedPool) Reset() { *m = MsgCreateConcentratedPool{} } @@ -155,35 +155,36 @@ func init() { } var fileDescriptor_6c324e8c9dd2851d = []byte{ - // 448 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0xc1, 0x6e, 0xd3, 0x40, - 0x10, 0x86, 0xe3, 0x12, 0x52, 0x58, 0x40, 0x08, 0x83, 0xc0, 0xe4, 0x60, 0x17, 0x23, 0x50, 0x39, - 0xc4, 0x8b, 0x8b, 0xb8, 0xf4, 0x04, 0x6e, 0x85, 0xda, 0x03, 0x12, 0x32, 0x37, 0x54, 0x29, 0x5a, - 0xef, 0x0e, 0x66, 0x55, 0xdb, 0x63, 0xbc, 0xdb, 0xd2, 0xbc, 0x05, 0x0f, 0xc1, 0x1b, 0x20, 0xf1, - 0x0c, 0x3d, 0xf6, 0x88, 0x38, 0x58, 0x28, 0x79, 0x83, 0x3c, 0x01, 0xb2, 0xbd, 0x89, 0x22, 0x44, - 0x24, 0xa4, 0x9e, 0xbc, 0xb3, 0xf3, 0xfd, 0x33, 0xde, 0x7f, 0x67, 0xc9, 0x0e, 0xaa, 0x1c, 0x95, - 0x54, 0x94, 0x63, 0xc1, 0xa1, 0xd0, 0x15, 0xd3, 0x20, 0x46, 0x99, 0xfc, 0x7c, 0x22, 0x85, 0xd4, - 0x13, 0x5a, 0x22, 0x66, 0xa3, 0x1c, 0x05, 0x64, 0x54, 0x9f, 0x05, 0x65, 0x85, 0x1a, 0xed, 0x27, - 0x46, 0x13, 0xac, 0x6a, 0x96, 0x92, 0xe0, 0x34, 0x4c, 0x40, 0xb3, 0x70, 0x78, 0x2f, 0xc5, 0x14, - 0x5b, 0x05, 0x6d, 0x56, 0x9d, 0x78, 0xe8, 0xf2, 0x56, 0x4d, 0x13, 0xa6, 0x80, 0x1a, 0x94, 0x72, - 0x94, 0x45, 0x97, 0xf7, 0x7f, 0x6c, 0x90, 0x87, 0x6f, 0x55, 0xba, 0x57, 0x01, 0xd3, 0xb0, 0xb7, - 0xd2, 0xe0, 0x1d, 0x62, 0x66, 0x3f, 0x23, 0x03, 0x05, 0x85, 0x80, 0xca, 0xb1, 0xb6, 0xac, 0xed, - 0xeb, 0xd1, 0x9d, 0x79, 0xed, 0xdd, 0x9a, 0xb0, 0x3c, 0xdb, 0xf5, 0xbb, 0x7d, 0x3f, 0x36, 0x40, - 0x83, 0x0a, 0x28, 0x30, 0x7f, 0xee, 0x6c, 0xfc, 0x8d, 0x76, 0xfb, 0x7e, 0x6c, 0x80, 0x25, 0x1a, - 0x3a, 0x57, 0xfe, 0x89, 0x86, 0x0b, 0x34, 0xb4, 0x77, 0xc9, 0x4d, 0x2d, 0xf9, 0xf1, 0x58, 0x95, - 0x8c, 0xcb, 0x22, 0x75, 0xfa, 0x5b, 0xd6, 0x76, 0x3f, 0x7a, 0x30, 0xaf, 0xbd, 0xbb, 0x9d, 0x60, - 0x35, 0xeb, 0xc7, 0x37, 0x9a, 0xf0, 0x7d, 0x17, 0xd9, 0x47, 0xe4, 0x9a, 0xfa, 0xc2, 0xca, 0xf1, - 0x47, 0x00, 0xe7, 0x6a, 0xdb, 0xe8, 0xf5, 0x79, 0xed, 0xf5, 0x7e, 0xd5, 0xde, 0xd3, 0x54, 0xea, - 0x4f, 0x27, 0x49, 0xc0, 0x31, 0xa7, 0xc6, 0x9f, 0xee, 0x33, 0x52, 0xe2, 0x98, 0xea, 0x49, 0x09, - 0x2a, 0xd8, 0x07, 0x3e, 0xaf, 0xbd, 0xdb, 0xe6, 0xb0, 0xa6, 0x8e, 0x1f, 0x6f, 0x36, 0xcb, 0x37, - 0x00, 0xfe, 0x01, 0x79, 0xb4, 0xd6, 0xb7, 0x18, 0x54, 0x89, 0x85, 0x02, 0xfb, 0x31, 0xd9, 0x6c, - 0x6e, 0x74, 0x2c, 0x45, 0x6b, 0x60, 0x3f, 0x22, 0xd3, 0xda, 0x1b, 0x34, 0xc8, 0xe1, 0x7e, 0x3c, - 0x68, 0x52, 0x87, 0x62, 0xe7, 0xbb, 0x45, 0xc8, 0xa2, 0x14, 0x56, 0xf6, 0x37, 0x8b, 0xdc, 0x5f, - 0x73, 0x1d, 0xaf, 0x82, 0xff, 0x1a, 0x85, 0x60, 0xed, 0x8f, 0x0d, 0x0f, 0x2e, 0x5b, 0x61, 0x71, - 0xb4, 0xe8, 0xe8, 0x7c, 0xea, 0x5a, 0x17, 0x53, 0xd7, 0xfa, 0x3d, 0x75, 0xad, 0xaf, 0x33, 0xb7, - 0x77, 0x31, 0x73, 0x7b, 0x3f, 0x67, 0x6e, 0xef, 0x43, 0xb4, 0xe2, 0xae, 0xe9, 0x36, 0xca, 0x58, - 0xa2, 0x16, 0x01, 0x3d, 0x0d, 0x5f, 0xd2, 0xb3, 0x75, 0x2f, 0xa0, 0x1d, 0xfe, 0x64, 0xd0, 0x4e, - 0xe7, 0x8b, 0x3f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x4e, 0x72, 0x61, 0x39, 0x30, 0x03, 0x00, 0x00, + // 449 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0x41, 0x6e, 0xd4, 0x30, + 0x14, 0x86, 0xc7, 0x65, 0x18, 0x84, 0x69, 0x17, 0x84, 0x0a, 0xc2, 0x2c, 0x92, 0x12, 0x04, 0x2a, + 0x8b, 0x89, 0x49, 0x11, 0x9b, 0xae, 0x50, 0x5a, 0x55, 0xed, 0x02, 0x09, 0x85, 0x1d, 0x42, 0x1a, + 0x39, 0xb6, 0x09, 0xd6, 0x24, 0x79, 0x21, 0x76, 0xab, 0xce, 0x2d, 0x38, 0x04, 0x37, 0xe0, 0x0c, + 0x48, 0x5d, 0x76, 0x89, 0x58, 0x44, 0x68, 0xe6, 0x06, 0x73, 0x02, 0x94, 0x38, 0x33, 0x8a, 0x10, + 0x91, 0x90, 0xba, 0x4a, 0x7e, 0xbf, 0xef, 0x7f, 0xcf, 0x7e, 0xf6, 0xc3, 0x07, 0xa0, 0x32, 0x50, + 0x52, 0x11, 0x06, 0x39, 0x13, 0xb9, 0x2e, 0xa9, 0x16, 0x7c, 0x92, 0xca, 0x2f, 0xe7, 0x92, 0x4b, + 0x3d, 0x27, 0x05, 0x40, 0x3a, 0xc9, 0x80, 0x8b, 0x94, 0xe8, 0x4b, 0xbf, 0x28, 0x41, 0x83, 0xf5, + 0xac, 0xf5, 0xf8, 0x5d, 0xcf, 0xc6, 0xe2, 0x5f, 0x04, 0xb1, 0xd0, 0x34, 0x18, 0xef, 0x26, 0x90, + 0x40, 0xe3, 0x20, 0xf5, 0x9f, 0x31, 0x8f, 0x1d, 0xd6, 0xb8, 0x49, 0x4c, 0x95, 0x20, 0x2d, 0x4a, + 0x18, 0xc8, 0xdc, 0xc4, 0xbd, 0x1f, 0x5b, 0xf8, 0xf1, 0x5b, 0x95, 0x1c, 0x95, 0x82, 0x6a, 0x71, + 0xd4, 0x29, 0xf0, 0x0e, 0x20, 0xb5, 0x5e, 0xe0, 0x91, 0x12, 0x39, 0x17, 0xa5, 0x8d, 0xf6, 0xd0, + 0xfe, 0xdd, 0xf0, 0xfe, 0xaa, 0x72, 0x77, 0xe6, 0x34, 0x4b, 0x0f, 0x3d, 0xb3, 0xee, 0x45, 0x2d, + 0x50, 0xa3, 0x5c, 0xe4, 0x90, 0xbd, 0xb4, 0xb7, 0xfe, 0x46, 0xcd, 0xba, 0x17, 0xb5, 0xc0, 0x06, + 0x0d, 0xec, 0x5b, 0xff, 0x44, 0x83, 0x35, 0x1a, 0x58, 0x87, 0x78, 0x5b, 0x4b, 0x36, 0x9b, 0xaa, + 0x82, 0x32, 0x99, 0x27, 0xf6, 0x70, 0x0f, 0xed, 0x0f, 0xc3, 0x47, 0xab, 0xca, 0x7d, 0x60, 0x0c, + 0xdd, 0xa8, 0x17, 0xdd, 0xab, 0xe5, 0x7b, 0xa3, 0xac, 0x19, 0xde, 0x51, 0x45, 0x29, 0x28, 0x9f, + 0x7e, 0xa2, 0x4c, 0x43, 0x69, 0xdf, 0x6e, 0xaa, 0x9d, 0x5c, 0x55, 0xee, 0xe0, 0x57, 0xe5, 0x3e, + 0x4f, 0xa4, 0xfe, 0x7c, 0x1e, 0xfb, 0x0c, 0x32, 0xd2, 0x36, 0xc9, 0x7c, 0x26, 0x8a, 0xcf, 0x88, + 0x9e, 0x17, 0x42, 0xf9, 0xc7, 0x82, 0xad, 0x2a, 0x77, 0xb7, 0x3d, 0x71, 0x37, 0x99, 0x17, 0x6d, + 0x1b, 0x7d, 0x62, 0xe4, 0x29, 0x7e, 0xd2, 0xdb, 0xc6, 0x48, 0xa8, 0x02, 0x72, 0x25, 0xac, 0xa7, + 0xf8, 0x4e, 0x7d, 0xc1, 0x53, 0xc9, 0x9b, 0x7e, 0x0e, 0x43, 0xbc, 0xa8, 0xdc, 0x51, 0x8d, 0x9c, + 0x1d, 0x47, 0xa3, 0x3a, 0x74, 0xc6, 0x0f, 0xbe, 0x23, 0x8c, 0xd7, 0xa9, 0xa0, 0xb4, 0xbe, 0x21, + 0xfc, 0xb0, 0xe7, 0x76, 0xde, 0xf8, 0xff, 0xf5, 0x32, 0xfc, 0xde, 0x8d, 0x8d, 0x4f, 0x6f, 0x9a, + 0x61, 0x7d, 0xb4, 0xf0, 0xe3, 0xd5, 0xc2, 0x41, 0xd7, 0x0b, 0x07, 0xfd, 0x5e, 0x38, 0xe8, 0xeb, + 0xd2, 0x19, 0x5c, 0x2f, 0x9d, 0xc1, 0xcf, 0xa5, 0x33, 0xf8, 0x10, 0x76, 0xfa, 0xdc, 0x56, 0x9b, + 0xa4, 0x34, 0x56, 0x6b, 0x41, 0x2e, 0x82, 0xd7, 0xe4, 0xb2, 0x6f, 0x20, 0x9a, 0x59, 0x88, 0x47, + 0xcd, 0x63, 0x7d, 0xf5, 0x27, 0x00, 0x00, 0xff, 0xff, 0xfd, 0x14, 0x6f, 0xc1, 0x3f, 0x03, 0x00, + 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -287,9 +288,9 @@ func (m *MsgCreateConcentratedPool) MarshalToSizedBuffer(dAtA []byte) (int, erro var l int _ = l { - size := m.SwapFee.Size() + size := m.SpreadFactor.Size() i -= size - if _, err := m.SwapFee.MarshalTo(dAtA[i:]); err != nil { + if _, err := m.SpreadFactor.MarshalTo(dAtA[i:]); err != nil { return 0, err } i = encodeVarintTx(dAtA, i, uint64(size)) @@ -385,7 +386,7 @@ func (m *MsgCreateConcentratedPool) Size() (n int) { if m.TickSpacing != 0 { n += 1 + sovTx(uint64(m.TickSpacing)) } - l = m.SwapFee.Size() + l = m.SpreadFactor.Size() n += 1 + l + sovTx(uint64(l)) return n } @@ -554,7 +555,7 @@ func (m *MsgCreateConcentratedPool) Unmarshal(dAtA []byte) error { } case 5: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapFee", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field SpreadFactor", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -582,7 +583,7 @@ func (m *MsgCreateConcentratedPool) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.SwapFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.SpreadFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex diff --git a/x/concentrated-liquidity/msg_server_test.go b/x/concentrated-liquidity/msg_server_test.go index 1b16b9c0090..40d67c9bfef 100644 --- a/x/concentrated-liquidity/msg_server_test.go +++ b/x/concentrated-liquidity/msg_server_test.go @@ -63,11 +63,11 @@ func (s *KeeperTestSuite) TestCreateConcentratedPool_Events() { s.Equal(0, len(ctx.EventManager().Events())) response, err := msgServer.CreateConcentratedPool(sdk.WrapSDKContext(ctx), &clmodel.MsgCreateConcentratedPool{ - Sender: s.TestAccs[0].String(), - Denom0: tc.denom0, - Denom1: tc.denom1, - TickSpacing: tc.tickSpacing, - SwapFee: DefaultZeroSwapFee, + Sender: s.TestAccs[0].String(), + Denom0: tc.denom0, + Denom1: tc.denom1, + TickSpacing: tc.tickSpacing, + SpreadFactor: DefaultZeroSpreadFactor, }) if tc.expectedError == nil { diff --git a/x/concentrated-liquidity/pool.go b/x/concentrated-liquidity/pool.go index 64612d40282..7a82e809a89 100644 --- a/x/concentrated-liquidity/pool.go +++ b/x/concentrated-liquidity/pool.go @@ -16,14 +16,14 @@ import ( ) // InitializePool initializes a new concentrated liquidity pool with the given PoolI interface and creator address. -// It validates tick spacing, swap fee, and authorized quote denominations before creating and setting +// It validates tick spacing, spread factor, and authorized quote denominations before creating and setting // the pool's fee and uptime accumulators. If the pool is successfully created, it calls the AfterConcentratedPoolCreated // listener function. // // Returns an error if any of the following conditions are met: // - The poolI cannot be converted to a ConcentratedPool. // - The tick spacing is invalid. -// - The swap fee is invalid. +// - The spread factor is invalid. // - The quote denomination is unauthorized. // - There is an error creating the fee or uptime accumulator. // - There is an error setting the pool in the keeper's state. @@ -35,7 +35,7 @@ func (k Keeper) InitializePool(ctx sdk.Context, poolI poolmanagertypes.PoolI, cr params := k.GetParams(ctx) tickSpacing := concentratedPool.GetTickSpacing() - swapFee := concentratedPool.GetSwapFee(ctx) + spreadFactor := concentratedPool.GetSpreadFactor(ctx) poolId := concentratedPool.GetId() quoteAsset := concentratedPool.GetToken1() @@ -43,8 +43,8 @@ func (k Keeper) InitializePool(ctx sdk.Context, poolI poolmanagertypes.PoolI, cr return types.UnauthorizedTickSpacingError{ProvidedTickSpacing: tickSpacing, AuthorizedTickSpacings: params.AuthorizedTickSpacing} } - if !k.validateSwapFee(ctx, params, swapFee) { - return types.UnauthorizedSwapFeeError{ProvidedSwapFee: swapFee, AuthorizedSwapFees: params.AuthorizedSwapFees} + if !k.validateSpreadFactor(ctx, params, spreadFactor) { + return types.UnauthorizedSpreadFactorError{ProvidedSpreadFactor: spreadFactor, AuthorizedSpreadFactors: params.AuthorizedSpreadFactors} } if !validateAuthorizedQuoteDenoms(ctx, quoteAsset, params.AuthorizedQuoteDenoms) { @@ -316,11 +316,11 @@ func (k Keeper) validateTickSpacingUpdate(ctx sdk.Context, pool types.Concentrat return false } -// validateSwapFee returns true if the given swap fee is one of the authorized swap fees set in the +// validateSpreadFactor returns true if the given spread factor is one of the authorized spread factors set in the // params. False otherwise. -func (k Keeper) validateSwapFee(ctx sdk.Context, params types.Params, swapFee sdk.Dec) bool { - for _, authorizedSwapFee := range params.AuthorizedSwapFees { - if swapFee.Equal(authorizedSwapFee) { +func (k Keeper) validateSpreadFactor(ctx sdk.Context, params types.Params, spreadFactor sdk.Dec) bool { + for _, authorizedSpreadFactor := range params.AuthorizedSpreadFactors { + if spreadFactor.Equal(authorizedSpreadFactor) { return true } } diff --git a/x/concentrated-liquidity/pool_test.go b/x/concentrated-liquidity/pool_test.go index dbd12441169..3cb7f89fd9f 100644 --- a/x/concentrated-liquidity/pool_test.go +++ b/x/concentrated-liquidity/pool_test.go @@ -20,12 +20,12 @@ func (s *KeeperTestSuite) TestInitializePool() { // Create a concentrated liquidity pool with unauthorized tick spacing invalidTickSpacing := uint64(25) - invalidTickSpacingConcentratedPool, err := clmodel.NewConcentratedLiquidityPool(2, ETH, USDC, invalidTickSpacing, DefaultZeroSwapFee) + invalidTickSpacingConcentratedPool, err := clmodel.NewConcentratedLiquidityPool(2, ETH, USDC, invalidTickSpacing, DefaultZeroSpreadFactor) s.Require().NoError(err) - // Create a concentrated liquidity pool with unauthorized swap fee - invalidSwapFee := sdk.MustNewDecFromStr("0.1") - invalidSwapFeeConcentratedPool, err := clmodel.NewConcentratedLiquidityPool(3, ETH, USDC, DefaultTickSpacing, invalidSwapFee) + // Create a concentrated liquidity pool with unauthorized spread factor + invalidSpreadFactor := sdk.MustNewDecFromStr("0.1") + invalidSpreadFactorConcentratedPool, err := clmodel.NewConcentratedLiquidityPool(3, ETH, USDC, DefaultTickSpacing, invalidSpreadFactor) s.Require().NoError(err) // Create an invalid PoolI that doesn't implement ConcentratedPoolExtension @@ -60,10 +60,10 @@ func (s *KeeperTestSuite) TestInitializePool() { expectedErr: types.UnauthorizedTickSpacingError{ProvidedTickSpacing: invalidTickSpacing, AuthorizedTickSpacings: s.App.ConcentratedLiquidityKeeper.GetParams(s.Ctx).AuthorizedTickSpacing}, }, { - name: "Invalid swap fee", - poolI: &invalidSwapFeeConcentratedPool, + name: "Invalid spread factor", + poolI: &invalidSpreadFactorConcentratedPool, creatorAddress: validCreatorAddress, - expectedErr: types.UnauthorizedSwapFeeError{ProvidedSwapFee: invalidSwapFee, AuthorizedSwapFees: s.App.ConcentratedLiquidityKeeper.GetParams(s.Ctx).AuthorizedSwapFees}, + expectedErr: types.UnauthorizedSpreadFactorError{ProvidedSpreadFactor: invalidSpreadFactor, AuthorizedSpreadFactors: s.App.ConcentratedLiquidityKeeper.GetParams(s.Ctx).AuthorizedSpreadFactors}, }, { name: "unauthorized quote denom", @@ -277,30 +277,30 @@ func (s *KeeperTestSuite) TestCalculateSpotPrice() { s.Require().True(spotPrice.IsNil()) } -func (s *KeeperTestSuite) TestValidateSwapFee() { +func (s *KeeperTestSuite) TestValidateSpreadFactor() { s.SetupTest() params := s.App.ConcentratedLiquidityKeeper.GetParams(s.Ctx) tests := []struct { - name string - swapFee sdk.Dec - expectValid bool + name string + spreadFactor sdk.Dec + expectValid bool }{ { - name: "Valid swap fee", - swapFee: params.AuthorizedSwapFees[0], - expectValid: true, + name: "Valid spread factor", + spreadFactor: params.AuthorizedSpreadFactors[0], + expectValid: true, }, { - name: "Invalid swap fee", - swapFee: params.AuthorizedSwapFees[0].Add(sdk.SmallestDec()), - expectValid: false, + name: "Invalid spread factor", + spreadFactor: params.AuthorizedSpreadFactors[0].Add(sdk.SmallestDec()), + expectValid: false, }, } for _, test := range tests { s.Run(test.name, func() { // Method under test. - isValid := s.App.ConcentratedLiquidityKeeper.ValidateSwapFee(s.Ctx, params, test.swapFee) + isValid := s.App.ConcentratedLiquidityKeeper.ValidateSpreadFactor(s.Ctx, params, test.spreadFactor) s.Require().Equal(test.expectValid, isValid) }) @@ -350,7 +350,7 @@ func (s *KeeperTestSuite) TestSetPool() { CurrentTick: 0, TickSpacing: DefaultTickSpacing, ExponentAtPriceOne: -6, - SwapFee: sdk.MustNewDecFromStr("0.003"), + SpreadFactor: sdk.MustNewDecFromStr("0.003"), LastLiquidityUpdate: s.Ctx.BlockTime(), } tests := []struct { diff --git a/x/concentrated-liquidity/position_test.go b/x/concentrated-liquidity/position_test.go index 9d5a90a2be2..332275f4cfd 100644 --- a/x/concentrated-liquidity/position_test.go +++ b/x/concentrated-liquidity/position_test.go @@ -1147,7 +1147,7 @@ func (s *KeeperTestSuite) TestFungifyChargedPositions_SwapAndClaimFees() { var ( defaultAddress = s.TestAccs[0] defaultBlockTime = time.Unix(1, 1).UTC() - swapFee = sdk.NewDecWithPrec(2, 3) + spreadFactor = sdk.NewDecWithPrec(2, 3) ) expectedPositionIds := make([]uint64, numPositions) @@ -1169,7 +1169,7 @@ func (s *KeeperTestSuite) TestFungifyChargedPositions_SwapAndClaimFees() { s.FundAcc(defaultAddress, requiredBalances) // Create CL pool - s.PrepareCustomConcentratedPool(s.TestAccs[0], ETH, USDC, DefaultTickSpacing, swapFee) + s.PrepareCustomConcentratedPool(s.TestAccs[0], ETH, USDC, DefaultTickSpacing, spreadFactor) // Set incentives for pool to ensure accumulators work correctly err := s.App.ConcentratedLiquidityKeeper.SetMultipleIncentiveRecords(s.Ctx, DefaultIncentiveRecords) @@ -1185,7 +1185,7 @@ func (s *KeeperTestSuite) TestFungifyChargedPositions_SwapAndClaimFees() { // Perform a swap to earn fees swapAmountIn := sdk.NewCoin(ETH, sdk.NewInt(swapAmount)) - expectedFee := swapAmountIn.Amount.ToDec().Mul(swapFee) + expectedFee := swapAmountIn.Amount.ToDec().Mul(spreadFactor) // We run expected fees through a cycle of divison and multiplication by liquidity to capture appropriate rounding behavior. // Note that we truncate the int at the end since it is not possible to have a decimal fee amount collected (the QuoTruncate // and MulTruncates are much smaller operations that round down for values past the 18th decimal place). @@ -1242,7 +1242,7 @@ func (s *KeeperTestSuite) TestFungifyChargedPositions_ClaimIncentives() { var ( defaultAddress = s.TestAccs[0] defaultBlockTime = time.Unix(1, 1).UTC() - swapFee = sdk.NewDecWithPrec(2, 3) + spreadFactor = sdk.NewDecWithPrec(2, 3) ) expectedPositionIds := make([]uint64, numPositions) @@ -1264,7 +1264,7 @@ func (s *KeeperTestSuite) TestFungifyChargedPositions_ClaimIncentives() { s.FundAcc(defaultAddress, requiredBalances) // Create CL pool - pool := s.PrepareCustomConcentratedPool(s.TestAccs[0], ETH, USDC, DefaultTickSpacing, swapFee) + pool := s.PrepareCustomConcentratedPool(s.TestAccs[0], ETH, USDC, DefaultTickSpacing, spreadFactor) // an error of 1 for each position roundingError := int64(numPositions) diff --git a/x/concentrated-liquidity/simulation/sim_msgs.go b/x/concentrated-liquidity/simulation/sim_msgs.go index d6ef5f21c8c..73e719c3e44 100644 --- a/x/concentrated-liquidity/simulation/sim_msgs.go +++ b/x/concentrated-liquidity/simulation/sim_msgs.go @@ -19,7 +19,7 @@ import ( var PoolCreationFee = sdk.NewInt64Coin("stake", 10_000_000) func RandomMsgCreateConcentratedPool(k clkeeper.Keeper, sim *osmosimtypes.SimCtx, ctx sdk.Context) (*clmodeltypes.MsgCreateConcentratedPool, error) { - poolCreator, coin0, coin1, tickSpacing, swapFee, err := RandomPreparePoolFunc(sim, ctx, k) + poolCreator, coin0, coin1, tickSpacing, spreadFactor, err := RandomPreparePoolFunc(sim, ctx, k) if err != nil { return nil, err } @@ -46,11 +46,11 @@ func RandomMsgCreateConcentratedPool(k clkeeper.Keeper, sim *osmosimtypes.SimCtx } return &clmodeltypes.MsgCreateConcentratedPool{ - Sender: poolCreator.String(), - Denom0: coin0.Denom, - Denom1: coin1.Denom, - TickSpacing: tickSpacing, - SwapFee: swapFee, + Sender: poolCreator.String(), + Denom0: coin0.Denom, + Denom1: coin1.Denom, + TickSpacing: tickSpacing, + SpreadFactor: spreadFactor, }, nil } @@ -308,7 +308,7 @@ func RandomPreparePoolFunc(sim *osmosimtypes.SimCtx, ctx sdk.Context, k clkeeper rand := sim.GetRand() authorizedTickSpacing := cltypes.AuthorizedTickSpacing - authorizedSwapFee := cltypes.AuthorizedSwapFees + authorizedSpreadFactor := cltypes.AuthorizedSpreadFactors // find an address with two or more distinct denoms in their wallet sender, senderExists := sim.RandomSimAccountWithConstraint(createPoolRestriction(k, sim, ctx)) @@ -334,9 +334,9 @@ func RandomPreparePoolFunc(sim *osmosimtypes.SimCtx, ctx sdk.Context, k clkeeper coin0 := poolCoins[0] coin1 := poolCoins[1] tickSpacing := authorizedTickSpacing[rand.Intn(len(authorizedTickSpacing))] - swapFee := authorizedSwapFee[rand.Intn(len(authorizedSwapFee))] + spreadFactor := authorizedSpreadFactor[rand.Intn(len(authorizedSpreadFactor))] - return sender.Address, coin0, coin1, tickSpacing, swapFee, nil + return sender.Address, coin0, coin1, tickSpacing, spreadFactor, nil } func RandomPrepareCreatePositionFunc(sim *osmosimtypes.SimCtx, ctx sdk.Context, clPool cltypes.ConcentratedPoolExtension, poolDenoms []string) (sdk.AccAddress, sdk.Coins, int64, int64, error) { diff --git a/x/concentrated-liquidity/swaps.go b/x/concentrated-liquidity/swaps.go index 0b1c3e663a1..bb9edea550e 100644 --- a/x/concentrated-liquidity/swaps.go +++ b/x/concentrated-liquidity/swaps.go @@ -82,7 +82,7 @@ func (k Keeper) SwapExactAmountIn( tokenIn sdk.Coin, tokenOutDenom string, tokenOutMinAmount sdk.Int, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (tokenOutAmount sdk.Int, err error) { if tokenIn.Denom == tokenOutDenom { return sdk.Int{}, types.DenomDuplicatedError{TokenInDenom: tokenIn.Denom, TokenOutDenom: tokenOutDenom} @@ -100,7 +100,7 @@ func (k Keeper) SwapExactAmountIn( // Change priceLimit based on which direction we are swapping priceLimit := swapstrategy.GetPriceLimit(zeroForOne) - tokenIn, tokenOut, _, _, _, err := k.swapOutAmtGivenIn(ctx, sender, pool, tokenIn, tokenOutDenom, swapFee, priceLimit) + tokenIn, tokenOut, _, _, _, err := k.swapOutAmtGivenIn(ctx, sender, pool, tokenIn, tokenOutDenom, spreadFactor, priceLimit) if err != nil { return sdk.Int{}, err } @@ -123,7 +123,7 @@ func (k Keeper) SwapExactAmountOut( tokenInDenom string, tokenInMaxAmount sdk.Int, tokenOut sdk.Coin, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (tokenInAmount sdk.Int, err error) { if tokenOut.Denom == tokenInDenom { return sdk.Int{}, types.DenomDuplicatedError{TokenInDenom: tokenInDenom, TokenOutDenom: tokenOut.Denom} @@ -142,7 +142,7 @@ func (k Keeper) SwapExactAmountOut( // change priceLimit based on which direction we are swapping // if zeroForOne == true, use MinSpotPrice else use MaxSpotPrice priceLimit := swapstrategy.GetPriceLimit(zeroForOne) - tokenIn, tokenOut, _, _, _, err := k.swapInAmtGivenOut(ctx, sender, pool, tokenOut, tokenInDenom, swapFee, priceLimit) + tokenIn, tokenOut, _, _, _, err := k.swapInAmtGivenOut(ctx, sender, pool, tokenOut, tokenInDenom, spreadFactor, priceLimit) if err != nil { return sdk.Int{}, err } @@ -164,10 +164,10 @@ func (k Keeper) swapOutAmtGivenIn( pool types.ConcentratedPoolExtension, tokenIn sdk.Coin, tokenOutDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, priceLimit sdk.Dec, ) (calcTokenIn, calcTokenOut sdk.Coin, currentTick int64, liquidity, sqrtPrice sdk.Dec, err error) { - tokenIn, tokenOut, newCurrentTick, newLiquidity, newSqrtPrice, totalFees, err := k.computeOutAmtGivenIn(ctx, pool.GetId(), tokenIn, tokenOutDenom, swapFee, priceLimit) + tokenIn, tokenOut, newCurrentTick, newLiquidity, newSqrtPrice, totalFees, err := k.computeOutAmtGivenIn(ctx, pool.GetId(), tokenIn, tokenOutDenom, spreadFactor, priceLimit) if err != nil { return sdk.Coin{}, sdk.Coin{}, 0, sdk.Dec{}, sdk.Dec{}, err } @@ -193,10 +193,10 @@ func (k *Keeper) swapInAmtGivenOut( pool types.ConcentratedPoolExtension, desiredTokenOut sdk.Coin, tokenInDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, priceLimit sdk.Dec, ) (calcTokenIn, calcTokenOut sdk.Coin, currentTick int64, liquidity, sqrtPrice sdk.Dec, err error) { - tokenIn, tokenOut, newCurrentTick, newLiquidity, newSqrtPrice, totalFees, err := k.computeInAmtGivenOut(ctx, desiredTokenOut, tokenInDenom, swapFee, priceLimit, pool.GetId()) + tokenIn, tokenOut, newCurrentTick, newLiquidity, newSqrtPrice, totalFees, err := k.computeInAmtGivenOut(ctx, desiredTokenOut, tokenInDenom, spreadFactor, priceLimit, pool.GetId()) if err != nil { return sdk.Coin{}, sdk.Coin{}, 0, sdk.Dec{}, sdk.Dec{}, err } @@ -220,10 +220,10 @@ func (k Keeper) CalcOutAmtGivenIn( poolI poolmanagertypes.PoolI, tokenIn sdk.Coin, tokenOutDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (tokenOut sdk.Coin, err error) { cacheCtx, _ := ctx.CacheContext() - _, tokenOut, _, _, _, _, err = k.computeOutAmtGivenIn(cacheCtx, poolI.GetId(), tokenIn, tokenOutDenom, swapFee, sdk.ZeroDec()) + _, tokenOut, _, _, _, _, err = k.computeOutAmtGivenIn(cacheCtx, poolI.GetId(), tokenIn, tokenOutDenom, spreadFactor, sdk.ZeroDec()) if err != nil { return sdk.Coin{}, err } @@ -235,10 +235,10 @@ func (k Keeper) CalcInAmtGivenOut( poolI poolmanagertypes.PoolI, tokenOut sdk.Coin, tokenInDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (tokenIn sdk.Coin, err error) { cacheCtx, _ := ctx.CacheContext() - tokenIn, _, _, _, _, _, err = k.computeInAmtGivenOut(cacheCtx, tokenOut, tokenInDenom, swapFee, sdk.ZeroDec(), poolI.GetId()) + tokenIn, _, _, _, _, _, err = k.computeInAmtGivenOut(cacheCtx, tokenOut, tokenInDenom, spreadFactor, sdk.ZeroDec(), poolI.GetId()) if err != nil { return sdk.Coin{}, err } @@ -255,7 +255,7 @@ func (k Keeper) computeOutAmtGivenIn( poolId uint64, tokenInMin sdk.Coin, tokenOutDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, priceLimit sdk.Dec, ) (tokenIn, tokenOut sdk.Coin, updatedTick int64, updatedLiquidity, updatedSqrtPrice sdk.Dec, totalFees sdk.Dec, err error) { // Get pool and asset info @@ -296,7 +296,7 @@ func (k Keeper) computeOutAmtGivenIn( } // Set the swap strategy - swapStrategy := swapstrategy.New(zeroForOne, sqrtPriceLimit, k.storeKey, swapFee, p.GetTickSpacing()) + swapStrategy := swapstrategy.New(zeroForOne, sqrtPriceLimit, k.storeKey, spreadFactor, p.GetTickSpacing()) // Get current sqrt price from pool and run sanity check that current sqrt price is // on the correct side of the price limit given swap direction. @@ -459,7 +459,7 @@ func (k Keeper) computeInAmtGivenOut( ctx sdk.Context, desiredTokenOut sdk.Coin, tokenInDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, priceLimit sdk.Dec, poolId uint64, ) (tokenIn, tokenOut sdk.Coin, updatedTick int64, updatedLiquidity, updatedSqrtPrice sdk.Dec, totalFees sdk.Dec, err error) { @@ -500,7 +500,7 @@ func (k Keeper) computeInAmtGivenOut( } // set the swap strategy - swapStrategy := swapstrategy.New(zeroForOne, sqrtPriceLimit, k.storeKey, swapFee, tickSpacing) + swapStrategy := swapstrategy.New(zeroForOne, sqrtPriceLimit, k.storeKey, spreadFactor, tickSpacing) // get current sqrt price from pool curSqrtPrice := p.GetCurrentSqrtPrice() diff --git a/x/concentrated-liquidity/swaps_test.go b/x/concentrated-liquidity/swaps_test.go index 2fbb85a8952..293e36c6ab8 100644 --- a/x/concentrated-liquidity/swaps_test.go +++ b/x/concentrated-liquidity/swaps_test.go @@ -32,7 +32,7 @@ type SwapTest struct { // Shared. priceLimit sdk.Dec - swapFee sdk.Dec + spreadFactor sdk.Dec secondPositionLowerPrice sdk.Dec secondPositionUpperPrice sdk.Dec @@ -73,7 +73,7 @@ var ( tokenIn: sdk.NewCoin("usdc", sdk.NewInt(42000000)), tokenOutDenom: "eth", priceLimit: sdk.NewDec(5004), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // params // liquidity: 1517882343.751510418088349649 // sqrtPriceNext: 70.738348247484497717 which is 5003.9139127823931095409 https://www.wolframalpha.com/input?i=70.710678118654752440+%2B+42000000+%2F+1517882343.751510418088349649 @@ -92,7 +92,7 @@ var ( tokenIn: sdk.NewCoin("eth", sdk.NewInt(13370)), tokenOutDenom: "usdc", priceLimit: sdk.NewDec(4993), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // params // liquidity: 1517882343.751510418088349649 // sqrtPriceNext: 70.6666639108571443311 which is 4993.7773882900395488 https://www.wolframalpha.com/input?i=%28%281517882343.751510418088349649%29%29+%2F+%28%28%281517882343.751510418088349649%29+%2F+%2870.710678118654752440%29%29+%2B+%2813370%29%29 @@ -115,7 +115,7 @@ var ( tokenIn: sdk.NewCoin("usdc", sdk.NewInt(42000000)), tokenOutDenom: "eth", priceLimit: sdk.NewDec(5002), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), secondPositionLowerPrice: DefaultLowerPrice, secondPositionUpperPrice: DefaultUpperPrice, // params @@ -138,7 +138,7 @@ var ( tokenIn: sdk.NewCoin("eth", sdk.NewInt(13370)), tokenOutDenom: "usdc", priceLimit: sdk.NewDec(4996), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), secondPositionLowerPrice: DefaultLowerPrice, secondPositionUpperPrice: DefaultUpperPrice, // params @@ -167,7 +167,7 @@ var ( tokenIn: sdk.NewCoin("usdc", sdk.NewInt(10000000000)), tokenOutDenom: "eth", priceLimit: sdk.NewDec(6255), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), secondPositionLowerPrice: sdk.NewDec(5500), secondPositionUpperPrice: sdk.NewDec(6250), // params @@ -206,7 +206,7 @@ var ( tokenIn: sdk.NewCoin("eth", sdk.NewInt(2000000)), tokenOutDenom: "usdc", priceLimit: sdk.NewDec(3900), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // params // liquidity (1st): 1517882343.751510418088349649 // sqrtPriceNext: 67.416615162732695594 which is 4545 @@ -241,7 +241,7 @@ var ( tokenIn: sdk.NewCoin("usdc", sdk.NewInt(10000000000)), tokenOutDenom: "eth", priceLimit: sdk.NewDec(6056), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // params // liquidity (1st): 1517882343.751510418088349649 // sqrtPriceNext: 74.161984870956629487 which is 5500 @@ -272,7 +272,7 @@ var ( tokenIn: sdk.NewCoin("usdc", sdk.NewInt(8500000000)), tokenOutDenom: "eth", priceLimit: sdk.NewDec(6056), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // params // liquidity (1st): 1517882343.751510418088349649 // sqrtPriceNext: 74.161984870956629487 which is 5500 @@ -309,7 +309,7 @@ var ( tokenIn: sdk.NewCoin("eth", sdk.NewInt(2000000)), tokenOutDenom: "usdc", priceLimit: sdk.NewDec(4128), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // params // liquidity (1st): 1517882343.751510418088349649 // sqrtPriceNext: 67.416615162732695594 which is 4545 @@ -339,7 +339,7 @@ var ( tokenIn: sdk.NewCoin("eth", sdk.NewInt(1800000)), tokenOutDenom: "usdc", priceLimit: sdk.NewDec(4128), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // params // liquidity (1st): 1517882343.751510418088349649 // sqrtPriceNext: 67.416615162732695594 which is 4545 @@ -372,7 +372,7 @@ var ( tokenIn: sdk.NewCoin("usdc", sdk.NewInt(10000000000)), tokenOutDenom: "eth", priceLimit: sdk.NewDec(6106), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // params // liquidity (1st): 1517882343.751510418088349649 // sqrtPriceNext: 74.161984870956629487 which is 5500 @@ -406,7 +406,7 @@ var ( tokenIn: sdk.NewCoin("eth", sdk.NewInt(13370)), tokenOutDenom: "usdc", priceLimit: sdk.NewDec(4994), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // params // liquidity: 1517882343.751510418088349649 // sqrtPriceNext: 70.668238976219012614 which is 4994 https://www.wolframalpha.com/input?i=70.710678118654752440+%2B+42000000+%2F+1517882343.751510418088349649 @@ -434,7 +434,7 @@ var ( tokenIn: sdk.NewCoin("usdc", sdk.NewInt(42000000)), tokenOutDenom: "eth", priceLimit: sdk.NewDec(5004), - swapFee: sdk.MustNewDecFromStr("0.01"), + spreadFactor: sdk.MustNewDecFromStr("0.01"), // params // liquidity: 1517882343.751510418088349649 // sqrtPriceNext: 70.738071546196200264 which is 5003.9139127814610432508 @@ -458,7 +458,7 @@ var ( tokenIn: sdk.NewCoin("eth", sdk.NewInt(13370)), tokenOutDenom: "usdc", priceLimit: sdk.NewDec(4990), - swapFee: sdk.MustNewDecFromStr("0.03"), + spreadFactor: sdk.MustNewDecFromStr("0.03"), secondPositionLowerPrice: DefaultLowerPrice, secondPositionUpperPrice: DefaultUpperPrice, // params @@ -486,7 +486,7 @@ var ( tokenIn: sdk.NewCoin("eth", sdk.NewInt(2000000)), tokenOutDenom: "usdc", priceLimit: sdk.NewDec(4094), - swapFee: sdk.MustNewDecFromStr("0.05"), + spreadFactor: sdk.MustNewDecFromStr("0.05"), secondPositionLowerPrice: sdk.NewDec(4000), secondPositionUpperPrice: sdk.NewDec(4545), // params @@ -510,7 +510,7 @@ var ( tokenIn: sdk.NewCoin("usdc", sdk.NewInt(10000000000)), tokenOutDenom: "eth", priceLimit: sdk.NewDec(6056), - swapFee: sdk.MustNewDecFromStr("0.1"), + spreadFactor: sdk.MustNewDecFromStr("0.1"), secondPositionLowerPrice: sdk.NewDec(5001), secondPositionUpperPrice: sdk.NewDec(6250), // expectedTokenIn: 5762545340.40832543134898983723 + 4237454659.59167456865101016277 = 10000000000.0000 = 10000.00 usdc @@ -533,7 +533,7 @@ var ( tokenIn: sdk.NewCoin("eth", sdk.NewInt(1800000)), tokenOutDenom: "usdc", priceLimit: sdk.NewDec(4128), - swapFee: sdk.MustNewDecFromStr("0.005"), + spreadFactor: sdk.MustNewDecFromStr("0.005"), secondPositionLowerPrice: sdk.NewDec(4000), secondPositionUpperPrice: sdk.NewDec(4999), expectedTokenIn: sdk.NewCoin("eth", sdk.NewInt(1800000)), @@ -555,7 +555,7 @@ var ( priceLimit: sdk.NewDec(6106), secondPositionLowerPrice: sdk.NewDec(5501), secondPositionUpperPrice: sdk.NewDec(6250), - swapFee: sdk.MustNewDecFromStr("0.03"), + spreadFactor: sdk.MustNewDecFromStr("0.03"), expectedTokenIn: sdk.NewCoin("usdc", sdk.NewInt(10000000000)), expectedTokenOut: sdk.NewCoin("eth", sdk.NewInt(1771252)), expectedFeeGrowthAccumulatorValue: sdk.MustNewDecFromStr("0.221769187794051751"), @@ -572,7 +572,7 @@ var ( tokenIn: sdk.NewCoin("eth", sdk.NewInt(13370)), tokenOutDenom: "usdc", priceLimit: sdk.NewDec(4994), - swapFee: sdk.MustNewDecFromStr("0.01"), + spreadFactor: sdk.MustNewDecFromStr("0.01"), // params // liquidity: 1517882343.751510418088349649 // sqrtPriceNext: 70.668238976219012614 which is 4994 @@ -593,14 +593,14 @@ var ( tokenIn: sdk.NewCoin("usdc", sdk.NewInt(5300000000)), tokenOutDenom: "eth", priceLimit: sdk.NewDec(6000), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectErr: true, }, "single position within one tick, trade does not complete due to lack of liquidity: eth -> usdc": { tokenIn: sdk.NewCoin("eth", sdk.NewInt(1100000)), tokenOutDenom: "usdc", priceLimit: sdk.NewDec(4000), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectErr: true, }, } @@ -615,7 +615,7 @@ var ( tokenOut: sdk.NewCoin(USDC, sdk.NewInt(42000000)), tokenInDenom: ETH, priceLimit: sdk.NewDec(4993), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // from math import * // from decimal import * // liq = Decimal("1517882343.751510418088349649") @@ -636,7 +636,7 @@ var ( tokenOut: sdk.NewCoin(ETH, sdk.NewInt(13370)), tokenInDenom: USDC, priceLimit: sdk.NewDec(5010), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // from math import * // from decimal import * // liq = Decimal("1517882343.751510418088349649") @@ -662,7 +662,7 @@ var ( tokenOut: sdk.NewCoin("usdc", sdk.NewInt(66829187)), tokenInDenom: "eth", priceLimit: sdk.NewDec(4990), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), secondPositionLowerPrice: DefaultLowerPrice, secondPositionUpperPrice: DefaultUpperPrice, // from math import * @@ -688,7 +688,7 @@ var ( tokenOut: sdk.NewCoin("eth", sdk.NewInt(8398)), tokenInDenom: "usdc", priceLimit: sdk.NewDec(5020), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), secondPositionLowerPrice: DefaultLowerPrice, secondPositionUpperPrice: DefaultUpperPrice, // from math import * @@ -719,7 +719,7 @@ var ( tokenOut: sdk.NewCoin("usdc", sdk.NewInt(9103422788)), tokenInDenom: "eth", priceLimit: sdk.NewDec(3900), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), secondPositionLowerPrice: sdk.NewDec(4000), secondPositionUpperPrice: sdk.NewDec(4545), // from math import * @@ -767,7 +767,7 @@ var ( tokenOut: sdk.NewCoin(ETH, sdk.NewInt(1820630)), tokenInDenom: USDC, priceLimit: sdk.NewDec(6106), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), secondPositionLowerPrice: sdk.NewDec(5500), // 315000 secondPositionUpperPrice: sdk.NewDec(6250), // 322500 // from math import * @@ -815,7 +815,7 @@ var ( tokenOut: sdk.NewCoin(USDC, sdk.NewInt(9321276930)), tokenInDenom: ETH, priceLimit: sdk.NewDec(4128), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), secondPositionLowerPrice: sdk.NewDec(4000), secondPositionUpperPrice: sdk.NewDec(4999), // from math import * @@ -871,7 +871,7 @@ var ( tokenOut: sdk.NewCoin(USDC, sdk.NewInt(8479320318)), tokenInDenom: ETH, priceLimit: sdk.NewDec(4128), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), secondPositionLowerPrice: sdk.NewDec(4000), secondPositionUpperPrice: sdk.NewDec(4999), // from math import * @@ -930,7 +930,7 @@ var ( tokenOut: sdk.NewCoin(ETH, sdk.NewInt(1864161)), tokenInDenom: USDC, priceLimit: sdk.NewDec(6056), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), secondPositionLowerPrice: sdk.NewDec(5001), secondPositionUpperPrice: sdk.NewDec(6250), // from math import * @@ -981,7 +981,7 @@ var ( tokenOut: sdk.NewCoin(ETH, sdk.NewInt(1609138)), tokenInDenom: USDC, priceLimit: sdk.NewDec(6056), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), secondPositionLowerPrice: sdk.NewDec(5001), secondPositionUpperPrice: sdk.NewDec(6250), // from math import * @@ -1038,7 +1038,7 @@ var ( tokenOut: sdk.NewCoin(ETH, sdk.NewInt(1820545)), tokenInDenom: USDC, priceLimit: sdk.NewDec(6106), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), secondPositionLowerPrice: sdk.NewDec(5501), // 315010 secondPositionUpperPrice: sdk.NewDec(6250), // 322500 // from math import * @@ -1082,7 +1082,7 @@ var ( tokenOut: sdk.NewCoin(ETH, sdk.NewInt(1820545)), tokenInDenom: USDC, priceLimit: sdk.NewDec(5002), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // from math import * // from decimal import * // # Range 1: From 5000 to 5002 @@ -1111,17 +1111,17 @@ var ( tokenOut: sdk.NewCoin(USDC, sdk.NewInt(42000000)), tokenInDenom: ETH, priceLimit: sdk.NewDec(4993), - swapFee: sdk.MustNewDecFromStr("0.01"), + spreadFactor: sdk.MustNewDecFromStr("0.01"), // from math import * // from decimal import * // token_out = Decimal("42000000") // liq = Decimal("1517882343.751510418088349649") // sqrt_cur = Decimal("5000").sqrt() // sqrt_next = sqrt_cur - token_out / liq - // swap_fee = Decimal("0.01") + // spread_factor = Decimal("0.01") // token_in = ceil(liq * abs(sqrt_cur - sqrt_next) / (sqrt_cur * sqrt_next)) - // fee = token_in * swap_fee / (1 - swap_fee) + // fee = token_in * spread_factor / (1 - spread_factor) // # Summary: // token_in = ceil(token_in + fee) @@ -1141,7 +1141,7 @@ var ( tokenOut: sdk.NewCoin(ETH, sdk.NewInt(8398)), tokenInDenom: USDC, priceLimit: sdk.NewDec(5020), - swapFee: sdk.MustNewDecFromStr("0.03"), + spreadFactor: sdk.MustNewDecFromStr("0.03"), secondPositionLowerPrice: DefaultLowerPrice, secondPositionUpperPrice: DefaultUpperPrice, // from math import * @@ -1150,10 +1150,10 @@ var ( // liq = Decimal("1517882343.751510418088349649") * 2 // sqrt_cur = Decimal("5000").sqrt() // sqrt_next = liq * sqrt_cur / (liq - token_out * sqrt_cur) - // swap_fee = Decimal("0.03") + // spread_factor = Decimal("0.03") // token_in = ceil(liq * abs(sqrt_cur - sqrt_next)) - // fee = token_in * swap_fee / (1 - swap_fee) + // fee = token_in * spread_factor / (1 - spread_factor) // # Summary: // token_in = ceil(token_in + fee) @@ -1176,7 +1176,7 @@ var ( tokenOut: sdk.NewCoin(ETH, sdk.NewInt(1820630)), tokenInDenom: USDC, priceLimit: sdk.NewDec(6106), - swapFee: sdk.MustNewDecFromStr("0.001"), + spreadFactor: sdk.MustNewDecFromStr("0.001"), secondPositionLowerPrice: sdk.NewDec(5500), // 315000 secondPositionUpperPrice: sdk.NewDec(6250), // 322500 // from math import * @@ -1186,11 +1186,11 @@ var ( // liq_1 = Decimal("1517882343.751510418088349649") // sqrt_cur = Decimal("5000").sqrt() // sqrt_next_1 = Decimal("5500").sqrt() - // swap_fee = Decimal("0.001") + // spread_factor = Decimal("0.001") // token_out_1 = liq_1 * (sqrt_next_1 - sqrt_cur ) / (sqrt_next_1 * sqrt_cur) // token_in_1 = ceil(liq_1 * abs(sqrt_cur - sqrt_next_1 )) - // fee_1 = token_in_1 * swap_fee / (1 - swap_fee) + // fee_1 = token_in_1 * spread_factor / (1 - spread_factor) // token_out = token_out - token_out_1 @@ -1200,7 +1200,7 @@ var ( // token_out_2 = liq_2 * (sqrt_next_2 - sqrt_next_1 ) / (sqrt_next_1 * sqrt_next_2) // token_in_2 = ceil(liq_2 * (sqrt_next_2 - sqrt_next_1 )) - // fee_2 = token_in_2 * swap_fee / (1 - swap_fee) + // fee_2 = token_in_2 * spread_factor / (1 - spread_factor) // # Summary: // token_in = ceil(token_in_1 + fee_1 + token_in_2 + fee_2) @@ -1224,7 +1224,7 @@ var ( tokenOut: sdk.NewCoin(USDC, sdk.NewInt(9321276930)), tokenInDenom: ETH, priceLimit: sdk.NewDec(4128), - swapFee: sdk.MustNewDecFromStr("0.1"), + spreadFactor: sdk.MustNewDecFromStr("0.1"), secondPositionLowerPrice: sdk.NewDec(4000), secondPositionUpperPrice: sdk.NewDec(4999), // from math import * @@ -1234,11 +1234,11 @@ var ( // liq_1 = Decimal("1517882343.751510418088349649") // sqrt_cur = Decimal("5000").sqrt() // sqrt_next_1 = Decimal("4999").sqrt() - // swap_fee = Decimal("0.1") + // spread_factor = Decimal("0.1") // token_out_1 = liq_1 * (sqrt_cur - sqrt_next_1 ) // token_in_1 = ceil(liq_1 * (sqrt_cur - sqrt_next_1 ) / (sqrt_next_1 * sqrt_cur)) - // fee_1 = token_in_1 * swap_fee / (1 - swap_fee) + // fee_1 = token_in_1 * spread_factor / (1 - spread_factor) // token_out = token_out - token_out_1 @@ -1248,7 +1248,7 @@ var ( // token_out_2 = liq_2 * (sqrt_next_1 - sqrt_next_2 ) // token_in_2 = ceil(liq_2 * (sqrt_next_1 - sqrt_next_2 ) / (sqrt_next_2 * sqrt_next_1)) - // fee_2 = token_in_2 * swap_fee / (1 - swap_fee) + // fee_2 = token_in_2 * spread_factor / (1 - spread_factor) // token_out = token_out - token_out_2 @@ -1258,7 +1258,7 @@ var ( // token_out_3 = liq_3 * (sqrt_next_2 - sqrt_next_3 ) // token_in_3 = ceil(liq_3 * (sqrt_next_2 - sqrt_next_3 ) / (sqrt_next_3 * sqrt_next_2)) - // fee_3 = token_in_3 * swap_fee / (1 - swap_fee) + // fee_3 = token_in_3 * spread_factor / (1 - spread_factor) // # Summary: // token_in = token_in_1 + token_in_2 + token_in_3 + fee_1 + fee_2 + fee_3 @@ -1284,7 +1284,7 @@ var ( tokenOut: sdk.NewCoin(ETH, sdk.NewInt(1609138)), tokenInDenom: USDC, priceLimit: sdk.NewDec(6056), - swapFee: sdk.MustNewDecFromStr("0.05"), + spreadFactor: sdk.MustNewDecFromStr("0.05"), secondPositionLowerPrice: sdk.NewDec(5001), secondPositionUpperPrice: sdk.NewDec(6250), // from math import * @@ -1294,11 +1294,11 @@ var ( // liq_1 = Decimal("1517882343.751510418088349649") // sqrt_cur = Decimal("5000").sqrt() // sqrt_next_1 = Decimal("5001").sqrt() - // swap_fee = Decimal("0.05") + // spread_factor = Decimal("0.05") // token_out_1 = liq_1 * (sqrt_next_1 - sqrt_cur ) / (sqrt_next_1 * sqrt_cur) // token_in_1 = ceil(liq_1 * (sqrt_next_1 - sqrt_cur )) - // fee_1 = token_in_1 * swap_fee / (1 - swap_fee) + // fee_1 = token_in_1 * spread_factor / (1 - spread_factor) // token_out = token_out - token_out_1 @@ -1308,7 +1308,7 @@ var ( // token_out_2 = liq_2 * (sqrt_next_2 - sqrt_next_1 ) / (sqrt_next_1 * sqrt_next_2) // token_in_2 = ceil(liq_2 * (sqrt_next_2 - sqrt_next_1 )) - // fee_2 = token_in_2 * swap_fee / (1 - swap_fee) + // fee_2 = token_in_2 * spread_factor / (1 - spread_factor) // token_out = token_out - token_out_2 @@ -1318,7 +1318,7 @@ var ( // token_out_3 = liq_3 * (sqrt_next_3 - sqrt_next_2 ) / (sqrt_next_3 * sqrt_next_2) // token_in_3 = ceil(liq_3 * (sqrt_next_3 - sqrt_next_2 )) - // fee_3 = token_in_3 * swap_fee / (1 - swap_fee) + // fee_3 = token_in_3 * spread_factor / (1 - spread_factor) // # Summary: // token_in = token_in_1 + token_in_2 +token_in_3 + fee_1 + fee_2 + fee_3 @@ -1342,7 +1342,7 @@ var ( tokenOut: sdk.NewCoin(ETH, sdk.NewInt(1820545)), tokenInDenom: USDC, priceLimit: sdk.NewDec(6106), - swapFee: sdk.MustNewDecFromStr("0.0003"), + spreadFactor: sdk.MustNewDecFromStr("0.0003"), secondPositionLowerPrice: sdk.NewDec(5501), // 315010 secondPositionUpperPrice: sdk.NewDec(6250), // 322500 // from math import * @@ -1352,11 +1352,11 @@ var ( // liq_1 = Decimal("1517882343.751510418088349649") // sqrt_cur = Decimal("5000").sqrt() // sqrt_next_1 = Decimal("5500").sqrt() - // swap_fee = Decimal("0.0003") + // spread_factor = Decimal("0.0003") // token_out_1 = liq_1 * (sqrt_next_1 - sqrt_cur ) / (sqrt_next_1 * sqrt_cur) // token_in_1 = ceil(liq_1 * (sqrt_next_1 - sqrt_cur )) - // fee_1 = token_in_1 * swap_fee / (1 - swap_fee) + // fee_1 = token_in_1 * spread_factor / (1 - spread_factor) // token_out = token_out - token_out_1 // # Range 2: from 5501 till end @@ -1365,7 +1365,7 @@ var ( // sqrt_next_2 = liq_2 * sqrt_cur_2 / (liq_2 - token_out * sqrt_cur_2) // token_out_2 = liq_2 * (sqrt_next_2 - sqrt_cur_2 ) / (sqrt_cur_2 * sqrt_next_2) // token_in_2 = ceil(liq_2 * (sqrt_next_2 - sqrt_cur_2 )) - // fee_2 = token_in_2 * swap_fee / (1 - swap_fee) + // fee_2 = token_in_2 * spread_factor / (1 - spread_factor) // # Summary: // token_in = token_in_1 + token_in_2 + fee_1 + fee_2 @@ -1389,7 +1389,7 @@ var ( tokenOut: sdk.NewCoin(ETH, sdk.NewInt(1820545)), tokenInDenom: USDC, priceLimit: sdk.NewDec(5002), - swapFee: sdk.MustNewDecFromStr("0.01"), + spreadFactor: sdk.MustNewDecFromStr("0.01"), // from math import * // from decimal import * // # Range 1: From 5000 to 5002 @@ -1397,11 +1397,11 @@ var ( // liq_1 = Decimal("1517882343.751510418088349649") // sqrt_cur = Decimal("5000").sqrt() // sqrt_next_1 = Decimal("5002").sqrt() - // swap_fee = Decimal("0.01") + // spread_factor = Decimal("0.01") // token_out_1 = liq_1 * (sqrt_next_1 - sqrt_cur ) / (sqrt_next_1 * sqrt_cur) // token_in_1 = ceil(liq_1 * (sqrt_next_1 - sqrt_cur )) - // fee_1 = token_in_1 * swap_fee / (1 - swap_fee) + // fee_1 = token_in_1 * spread_factor / (1 - spread_factor) // # Summary: // token_in = ceil(token_in_1 + fee_1) @@ -1424,14 +1424,14 @@ var ( tokenOut: sdk.NewCoin("usdc", sdk.NewInt(5300000000)), tokenInDenom: "eth", priceLimit: sdk.NewDec(6000), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectErr: true, }, "single position within one tick, trade does not complete due to lack of liquidity: eth -> usdc ": { tokenOut: sdk.NewCoin("eth", sdk.NewInt(1100000)), tokenInDenom: "usdc", priceLimit: sdk.NewDec(4000), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectErr: true, }, } @@ -1466,9 +1466,9 @@ func (s *KeeperTestSuite) TestComputeAndSwapOutAmtGivenIn() { // Create default CL pool clParams := s.App.ConcentratedLiquidityKeeper.GetParams(s.Ctx) - clParams.AuthorizedSwapFees = append(clParams.AuthorizedSwapFees, test.swapFee) + clParams.AuthorizedSpreadFactors = append(clParams.AuthorizedSpreadFactors, test.spreadFactor) s.App.ConcentratedLiquidityKeeper.SetParams(s.Ctx, clParams) - pool := s.PrepareCustomConcentratedPool(s.TestAccs[0], "eth", "usdc", DefaultTickSpacing, test.swapFee) + pool := s.PrepareCustomConcentratedPool(s.TestAccs[0], "eth", "usdc", DefaultTickSpacing, test.spreadFactor) // add default position s.SetupDefaultPosition(pool.GetId()) @@ -1497,7 +1497,7 @@ func (s *KeeperTestSuite) TestComputeAndSwapOutAmtGivenIn() { cacheCtx, pool.GetId(), test.tokenIn, test.tokenOutDenom, - test.swapFee, test.priceLimit) + test.spreadFactor, test.priceLimit) if test.expectErr { s.Require().Error(err) @@ -1510,7 +1510,7 @@ func (s *KeeperTestSuite) TestComputeAndSwapOutAmtGivenIn() { s.Require().Equal(test.expectedTokenOut.String(), tokenOut.String()) s.Require().Equal(test.expectedSqrtPrice, sqrtPrice) - expectedFees := tokenIn.Amount.ToDec().Mul(pool.GetSwapFee(s.Ctx)).TruncateInt() + expectedFees := tokenIn.Amount.ToDec().Mul(pool.GetSpreadFactor(s.Ctx)).TruncateInt() s.Require().Equal(expectedFees.String(), totalFees.TruncateInt().String()) if test.newLowerPrice.IsNil() && test.newUpperPrice.IsNil() { @@ -1551,7 +1551,7 @@ func (s *KeeperTestSuite) TestComputeAndSwapOutAmtGivenIn() { tokenIn, tokenOut, updatedTick, updatedLiquidity, sqrtPrice, err = s.App.ConcentratedLiquidityKeeper.SwapOutAmtGivenIn( s.Ctx, s.TestAccs[0], pool, test.tokenIn, test.tokenOutDenom, - test.swapFee, test.priceLimit, + test.spreadFactor, test.priceLimit, ) if test.expectErr { @@ -1684,7 +1684,7 @@ func (s *KeeperTestSuite) TestSwapOutAmtGivenIn_TickUpdates() { _, _, _, _, _, err = s.App.ConcentratedLiquidityKeeper.SwapOutAmtGivenIn( s.Ctx, s.TestAccs[0], pool, test.tokenIn, test.tokenOutDenom, - test.swapFee, test.priceLimit) + test.spreadFactor, test.priceLimit) s.Require().NoError(err) @@ -1742,9 +1742,9 @@ func (s *KeeperTestSuite) TestComputeAndSwapInAmtGivenOut() { // Create default CL pool clParams := s.App.ConcentratedLiquidityKeeper.GetParams(s.Ctx) - clParams.AuthorizedSwapFees = append(clParams.AuthorizedSwapFees, test.swapFee) + clParams.AuthorizedSpreadFactors = append(clParams.AuthorizedSpreadFactors, test.spreadFactor) s.App.ConcentratedLiquidityKeeper.SetParams(s.Ctx, clParams) - pool := s.PrepareCustomConcentratedPool(s.TestAccs[0], "eth", "usdc", DefaultTickSpacing, test.swapFee) + pool := s.PrepareCustomConcentratedPool(s.TestAccs[0], "eth", "usdc", DefaultTickSpacing, test.spreadFactor) // add default position s.SetupDefaultPosition(pool.GetId()) @@ -1768,7 +1768,7 @@ func (s *KeeperTestSuite) TestComputeAndSwapInAmtGivenOut() { tokenIn, tokenOut, updatedTick, updatedLiquidity, sqrtPrice, totalFees, err := s.App.ConcentratedLiquidityKeeper.ComputeInAmtGivenOut( cacheCtx, test.tokenOut, test.tokenInDenom, - test.swapFee, test.priceLimit, pool.GetId()) + test.spreadFactor, test.priceLimit, pool.GetId()) if test.expectErr { s.Require().Error(err) } else { @@ -1780,7 +1780,7 @@ func (s *KeeperTestSuite) TestComputeAndSwapInAmtGivenOut() { s.Require().Equal(test.expectedTokenIn.String(), tokenIn.String()) s.Require().Equal(test.expectedTick, updatedTick) - expectedFees := tokenIn.Amount.ToDec().Mul(pool.GetSwapFee(s.Ctx)).TruncateInt() + expectedFees := tokenIn.Amount.ToDec().Mul(pool.GetSpreadFactor(s.Ctx)).TruncateInt() s.Require().Equal(expectedFees.String(), totalFees.TruncateInt().String()) if test.newLowerPrice.IsNil() && test.newUpperPrice.IsNil() { @@ -1821,7 +1821,7 @@ func (s *KeeperTestSuite) TestComputeAndSwapInAmtGivenOut() { tokenIn, tokenOut, updatedTick, updatedLiquidity, sqrtPrice, err = s.App.ConcentratedLiquidityKeeper.SwapInAmtGivenOut( s.Ctx, s.TestAccs[0], pool, test.tokenOut, test.tokenInDenom, - test.swapFee, test.priceLimit) + test.spreadFactor, test.priceLimit) if test.expectErr { s.Require().Error(err) } else { @@ -1870,7 +1870,7 @@ func (s *KeeperTestSuite) TestComputeAndSwapInAmtGivenOut() { feeAccValue := feeAcc.GetValue() actualValue := feeAccValue.AmountOf(test.tokenInDenom) - if test.swapFee.IsZero() { + if test.spreadFactor.IsZero() { s.Require().Equal(sdk.ZeroDec(), actualValue) return } @@ -1936,7 +1936,7 @@ func (s *KeeperTestSuite) TestSwapInAmtGivenOut_TickUpdates() { _, _, _, _, _, err = s.App.ConcentratedLiquidityKeeper.SwapInAmtGivenOut( s.Ctx, s.TestAccs[0], pool, test.tokenOut, test.tokenInDenom, - test.swapFee, test.priceLimit) + test.spreadFactor, test.priceLimit) s.Require().NoError(err) // check lower tick and upper tick fee growth @@ -2108,7 +2108,7 @@ func (s *KeeperTestSuite) TestSwapExactAmountIn() { prevGasConsumed := s.Ctx.GasMeter().GasConsumed() // Execute the swap directed in the test case - tokenOutAmount, err := s.App.ConcentratedLiquidityKeeper.SwapExactAmountIn(s.Ctx, s.TestAccs[0], pool.(poolmanagertypes.PoolI), test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount, DefaultZeroSwapFee) + tokenOutAmount, err := s.App.ConcentratedLiquidityKeeper.SwapExactAmountIn(s.Ctx, s.TestAccs[0], pool.(poolmanagertypes.PoolI), test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount, DefaultZeroSpreadFactor) if test.expectedErr != nil { s.Require().Error(err) s.Require().ErrorAs(err, test.expectedErr) @@ -2284,7 +2284,7 @@ func (s *KeeperTestSuite) TestSwapExactAmountOut() { prevGasConsumed := s.Ctx.GasMeter().GasConsumed() // Execute the swap directed in the test case - tokenIn, err := s.App.ConcentratedLiquidityKeeper.SwapExactAmountOut(s.Ctx, s.TestAccs[0], pool.(poolmanagertypes.PoolI), test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut, DefaultZeroSwapFee) + tokenIn, err := s.App.ConcentratedLiquidityKeeper.SwapExactAmountOut(s.Ctx, s.TestAccs[0], pool.(poolmanagertypes.PoolI), test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut, DefaultZeroSpreadFactor) if test.expectedErr != nil { s.Require().Error(err) @@ -2370,7 +2370,7 @@ func (s *KeeperTestSuite) TestComputeOutAmtGivenIn() { s.Ctx, pool.GetId(), test.tokenIn, test.tokenOutDenom, - test.swapFee, test.priceLimit) + test.spreadFactor, test.priceLimit) // check that the pool has not been modified after performing calc poolAfterCalc, err := s.App.ConcentratedLiquidityKeeper.GetPoolById(s.Ctx, pool.GetId()) @@ -2438,7 +2438,7 @@ func (s *KeeperTestSuite) TestCalcOutAmtGivenIn_NonMutative() { s.Ctx, poolBeforeCalc, test.tokenIn, test.tokenOutDenom, - test.swapFee) + test.spreadFactor) s.Require().NoError(err) // check that the pool has not been modified after performing calc @@ -2506,7 +2506,7 @@ func (s *KeeperTestSuite) TestCalcInAmtGivenOut_NonMutative() { s.Ctx, poolBeforeCalc, test.tokenIn, test.tokenOutDenom, - test.swapFee) + test.spreadFactor) s.Require().NoError(err) // check that the pool has not been modified after performing calc @@ -2573,7 +2573,7 @@ func (s *KeeperTestSuite) TestComputeInAmtGivenOut() { _, _, _, _, _, _, err = s.App.ConcentratedLiquidityKeeper.ComputeInAmtGivenOut( s.Ctx, test.tokenOut, test.tokenInDenom, - test.swapFee, test.priceLimit, pool.GetId()) + test.spreadFactor, test.priceLimit, pool.GetId()) s.Require().NoError(err) // check that the pool has not been modified after performing calc @@ -2637,13 +2637,13 @@ func (s *KeeperTestSuite) TestInverseRelationshipSwapOutAmtGivenIn() { firstTokenIn, firstTokenOut, _, _, _, err := s.App.ConcentratedLiquidityKeeper.SwapOutAmtGivenIn( s.Ctx, s.TestAccs[0], pool, test.tokenIn, test.tokenOutDenom, - DefaultZeroSwapFee, test.priceLimit) + DefaultZeroSpreadFactor, test.priceLimit) s.Require().NoError(err) secondTokenIn, secondTokenOut, _, _, _, err := s.App.ConcentratedLiquidityKeeper.SwapOutAmtGivenIn( s.Ctx, s.TestAccs[0], pool, firstTokenOut, firstTokenIn.Denom, - DefaultZeroSwapFee, sdk.ZeroDec(), + DefaultZeroSpreadFactor, sdk.ZeroDec(), ) s.Require().NoError(err) @@ -2735,13 +2735,13 @@ func (s *KeeperTestSuite) TestInverseRelationshipSwapInAmtGivenOut() { firstTokenIn, firstTokenOut, _, _, _, err := s.App.ConcentratedLiquidityKeeper.SwapInAmtGivenOut( s.Ctx, s.TestAccs[0], pool, test.tokenOut, test.tokenInDenom, - DefaultZeroSwapFee, test.priceLimit) + DefaultZeroSpreadFactor, test.priceLimit) s.Require().NoError(err) secondTokenIn, secondTokenOut, _, _, _, err := s.App.ConcentratedLiquidityKeeper.SwapInAmtGivenOut( s.Ctx, s.TestAccs[0], pool, firstTokenIn, firstTokenOut.Denom, - DefaultZeroSwapFee, sdk.ZeroDec(), + DefaultZeroSpreadFactor, sdk.ZeroDec(), ) s.Require().NoError(err) @@ -2763,7 +2763,7 @@ func (s *KeeperTestSuite) TestUpdatePoolForSwap() { poolInitialBalance sdk.Coins tokenIn sdk.Coin tokenOut sdk.Coin - swapFee sdk.Dec + spreadFactor sdk.Dec newCurrentTick int64 newLiquidity sdk.Dec newSqrtPrice sdk.Dec @@ -2774,7 +2774,7 @@ func (s *KeeperTestSuite) TestUpdatePoolForSwap() { poolInitialBalance: defaultInitialBalance, tokenIn: oneHundredETH, tokenOut: oneHundredUSDC, - swapFee: sdk.MustNewDecFromStr("0.003"), // 0.3% + spreadFactor: sdk.MustNewDecFromStr("0.003"), // 0.3% newCurrentTick: 2, newLiquidity: sdk.NewDec(2), newSqrtPrice: sdk.NewDec(2), @@ -2784,7 +2784,7 @@ func (s *KeeperTestSuite) TestUpdatePoolForSwap() { poolInitialBalance: defaultInitialBalance, tokenIn: oneHundredETH.Add(oneHundredETH), tokenOut: oneHundredUSDC, - swapFee: sdk.MustNewDecFromStr("0.002"), // 0.2% + spreadFactor: sdk.MustNewDecFromStr("0.002"), // 0.2% newCurrentTick: 8, newLiquidity: sdk.NewDec(37), newSqrtPrice: sdk.NewDec(91), @@ -2794,7 +2794,7 @@ func (s *KeeperTestSuite) TestUpdatePoolForSwap() { poolInitialBalance: defaultInitialBalance, tokenIn: oneHundredETH.Add(oneHundredETH), tokenOut: oneHundredUSDC, - swapFee: sdk.MustNewDecFromStr("0.003"), + spreadFactor: sdk.MustNewDecFromStr("0.003"), newCurrentTick: 2, newLiquidity: sdk.NewDec(2), newSqrtPrice: sdk.NewDec(2), @@ -2805,7 +2805,7 @@ func (s *KeeperTestSuite) TestUpdatePoolForSwap() { poolInitialBalance: defaultInitialBalance, tokenIn: oneHundredETH, tokenOut: oneHundredUSDC.Add(oneHundredUSDC), - swapFee: sdk.MustNewDecFromStr("0.003"), + spreadFactor: sdk.MustNewDecFromStr("0.003"), newCurrentTick: 2, newLiquidity: sdk.NewDec(2), newSqrtPrice: sdk.NewDec(2), @@ -2821,9 +2821,9 @@ func (s *KeeperTestSuite) TestUpdatePoolForSwap() { // Create pool with initial balance clParams := s.App.ConcentratedLiquidityKeeper.GetParams(s.Ctx) - clParams.AuthorizedSwapFees = append(clParams.AuthorizedSwapFees, tc.swapFee) + clParams.AuthorizedSpreadFactors = append(clParams.AuthorizedSpreadFactors, tc.spreadFactor) s.App.ConcentratedLiquidityKeeper.SetParams(s.Ctx, clParams) - pool := s.PrepareCustomConcentratedPool(s.TestAccs[0], "eth", "usdc", DefaultTickSpacing, tc.swapFee) + pool := s.PrepareCustomConcentratedPool(s.TestAccs[0], "eth", "usdc", DefaultTickSpacing, tc.spreadFactor) s.FundAcc(pool.GetAddress(), tc.poolInitialBalance) // Create account with empty balance and fund with initial balance @@ -2841,7 +2841,7 @@ func (s *KeeperTestSuite) TestUpdatePoolForSwap() { // Set mock listener to make sure that is is called when desired. s.setListenerMockOnConcentratedLiquidityKeeper() - expectedFees := tc.tokenIn.Amount.ToDec().Mul(pool.GetSwapFee(s.Ctx)).Ceil() + expectedFees := tc.tokenIn.Amount.ToDec().Mul(pool.GetSpreadFactor(s.Ctx)).Ceil() expectedFeesCoins := sdk.NewCoins(sdk.NewCoin(tc.tokenIn.Denom, expectedFees.TruncateInt())) err = concentratedLiquidityKeeper.UpdatePoolForSwap(s.Ctx, pool, sender, tc.tokenIn, tc.tokenOut, tc.newCurrentTick, tc.newLiquidity, tc.newSqrtPrice, expectedFees) @@ -3029,8 +3029,8 @@ func (s *KeeperTestSuite) TestFunctionalSwaps() { // liq = Decimal("4836489743.729150266025048947") // sqrt_cur = Decimal("5000").sqrt() // token_in = Decimal("5000000000") - // swap_fee = Decimal("0.003") - // token_in_after_fee = token_in * (Decimal("1") - swap_fee) + // spread_factor = Decimal("0.003") + // token_in_after_fee = token_in * (Decimal("1") - spread_factor) // sqrt_next = sqrt_cur + token_in_after_fee / liq // token_out = liq * (sqrt_next - sqrt_cur) / (sqrt_cur * sqrt_next) @@ -3075,8 +3075,8 @@ func (s *KeeperTestSuite) TestFunctionalSwaps() { // from decimal import * // # Range 1: From 5146 to 4999 // token_in = Decimal("1000000") - // swap_fee = Decimal("0.003") - // token_in_after_fee = token_in - (token_in * swap_fee) + // spread_factor = Decimal("0.003") + // token_in_after_fee = token_in - (token_in * spread_factor) // liq_1 = Decimal("4553647031.254531254265048947") // sqrt_cur = Decimal("71.741384325871133645") // sqrt_next_1 = Decimal("4999").sqrt() @@ -3134,8 +3134,8 @@ func (s *KeeperTestSuite) TestFunctionalSwaps() { // from decimal import * // # Range 1: From 4990.16... to 4999 // token_in = Decimal("5000000000") - // swap_fee = Decimal("0.003") - // token_in_after_fee = token_in - (token_in * swap_fee) + // spread_factor = Decimal("0.003") + // token_in_after_fee = token_in - (token_in * spread_factor) // liq_1 = Decimal("670416215.718827443660400593") // sqrt_cur = Decimal("70.641127368418251403") // sqrt_next_1 = Decimal("4999").sqrt() @@ -3195,8 +3195,8 @@ func (s *KeeperTestSuite) TestFunctionalSwaps() { // liq = Decimal("670416215.718827443660400593") // sqrt_cur = Decimal("4999").sqrt() // token_in = Decimal("1000000") - // swap_fee = Decimal("0.003") - // token_in_after_fee = token_in * (Decimal("1") - swap_fee) + // spread_factor = Decimal("0.003") + // token_in_after_fee = token_in * (Decimal("1") - spread_factor) // sqrt_next = liq / ((liq / sqrt_cur) + token_in_after_fee) // token_out = liq * (sqrt_cur - sqrt_next) diff --git a/x/concentrated-liquidity/swapstrategy/export_test.go b/x/concentrated-liquidity/swapstrategy/export_test.go index 7290ea76e67..ef3ff64f6eb 100644 --- a/x/concentrated-liquidity/swapstrategy/export_test.go +++ b/x/concentrated-liquidity/swapstrategy/export_test.go @@ -2,10 +2,10 @@ package swapstrategy import sdk "github.com/cosmos/cosmos-sdk/types" -func ComputeFeeChargePerSwapStepOutGivenIn(hasReachedTarget bool, amountIn, amountSpecifiedRemaining, swapFee sdk.Dec) sdk.Dec { - return computeFeeChargePerSwapStepOutGivenIn(hasReachedTarget, amountIn, amountSpecifiedRemaining, swapFee) +func ComputeFeeChargePerSwapStepOutGivenIn(hasReachedTarget bool, amountIn, amountSpecifiedRemaining, spreadFactor sdk.Dec) sdk.Dec { + return computeFeeChargePerSwapStepOutGivenIn(hasReachedTarget, amountIn, amountSpecifiedRemaining, spreadFactor) } -func ComputeFeeChargeFromAmountIn(amountIn, swapFee sdk.Dec) sdk.Dec { - return computeFeeChargeFromAmountIn(amountIn, swapFee) +func ComputeFeeChargeFromAmountIn(amountIn, spreadFactor sdk.Dec) sdk.Dec { + return computeFeeChargeFromAmountIn(amountIn, spreadFactor) } diff --git a/x/concentrated-liquidity/swapstrategy/fees.go b/x/concentrated-liquidity/swapstrategy/fees.go index 188a4d16b78..86b902e1dd9 100644 --- a/x/concentrated-liquidity/swapstrategy/fees.go +++ b/x/concentrated-liquidity/swapstrategy/fees.go @@ -18,19 +18,19 @@ import ( // // - amountSpecifiedRemaining is the total remaining amount of token in that needs to be consumed to complete the swap. -// - swapFee the swap fee to be charged. +// - spreadFactor the spread factor to be charged. // -// If swap fee is negative, it panics. -// If swap fee is 0, returns 0. Otherwise, computes and returns the fee charge per step. -func computeFeeChargePerSwapStepOutGivenIn(hasReachedTarget bool, amountIn, amountSpecifiedRemaining, swapFee sdk.Dec) sdk.Dec { +// If spread factor is negative, it panics. +// If spread factor is 0, returns 0. Otherwise, computes and returns the fee charge per step. +func computeFeeChargePerSwapStepOutGivenIn(hasReachedTarget bool, amountIn, amountSpecifiedRemaining, spreadFactor sdk.Dec) sdk.Dec { feeChargeTotal := sdk.ZeroDec() - if swapFee.IsNegative() { + if spreadFactor.IsNegative() { // This should never happen but is added as a defense-in-depth measure. - panic(fmt.Errorf("swap fee must be non-negative, was (%s)", swapFee)) + panic(fmt.Errorf("spread factor must be non-negative, was (%s)", spreadFactor)) } - if swapFee.IsZero() { + if spreadFactor.IsZero() { return feeChargeTotal } @@ -40,7 +40,7 @@ func computeFeeChargePerSwapStepOutGivenIn(hasReachedTarget bool, amountIn, amou // 2) or sqrtPriceLimit is reached // In both cases, we charge the fee on the amount in actually consumed before // hitting the target. - feeChargeTotal = computeFeeChargeFromAmountIn(amountIn, swapFee) + feeChargeTotal = computeFeeChargeFromAmountIn(amountIn, spreadFactor) } else { // Otherwise, the current tick had enough liquidity to fulfill the swap // and we ran out of amount remaining before reaching either the next tick or the limit. @@ -57,10 +57,10 @@ func computeFeeChargePerSwapStepOutGivenIn(hasReachedTarget bool, amountIn, amou return feeChargeTotal } -// computeFeeChargeFromAmountIn returns the fee charge given the amount in and swap fee. -// Computes amountIn * swapFee / (1 - swapFee) where math operations round up +// computeFeeChargeFromAmountIn returns the fee charge given the amount in and spread factor. +// Computes amountIn * spreadFactor / (1 - spreadFactor) where math operations round up // at precision end. This is necessary to ensure that the fee charge is always // rounded in favor of the pool. -func computeFeeChargeFromAmountIn(amountIn sdk.Dec, swapFee sdk.Dec) sdk.Dec { - return amountIn.MulRoundUp(swapFee).QuoRoundupMut(sdk.OneDec().SubMut(swapFee)) +func computeFeeChargeFromAmountIn(amountIn sdk.Dec, spreadFactor sdk.Dec) sdk.Dec { + return amountIn.MulRoundUp(spreadFactor).QuoRoundupMut(sdk.OneDec().SubMut(spreadFactor)) } diff --git a/x/concentrated-liquidity/swapstrategy/fees_test.go b/x/concentrated-liquidity/swapstrategy/fees_test.go index b6e476b953f..b563ff3bf72 100644 --- a/x/concentrated-liquidity/swapstrategy/fees_test.go +++ b/x/concentrated-liquidity/swapstrategy/fees_test.go @@ -15,7 +15,7 @@ func (suite *StrategyTestSuite) TestComputeFeeChargePerSwapStepOutGivenIn() { hasReachedTarget bool amountIn sdk.Dec amountSpecifiedRemaining sdk.Dec - swapFee sdk.Dec + spreadFactor sdk.Dec expectedFeeCharge sdk.Dec expectPanic bool @@ -24,32 +24,32 @@ func (suite *StrategyTestSuite) TestComputeFeeChargePerSwapStepOutGivenIn() { hasReachedTarget: true, amountIn: sdk.NewDec(100), amountSpecifiedRemaining: five, - swapFee: onePercentFee, + spreadFactor: onePercentFee, - // amount in * swap fee / (1 - swap fee) + // amount in * spread factor / (1 - spread factor) expectedFeeCharge: swapstrategy.ComputeFeeChargeFromAmountIn(sdk.NewDec(100), onePercentFee), }, "did not reach target -> charge fee on the difference between amount remaining and amount in": { hasReachedTarget: false, amountIn: five, amountSpecifiedRemaining: sdk.NewDec(100), - swapFee: onePercentFee, + spreadFactor: onePercentFee, expectedFeeCharge: sdk.MustNewDecFromStr("95"), }, - "zero swap fee": { + "zero spread factor": { hasReachedTarget: true, amountIn: five, amountSpecifiedRemaining: sdk.NewDec(100), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectedFeeCharge: sdk.ZeroDec(), }, - "negative swap fee - panic": { + "negative spread factor - panic": { hasReachedTarget: false, amountIn: sdk.NewDec(100), amountSpecifiedRemaining: five, - swapFee: sdk.OneDec().Neg(), + spreadFactor: sdk.OneDec().Neg(), expectPanic: true, }, @@ -57,7 +57,7 @@ func (suite *StrategyTestSuite) TestComputeFeeChargePerSwapStepOutGivenIn() { hasReachedTarget: false, amountIn: sdk.NewDec(102), amountSpecifiedRemaining: sdk.NewDec(101), - swapFee: onePercentFee, + spreadFactor: onePercentFee, // 101 - 102 = -1 -> panic expectPanic: true, @@ -70,7 +70,7 @@ func (suite *StrategyTestSuite) TestComputeFeeChargePerSwapStepOutGivenIn() { suite.SetupTest() osmoassert.ConditionalPanic(suite.T(), tc.expectPanic, func() { - actualFeeCharge := swapstrategy.ComputeFeeChargePerSwapStepOutGivenIn(tc.hasReachedTarget, tc.amountIn, tc.amountSpecifiedRemaining, tc.swapFee) + actualFeeCharge := swapstrategy.ComputeFeeChargePerSwapStepOutGivenIn(tc.hasReachedTarget, tc.amountIn, tc.amountSpecifiedRemaining, tc.spreadFactor) suite.Require().Equal(tc.expectedFeeCharge, actualFeeCharge) }) diff --git a/x/concentrated-liquidity/swapstrategy/one_for_zero.go b/x/concentrated-liquidity/swapstrategy/one_for_zero.go index 411f6ba428f..2f9c9cb6b59 100644 --- a/x/concentrated-liquidity/swapstrategy/one_for_zero.go +++ b/x/concentrated-liquidity/swapstrategy/one_for_zero.go @@ -20,7 +20,7 @@ import ( type oneForZeroStrategy struct { sqrtPriceLimit sdk.Dec storeKey sdk.StoreKey - swapFee sdk.Dec + spreadFactor sdk.Dec tickSpacing uint64 } @@ -60,7 +60,7 @@ func (s oneForZeroStrategy) ComputeSwapStepOutGivenIn(sqrtPriceCurrent, sqrtPric amountOneIn := math.CalcAmount1Delta(liquidity, sqrtPriceTarget, sqrtPriceCurrent, true) // N.B.: if this is false, causes infinite loop // Calculate sqrtPriceNext on the amount of token remaining after fee. - amountOneInRemainingLessFee := amountOneInRemaining.Mul(sdk.OneDec().Sub(s.swapFee)) + amountOneInRemainingLessFee := amountOneInRemaining.Mul(sdk.OneDec().Sub(s.spreadFactor)) var sqrtPriceNext sdk.Dec // If have more of the amount remaining after fee than estimated until target, @@ -86,7 +86,7 @@ func (s oneForZeroStrategy) ComputeSwapStepOutGivenIn(sqrtPriceCurrent, sqrtPric // Handle fees. // Note that fee is always charged on the amount in. - feeChargeTotal := computeFeeChargePerSwapStepOutGivenIn(hasReachedTarget, amountOneIn, amountOneInRemaining, s.swapFee) + feeChargeTotal := computeFeeChargePerSwapStepOutGivenIn(hasReachedTarget, amountOneIn, amountOneInRemaining, s.spreadFactor) return sqrtPriceNext, amountOneIn, amountZeroOut, feeChargeTotal } @@ -143,7 +143,7 @@ func (s oneForZeroStrategy) ComputeSwapStepInGivenOut(sqrtPriceCurrent, sqrtPric // Handle fees. // Note that fee is always charged on the amount in. - feeChargeTotal := computeFeeChargeFromAmountIn(amountOneIn, s.swapFee) + feeChargeTotal := computeFeeChargeFromAmountIn(amountOneIn, s.spreadFactor) return sqrtPriceNext, amountZeroOut, amountOneIn, feeChargeTotal } diff --git a/x/concentrated-liquidity/swapstrategy/one_for_zero_test.go b/x/concentrated-liquidity/swapstrategy/one_for_zero_test.go index 48c7cd3bf2d..9c0585bdd35 100644 --- a/x/concentrated-liquidity/swapstrategy/one_for_zero_test.go +++ b/x/concentrated-liquidity/swapstrategy/one_for_zero_test.go @@ -67,7 +67,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepOutGivenIn_OneForZero() { sqrtPriceTarget sdk.Dec liquidity sdk.Dec amountOneInRemaining sdk.Dec - swapFee sdk.Dec + spreadFactor sdk.Dec expectedSqrtPriceNext sdk.Dec expectedAmountInConsumed sdk.Dec @@ -82,7 +82,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepOutGivenIn_OneForZero() { liquidity: defaultLiquidity, // Add 100. amountOneInRemaining: defaultAmountOne.Add(sdk.NewDec(100)), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectedSqrtPriceNext: sqrtPriceNext, // Reached target, so 100 is not consumed. @@ -96,7 +96,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepOutGivenIn_OneForZero() { sqrtPriceTarget: sqrtPriceNext, liquidity: defaultLiquidity, amountOneInRemaining: defaultAmountOne.Sub(sdk.NewDec(100)), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // sqrt_price_current + token_in / liquidity expectedSqrtPriceNext: sqrtPriceTargetNotReached, @@ -110,7 +110,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepOutGivenIn_OneForZero() { sqrtPriceTarget: sqrtPriceNext, liquidity: defaultLiquidity, amountOneInRemaining: defaultAmountOne.Add(sdk.NewDec(100)).Quo(sdk.OneDec().Sub(defaultFee)), - swapFee: defaultFee, + spreadFactor: defaultFee, expectedSqrtPriceNext: sqrtPriceNext, expectedAmountInConsumed: defaultAmountOne.Ceil(), @@ -123,7 +123,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepOutGivenIn_OneForZero() { sqrtPriceTarget: sqrtPriceNext, liquidity: defaultLiquidity, amountOneInRemaining: defaultAmountOne.Sub(sdk.NewDec(100)).Quo(sdk.OneDec().Sub(defaultFee)), - swapFee: defaultFee, + spreadFactor: defaultFee, expectedSqrtPriceNext: sqrtPriceTargetNotReached, expectedAmountInConsumed: defaultAmountOne.Sub(sdk.NewDec(100)).Ceil(), @@ -139,7 +139,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepOutGivenIn_OneForZero() { // this value is exactly enough to reach the target amountOneInRemaining: sdk.NewDec(1336900668450), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectedSqrtPriceNext: sqrt(100_000_100), @@ -154,7 +154,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepOutGivenIn_OneForZero() { tc := tc suite.Run(name, func() { suite.SetupTest() - strategy := swapstrategy.New(false, types.MaxSqrtPrice, suite.App.GetKey(types.ModuleName), tc.swapFee, defaultTickSpacing) + strategy := swapstrategy.New(false, types.MaxSqrtPrice, suite.App.GetKey(types.ModuleName), tc.spreadFactor, defaultTickSpacing) sqrtPriceNext, amountInConsumed, amountZeroOut, feeChargeTotal := strategy.ComputeSwapStepOutGivenIn(tc.sqrtPriceCurrent, tc.sqrtPriceTarget, tc.liquidity, tc.amountOneInRemaining) @@ -188,7 +188,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepInGivenOut_OneForZero() { sqrtPriceTarget sdk.Dec liquidity sdk.Dec amountZeroOutRemaining sdk.Dec - swapFee sdk.Dec + spreadFactor sdk.Dec expectedSqrtPriceNext sdk.Dec expectedAmountZeroOutConsumed sdk.Dec @@ -203,7 +203,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepInGivenOut_OneForZero() { liquidity: defaultLiquidity, // Add 100. amountZeroOutRemaining: defaultAmountZero.Add(sdk.NewDec(100)), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectedSqrtPriceNext: sqrtPriceNext, // Reached target, so 100 is not consumed. @@ -217,7 +217,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepInGivenOut_OneForZero() { sqrtPriceTarget: sqrtPriceNext, liquidity: defaultLiquidity, amountZeroOutRemaining: defaultAmountZero.Sub(sdk.NewDec(1000)), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectedSqrtPriceNext: sqrtPriceTargetNotReached, @@ -232,7 +232,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepInGivenOut_OneForZero() { sqrtPriceTarget: sqrtPriceNext, liquidity: defaultLiquidity, amountZeroOutRemaining: defaultAmountZero.Quo(sdk.OneDec().Sub(defaultFee)), - swapFee: defaultFee, + spreadFactor: defaultFee, expectedSqrtPriceNext: sqrtPriceNext, expectedAmountZeroOutConsumed: defaultAmountZero.Sub(sdk.SmallestDec()), // subtracting smallest dec to account for truncations in favor of the pool. @@ -244,7 +244,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepInGivenOut_OneForZero() { sqrtPriceTarget: sqrtPriceNext, liquidity: defaultLiquidity, amountZeroOutRemaining: defaultAmountZero.Sub(sdk.NewDec(1000)), - swapFee: defaultFee, + spreadFactor: defaultFee, expectedSqrtPriceNext: sqrtPriceTargetNotReached, // subtracting 3 * smallest dec to account for truncations in favor of the pool. @@ -258,7 +258,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepInGivenOut_OneForZero() { tc := tc suite.Run(name, func() { suite.SetupTest() - strategy := swapstrategy.New(false, types.MaxSqrtPrice, suite.App.GetKey(types.ModuleName), tc.swapFee, defaultTickSpacing) + strategy := swapstrategy.New(false, types.MaxSqrtPrice, suite.App.GetKey(types.ModuleName), tc.spreadFactor, defaultTickSpacing) sqrtPriceNext, amountZeroOutConsumed, amountOneIn, feeChargeTotal := strategy.ComputeSwapStepInGivenOut(tc.sqrtPriceCurrent, tc.sqrtPriceTarget, tc.liquidity, tc.amountZeroOutRemaining) diff --git a/x/concentrated-liquidity/swapstrategy/swap_strategy.go b/x/concentrated-liquidity/swapstrategy/swap_strategy.go index 41ad1d94d58..9f3f93dd974 100644 --- a/x/concentrated-liquidity/swapstrategy/swap_strategy.go +++ b/x/concentrated-liquidity/swapstrategy/swap_strategy.go @@ -82,11 +82,11 @@ type swapStrategy interface { // New returns a swap strategy based on the provided zeroForOne parameter // with sqrtPriceLimit for the maximum square root price until which to perform // the swap and the stor key of the module that stores swap data. -func New(zeroForOne bool, sqrtPriceLimit sdk.Dec, storeKey sdk.StoreKey, swapFee sdk.Dec, tickSpacing uint64) swapStrategy { +func New(zeroForOne bool, sqrtPriceLimit sdk.Dec, storeKey sdk.StoreKey, spreadFactor sdk.Dec, tickSpacing uint64) swapStrategy { if zeroForOne { - return &zeroForOneStrategy{sqrtPriceLimit: sqrtPriceLimit, storeKey: storeKey, swapFee: swapFee, tickSpacing: tickSpacing} + return &zeroForOneStrategy{sqrtPriceLimit: sqrtPriceLimit, storeKey: storeKey, spreadFactor: spreadFactor, tickSpacing: tickSpacing} } - return &oneForZeroStrategy{sqrtPriceLimit: sqrtPriceLimit, storeKey: storeKey, swapFee: swapFee, tickSpacing: tickSpacing} + return &oneForZeroStrategy{sqrtPriceLimit: sqrtPriceLimit, storeKey: storeKey, spreadFactor: spreadFactor, tickSpacing: tickSpacing} } // GetPriceLimit returns the price limit based on which token is being swapped in. diff --git a/x/concentrated-liquidity/swapstrategy/swap_strategy_test.go b/x/concentrated-liquidity/swapstrategy/swap_strategy_test.go index a9732d493ef..bf809c8c871 100644 --- a/x/concentrated-liquidity/swapstrategy/swap_strategy_test.go +++ b/x/concentrated-liquidity/swapstrategy/swap_strategy_test.go @@ -164,7 +164,7 @@ func (suite *StrategyTestSuite) TestComputeSwapState_Inverse() { amountIn sdk.Dec amountOut sdk.Dec zeroForOne bool - swapFee sdk.Dec + spreadFactor sdk.Dec expectedSqrtPriceNextOutGivenIn sdk.Dec expectedSqrtPriceNextInGivenOut sdk.Dec @@ -178,7 +178,7 @@ func (suite *StrategyTestSuite) TestComputeSwapState_Inverse() { amountIn: sdk.NewDec(42000000), amountOut: sdk.NewDec(8398), zeroForOne: false, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // from token_in: sqrt_next = sqrt_cur + token_in / liq2 = 70.72451318306962507883763621 expectedSqrtPriceNextOutGivenIn: sdk.MustNewDecFromStr("70.724513183069625078"), // approx 5001.96 @@ -195,7 +195,7 @@ func (suite *StrategyTestSuite) TestComputeSwapState_Inverse() { amountIn: sdk.NewDec(13370), amountOut: sdk.NewDec(66829187), zeroForOne: true, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // from amount in: sqrt_next = liq2 * sqrt_cur / (liq2 + token_in * sqrt_cur) quo round up = 70.68866416340883631930670240 expectedSqrtPriceNextOutGivenIn: sdk.MustNewDecFromStr("70.688664163408836320"), // approx 4996.89 @@ -212,7 +212,7 @@ func (suite *StrategyTestSuite) TestComputeSwapState_Inverse() { liquidity: sdk.MustNewDecFromStr("3035764687.503020836176699298"), amountIn: sdk.NewDec(42000000), amountOut: sdk.NewDec(8398), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), zeroForOne: false, // from token_in: sqrt_next = sqrt_cur + token_in / liq2 = 70.72451318306962507883763621 @@ -230,7 +230,7 @@ func (suite *StrategyTestSuite) TestComputeSwapState_Inverse() { amountIn: sdk.NewDec(13370), amountOut: sdk.NewDec(66829187), zeroForOne: true, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // from amount in: sqrt_next = liq2 * sqrt_cur / (liq2 + token_in * sqrt_cur) = 70.68866416340883631930670240 expectedSqrtPriceNextOutGivenIn: sdk.MustNewDecFromStr("70.688664163408836320"), // approx 4996.89 diff --git a/x/concentrated-liquidity/swapstrategy/zero_for_one.go b/x/concentrated-liquidity/swapstrategy/zero_for_one.go index 5f65897852f..309a11b7bab 100644 --- a/x/concentrated-liquidity/swapstrategy/zero_for_one.go +++ b/x/concentrated-liquidity/swapstrategy/zero_for_one.go @@ -20,7 +20,7 @@ import ( type zeroForOneStrategy struct { sqrtPriceLimit sdk.Dec storeKey sdk.StoreKey - swapFee sdk.Dec + spreadFactor sdk.Dec tickSpacing uint64 } @@ -60,7 +60,7 @@ func (s zeroForOneStrategy) ComputeSwapStepOutGivenIn(sqrtPriceCurrent, sqrtPric amountZeroIn := math.CalcAmount0Delta(liquidity, sqrtPriceTarget, sqrtPriceCurrent, true) // N.B.: if this is false, causes infinite loop // Calculate sqrtPriceNext on the amount of token remaining after fee. - amountZeroInRemainingLessFee := amountZeroInRemaining.Mul(sdk.OneDec().Sub(s.swapFee)) + amountZeroInRemainingLessFee := amountZeroInRemaining.Mul(sdk.OneDec().Sub(s.spreadFactor)) var sqrtPriceNext sdk.Dec // If have more of the amount remaining after fee than estimated until target, // bound the next sqrtPriceNext by the target sqrt price. @@ -85,7 +85,7 @@ func (s zeroForOneStrategy) ComputeSwapStepOutGivenIn(sqrtPriceCurrent, sqrtPric // Handle fees. // Note that fee is always charged on the amount in. - feeChargeTotal := computeFeeChargePerSwapStepOutGivenIn(hasReachedTarget, amountZeroIn, amountZeroInRemaining, s.swapFee) + feeChargeTotal := computeFeeChargePerSwapStepOutGivenIn(hasReachedTarget, amountZeroIn, amountZeroInRemaining, s.spreadFactor) return sqrtPriceNext, amountZeroIn, amountOneOut, feeChargeTotal } @@ -140,7 +140,7 @@ func (s zeroForOneStrategy) ComputeSwapStepInGivenOut(sqrtPriceCurrent, sqrtPric // Handle fees. // Note that fee is always charged on the amount in. - feeChargeTotal := computeFeeChargeFromAmountIn(amountZeroIn, s.swapFee) + feeChargeTotal := computeFeeChargeFromAmountIn(amountZeroIn, s.spreadFactor) return sqrtPriceNext, amountOneOut, amountZeroIn, feeChargeTotal } diff --git a/x/concentrated-liquidity/swapstrategy/zero_for_one_test.go b/x/concentrated-liquidity/swapstrategy/zero_for_one_test.go index c1295f36fdd..f8351947575 100644 --- a/x/concentrated-liquidity/swapstrategy/zero_for_one_test.go +++ b/x/concentrated-liquidity/swapstrategy/zero_for_one_test.go @@ -69,7 +69,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepOutGivenIn_ZeroForOne() { sqrtPriceTarget sdk.Dec liquidity sdk.Dec amountZeroInRemaining sdk.Dec - swapFee sdk.Dec + spreadFactor sdk.Dec expectedSqrtPriceNext sdk.Dec amountZeroInConsumed sdk.Dec @@ -84,7 +84,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepOutGivenIn_ZeroForOne() { liquidity: defaultLiquidity, // add 100 more amountZeroInRemaining: defaultAmountZero.Add(sdk.NewDec(100)), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectedSqrtPriceNext: sqrtPriceNext, // consumed without 100 since reached target. @@ -98,7 +98,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepOutGivenIn_ZeroForOne() { sqrtPriceTarget: sqrtPriceNext, liquidity: defaultLiquidity, amountZeroInRemaining: defaultAmountZero.Sub(sdk.NewDec(100)), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectedSqrtPriceNext: sqrtPriceTargetNotReached, amountZeroInConsumed: defaultAmountZero.Sub(sdk.NewDec(100)).Ceil(), @@ -112,7 +112,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepOutGivenIn_ZeroForOne() { liquidity: defaultLiquidity, // add 100 more amountZeroInRemaining: defaultAmountZero.Add(sdk.NewDec(100)).Quo(sdk.OneDec().Sub(defaultFee)), - swapFee: defaultFee, + spreadFactor: defaultFee, expectedSqrtPriceNext: sqrtPriceNext, // Consumes without 100 since reached target and fee is applied. @@ -126,7 +126,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepOutGivenIn_ZeroForOne() { sqrtPriceTarget: sqrtPriceNext, liquidity: defaultLiquidity, amountZeroInRemaining: defaultAmountZero.Sub(sdk.NewDec(100)).Quo(sdk.OneDec().Sub(defaultFee)), - swapFee: defaultFee, + spreadFactor: defaultFee, expectedSqrtPriceNext: sqrtPriceTargetNotReached, amountZeroInConsumed: defaultAmountZero.Sub(sdk.NewDec(100)).Ceil(), @@ -140,7 +140,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepOutGivenIn_ZeroForOne() { tc := tc suite.Run(name, func() { suite.SetupTest() - strategy := swapstrategy.New(true, types.MaxSqrtPrice, suite.App.GetKey(types.ModuleName), tc.swapFee, defaultTickSpacing) + strategy := swapstrategy.New(true, types.MaxSqrtPrice, suite.App.GetKey(types.ModuleName), tc.spreadFactor, defaultTickSpacing) sqrtPriceNext, amountZeroIn, amountOneOut, feeChargeTotal := strategy.ComputeSwapStepOutGivenIn(tc.sqrtPriceCurrent, tc.sqrtPriceTarget, tc.liquidity, tc.amountZeroInRemaining) @@ -173,7 +173,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepInGivenOut_ZeroForOne() { sqrtPriceTarget sdk.Dec liquidity sdk.Dec amountOneOutRemaining sdk.Dec - swapFee sdk.Dec + spreadFactor sdk.Dec expectedSqrtPriceNext sdk.Dec amountOneOutConsumed sdk.Dec @@ -188,7 +188,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepInGivenOut_ZeroForOne() { liquidity: defaultLiquidity, // Add 100. amountOneOutRemaining: defaultAmountOne.Add(sdk.NewDec(100)), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectedSqrtPriceNext: sqrtPriceNext, // Consumes without 100 since reaches target. @@ -201,7 +201,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepInGivenOut_ZeroForOne() { sqrtPriceTarget: sqrtPriceNext, liquidity: defaultLiquidity, amountOneOutRemaining: defaultAmountOne.Sub(sdk.NewDec(10000)), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), // sqrt_cur - amt_one / liq quo round up expectedSqrtPriceNext: sqrtPriceTargetNotReached, @@ -216,7 +216,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepInGivenOut_ZeroForOne() { liquidity: defaultLiquidity, // Add 100. amountOneOutRemaining: defaultAmountOne.Quo(sdk.OneDec().Sub(defaultFee)), - swapFee: defaultFee, + spreadFactor: defaultFee, expectedSqrtPriceNext: sqrtPriceNext, // Consumes without 100 since reaches target. @@ -230,7 +230,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepInGivenOut_ZeroForOne() { sqrtPriceTarget: sqrtPriceNext, liquidity: defaultLiquidity, amountOneOutRemaining: defaultAmountOne.Sub(sdk.NewDec(10000)), - swapFee: defaultFee, + spreadFactor: defaultFee, expectedSqrtPriceNext: sqrtPriceTargetNotReached, // subtracting 1 * smallest dec to account for truncations in favor of the pool. @@ -244,7 +244,7 @@ func (suite *StrategyTestSuite) TestComputeSwapStepInGivenOut_ZeroForOne() { tc := tc suite.Run(name, func() { suite.SetupTest() - strategy := swapstrategy.New(true, types.MaxSqrtPrice, suite.App.GetKey(types.ModuleName), tc.swapFee, defaultTickSpacing) + strategy := swapstrategy.New(true, types.MaxSqrtPrice, suite.App.GetKey(types.ModuleName), tc.spreadFactor, defaultTickSpacing) sqrtPriceNext, amountOneOut, amountZeroIn, feeChargeTotal := strategy.ComputeSwapStepInGivenOut(tc.sqrtPriceCurrent, tc.sqrtPriceTarget, tc.liquidity, tc.amountOneOutRemaining) diff --git a/x/concentrated-liquidity/types/constants.go b/x/concentrated-liquidity/types/constants.go index 3c8549431f1..4b5825a5d18 100644 --- a/x/concentrated-liquidity/types/constants.go +++ b/x/concentrated-liquidity/types/constants.go @@ -18,10 +18,10 @@ var ( MaxSqrtPrice, _ = MaxSpotPrice.ApproxRoot(2) MinSqrtPrice, _ = MinSpotPrice.ApproxRoot(2) // Supported uptimes preset to 1 ns, 1 min, 1 hr, 1D, 1W - SupportedUptimes = []time.Duration{time.Nanosecond, time.Minute, time.Hour, time.Hour * 24, time.Hour * 24 * 7} - ExponentAtPriceOne int64 = -6 - AuthorizedTickSpacing = []uint64{1, 10, 100, 1000} - AuthorizedSwapFees = []sdk.Dec{ + SupportedUptimes = []time.Duration{time.Nanosecond, time.Minute, time.Hour, time.Hour * 24, time.Hour * 24 * 7} + ExponentAtPriceOne int64 = -6 + AuthorizedTickSpacing = []uint64{1, 10, 100, 1000} + AuthorizedSpreadFactors = []sdk.Dec{ sdk.ZeroDec(), sdk.MustNewDecFromStr("0.0001"), // 0.01% sdk.MustNewDecFromStr("0.0005"), // 0.05% diff --git a/x/concentrated-liquidity/types/errors.go b/x/concentrated-liquidity/types/errors.go index 90e2d3dbfcf..f64a8470d78 100644 --- a/x/concentrated-liquidity/types/errors.go +++ b/x/concentrated-liquidity/types/errors.go @@ -285,12 +285,12 @@ func (e SqrtPriceNegativeError) Error() string { return fmt.Sprintf("provided sqrt price (%s) must be positive", e.ProvidedSqrtPrice) } -type InvalidSwapFeeError struct { +type InvalidSpreadFactorError struct { ActualFee sdk.Dec } -func (e InvalidSwapFeeError) Error() string { - return fmt.Sprintf("invalid swap fee(%s), must be in [0, 1) range", e.ActualFee) +func (e InvalidSpreadFactorError) Error() string { + return fmt.Sprintf("invalid spread factor(%s), must be in [0, 1) range", e.ActualFee) } type PositionAlreadyExistsError struct { @@ -681,13 +681,13 @@ func (e UnauthorizedQuoteDenomError) Error() string { return fmt.Sprintf("attempted to create pool with unauthorized quote denom (%s), must be one of the following: (%s)", e.ProvidedQuoteDenom, e.AuthorizedQuoteDenoms) } -type UnauthorizedSwapFeeError struct { - ProvidedSwapFee sdk.Dec - AuthorizedSwapFees []sdk.Dec +type UnauthorizedSpreadFactorError struct { + ProvidedSpreadFactor sdk.Dec + AuthorizedSpreadFactors []sdk.Dec } -func (e UnauthorizedSwapFeeError) Error() string { - return fmt.Sprintf("attempted to create pool with unauthorized swap fee (%s), must be one of the following: (%s)", e.ProvidedSwapFee, e.AuthorizedSwapFees) +func (e UnauthorizedSpreadFactorError) Error() string { + return fmt.Sprintf("attempted to create pool with unauthorized spread factor (%s), must be one of the following: (%s)", e.ProvidedSpreadFactor, e.AuthorizedSpreadFactors) } type UnauthorizedTickSpacingError struct { diff --git a/x/concentrated-liquidity/types/events.go b/x/concentrated-liquidity/types/events.go index 091a8189c6f..6d9148dd13c 100644 --- a/x/concentrated-liquidity/types/events.go +++ b/x/concentrated-liquidity/types/events.go @@ -17,7 +17,7 @@ const ( AttributeKeyPoolId = "pool_id" AttributeAmount0 = "amount0" AttributeAmount1 = "amount1" - AttributeKeySwapFee = "swap_fee" + AttributeKeySpreadFactor = "spread_factor" AttributeKeyTokensIn = "tokens_in" AttributeKeyTokensOut = "tokens_out" AttributeKeyForfeitedTokens = "forfeited_tokens" diff --git a/x/concentrated-liquidity/types/gov.go b/x/concentrated-liquidity/types/gov.go index fef6dc7a78c..5ca0e89bbf4 100644 --- a/x/concentrated-liquidity/types/gov.go +++ b/x/concentrated-liquidity/types/gov.go @@ -26,7 +26,7 @@ var ( ) // NewCreateConcentratedLiquidityPoolProposal returns a new instance of a create concentrated liquidity pool proposal struct. -func NewCreateConcentratedLiquidityPoolProposal(title, description string, denom0, denom1 string, tickSpacing uint64, exponentAtPriceOne sdk.Int, swapFee sdk.Dec) govtypes.Content { +func NewCreateConcentratedLiquidityPoolProposal(title, description string, denom0, denom1 string, tickSpacing uint64, exponentAtPriceOne sdk.Int, spreadFactor sdk.Dec) govtypes.Content { return &CreateConcentratedLiquidityPoolProposal{ Title: title, Description: description, @@ -34,7 +34,7 @@ func NewCreateConcentratedLiquidityPoolProposal(title, description string, denom Denom1: denom1, TickSpacing: tickSpacing, ExponentAtPriceOne: exponentAtPriceOne, - SwapFee: swapFee, + SpreadFactor: spreadFactor, } } @@ -74,9 +74,9 @@ func (p *CreateConcentratedLiquidityPoolProposal) ValidateBasic() error { return fmt.Errorf("denom1 is invalid: %s", sdk.ValidateDenom(p.Denom1)) } - swapFee := p.SwapFee - if swapFee.IsNegative() || swapFee.GTE(sdk.OneDec()) { - return InvalidSwapFeeError{ActualFee: swapFee} + spreadFactor := p.SpreadFactor + if spreadFactor.IsNegative() || spreadFactor.GTE(sdk.OneDec()) { + return InvalidSpreadFactorError{ActualFee: spreadFactor} } return nil @@ -128,7 +128,7 @@ func (p CreateConcentratedLiquidityPoolProposal) String() string { Tick Spacing: %d ExponentAtPriceOne %s Swap Fee: %s -`, p.Title, p.Description, p.Denom0, p.Denom1, p.TickSpacing, p.ExponentAtPriceOne.String(), p.SwapFee.String())) +`, p.Title, p.Description, p.Denom0, p.Denom1, p.TickSpacing, p.ExponentAtPriceOne.String(), p.SpreadFactor.String())) return b.String() } diff --git a/x/concentrated-liquidity/types/gov.pb.go b/x/concentrated-liquidity/types/gov.pb.go index 2dc9ab5e06a..0fa26f50a93 100644 --- a/x/concentrated-liquidity/types/gov.pb.go +++ b/x/concentrated-liquidity/types/gov.pb.go @@ -34,7 +34,7 @@ type CreateConcentratedLiquidityPoolProposal struct { Denom1 string `protobuf:"bytes,4,opt,name=denom1,proto3" json:"denom1,omitempty" yaml:"denom1"` TickSpacing uint64 `protobuf:"varint,5,opt,name=tick_spacing,json=tickSpacing,proto3" json:"tick_spacing,omitempty" yaml:"tick_spacing"` ExponentAtPriceOne github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,6,opt,name=exponent_at_price_one,json=exponentAtPriceOne,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"exponent_at_price_one" yaml:"exponent_at_price_one"` - SwapFee github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=swap_fee,json=swapFee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"swap_fee" yaml:"swap_fee"` + SpreadFactor github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=spread_factor,json=spreadFactor,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"spread_factor" yaml:"spread_factor"` } func (m *CreateConcentratedLiquidityPoolProposal) Reset() { @@ -178,42 +178,42 @@ func init() { } var fileDescriptor_e6d167276ceeedc2 = []byte{ - // 548 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x53, 0xbf, 0x6f, 0xd3, 0x40, - 0x14, 0xb6, 0x89, 0x9b, 0xc0, 0xa5, 0xfc, 0x32, 0x45, 0x35, 0x05, 0xd9, 0x91, 0x25, 0x20, 0x0c, - 0xb1, 0x31, 0x88, 0x25, 0x13, 0x4d, 0x2b, 0xa4, 0x4a, 0x08, 0x22, 0xd3, 0x09, 0x55, 0xb2, 0x1c, - 0xfb, 0x11, 0x4e, 0x75, 0xee, 0x19, 0xdf, 0x35, 0x69, 0x46, 0x36, 0x24, 0x16, 0x46, 0xc6, 0xfc, - 0x39, 0x1d, 0x3b, 0x22, 0x06, 0x0b, 0x25, 0x0b, 0x2b, 0xf9, 0x0b, 0x90, 0xed, 0xa4, 0x18, 0xd4, - 0x48, 0x20, 0x26, 0xfb, 0xbd, 0xf7, 0xbd, 0xef, 0xbb, 0xef, 0xbd, 0x3b, 0xd2, 0x44, 0x3e, 0x40, - 0x4e, 0xb9, 0x1d, 0x20, 0x0b, 0x80, 0x89, 0xc4, 0x17, 0x10, 0xb6, 0x22, 0xfa, 0xee, 0x88, 0x86, - 0x54, 0x8c, 0xed, 0x3e, 0x0e, 0xad, 0x38, 0x41, 0x81, 0xea, 0xdd, 0x05, 0xd2, 0x2a, 0x23, 0xcf, - 0x80, 0xd6, 0xd0, 0xe9, 0x81, 0xf0, 0x9d, 0xad, 0x8d, 0x3e, 0xf6, 0x31, 0xef, 0xb0, 0xb3, 0xbf, - 0xa2, 0xd9, 0x9c, 0x55, 0xc8, 0xfd, 0x9d, 0x04, 0x7c, 0x01, 0x3b, 0xa5, 0xee, 0xe7, 0xcb, 0xee, - 0x2e, 0x62, 0xd4, 0x4d, 0x30, 0x46, 0xee, 0x47, 0xea, 0x06, 0x59, 0x13, 0x54, 0x44, 0xa0, 0xc9, - 0x0d, 0xb9, 0x79, 0xc9, 0x2d, 0x02, 0xb5, 0x41, 0xea, 0x21, 0xf0, 0x20, 0xa1, 0xb1, 0xa0, 0xc8, - 0xb4, 0x0b, 0x79, 0xad, 0x9c, 0x52, 0x1f, 0x90, 0x6a, 0x08, 0x0c, 0x07, 0x0f, 0xb5, 0x4a, 0x56, - 0xec, 0x5c, 0x9f, 0xa7, 0xc6, 0xe5, 0xb1, 0x3f, 0x88, 0xda, 0x66, 0x91, 0x37, 0xdd, 0x05, 0xe0, - 0x0c, 0xea, 0x68, 0xca, 0xb9, 0x50, 0x67, 0x09, 0x75, 0xd4, 0x36, 0x59, 0x17, 0x34, 0x38, 0xf4, - 0x78, 0xec, 0x07, 0x94, 0xf5, 0xb5, 0xb5, 0x86, 0xdc, 0x54, 0x3a, 0x9b, 0xf3, 0xd4, 0xb8, 0x51, - 0x34, 0x94, 0xab, 0xa6, 0x5b, 0xcf, 0xc2, 0x57, 0x45, 0xa4, 0xbe, 0x97, 0xc9, 0x4d, 0x38, 0x8e, - 0x91, 0x01, 0x13, 0x9e, 0x2f, 0xbc, 0x38, 0xa1, 0x01, 0x78, 0xc8, 0x40, 0xab, 0xe6, 0xb2, 0x2f, - 0x4e, 0x52, 0x43, 0xfa, 0x9a, 0x1a, 0xf7, 0xfa, 0x54, 0xbc, 0x3d, 0xea, 0x59, 0x01, 0x0e, 0xec, - 0x20, 0x1f, 0xf3, 0xe2, 0xd3, 0xe2, 0xe1, 0xa1, 0x2d, 0xc6, 0x31, 0x70, 0x6b, 0x8f, 0x89, 0x79, - 0x6a, 0xdc, 0x29, 0x34, 0xcf, 0x25, 0x35, 0x5d, 0x75, 0x99, 0xdf, 0x16, 0xdd, 0x2c, 0xfb, 0x92, - 0x81, 0x7a, 0x40, 0x2e, 0xf2, 0x91, 0x1f, 0x7b, 0x6f, 0x00, 0xb4, 0x5a, 0xae, 0xba, 0xfd, 0x0f, - 0xaa, 0xbb, 0x10, 0xcc, 0x53, 0xe3, 0x6a, 0xa1, 0xba, 0xe4, 0x31, 0xdd, 0x5a, 0xf6, 0xfb, 0x0c, - 0xa0, 0xbd, 0xfe, 0x61, 0x62, 0x48, 0x9f, 0x27, 0x86, 0xf4, 0x7d, 0x62, 0xc8, 0xe6, 0x0f, 0x99, - 0xdc, 0xde, 0xff, 0xe5, 0x7f, 0x17, 0x82, 0x04, 0x7c, 0x0e, 0xff, 0xbd, 0xd9, 0x8f, 0x32, 0x31, - 0x62, 0xc4, 0xc8, 0xa3, 0xa1, 0x27, 0xd0, 0x2b, 0x4f, 0xdc, 0x4b, 0x20, 0xc0, 0x24, 0xe4, 0x5a, - 0xa5, 0x51, 0x69, 0xd6, 0x1f, 0x3d, 0xb5, 0xfe, 0xea, 0x96, 0x5a, 0xd9, 0x85, 0xdb, 0x0b, 0xf7, - 0xb1, 0x74, 0x5a, 0x37, 0x27, 0xea, 0x28, 0xd9, 0x74, 0xdc, 0xad, 0x78, 0x15, 0x80, 0xff, 0xe1, - 0x39, 0x24, 0xb7, 0x56, 0x92, 0xa9, 0x9b, 0xa4, 0xb6, 0x38, 0x77, 0x6e, 0x59, 0x71, 0xab, 0x05, - 0xaf, 0xda, 0x24, 0xd7, 0x18, 0x8c, 0x7e, 0x73, 0x92, 0x1b, 0x57, 0xdc, 0x2b, 0x0c, 0x46, 0x25, - 0xa2, 0xb6, 0x92, 0xa9, 0x74, 0x0e, 0x4e, 0xa6, 0xba, 0x7c, 0x3a, 0xd5, 0xe5, 0x6f, 0x53, 0x5d, - 0xfe, 0x34, 0xd3, 0xa5, 0xd3, 0x99, 0x2e, 0x7d, 0x99, 0xe9, 0xd2, 0xeb, 0x4e, 0x69, 0x8b, 0x0b, - 0xef, 0xad, 0xc8, 0xef, 0xf1, 0x65, 0x60, 0x0f, 0x9d, 0x27, 0xf6, 0xf1, 0xaa, 0xe7, 0x9d, 0x6f, - 0xb9, 0x57, 0xcd, 0x1f, 0xe9, 0xe3, 0x9f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xf8, 0xa2, 0x31, 0x0e, - 0x0d, 0x04, 0x00, 0x00, + // 553 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x53, 0xb1, 0x6f, 0xd3, 0x4e, + 0x14, 0xb6, 0x7f, 0x71, 0x53, 0xfd, 0x2e, 0x29, 0x02, 0x13, 0x54, 0x53, 0x90, 0x1d, 0x59, 0x02, + 0xc2, 0x10, 0x1b, 0x83, 0x58, 0x32, 0x41, 0x5a, 0x55, 0xaa, 0x84, 0x20, 0x32, 0x9d, 0x10, 0x92, + 0xe5, 0x9c, 0x8f, 0x70, 0x8a, 0x73, 0xcf, 0xf8, 0xae, 0x69, 0x33, 0xb2, 0x21, 0xb1, 0x30, 0x32, + 0xe6, 0xcf, 0xe9, 0xd8, 0x11, 0x31, 0x58, 0x28, 0x59, 0x58, 0xc9, 0x5f, 0x80, 0x7c, 0x4e, 0x8a, + 0x8b, 0x1a, 0x09, 0xc4, 0x64, 0x7f, 0xef, 0x7d, 0xef, 0xfb, 0xee, 0xbd, 0x77, 0x87, 0x5a, 0xc0, + 0x47, 0xc0, 0x29, 0x77, 0x31, 0x30, 0x4c, 0x98, 0x48, 0x43, 0x41, 0xa2, 0x76, 0x4c, 0xdf, 0x1d, + 0xd1, 0x88, 0x8a, 0x89, 0x3b, 0x80, 0xb1, 0x93, 0xa4, 0x20, 0x40, 0xbf, 0xb3, 0x64, 0x3a, 0x65, + 0xe6, 0x39, 0xd1, 0x19, 0x7b, 0x7d, 0x22, 0x42, 0x6f, 0xa7, 0x31, 0x80, 0x01, 0xc8, 0x0a, 0x37, + 0xff, 0x2b, 0x8a, 0xed, 0x45, 0x05, 0xdd, 0xdb, 0x4d, 0x49, 0x28, 0xc8, 0x6e, 0xa9, 0xfa, 0xd9, + 0xaa, 0xba, 0x07, 0x10, 0xf7, 0x52, 0x48, 0x80, 0x87, 0xb1, 0xde, 0x40, 0x1b, 0x82, 0x8a, 0x98, + 0x18, 0x6a, 0x53, 0x6d, 0xfd, 0xef, 0x17, 0x40, 0x6f, 0xa2, 0x5a, 0x44, 0x38, 0x4e, 0x69, 0x22, + 0x28, 0x30, 0xe3, 0x3f, 0x99, 0x2b, 0x87, 0xf4, 0xfb, 0xa8, 0x1a, 0x11, 0x06, 0xa3, 0x07, 0x46, + 0x25, 0x4f, 0x76, 0xaf, 0x2d, 0x32, 0x6b, 0x6b, 0x12, 0x8e, 0xe2, 0x8e, 0x5d, 0xc4, 0x6d, 0x7f, + 0x49, 0x38, 0xa7, 0x7a, 0x86, 0x76, 0x29, 0xd5, 0x5b, 0x51, 0x3d, 0xbd, 0x83, 0xea, 0x82, 0xe2, + 0x61, 0xc0, 0x93, 0x10, 0x53, 0x36, 0x30, 0x36, 0x9a, 0x6a, 0x4b, 0xeb, 0x6e, 0x2f, 0x32, 0xeb, + 0x7a, 0x51, 0x50, 0xce, 0xda, 0x7e, 0x2d, 0x87, 0x2f, 0x0b, 0xa4, 0xbf, 0x57, 0xd1, 0x0d, 0x72, + 0x92, 0x00, 0x23, 0x4c, 0x04, 0xa1, 0x08, 0x92, 0x94, 0x62, 0x12, 0x00, 0x23, 0x46, 0x55, 0xda, + 0x3e, 0x3f, 0xcd, 0x2c, 0xe5, 0x6b, 0x66, 0xdd, 0x1d, 0x50, 0xf1, 0xf6, 0xa8, 0xef, 0x60, 0x18, + 0xb9, 0x58, 0x8e, 0x79, 0xf9, 0x69, 0xf3, 0x68, 0xe8, 0x8a, 0x49, 0x42, 0xb8, 0x73, 0xc0, 0xc4, + 0x22, 0xb3, 0x6e, 0x17, 0x9e, 0x97, 0x8a, 0xda, 0xbe, 0xbe, 0x8a, 0x3f, 0x15, 0xbd, 0x3c, 0xfa, + 0x82, 0x11, 0x7d, 0x88, 0xb6, 0x78, 0x92, 0x92, 0x30, 0x0a, 0xde, 0x84, 0x58, 0x40, 0x6a, 0x6c, + 0x4a, 0xeb, 0xfd, 0xbf, 0xb0, 0xde, 0x23, 0x78, 0x91, 0x59, 0x8d, 0xc2, 0xfa, 0x82, 0x98, 0xed, + 0xd7, 0x0b, 0xbc, 0x2f, 0x61, 0xa7, 0xfe, 0x61, 0x6a, 0x29, 0x9f, 0xa7, 0x96, 0xf2, 0x7d, 0x6a, + 0xa9, 0xf6, 0x0f, 0x15, 0xdd, 0x3a, 0xfc, 0x35, 0x8e, 0x3d, 0x82, 0x53, 0x12, 0x72, 0xf2, 0xcf, + 0x8b, 0xfe, 0xa8, 0x22, 0x2b, 0x01, 0x88, 0x03, 0x1a, 0x05, 0x02, 0x82, 0xf2, 0x02, 0x82, 0x94, + 0x60, 0x48, 0x23, 0x6e, 0x54, 0x9a, 0x95, 0x56, 0xed, 0xe1, 0x13, 0xe7, 0x8f, 0x2e, 0xad, 0x93, + 0xdf, 0xbf, 0x83, 0xe8, 0x10, 0x4a, 0xa7, 0xf5, 0xa5, 0x50, 0x57, 0xcb, 0xe7, 0xe4, 0xef, 0x24, + 0xeb, 0x08, 0xfc, 0xb7, 0x9e, 0x23, 0x74, 0x73, 0xad, 0x98, 0xbe, 0x8d, 0x36, 0x97, 0xe7, 0x96, + 0x2d, 0x6b, 0x7e, 0xb5, 0xd0, 0xd5, 0x5b, 0xe8, 0x2a, 0x23, 0xc7, 0x17, 0x3a, 0x91, 0x8d, 0x6b, + 0xfe, 0x15, 0x46, 0x8e, 0x4b, 0x42, 0x1d, 0x2d, 0x77, 0xe9, 0xbe, 0x3e, 0x9d, 0x99, 0xea, 0xd9, + 0xcc, 0x54, 0xbf, 0xcd, 0x4c, 0xf5, 0xd3, 0xdc, 0x54, 0xce, 0xe6, 0xa6, 0xf2, 0x65, 0x6e, 0x2a, + 0xaf, 0xba, 0xa5, 0x7d, 0x2e, 0x7b, 0x6f, 0xc7, 0x61, 0x9f, 0xaf, 0x80, 0x3b, 0xf6, 0x1e, 0xbb, + 0x27, 0xeb, 0x5e, 0xbb, 0xdc, 0x77, 0xbf, 0x2a, 0xdf, 0xec, 0xa3, 0x9f, 0x01, 0x00, 0x00, 0xff, + 0xff, 0xcd, 0x50, 0xb8, 0x56, 0x1c, 0x04, 0x00, 0x00, } func (this *CreateConcentratedLiquidityPoolProposal) Equal(that interface{}) bool { @@ -253,7 +253,7 @@ func (this *CreateConcentratedLiquidityPoolProposal) Equal(that interface{}) boo if !this.ExponentAtPriceOne.Equal(that1.ExponentAtPriceOne) { return false } - if !this.SwapFee.Equal(that1.SwapFee) { + if !this.SpreadFactor.Equal(that1.SpreadFactor) { return false } return true @@ -341,9 +341,9 @@ func (m *CreateConcentratedLiquidityPoolProposal) MarshalToSizedBuffer(dAtA []by var l int _ = l { - size := m.SwapFee.Size() + size := m.SpreadFactor.Size() i -= size - if _, err := m.SwapFee.MarshalTo(dAtA[i:]); err != nil { + if _, err := m.SpreadFactor.MarshalTo(dAtA[i:]); err != nil { return 0, err } i = encodeVarintGov(dAtA, i, uint64(size)) @@ -518,7 +518,7 @@ func (m *CreateConcentratedLiquidityPoolProposal) Size() (n int) { } l = m.ExponentAtPriceOne.Size() n += 1 + l + sovGov(uint64(l)) - l = m.SwapFee.Size() + l = m.SpreadFactor.Size() n += 1 + l + sovGov(uint64(l)) return n } @@ -779,7 +779,7 @@ func (m *CreateConcentratedLiquidityPoolProposal) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 7: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapFee", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field SpreadFactor", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -807,7 +807,7 @@ func (m *CreateConcentratedLiquidityPoolProposal) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if err := m.SwapFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.SpreadFactor.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex diff --git a/x/concentrated-liquidity/types/gov_test.go b/x/concentrated-liquidity/types/gov_test.go index 7e311a79575..02394f4eb1e 100644 --- a/x/concentrated-liquidity/types/gov_test.go +++ b/x/concentrated-liquidity/types/gov_test.go @@ -34,7 +34,7 @@ func TestCreateConcentratedLiquidityPoolProposalMarshalUnmarshal(t *testing.T) { Denom1: "denom1", TickSpacing: uint64(1), ExponentAtPriceOne: sdk.NewInt(-1), - SwapFee: sdk.MustNewDecFromStr("0.01"), + SpreadFactor: sdk.MustNewDecFromStr("0.01"), }, }, } diff --git a/x/concentrated-liquidity/types/incentive_record.pb.go b/x/concentrated-liquidity/types/incentive_record.pb.go index e01d7de8dd7..6a44813249e 100644 --- a/x/concentrated-liquidity/types/incentive_record.pb.go +++ b/x/concentrated-liquidity/types/incentive_record.pb.go @@ -124,7 +124,7 @@ type IncentiveRecordBody struct { // remaining_amount is the total amount of incentives to be distributed RemainingAmount github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=remaining_amount,json=remainingAmount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"remaining_amount" yaml:"remaining_amount"` // emission_rate is the incentive emission rate per second - EmissionRate github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=emission_rate,json=emissionRate,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"emission_rate" yaml:"swap_fee"` + EmissionRate github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=emission_rate,json=emissionRate,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"emission_rate" yaml:"emission_rate"` // start_time is the time when the incentive starts distributing StartTime time.Time `protobuf:"bytes,3,opt,name=start_time,json=startTime,proto3,stdtime" json:"start_time" yaml:"start_time"` } @@ -179,43 +179,42 @@ func init() { } var fileDescriptor_9d38bf94e42ee434 = []byte{ - // 562 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0xcd, 0x6e, 0xd3, 0x4c, - 0x14, 0x8d, 0x9b, 0x7e, 0xfd, 0x94, 0xe1, 0x27, 0xe0, 0x96, 0x36, 0x8d, 0xa8, 0x1d, 0x2c, 0x40, - 0xd9, 0xc4, 0x56, 0x40, 0xdd, 0x74, 0x17, 0x37, 0x9b, 0x6c, 0x2d, 0x50, 0x11, 0x42, 0xb2, 0xc6, - 0x9e, 0x89, 0x19, 0x91, 0xf1, 0x98, 0x99, 0x71, 0x20, 0x6f, 0xd1, 0x05, 0x0b, 0x1e, 0x85, 0x47, - 0xe8, 0x06, 0xa9, 0x4b, 0xc4, 0xc2, 0xa0, 0xe4, 0x0d, 0xf2, 0x04, 0xc8, 0x63, 0xe7, 0x47, 0x2e, - 0x48, 0xb0, 0x4a, 0xee, 0x99, 0x73, 0xee, 0x3d, 0x73, 0xee, 0x24, 0xe0, 0x94, 0x09, 0xca, 0x04, - 0x11, 0x4e, 0xc8, 0xe2, 0x10, 0xc7, 0x92, 0x43, 0x89, 0x51, 0x6f, 0x42, 0xde, 0xa7, 0x04, 0x11, - 0x39, 0x73, 0x88, 0x42, 0xc9, 0x14, 0xfb, 0x1c, 0x87, 0x8c, 0x23, 0x3b, 0xe1, 0x4c, 0x32, 0xfd, - 0x49, 0x29, 0xb3, 0xb7, 0x65, 0x6b, 0x95, 0x3d, 0xed, 0x07, 0x58, 0xc2, 0x7e, 0xfb, 0x38, 0x54, - 0x3c, 0x5f, 0x89, 0x9c, 0xa2, 0x28, 0x3a, 0xb4, 0x0f, 0x22, 0x16, 0xb1, 0x02, 0xcf, 0xbf, 0x95, - 0xa8, 0x19, 0x31, 0x16, 0x4d, 0xb0, 0xa3, 0xaa, 0x20, 0x1d, 0x3b, 0x92, 0x50, 0x2c, 0x24, 0xa4, - 0x49, 0x49, 0x30, 0xaa, 0x04, 0x94, 0x72, 0x28, 0x09, 0x8b, 0x8b, 0x73, 0xeb, 0x4b, 0x1d, 0x34, - 0x47, 0x2b, 0xcf, 0x9e, 0xb2, 0xac, 0x1f, 0x81, 0xff, 0x13, 0xc6, 0x26, 0x3e, 0x41, 0x2d, 0xad, - 0xa3, 0x75, 0x77, 0xbd, 0xbd, 0xbc, 0x1c, 0x21, 0xfd, 0x1c, 0x34, 0x37, 0xf7, 0x43, 0x38, 0x66, - 0xb4, 0xb5, 0xd3, 0xd1, 0xba, 0x0d, 0xb7, 0xbd, 0xcc, 0xcc, 0xc3, 0x19, 0xa4, 0x93, 0x33, 0xab, - 0x42, 0xb0, 0xbc, 0xbb, 0x6b, 0x64, 0x98, 0x03, 0xfa, 0x05, 0x38, 0xdc, 0x70, 0x42, 0x8e, 0xa1, - 0x64, 0xdc, 0x87, 0x08, 0xf1, 0x56, 0x5d, 0xf5, 0x7a, 0xb4, 0xcc, 0xcc, 0x93, 0x6a, 0xaf, 0x6d, - 0x9e, 0xe5, 0x1d, 0xac, 0x0f, 0xce, 0x0b, 0x7c, 0x80, 0x10, 0xd7, 0x3f, 0x69, 0xe0, 0x41, 0x35, - 0x7e, 0x3f, 0x60, 0x68, 0xd6, 0xda, 0xed, 0x68, 0xdd, 0x5b, 0xcf, 0xce, 0xec, 0xbf, 0x5a, 0x82, - 0x5d, 0x89, 0xc3, 0x65, 0x68, 0xe6, 0x3e, 0xbe, 0xca, 0xcc, 0xda, 0x32, 0x33, 0x1f, 0x56, 0x8d, - 0x6d, 0x8d, 0xb1, 0xbc, 0x7d, 0x72, 0x53, 0xaa, 0x5f, 0x00, 0x40, 0x49, 0xec, 0xa7, 0x49, 0xbe, - 0x9a, 0xd6, 0x7f, 0xca, 0xca, 0xb1, 0x5d, 0xac, 0xc5, 0x5e, 0xad, 0xc5, 0x1e, 0x96, 0x6b, 0x71, - 0x4f, 0xca, 0x49, 0xf7, 0x8b, 0x49, 0x1b, 0xa9, 0xf5, 0xf9, 0x87, 0xa9, 0x79, 0x0d, 0x4a, 0xe2, - 0x97, 0x45, 0xfd, 0x75, 0x07, 0xec, 0xff, 0xc6, 0xab, 0x2e, 0xc1, 0x3d, 0x8e, 0x29, 0x24, 0x31, - 0x89, 0x23, 0x1f, 0x52, 0x96, 0xc6, 0x52, 0xed, 0xb1, 0xe1, 0x8e, 0xf2, 0xde, 0xdf, 0x33, 0xf3, - 0x69, 0x44, 0xe4, 0xdb, 0x34, 0xb0, 0x43, 0x46, 0xcb, 0x47, 0x56, 0x7e, 0xf4, 0x04, 0x7a, 0xe7, - 0xc8, 0x59, 0x82, 0x85, 0x3d, 0xc4, 0xe1, 0x32, 0x33, 0x8f, 0x0a, 0x17, 0xd5, 0x7e, 0x96, 0xd7, - 0x5c, 0x43, 0x03, 0x85, 0xe8, 0x63, 0x70, 0x07, 0x53, 0x22, 0x04, 0x61, 0xb1, 0x9f, 0x07, 0x5b, - 0xbe, 0x8c, 0xc1, 0x3f, 0x8f, 0x6c, 0x16, 0x23, 0xc5, 0x07, 0x98, 0xf8, 0x63, 0x8c, 0x2d, 0xef, - 0xf6, 0xaa, 0xaf, 0x07, 0x25, 0xd6, 0x5f, 0x01, 0x20, 0x24, 0xe4, 0xd2, 0x57, 0x71, 0xd6, 0x55, - 0x9c, 0xed, 0x1b, 0x71, 0xbe, 0x58, 0xfd, 0x0c, 0xaa, 0x79, 0x6e, 0xb4, 0xd6, 0xa5, 0xca, 0x53, - 0x01, 0x39, 0xdd, 0x7d, 0x73, 0x35, 0x37, 0xb4, 0xeb, 0xb9, 0xa1, 0xfd, 0x9c, 0x1b, 0xda, 0xe5, - 0xc2, 0xa8, 0x5d, 0x2f, 0x8c, 0xda, 0xb7, 0x85, 0x51, 0x7b, 0xed, 0x6e, 0x99, 0x2f, 0xdf, 0x50, - 0x6f, 0x02, 0x03, 0xb1, 0x2a, 0x9c, 0x69, 0xff, 0xd4, 0xf9, 0xf8, 0xa7, 0xbf, 0x04, 0x75, 0xb9, - 0x60, 0x4f, 0x79, 0x7b, 0xfe, 0x2b, 0x00, 0x00, 0xff, 0xff, 0x56, 0x5e, 0xf4, 0xd1, 0x41, 0x04, - 0x00, 0x00, + // 558 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0x4d, 0x6e, 0xd3, 0x40, + 0x18, 0x8d, 0x9b, 0x52, 0x94, 0xe1, 0x27, 0xe0, 0x86, 0x36, 0x8d, 0xa8, 0x1d, 0x2c, 0x40, 0xd9, + 0xc4, 0x56, 0x40, 0xdd, 0x74, 0x57, 0x37, 0x42, 0xca, 0xd6, 0x02, 0x15, 0x21, 0x24, 0x6b, 0xec, + 0x19, 0xcc, 0xa8, 0x19, 0x4f, 0x18, 0x8f, 0x23, 0x72, 0x8b, 0x2e, 0x58, 0x70, 0x14, 0x8e, 0xd0, + 0x65, 0xc5, 0x0a, 0xb1, 0x30, 0x28, 0xb9, 0x41, 0x4e, 0x80, 0x3c, 0x63, 0x27, 0xc1, 0x05, 0x09, + 0x56, 0xc9, 0xf7, 0xe6, 0xbd, 0xef, 0x7b, 0xf3, 0xbe, 0x49, 0xc0, 0x11, 0x4b, 0x28, 0x4b, 0x48, + 0xe2, 0x84, 0x2c, 0x0e, 0x71, 0x2c, 0x38, 0x14, 0x18, 0xf5, 0xc7, 0xe4, 0x43, 0x4a, 0x10, 0x11, + 0x33, 0x87, 0x48, 0x94, 0x4c, 0xb1, 0xcf, 0x71, 0xc8, 0x38, 0xb2, 0x27, 0x9c, 0x09, 0xa6, 0x3f, + 0x29, 0x64, 0xf6, 0xa6, 0x6c, 0xa5, 0xb2, 0xa7, 0x83, 0x00, 0x0b, 0x38, 0xe8, 0x1c, 0x84, 0x92, + 0xe7, 0x4b, 0x91, 0xa3, 0x0a, 0xd5, 0xa1, 0xd3, 0x8a, 0x58, 0xc4, 0x14, 0x9e, 0x7f, 0x2b, 0x50, + 0x33, 0x62, 0x2c, 0x1a, 0x63, 0x47, 0x56, 0x41, 0xfa, 0xce, 0x11, 0x84, 0xe2, 0x44, 0x40, 0x3a, + 0x29, 0x08, 0x46, 0x95, 0x80, 0x52, 0x0e, 0x05, 0x61, 0xb1, 0x3a, 0xb7, 0xbe, 0xd4, 0x41, 0x73, + 0x54, 0x7a, 0xf6, 0xa4, 0x65, 0x7d, 0x1f, 0xdc, 0x9c, 0x30, 0x36, 0xf6, 0x09, 0x6a, 0x6b, 0x5d, + 0xad, 0xb7, 0xed, 0xed, 0xe4, 0xe5, 0x08, 0xe9, 0xa7, 0xa0, 0xb9, 0xbe, 0x1f, 0xc2, 0x31, 0xa3, + 0xed, 0xad, 0xae, 0xd6, 0x6b, 0xb8, 0x9d, 0x65, 0x66, 0xee, 0xcd, 0x20, 0x1d, 0x1f, 0x5b, 0x15, + 0x82, 0xe5, 0xdd, 0x5d, 0x21, 0xc3, 0x1c, 0xd0, 0xcf, 0xc0, 0xde, 0x9a, 0x13, 0x72, 0x0c, 0x05, + 0xe3, 0x3e, 0x44, 0x88, 0xb7, 0xeb, 0xb2, 0xd7, 0xa3, 0x65, 0x66, 0x1e, 0x56, 0x7b, 0x6d, 0xf2, + 0x2c, 0xaf, 0xb5, 0x3a, 0x38, 0x55, 0xf8, 0x09, 0x42, 0x5c, 0xff, 0xa4, 0x81, 0x07, 0xd5, 0xf8, + 0xfd, 0x80, 0xa1, 0x59, 0x7b, 0xbb, 0xab, 0xf5, 0x6e, 0x3d, 0x3b, 0xb6, 0xff, 0x69, 0x09, 0x76, + 0x25, 0x0e, 0x97, 0xa1, 0x99, 0xfb, 0xf8, 0x32, 0x33, 0x6b, 0xcb, 0xcc, 0x7c, 0x58, 0x35, 0xb6, + 0x31, 0xc6, 0xf2, 0x76, 0xc9, 0x75, 0xa9, 0x7e, 0x06, 0x00, 0x25, 0xb1, 0x9f, 0x4e, 0xf2, 0xd5, + 0xb4, 0x6f, 0x48, 0x2b, 0x07, 0xb6, 0x5a, 0x8b, 0x5d, 0xae, 0xc5, 0x1e, 0x16, 0x6b, 0x71, 0x0f, + 0x8b, 0x49, 0xf7, 0xd5, 0xa4, 0xb5, 0xd4, 0xfa, 0xfc, 0xc3, 0xd4, 0xbc, 0x06, 0x25, 0xf1, 0x2b, + 0x55, 0x7f, 0xdd, 0x02, 0xbb, 0x7f, 0xf0, 0xaa, 0x0b, 0x70, 0x8f, 0x63, 0x0a, 0x49, 0x4c, 0xe2, + 0xc8, 0x87, 0x94, 0xa5, 0xb1, 0x90, 0x7b, 0x6c, 0xb8, 0xa3, 0xbc, 0xf7, 0xf7, 0xcc, 0x7c, 0x1a, + 0x11, 0xf1, 0x3e, 0x0d, 0xec, 0x90, 0xd1, 0xe2, 0x91, 0x15, 0x1f, 0xfd, 0x04, 0x9d, 0x3b, 0x62, + 0x36, 0xc1, 0x89, 0x3d, 0xc4, 0xe1, 0x32, 0x33, 0xf7, 0x95, 0x8b, 0x6a, 0x3f, 0xcb, 0x6b, 0xae, + 0xa0, 0x13, 0x89, 0xe8, 0xe7, 0xe0, 0x0e, 0xa6, 0x24, 0x49, 0x08, 0x8b, 0xfd, 0x3c, 0xd8, 0xe2, + 0x65, 0xbc, 0xf8, 0xef, 0x91, 0x2d, 0x35, 0xf2, 0xb7, 0x66, 0x96, 0x77, 0xbb, 0xac, 0x3d, 0x28, + 0xb0, 0xfe, 0x1a, 0x80, 0x44, 0x40, 0x2e, 0x7c, 0x99, 0x69, 0x5d, 0x66, 0xda, 0xb9, 0x96, 0xe9, + 0xcb, 0xf2, 0xb7, 0x50, 0x0d, 0x75, 0xad, 0xb5, 0x2e, 0x64, 0xa8, 0x12, 0xc8, 0xe9, 0xee, 0xdb, + 0xcb, 0xb9, 0xa1, 0x5d, 0xcd, 0x0d, 0xed, 0xe7, 0xdc, 0xd0, 0x2e, 0x16, 0x46, 0xed, 0x6a, 0x61, + 0xd4, 0xbe, 0x2d, 0x8c, 0xda, 0x1b, 0x77, 0xe3, 0x06, 0xc5, 0x43, 0xea, 0x8f, 0x61, 0x90, 0x94, + 0x85, 0x33, 0x1d, 0x1c, 0x39, 0x1f, 0xff, 0xf6, 0xbf, 0x20, 0x6f, 0x18, 0xec, 0x48, 0x6f, 0xcf, + 0x7f, 0x05, 0x00, 0x00, 0xff, 0xff, 0x95, 0x8c, 0x40, 0x92, 0x46, 0x04, 0x00, 0x00, } func (m *IncentiveRecord) Marshal() (dAtA []byte, err error) { diff --git a/x/concentrated-liquidity/types/params.go b/x/concentrated-liquidity/types/params.go index ca9dc0a5f91..e13ccd2bb09 100644 --- a/x/concentrated-liquidity/types/params.go +++ b/x/concentrated-liquidity/types/params.go @@ -11,7 +11,7 @@ import ( // Parameter store keys. var ( KeyAuthorizedTickSpacing = []byte("AuthorizedTickSpacing") - KeyAuthorizedSwapFees = []byte("AuthorizedSwapFees") + KeyAuthorizedSpreadFactors = []byte("AuthorizedSpreadFactors") KeyDiscountRate = []byte("DiscountRate") KeyAuthorizedQuoteDenoms = []byte("AuthorizedQuoteDenoms") KeyAuthorizedUptimes = []byte("AuthorizedUptimes") @@ -25,10 +25,10 @@ func ParamKeyTable() paramtypes.KeyTable { return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) } -func NewParams(authorizedTickSpacing []uint64, authorizedSwapFees []sdk.Dec, discountRate sdk.Dec, authorizedQuoteDenoms []string, authorizedUptimes []time.Duration, isPermissionlessPoolCreationEnabled bool) Params { +func NewParams(authorizedTickSpacing []uint64, authorizedSpreadFactors []sdk.Dec, discountRate sdk.Dec, authorizedQuoteDenoms []string, authorizedUptimes []time.Duration, isPermissionlessPoolCreationEnabled bool) Params { return Params{ AuthorizedTickSpacing: authorizedTickSpacing, - AuthorizedSwapFees: authorizedSwapFees, + AuthorizedSpreadFactors: authorizedSpreadFactors, AuthorizedQuoteDenoms: authorizedQuoteDenoms, BalancerSharesRewardDiscount: discountRate, AuthorizedUptimes: authorizedUptimes, @@ -39,8 +39,8 @@ func NewParams(authorizedTickSpacing []uint64, authorizedSwapFees []sdk.Dec, dis // DefaultParams returns default concentrated-liquidity module parameters. func DefaultParams() Params { return Params{ - AuthorizedTickSpacing: AuthorizedTickSpacing, - AuthorizedSwapFees: AuthorizedSwapFees, + AuthorizedTickSpacing: AuthorizedTickSpacing, + AuthorizedSpreadFactors: AuthorizedSpreadFactors, AuthorizedQuoteDenoms: []string{ "uosmo", "ibc/0CD3A0285E1341859B5E86B6AB7682F023D03E97607CCC1DC95706411D866DF7", // DAI @@ -57,7 +57,7 @@ func (p Params) Validate() error { if err := validateTicks(p.AuthorizedTickSpacing); err != nil { return err } - if err := validateSwapFees(p.AuthorizedSwapFees); err != nil { + if err := validateSpreadFactors(p.AuthorizedSpreadFactors); err != nil { return err } if err := validateAuthorizedQuoteDenoms(p.AuthorizedQuoteDenoms); err != nil { @@ -79,7 +79,7 @@ func (p Params) Validate() error { func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { return paramtypes.ParamSetPairs{ paramtypes.NewParamSetPair(KeyAuthorizedTickSpacing, &p.AuthorizedTickSpacing, validateTicks), - paramtypes.NewParamSetPair(KeyAuthorizedSwapFees, &p.AuthorizedSwapFees, validateSwapFees), + paramtypes.NewParamSetPair(KeyAuthorizedSpreadFactors, &p.AuthorizedSpreadFactors, validateSpreadFactors), paramtypes.NewParamSetPair(KeyAuthorizedQuoteDenoms, &p.AuthorizedQuoteDenoms, validateAuthorizedQuoteDenoms), paramtypes.NewParamSetPair(KeyIsPermisionlessPoolCreationEnabled, &p.IsPermissionlessPoolCreationEnabled, validateIsPermissionLessPoolCreationEnabled), paramtypes.NewParamSetPair(KeyDiscountRate, &p.BalancerSharesRewardDiscount, validateBalancerSharesDiscount), @@ -125,9 +125,9 @@ func validateTicks(i interface{}) error { return nil } -// validateSwapFees validates that the given parameter is a slice of strings that can be converted to sdk.Decs. +// validateSpreadFactors validates that the given parameter is a slice of strings that can be converted to sdk.Decs. // If the parameter is not of the correct type or any of the strings cannot be converted, an error is returned. -func validateSwapFees(i interface{}) error { +func validateSpreadFactors(i interface{}) error { // Convert the given parameter to a slice of sdk.Decs. _, ok := i.([]sdk.Dec) if !ok { diff --git a/x/concentrated-liquidity/types/params.pb.go b/x/concentrated-liquidity/types/params.pb.go index 7795770a013..45c9dc14246 100644 --- a/x/concentrated-liquidity/types/params.pb.go +++ b/x/concentrated-liquidity/types/params.pb.go @@ -34,8 +34,8 @@ type Params struct { // spacing values concentrated-liquidity pools can be created with. For // example, an authorized_tick_spacing of [1, 10, 30] allows for pools // to be created with tick spacing of 1, 10, or 30. - AuthorizedTickSpacing []uint64 `protobuf:"varint,1,rep,packed,name=authorized_tick_spacing,json=authorizedTickSpacing,proto3" json:"authorized_tick_spacing,omitempty" yaml:"authorized_tick_spacing"` - AuthorizedSwapFees []github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,rep,name=authorized_swap_fees,json=authorizedSwapFees,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"authorized_swap_fees" yaml:"authorized_swap_fees"` + AuthorizedTickSpacing []uint64 `protobuf:"varint,1,rep,packed,name=authorized_tick_spacing,json=authorizedTickSpacing,proto3" json:"authorized_tick_spacing,omitempty" yaml:"authorized_tick_spacing"` + AuthorizedSpreadFactors []github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,rep,name=authorized_spread_factors,json=authorizedSpreadFactors,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"authorized_spread_factors" yaml:"authorized_spread_factors"` // balancer_shares_reward_discount is the rate by which incentives flowing // from CL to Balancer pools will be discounted to encourage LPs to migrate. // e.g. a rate of 0.05 means Balancer LPs get 5% less incentives than full @@ -128,42 +128,42 @@ func init() { } var fileDescriptor_cd3784445b6f6ba7 = []byte{ - // 547 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x93, 0xb1, 0x6f, 0xd3, 0x40, - 0x14, 0xc6, 0x63, 0xd2, 0x56, 0xd4, 0x4c, 0x58, 0x45, 0xb8, 0x05, 0xec, 0xc8, 0x48, 0x25, 0x12, - 0xc4, 0x16, 0x45, 0x2c, 0xb0, 0x99, 0xc0, 0x86, 0x14, 0x1c, 0x90, 0x50, 0x85, 0x74, 0x3a, 0xdb, - 0xaf, 0xce, 0x29, 0xb6, 0xcf, 0xf5, 0x3b, 0x13, 0xc2, 0xc2, 0x84, 0xc4, 0xc8, 0xc8, 0xc6, 0xbf, - 0xd3, 0xb1, 0x23, 0x62, 0x30, 0x28, 0xd9, 0x18, 0x33, 0x30, 0xa3, 0x9c, 0x9d, 0x26, 0xa5, 0x54, - 0xc0, 0x64, 0xbf, 0xf7, 0xfd, 0xde, 0xbb, 0xe7, 0xcf, 0xef, 0xd4, 0xdb, 0x1c, 0x13, 0x8e, 0x0c, - 0x9d, 0x80, 0xa7, 0x01, 0xa4, 0x22, 0xa7, 0x02, 0xc2, 0x4e, 0xcc, 0x0e, 0x0b, 0x16, 0x32, 0x31, - 0x76, 0x32, 0x9a, 0xd3, 0x04, 0xed, 0x2c, 0xe7, 0x82, 0x6b, 0x37, 0x6a, 0xd8, 0x5e, 0x85, 0x4f, - 0xd8, 0x9d, 0xad, 0x88, 0x47, 0x5c, 0x92, 0xce, 0xfc, 0xad, 0x2a, 0xda, 0xd9, 0x0e, 0x64, 0x15, - 0xa9, 0x84, 0x2a, 0xa8, 0x25, 0x23, 0xe2, 0x3c, 0x8a, 0xc1, 0x91, 0x91, 0x5f, 0x1c, 0x38, 0x61, - 0x91, 0x53, 0xc1, 0x78, 0x5a, 0xe9, 0xd6, 0xcf, 0x75, 0x75, 0xa3, 0x27, 0x07, 0xd0, 0xf6, 0xd5, - 0xab, 0xb4, 0x10, 0x03, 0x9e, 0xb3, 0xb7, 0x10, 0x12, 0xc1, 0x82, 0x21, 0xc1, 0x8c, 0x06, 0x2c, - 0x8d, 0x74, 0xa5, 0xd5, 0x6c, 0xaf, 0xb9, 0xd6, 0xac, 0x34, 0x8d, 0x31, 0x4d, 0xe2, 0x07, 0xd6, - 0x39, 0xa0, 0xe5, 0x5d, 0x59, 0x2a, 0xcf, 0x59, 0x30, 0xec, 0x57, 0x79, 0xed, 0x9d, 0xba, 0xb5, - 0x52, 0x82, 0x23, 0x9a, 0x91, 0x03, 0x00, 0xd4, 0x2f, 0xb4, 0x9a, 0xed, 0x4d, 0xf7, 0xe9, 0x51, - 0x69, 0x36, 0xbe, 0x96, 0xe6, 0x6e, 0xc4, 0xc4, 0xa0, 0xf0, 0xed, 0x80, 0x27, 0xf5, 0x57, 0xd4, - 0x8f, 0x0e, 0x86, 0x43, 0x47, 0x8c, 0x33, 0x40, 0xbb, 0x0b, 0xc1, 0xac, 0x34, 0xaf, 0x9d, 0x19, - 0xe3, 0xa4, 0xa7, 0xe5, 0x69, 0xcb, 0x74, 0x7f, 0x44, 0xb3, 0x27, 0x00, 0xa8, 0x7d, 0x56, 0x54, - 0xd3, 0xa7, 0x31, 0x4d, 0x03, 0xc8, 0x09, 0x0e, 0x68, 0x0e, 0x48, 0x72, 0x18, 0xd1, 0x3c, 0x24, - 0x21, 0xc3, 0x80, 0x17, 0xa9, 0xd0, 0x9b, 0x2d, 0xa5, 0xbd, 0xe9, 0xbe, 0xfc, 0xef, 0x61, 0x76, - 0xab, 0x61, 0xfe, 0xd2, 0xde, 0xf2, 0xae, 0x2f, 0x88, 0xbe, 0x04, 0x3c, 0xa9, 0x77, 0x6b, 0xf9, - 0x37, 0xfb, 0x0f, 0x0b, 0x2e, 0x80, 0x84, 0x90, 0xf2, 0x04, 0xf5, 0x35, 0xe9, 0xd2, 0x9f, 0xed, - 0x5f, 0x05, 0x4f, 0xd9, 0xff, 0x6c, 0x2e, 0x74, 0x65, 0x5e, 0x7b, 0xaf, 0xa8, 0x2b, 0xa6, 0x90, - 0x22, 0x13, 0x2c, 0x01, 0xd4, 0xd7, 0x5b, 0xcd, 0xf6, 0xa5, 0xbd, 0x6d, 0xbb, 0xda, 0x11, 0x7b, - 0xb1, 0x23, 0x76, 0xb7, 0xde, 0x11, 0xf7, 0xe1, 0xdc, 0x8b, 0x1f, 0xa5, 0xa9, 0x2d, 0xb6, 0xe6, - 0x0e, 0x4f, 0x98, 0x80, 0x24, 0x13, 0xe3, 0x59, 0x69, 0x6e, 0x9f, 0x19, 0xa6, 0x6e, 0x6c, 0x7d, - 0xfa, 0x66, 0x2a, 0xde, 0xe5, 0xa5, 0xf0, 0xa2, 0xca, 0x6b, 0x1f, 0x14, 0xf5, 0x16, 0x43, 0x92, - 0x41, 0x9e, 0x30, 0x44, 0xc6, 0xd3, 0x18, 0x10, 0x49, 0xc6, 0x79, 0x4c, 0x82, 0x1c, 0xe4, 0x09, - 0x04, 0x52, 0xea, 0xc7, 0x10, 0xea, 0x1b, 0x2d, 0xa5, 0x7d, 0xd1, 0xdd, 0x9b, 0x95, 0xa6, 0x5d, - 0x9d, 0xf3, 0x8f, 0x85, 0x96, 0x77, 0x93, 0x61, 0xef, 0x14, 0xd8, 0xe3, 0x3c, 0x7e, 0x54, 0x63, - 0x8f, 0x2b, 0xca, 0x7d, 0x75, 0x34, 0x31, 0x94, 0xe3, 0x89, 0xa1, 0x7c, 0x9f, 0x18, 0xca, 0xc7, - 0xa9, 0xd1, 0x38, 0x9e, 0x1a, 0x8d, 0x2f, 0x53, 0xa3, 0xb1, 0xef, 0xae, 0xfc, 0xf8, 0xfa, 0x36, - 0x76, 0x62, 0xea, 0xe3, 0x22, 0x70, 0x5e, 0xdf, 0xbd, 0xef, 0xbc, 0x39, 0xef, 0x36, 0xcb, 0xc5, - 0xf0, 0x37, 0xa4, 0x97, 0xf7, 0x7e, 0x05, 0x00, 0x00, 0xff, 0xff, 0x68, 0x80, 0xbb, 0x53, 0xfc, - 0x03, 0x00, 0x00, + // 546 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x93, 0x31, 0x6f, 0xd3, 0x40, + 0x14, 0xc7, 0x63, 0x52, 0x22, 0x6a, 0x26, 0x2c, 0x10, 0x4e, 0x05, 0xb6, 0x65, 0xa4, 0x12, 0x09, + 0x6a, 0x8b, 0x22, 0x16, 0xd8, 0x4c, 0x60, 0x2e, 0x0e, 0x48, 0xa8, 0x42, 0x3a, 0x9d, 0xcf, 0x57, + 0xe7, 0x14, 0xdb, 0xcf, 0xbd, 0x3b, 0x03, 0x61, 0x07, 0x31, 0x21, 0x46, 0x36, 0xbe, 0x4e, 0xc7, + 0x8e, 0x88, 0xc1, 0xa0, 0x64, 0x63, 0xcc, 0x27, 0x40, 0x39, 0x3b, 0xd4, 0xa1, 0x54, 0xc0, 0x64, + 0xbf, 0xf7, 0xff, 0xbd, 0x77, 0xef, 0xde, 0x7b, 0xa7, 0xdf, 0x02, 0x91, 0x81, 0x60, 0xc2, 0x27, + 0x90, 0x13, 0x9a, 0x4b, 0x8e, 0x25, 0x8d, 0x77, 0x52, 0x76, 0x58, 0xb2, 0x98, 0xc9, 0xa9, 0x5f, + 0x60, 0x8e, 0x33, 0xe1, 0x15, 0x1c, 0x24, 0x18, 0xd7, 0x1b, 0xd8, 0x6b, 0xc3, 0xbf, 0xd8, 0xad, + 0xcb, 0x09, 0x24, 0xa0, 0x48, 0x7f, 0xf9, 0x57, 0x07, 0x6d, 0xf5, 0x89, 0x8a, 0x42, 0xb5, 0x50, + 0x1b, 0x8d, 0x64, 0x25, 0x00, 0x49, 0x4a, 0x7d, 0x65, 0x45, 0xe5, 0x81, 0x1f, 0x97, 0x1c, 0x4b, + 0x06, 0x79, 0xad, 0xbb, 0xef, 0x7a, 0x7a, 0x6f, 0x4f, 0x15, 0x60, 0xec, 0xeb, 0x57, 0x71, 0x29, + 0xc7, 0xc0, 0xd9, 0x1b, 0x1a, 0x23, 0xc9, 0xc8, 0x04, 0x89, 0x02, 0x13, 0x96, 0x27, 0xa6, 0xe6, + 0x74, 0x07, 0x1b, 0x81, 0xbb, 0xa8, 0x6c, 0x6b, 0x8a, 0xb3, 0xf4, 0xbe, 0x7b, 0x06, 0xe8, 0x86, + 0x57, 0x4e, 0x94, 0xa7, 0x8c, 0x4c, 0x46, 0xb5, 0xdf, 0xf8, 0xa0, 0xe9, 0xfd, 0x56, 0x8c, 0x28, + 0x38, 0xc5, 0x31, 0x3a, 0xc0, 0x44, 0x02, 0x17, 0xe6, 0x39, 0xa7, 0x3b, 0xd8, 0x0c, 0xc2, 0xa3, + 0xca, 0xee, 0x7c, 0xad, 0xec, 0xed, 0x84, 0xc9, 0x71, 0x19, 0x79, 0x04, 0xb2, 0xe6, 0x2e, 0xcd, + 0x67, 0x47, 0xc4, 0x13, 0x5f, 0x4e, 0x0b, 0x2a, 0xbc, 0x21, 0x25, 0x8b, 0xca, 0x76, 0x4e, 0x15, + 0xb3, 0x9e, 0xd8, 0x0d, 0x5b, 0x37, 0x1a, 0x29, 0xe9, 0x71, 0xad, 0x18, 0x9f, 0x35, 0xdd, 0x8e, + 0x70, 0x8a, 0x73, 0x42, 0x39, 0x12, 0x63, 0xcc, 0xa9, 0x40, 0x9c, 0xbe, 0xc2, 0x3c, 0x46, 0x31, + 0x13, 0x04, 0xca, 0x5c, 0x9a, 0x5d, 0x47, 0x1b, 0x6c, 0x06, 0xcf, 0xff, 0xbb, 0xac, 0xed, 0xba, + 0xac, 0xbf, 0xa4, 0x77, 0xc3, 0x6b, 0x2b, 0x62, 0xa4, 0x80, 0x50, 0xe9, 0xc3, 0x46, 0xfe, 0x6d, + 0x1c, 0x87, 0x25, 0x48, 0x8a, 0x62, 0x9a, 0x43, 0x26, 0xcc, 0x0d, 0xd5, 0xaf, 0x3f, 0x8f, 0xa3, + 0x0d, 0xae, 0x8d, 0xe3, 0xc9, 0x52, 0x18, 0x2a, 0xbf, 0xf1, 0x56, 0xd3, 0x8d, 0x56, 0x4c, 0x59, + 0x48, 0x96, 0x51, 0x61, 0x9e, 0x77, 0xba, 0x83, 0x8b, 0xbb, 0x7d, 0xaf, 0xde, 0x19, 0x6f, 0xb5, + 0x33, 0xde, 0xb0, 0xd9, 0x99, 0xe0, 0xc1, 0xb2, 0x17, 0x3f, 0x2a, 0xdb, 0x58, 0x6d, 0xd1, 0x6d, + 0xc8, 0x98, 0xa4, 0x59, 0x21, 0xa7, 0x8b, 0xca, 0xee, 0x9f, 0x2a, 0xa6, 0x49, 0xec, 0x7e, 0xfa, + 0x66, 0x6b, 0xe1, 0xa5, 0x13, 0xe1, 0x59, 0xed, 0x37, 0xde, 0x6b, 0xfa, 0x4d, 0x26, 0x50, 0x41, + 0x79, 0xc6, 0x84, 0x60, 0x90, 0xa7, 0x54, 0x08, 0x54, 0x00, 0xa4, 0x88, 0x70, 0xaa, 0x4e, 0x40, + 0x34, 0xc7, 0x51, 0x4a, 0x63, 0xb3, 0xe7, 0x68, 0x83, 0x0b, 0xc1, 0xee, 0xa2, 0xb2, 0xbd, 0xfa, + 0x9c, 0x7f, 0x0c, 0x74, 0xc3, 0x1b, 0x4c, 0xec, 0xad, 0x81, 0x7b, 0x00, 0xe9, 0xc3, 0x06, 0x7b, + 0x54, 0x53, 0xc1, 0x8b, 0xa3, 0x99, 0xa5, 0x1d, 0xcf, 0x2c, 0xed, 0xfb, 0xcc, 0xd2, 0x3e, 0xce, + 0xad, 0xce, 0xf1, 0xdc, 0xea, 0x7c, 0x99, 0x5b, 0x9d, 0xfd, 0xa0, 0x35, 0xf8, 0xe6, 0x75, 0xee, + 0xa4, 0x38, 0x12, 0x2b, 0xc3, 0x7f, 0x79, 0xe7, 0x9e, 0xff, 0xfa, 0xac, 0xd7, 0xad, 0x16, 0x23, + 0xea, 0xa9, 0x5e, 0xde, 0xfd, 0x19, 0x00, 0x00, 0xff, 0xff, 0x2a, 0x38, 0xad, 0x30, 0x0c, 0x04, + 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { @@ -227,12 +227,12 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { } i-- dAtA[i] = 0x1a - if len(m.AuthorizedSwapFees) > 0 { - for iNdEx := len(m.AuthorizedSwapFees) - 1; iNdEx >= 0; iNdEx-- { + if len(m.AuthorizedSpreadFactors) > 0 { + for iNdEx := len(m.AuthorizedSpreadFactors) - 1; iNdEx >= 0; iNdEx-- { { - size := m.AuthorizedSwapFees[iNdEx].Size() + size := m.AuthorizedSpreadFactors[iNdEx].Size() i -= size - if _, err := m.AuthorizedSwapFees[iNdEx].MarshalTo(dAtA[i:]); err != nil { + if _, err := m.AuthorizedSpreadFactors[iNdEx].MarshalTo(dAtA[i:]); err != nil { return 0, err } i = encodeVarintParams(dAtA, i, uint64(size)) @@ -286,8 +286,8 @@ func (m *Params) Size() (n int) { } n += 1 + sovParams(uint64(l)) + l } - if len(m.AuthorizedSwapFees) > 0 { - for _, e := range m.AuthorizedSwapFees { + if len(m.AuthorizedSpreadFactors) > 0 { + for _, e := range m.AuthorizedSpreadFactors { l = e.Size() n += 1 + l + sovParams(uint64(l)) } @@ -425,7 +425,7 @@ func (m *Params) Unmarshal(dAtA []byte) error { } case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AuthorizedSwapFees", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field AuthorizedSpreadFactors", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -454,8 +454,8 @@ func (m *Params) Unmarshal(dAtA []byte) error { return io.ErrUnexpectedEOF } var v github_com_cosmos_cosmos_sdk_types.Dec - m.AuthorizedSwapFees = append(m.AuthorizedSwapFees, v) - if err := m.AuthorizedSwapFees[len(m.AuthorizedSwapFees)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + m.AuthorizedSpreadFactors = append(m.AuthorizedSpreadFactors, v) + if err := m.AuthorizedSpreadFactors[len(m.AuthorizedSpreadFactors)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex diff --git a/x/gamm/README.md b/x/gamm/README.md index 40161de217a..db7617fb1fb 100644 --- a/x/gamm/README.md +++ b/x/gamm/README.md @@ -76,7 +76,7 @@ or positive number of LP shares. Otherwise transaction will be aborted and user will not be able to exit a pool. Therefore, it is not possible to "drain out" a pool. -When exiting a pool with a swap, both exit and swap fees are paid. +When exiting a pool with a swap, both exit and spread factors are paid. Existing Exit types: - ExitPool @@ -98,7 +98,7 @@ after the swap is denoted as `tokenOut` throughout the module. Given a `tokenIn`, the following calculations are done to calculate how many tokens are to be swapped into and removed from the pool: -`tokenBalanceOut * [1 - { tokenBalanceIn / (tokenBalanceIn + (1 - swapFee) * tokenAmountIn)} ^ (tokenWeightIn / tokenWeightOut)]` +`tokenBalanceOut * [1 - { tokenBalanceIn / (tokenBalanceIn + (1 - spreadFactor) * tokenAmountIn)} ^ (tokenWeightIn / tokenWeightOut)]` The calculation is also able to be reversed, the case where user provides `tokenOut`. The calculation for the amount of tokens that the @@ -112,10 +112,10 @@ Existing Swap types: #### Spot Price -Meanwhile, calculation of the spot price with a swap fee is done using +Meanwhile, calculation of the spot price with a spread factor is done using the following formula: -`spotPrice / (1 - swapFee)`, where `spotPrice` is defined as: +`spotPrice / (1 - spreadFactor)`, where `spotPrice` is defined as: `(tokenBalanceIn / tokenWeightIn) / (tokenBalanceOut / tokenWeightOut)` @@ -160,15 +160,15 @@ Pools have the following parameters: | Key | Type | | --------------------------| ----------------------------| -| SwapFee | sdk.Dec | +| SpreadFactor | sdk.Dec | | ExitFee | sdk.Dec | | FutureGovernor | \*FutureGovernor | | Weights | \*Weights | | SmoothWeightChangeParams | \*SmoothWeightChangeParams | | PoolCreationFee | sdk.Coins | -1. **SwapFee** - - The swap fee is the cut of all swaps that goes to the Liquidity Providers (LPs) for a pool. Suppose a pool has a swap fee `s`. Then if a user wants to swap `T` tokens in the pool, `sT` tokens go to the LP's, and then `(1 - s)T` tokens are swapped according to the AMM swap function. +1. **SpreadFactor** - + The spread factor is the cut of all swaps that goes to the Liquidity Providers (LPs) for a pool. Suppose a pool has a spread factor `s`. Then if a user wants to swap `T` tokens in the pool, `sT` tokens go to the LP's, and then `(1 - s)T` tokens are swapped according to the AMM swap function. 2. **ExitFee** - The exit fee is a fee that is applied to LP's that want to remove their liquidity from the pool. Suppose a pool has an exit fee `e`. If they currently have `S` LP shares, then when they remove their liquidity they get tokens worth `(1 - e)S` shares back. The remaining `eS` shares are then burned, and the tokens corresponding to these shares are kept as liquidity. 3. **FutureGovernor** - @@ -256,7 +256,7 @@ The JSON [config-file] must specify the following parameters: { "weights": [list weighted denoms], "initial-deposit": [list of denoms with initial deposit amount], - "swap-fee": [swap fee in percentage], + "swap-fee": [spread factor in percentage], "exit-fee": [exit fee in percentage], "future-governor": [see options in pool parameters section above] } diff --git a/x/gamm/client/cli/tx.go b/x/gamm/client/cli/tx.go index 6d0bbf05c24..34ecdb158e1 100644 --- a/x/gamm/client/cli/tx.go +++ b/x/gamm/client/cli/tx.go @@ -350,7 +350,7 @@ func NewBuildCreateBalancerPoolMsg(clientCtx client.Context, fs *flag.FlagSet) ( return nil, errors.New("deposit tokens and token weights should have same length") } - swapFee, err := sdk.NewDecFromStr(pool.SwapFee) + spreadFactor, err := sdk.NewDecFromStr(pool.SwapFee) if err != nil { return nil, err } @@ -373,7 +373,7 @@ func NewBuildCreateBalancerPoolMsg(clientCtx client.Context, fs *flag.FlagSet) ( } poolParams := &balancer.PoolParams{ - SwapFee: swapFee, + SwapFee: spreadFactor, ExitFee: exitFee, } @@ -445,7 +445,7 @@ func NewBuildCreateStableswapPoolMsg(clientCtx client.Context, fs *flag.FlagSet) return nil, err } - swapFee, err := sdk.NewDecFromStr(flags.SwapFee) + spreadFactor, err := sdk.NewDecFromStr(flags.SwapFee) if err != nil { return nil, err } @@ -456,7 +456,7 @@ func NewBuildCreateStableswapPoolMsg(clientCtx client.Context, fs *flag.FlagSet) } poolParams := &stableswap.PoolParams{ - SwapFee: swapFee, + SwapFee: spreadFactor, ExitFee: exitFee, } diff --git a/x/gamm/keeper/genesis_test.go b/x/gamm/keeper/genesis_test.go index 11dee61979d..25ffb2a70a1 100644 --- a/x/gamm/keeper/genesis_test.go +++ b/x/gamm/keeper/genesis_test.go @@ -59,7 +59,7 @@ func TestGammInitGenesis(t *testing.T) { require.NoError(t, err) require.Equal(t, balancerPool.GetId(), poolStored.GetId()) require.Equal(t, balancerPool.GetAddress(), poolStored.GetAddress()) - require.Equal(t, balancerPool.GetSwapFee(ctx), poolStored.GetSwapFee(ctx)) + require.Equal(t, balancerPool.GetSpreadFactor(ctx), poolStored.GetSpreadFactor(ctx)) require.Equal(t, balancerPool.GetExitFee(ctx), poolStored.GetExitFee(ctx)) // require.Equal(t, balancerPool.GetTotalWeight(), sdk.Nw) require.Equal(t, balancerPool.GetTotalShares(), poolStored.GetTotalShares()) diff --git a/x/gamm/keeper/grpc_query.go b/x/gamm/keeper/grpc_query.go index c2a17ffb596..bf81cfba6f5 100644 --- a/x/gamm/keeper/grpc_query.go +++ b/x/gamm/keeper/grpc_query.go @@ -160,7 +160,7 @@ func (q Querier) CalcJoinPoolShares(ctx context.Context, req *types.QueryCalcJoi return nil, err } - numShares, newLiquidity, err := pool.CalcJoinPoolShares(sdkCtx, req.TokensIn, pool.GetSwapFee(sdkCtx)) + numShares, newLiquidity, err := pool.CalcJoinPoolShares(sdkCtx, req.TokensIn, pool.GetSpreadFactor(sdkCtx)) if err != nil { return nil, err } @@ -276,7 +276,7 @@ func (q Querier) CalcJoinPoolNoSwapShares(ctx context.Context, req *types.QueryC return nil, err } - sharesOut, tokensJoined, err := pool.CalcJoinPoolNoSwapShares(sdkCtx, req.TokensIn, pool.GetSwapFee(sdkCtx)) + sharesOut, tokensJoined, err := pool.CalcJoinPoolNoSwapShares(sdkCtx, req.TokensIn, pool.GetSpreadFactor(sdkCtx)) if err != nil { return nil, err } diff --git a/x/gamm/keeper/grpc_query_test.go b/x/gamm/keeper/grpc_query_test.go index 87e0598e216..3286b8b1cba 100644 --- a/x/gamm/keeper/grpc_query_test.go +++ b/x/gamm/keeper/grpc_query_test.go @@ -95,7 +95,7 @@ func (s *KeeperTestSuite) TestCalcJoinPoolNoSwapShares() { queryClient := s.queryClient ctx := s.Ctx poolId := s.PrepareBalancerPool() - swapFee := sdk.ZeroDec() + spreadFactor := sdk.ZeroDec() testCases := []struct { name string @@ -157,7 +157,7 @@ func (s *KeeperTestSuite) TestCalcJoinPoolNoSwapShares() { err = s.App.InterfaceRegistry().UnpackAny(poolRes.Pool, &pool) s.Require().NoError(err) - numShares, numLiquidity, err := pool.CalcJoinPoolNoSwapShares(ctx, tc.tokensIn, swapFee) + numShares, numLiquidity, err := pool.CalcJoinPoolNoSwapShares(ctx, tc.tokensIn, spreadFactor) s.Require().NoError(err) s.Require().Equal(numShares, out.SharesOut) s.Require().Equal(numLiquidity, out.TokensOut) @@ -359,7 +359,7 @@ func (s *KeeperTestSuite) TestCalcJoinPoolShares() { queryClient := s.queryClient ctx := s.Ctx poolId := s.PrepareBalancerPool() - swapFee := sdk.ZeroDec() + spreadFactor := sdk.ZeroDec() testCases := []struct { name string @@ -421,7 +421,7 @@ func (s *KeeperTestSuite) TestCalcJoinPoolShares() { err = s.App.InterfaceRegistry().UnpackAny(poolRes.Pool, &pool) s.Require().NoError(err) - numShares, numLiquidity, err := pool.CalcJoinPoolShares(ctx, tc.tokensIn, swapFee) + numShares, numLiquidity, err := pool.CalcJoinPoolShares(ctx, tc.tokensIn, spreadFactor) s.Require().NoError(err) s.Require().Equal(numShares, out.ShareOutAmount) s.Require().Equal(numLiquidity, out.TokensOut) diff --git a/x/gamm/keeper/keeper_test.go b/x/gamm/keeper/keeper_test.go index 185c929dbcb..42804663683 100644 --- a/x/gamm/keeper/keeper_test.go +++ b/x/gamm/keeper/keeper_test.go @@ -20,8 +20,8 @@ type KeeperTestSuite struct { } var ( - defaultSwapFee = sdk.MustNewDecFromStr("0.025") - defaultZeroExitFee = sdk.ZeroDec() + defaultSpreadFactor = sdk.MustNewDecFromStr("0.025") + defaultZeroExitFee = sdk.ZeroDec() ) func TestKeeperTestSuite(t *testing.T) { diff --git a/x/gamm/keeper/pool_service.go b/x/gamm/keeper/pool_service.go index e2e53fc34d3..0509c00253b 100644 --- a/x/gamm/keeper/pool_service.go +++ b/x/gamm/keeper/pool_service.go @@ -167,7 +167,7 @@ func (k Keeper) JoinPoolNoSwap( } } - sharesOut, err = pool.JoinPoolNoSwap(ctx, neededLpLiquidity, pool.GetSwapFee(ctx)) + sharesOut, err = pool.JoinPoolNoSwap(ctx, neededLpLiquidity, pool.GetSpreadFactor(ctx)) if err != nil { return nil, sdk.ZeroInt(), err } @@ -236,7 +236,7 @@ func (k Keeper) JoinSwapExactAmountIn( return sdk.Int{}, err } - sharesOut, err = pool.JoinPool(ctx, tokensIn, pool.GetSwapFee(ctx)) + sharesOut, err = pool.JoinPool(ctx, tokensIn, pool.GetSpreadFactor(ctx)) switch { case err != nil: return sdk.ZeroInt(), err @@ -285,7 +285,7 @@ func (k Keeper) JoinSwapShareAmountOut( return sdk.Int{}, fmt.Errorf("pool with id %d does not support this kind of join", poolId) } - tokenInAmount, err = extendedPool.CalcTokenInShareAmountOut(ctx, tokenInDenom, shareOutAmount, pool.GetSwapFee(ctx)) + tokenInAmount, err = extendedPool.CalcTokenInShareAmountOut(ctx, tokenInDenom, shareOutAmount, pool.GetSpreadFactor(ctx)) if err != nil { return sdk.Int{}, err } @@ -362,14 +362,14 @@ func (k Keeper) ExitSwapShareAmountIn( if err != nil { return sdk.Int{}, err } - swapFee := pool.GetSwapFee(ctx) + spreadFactor := pool.GetSpreadFactor(ctx) tokenOutAmount = exitCoins.AmountOf(tokenOutDenom) for _, coin := range exitCoins { if coin.Denom == tokenOutDenom { continue } - swapOut, err := k.SwapExactAmountIn(ctx, sender, pool, coin, tokenOutDenom, sdk.ZeroInt(), swapFee) + swapOut, err := k.SwapExactAmountIn(ctx, sender, pool, coin, tokenOutDenom, sdk.ZeroInt(), spreadFactor) if err != nil { return sdk.Int{}, err } diff --git a/x/gamm/keeper/pool_service_test.go b/x/gamm/keeper/pool_service_test.go index 2a3e8d38232..103b36dc8cb 100644 --- a/x/gamm/keeper/pool_service_test.go +++ b/x/gamm/keeper/pool_service_test.go @@ -18,7 +18,7 @@ import ( var ( defaultPoolParams = balancer.PoolParams{ - SwapFee: defaultSwapFee, + SwapFee: defaultSpreadFactor, ExitFee: defaultZeroExitFee, } @@ -78,7 +78,7 @@ func (s *KeeperTestSuite) TestCreateBalancerPool() { emptySender: true, expectPass: false, }, { - name: "create a pool with negative swap fee", + name: "create a pool with negative spread factor", msg: balancer.NewMsgCreateBalancerPool(testAccount, balancer.PoolParams{ SwapFee: sdk.NewDecWithPrec(-1, 2), ExitFee: defaultZeroExitFee, @@ -293,7 +293,7 @@ func (s *KeeperTestSuite) TestInitializePool() { balancerPool, err := balancer.NewBalancerPool( defaultPoolId, balancer.PoolParams{ - SwapFee: defaultSwapFee, + SwapFee: defaultSpreadFactor, ExitFee: sdk.NewDecWithPrec(5, 1), }, defaultPoolAssets, @@ -831,7 +831,7 @@ func (s *KeeperTestSuite) TestActiveBalancerPool() { func (s *KeeperTestSuite) TestJoinSwapExactAmountInConsistency() { testCases := []struct { name string - poolSwapFee sdk.Dec + poolSpreadFactor sdk.Dec poolExitFee sdk.Dec tokensIn sdk.Coins shareOutMinAmount sdk.Int @@ -840,7 +840,7 @@ func (s *KeeperTestSuite) TestJoinSwapExactAmountInConsistency() { }{ { name: "single coin with zero swap and exit fees", - poolSwapFee: sdk.ZeroDec(), + poolSpreadFactor: sdk.ZeroDec(), poolExitFee: sdk.ZeroDec(), tokensIn: sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(1000000))), shareOutMinAmount: sdk.ZeroInt(), @@ -852,8 +852,8 @@ func (s *KeeperTestSuite) TestJoinSwapExactAmountInConsistency() { // // Ref: https://github.com/osmosis-labs/osmosis/issues/1196 // { - // name: "single coin with positive swap fee and zero exit fee", - // poolSwapFee: sdk.NewDecWithPrec(1, 2), + // name: "single coin with positive spread factor and zero exit fee", + // poolSpreadFactor: sdk.NewDecWithPrec(1, 2), // poolExitFee: sdk.ZeroDec(), // tokensIn: sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(1000000))), // shareOutMinAmount: sdk.ZeroInt(), @@ -884,7 +884,7 @@ func (s *KeeperTestSuite) TestJoinSwapExactAmountInConsistency() { }, }, balancer.PoolParams{ - SwapFee: tc.poolSwapFee, + SwapFee: tc.poolSpreadFactor, ExitFee: tc.poolExitFee, }, ) @@ -903,16 +903,16 @@ func (s *KeeperTestSuite) TestJoinSwapExactAmountInConsistency() { ) s.Require().NoError(err) - // require swapTokenOutAmt <= (tokenInAmt * (1 - tc.poolSwapFee)) - oneMinusSwapFee := sdk.OneDec().Sub(tc.poolSwapFee) - swapFeeAdjustedAmount := oneMinusSwapFee.MulInt(tc.tokensIn[0].Amount).RoundInt() - s.Require().True(tokenOutAmt.LTE(swapFeeAdjustedAmount)) + // require swapTokenOutAmt <= (tokenInAmt * (1 - tc.poolSpreadFactor)) + oneMinusSwapFee := sdk.OneDec().Sub(tc.poolSpreadFactor) + spreadFactorAdjustedAmount := oneMinusSwapFee.MulInt(tc.tokensIn[0].Amount).RoundInt() + s.Require().True(tokenOutAmt.LTE(spreadFactorAdjustedAmount)) // require swapTokenOutAmt + 10 > input s.Require().True( - swapFeeAdjustedAmount.Sub(tokenOutAmt).LTE(sdk.NewInt(10)), + spreadFactorAdjustedAmount.Sub(tokenOutAmt).LTE(sdk.NewInt(10)), "expected out amount %s, actual out amount %s", - swapFeeAdjustedAmount, tokenOutAmt, + spreadFactorAdjustedAmount, tokenOutAmt, ) }) } diff --git a/x/gamm/keeper/pool_test.go b/x/gamm/keeper/pool_test.go index 87b3ba6d0d1..961c6feb160 100644 --- a/x/gamm/keeper/pool_test.go +++ b/x/gamm/keeper/pool_test.go @@ -275,7 +275,7 @@ func (s *KeeperTestSuite) TestGetPoolAndPoke() { "weighted pool - change weights": { isPokePool: true, poolId: s.prepareCustomBalancerPool(defaultAcctFunds, startPoolWeightAssets, balancer.PoolParams{ - SwapFee: defaultSwapFee, + SwapFee: defaultSpreadFactor, ExitFee: defaultZeroExitFee, SmoothWeightChangeParams: &balancer.SmoothWeightChangeParams{ StartTime: time.Unix(startTime, 0), // start time is before block time so the weights should change @@ -289,7 +289,7 @@ func (s *KeeperTestSuite) TestGetPoolAndPoke() { poolId: s.prepareCustomStableswapPool( defaultAcctFunds, stableswap.PoolParams{ - SwapFee: defaultSwapFee, + SwapFee: defaultSpreadFactor, ExitFee: defaultZeroExitFee, }, sdk.NewCoins(sdk.NewCoin(defaultAcctFunds[0].Denom, defaultAcctFunds[0].Amount.QuoRaw(2)), sdk.NewCoin(defaultAcctFunds[1].Denom, defaultAcctFunds[1].Amount.QuoRaw(2))), @@ -490,7 +490,7 @@ func (s *KeeperTestSuite) TestSetStableSwapScalingFactors() { poolId := s.prepareCustomStableswapPool( defaultAcctFunds, stableswap.PoolParams{ - SwapFee: defaultSwapFee, + SwapFee: defaultSpreadFactor, ExitFee: defaultZeroExitFee, }, sdk.NewCoins(sdk.NewCoin(defaultAcctFunds[0].Denom, defaultAcctFunds[0].Amount.QuoRaw(2)), sdk.NewCoin(defaultAcctFunds[1].Denom, defaultAcctFunds[1].Amount.QuoRaw(2))), diff --git a/x/gamm/keeper/swap.go b/x/gamm/keeper/swap.go index 776fac54ca0..04a99cff1b8 100644 --- a/x/gamm/keeper/swap.go +++ b/x/gamm/keeper/swap.go @@ -13,10 +13,10 @@ import ( ) // swapExactAmountIn is an internal method for swapping an exact amount of tokens -// as input to a pool, using the provided swapFee. This is intended to allow -// different swap fees as determined by multi-hops, or when recovering from +// as input to a pool, using the provided spreadFactor. This is intended to allow +// different spread factors as determined by multi-hops, or when recovering from // chain liveness failures. -// TODO: investigate if swapFee can be unexported +// TODO: investigate if spreadFactor can be unexported // https://github.com/osmosis-labs/osmosis/issues/3130 func (k Keeper) SwapExactAmountIn( ctx sdk.Context, @@ -25,14 +25,14 @@ func (k Keeper) SwapExactAmountIn( tokenIn sdk.Coin, tokenOutDenom string, tokenOutMinAmount sdk.Int, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (tokenOutAmount sdk.Int, err error) { if tokenIn.Denom == tokenOutDenom { return sdk.Int{}, errors.New("cannot trade same denomination in and out") } - poolSwapFee := pool.GetSwapFee(ctx) - if swapFee.LT(poolSwapFee.QuoInt64(2)) { - return sdk.Int{}, fmt.Errorf("given swap fee (%s) must be greater than or equal to half of the pool's swap fee (%s)", swapFee, poolSwapFee) + poolSpreadFactor := pool.GetSpreadFactor(ctx) + if spreadFactor.LT(poolSpreadFactor.QuoInt64(2)) { + return sdk.Int{}, fmt.Errorf("given spread factor (%s) must be greater than or equal to half of the pool's spread factor (%s)", spreadFactor, poolSpreadFactor) } tokensIn := sdk.Coins{tokenIn} @@ -50,7 +50,7 @@ func (k Keeper) SwapExactAmountIn( // Executes the swap in the pool and stores the output. Updates pool assets but // does not actually transfer any tokens to or from the pool. - tokenOutCoin, err := cfmmPool.SwapOutAmtGivenIn(ctx, tokensIn, tokenOutDenom, swapFee) + tokenOutCoin, err := cfmmPool.SwapOutAmtGivenIn(ctx, tokensIn, tokenOutDenom, spreadFactor) if err != nil { return sdk.Int{}, err } @@ -75,8 +75,8 @@ func (k Keeper) SwapExactAmountIn( } // SwapExactAmountOut is a method for swapping to get an exact number of tokens out of a pool, -// using the provided swapFee. -// This is intended to allow different swap fees as determined by multi-hops, +// using the provided spreadFactor. +// This is intended to allow different spread factors as determined by multi-hops, // or when recovering from chain liveness failures. func (k Keeper) SwapExactAmountOut( ctx sdk.Context, @@ -85,7 +85,7 @@ func (k Keeper) SwapExactAmountOut( tokenInDenom string, tokenInMaxAmount sdk.Int, tokenOut sdk.Coin, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (tokenInAmount sdk.Int, err error) { if tokenInDenom == tokenOut.Denom { return sdk.Int{}, errors.New("cannot trade same denomination in and out") @@ -113,7 +113,7 @@ func (k Keeper) SwapExactAmountOut( return sdk.Int{}, err } - tokenIn, err := cfmmPool.SwapInAmtGivenOut(ctx, sdk.Coins{tokenOut}, tokenInDenom, swapFee) + tokenIn, err := cfmmPool.SwapInAmtGivenOut(ctx, sdk.Coins{tokenOut}, tokenInDenom, spreadFactor) if err != nil { return sdk.Int{}, err } @@ -141,13 +141,13 @@ func (k Keeper) CalcOutAmtGivenIn( poolI poolmanagertypes.PoolI, tokenIn sdk.Coin, tokenOutDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (tokenOut sdk.Coin, err error) { cfmmPool, err := convertToCFMMPool(poolI) if err != nil { return sdk.Coin{}, err } - return cfmmPool.CalcOutAmtGivenIn(ctx, sdk.NewCoins(tokenIn), tokenOutDenom, swapFee) + return cfmmPool.CalcOutAmtGivenIn(ctx, sdk.NewCoins(tokenIn), tokenOutDenom, spreadFactor) } // CalcInAmtGivenOut calculates the amount of tokenIn given tokenOut and the pool's current state. @@ -157,13 +157,13 @@ func (k Keeper) CalcInAmtGivenOut( poolI poolmanagertypes.PoolI, tokenOut sdk.Coin, tokenInDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (tokenIn sdk.Coin, err error) { cfmmPool, err := convertToCFMMPool(poolI) if err != nil { return sdk.Coin{}, err } - return cfmmPool.CalcInAmtGivenOut(ctx, sdk.NewCoins(tokenOut), tokenInDenom, swapFee) + return cfmmPool.CalcInAmtGivenOut(ctx, sdk.NewCoins(tokenOut), tokenInDenom, spreadFactor) } // updatePoolForSwap takes a pool, sender, and tokenIn, tokenOut amounts diff --git a/x/gamm/keeper/swap_test.go b/x/gamm/keeper/swap_test.go index 1b7d9979a30..d81433c714b 100644 --- a/x/gamm/keeper/swap_test.go +++ b/x/gamm/keeper/swap_test.go @@ -26,14 +26,14 @@ func (s *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountIn() { tests := []struct { name string param param - // Note: by default swap fee is zero in all tests + // Note: by default spread factor is zero in all tests // It is only set to non-zero when this overwrite is non-nil - swapFeeOverwrite sdk.Dec - // Note: this is the value by which the original swap fee is divided + spreadFactorOverwrite sdk.Dec + // Note: this is the value by which the original spread factor is divided // by if it is non-nil. This is done to test the case where the given - // parameter swap fee is reduced by more than allowed (max factor of 0.5) - swapFeeOverwriteQuotient sdk.Dec - expectPass bool + // parameter spread factor is reduced by more than allowed (max factor of 0.5) + spreadFactorOverwriteQuotient sdk.Dec + expectPass bool }{ { name: "Proper swap", @@ -56,28 +56,28 @@ func (s *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountIn() { expectPass: true, }, { - name: "boundary valid swap fee given (= 0.5 pool swap fee)", + name: "boundary valid spread factor given (= 0.5 pool spread factor)", param: param{ tokenIn: sdk.NewCoin("foo", sdk.NewInt(100000)), tokenOutDenom: "bar", tokenOutMinAmount: sdk.NewInt(1), expectedTokenOut: sdk.NewInt(46833), }, - swapFeeOverwrite: sdk.MustNewDecFromStr("0.1"), - swapFeeOverwriteQuotient: sdk.MustNewDecFromStr("2"), - expectPass: true, + spreadFactorOverwrite: sdk.MustNewDecFromStr("0.1"), + spreadFactorOverwriteQuotient: sdk.MustNewDecFromStr("2"), + expectPass: true, }, { - name: "invalid swap fee given (< 0.5 pool swap fee)", + name: "invalid spread factor given (< 0.5 pool spread factor)", param: param{ tokenIn: sdk.NewCoin("foo", sdk.NewInt(100000)), tokenOutDenom: "bar", tokenOutMinAmount: sdk.NewInt(1), expectedTokenOut: sdk.NewInt(49262), }, - swapFeeOverwrite: sdk.MustNewDecFromStr("0.1"), - swapFeeOverwriteQuotient: sdk.MustNewDecFromStr("3"), - expectPass: false, + spreadFactorOverwrite: sdk.MustNewDecFromStr("0.1"), + spreadFactorOverwriteQuotient: sdk.MustNewDecFromStr("3"), + expectPass: false, }, { name: "out is lesser than min amount", @@ -122,16 +122,16 @@ func (s *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountIn() { s.Run(test.name, func() { // Init suite for each test. s.SetupTest() - swapFee := sdk.ZeroDec() - if !test.swapFeeOverwrite.IsNil() { - swapFee = test.swapFeeOverwrite + spreadFactor := sdk.ZeroDec() + if !test.spreadFactorOverwrite.IsNil() { + spreadFactor = test.spreadFactorOverwrite } poolId := s.PrepareBalancerPoolWithPoolParams(balancer.PoolParams{ - SwapFee: swapFee, + SwapFee: spreadFactor, ExitFee: sdk.ZeroDec(), }) - if !test.swapFeeOverwriteQuotient.IsNil() { - swapFee = swapFee.Quo(test.swapFeeOverwriteQuotient) + if !test.spreadFactorOverwriteQuotient.IsNil() { + spreadFactor = spreadFactor.Quo(test.spreadFactorOverwriteQuotient) } keeper := s.App.GAMMKeeper ctx := s.Ctx @@ -143,7 +143,7 @@ func (s *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountIn() { s.NoError(err, "test: %v", test.name) prevGasConsumed := s.Ctx.GasMeter().GasConsumed() - tokenOutAmount, err := keeper.SwapExactAmountIn(ctx, s.TestAccs[0], pool, test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount, swapFee) + tokenOutAmount, err := keeper.SwapExactAmountIn(ctx, s.TestAccs[0], pool, test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount, spreadFactor) s.NoError(err, "test: %v", test.name) s.Require().Equal(test.param.expectedTokenOut.String(), tokenOutAmount.String()) gasConsumedForSwap := s.Ctx.GasMeter().GasConsumed() - prevGasConsumed @@ -155,7 +155,7 @@ func (s *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountIn() { spotPriceAfter, err := keeper.CalculateSpotPrice(ctx, poolId, test.param.tokenIn.Denom, test.param.tokenOutDenom) s.NoError(err, "test: %v", test.name) - if !test.swapFeeOverwrite.IsNil() { + if !test.spreadFactorOverwrite.IsNil() { return } @@ -163,7 +163,7 @@ func (s *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountIn() { tradeAvgPrice := test.param.tokenIn.Amount.ToDec().Quo(tokenOutAmount.ToDec()) s.True(tradeAvgPrice.GT(spotPriceBefore) && tradeAvgPrice.LT(spotPriceAfter), "test: %v", test.name) } else { - _, err := keeper.SwapExactAmountIn(ctx, s.TestAccs[0], pool, test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount, swapFee) + _, err := keeper.SwapExactAmountIn(ctx, s.TestAccs[0], pool, test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount, spreadFactor) s.Error(err, "test: %v", test.name) } }) @@ -224,9 +224,9 @@ func (s *KeeperTestSuite) TestCalcOutAmtGivenIn() { pool = poolExt.(poolmanagertypes.PoolI) } - swapFee := pool.GetSwapFee(s.Ctx) + spreadFactor := pool.GetSpreadFactor(s.Ctx) - _, err := keeper.CalcOutAmtGivenIn(ctx, pool, test.param.tokenIn, test.param.tokenOutDenom, swapFee) + _, err := keeper.CalcOutAmtGivenIn(ctx, pool, test.param.tokenIn, test.param.tokenOutDenom, spreadFactor) if test.expectPass { s.Require().NoError(err) @@ -295,9 +295,9 @@ func (s *KeeperTestSuite) TestCalcInAmtGivenOut() { s.Require().NotNil(pool) - swapFee := pool.GetSwapFee(s.Ctx) + spreadFactor := pool.GetSpreadFactor(s.Ctx) - _, err = keeper.CalcInAmtGivenOut(ctx, pool, test.param.tokenOut, test.param.tokenInDenom, swapFee) + _, err = keeper.CalcInAmtGivenOut(ctx, pool, test.param.tokenOut, test.param.tokenInDenom, spreadFactor) if test.expectPass { s.Require().NoError(err) @@ -389,7 +389,7 @@ func (s *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountOut() { ctx := s.Ctx pool, err := s.App.GAMMKeeper.GetPool(s.Ctx, poolId) s.Require().NoError(err) - swapFee := pool.GetSwapFee(s.Ctx) + spreadFactor := pool.GetSpreadFactor(s.Ctx) if test.expectPass { spotPriceBefore, err := keeper.CalculateSpotPrice(ctx, poolId, test.param.tokenInDenom, test.param.tokenOut.Denom) @@ -397,7 +397,7 @@ func (s *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountOut() { prevGasConsumed := s.Ctx.GasMeter().GasConsumed() - tokenInAmount, err := keeper.SwapExactAmountOut(ctx, s.TestAccs[0], pool, test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut, swapFee) + tokenInAmount, err := keeper.SwapExactAmountOut(ctx, s.TestAccs[0], pool, test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut, spreadFactor) s.NoError(err, "test: %v", test.name) s.True(tokenInAmount.Equal(test.param.expectedTokenInAmount), "test: %v\n expect_eq actual: %s, expected: %s", @@ -415,7 +415,7 @@ func (s *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountOut() { tradeAvgPrice := tokenInAmount.ToDec().Quo(test.param.tokenOut.Amount.ToDec()) s.True(tradeAvgPrice.GT(spotPriceBefore) && tradeAvgPrice.LT(spotPriceAfter), "test: %v", test.name) } else { - _, err := keeper.SwapExactAmountOut(s.Ctx, s.TestAccs[0], pool, test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut, swapFee) + _, err := keeper.SwapExactAmountOut(s.Ctx, s.TestAccs[0], pool, test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut, spreadFactor) s.Error(err, "test: %v", test.name) } }) @@ -448,19 +448,19 @@ func (s *KeeperTestSuite) TestActiveBalancerPoolSwap() { s.Ctx = s.Ctx.WithBlockTime(tc.blockTime) pool, err := s.App.GAMMKeeper.GetPool(s.Ctx, poolId) s.Require().NoError(err) - swapFee := pool.GetSwapFee(s.Ctx) + spreadFactor := pool.GetSpreadFactor(s.Ctx) foocoin := sdk.NewCoin("foo", sdk.NewInt(10)) if tc.expectPass { - _, err := s.App.GAMMKeeper.SwapExactAmountIn(s.Ctx, s.TestAccs[0], pool, foocoin, "bar", sdk.ZeroInt(), swapFee) + _, err := s.App.GAMMKeeper.SwapExactAmountIn(s.Ctx, s.TestAccs[0], pool, foocoin, "bar", sdk.ZeroInt(), spreadFactor) s.Require().NoError(err) - _, err = s.App.GAMMKeeper.SwapExactAmountOut(s.Ctx, s.TestAccs[0], pool, "bar", sdk.NewInt(1000000000000000000), foocoin, swapFee) + _, err = s.App.GAMMKeeper.SwapExactAmountOut(s.Ctx, s.TestAccs[0], pool, "bar", sdk.NewInt(1000000000000000000), foocoin, spreadFactor) s.Require().NoError(err) } else { - _, err := s.App.GAMMKeeper.SwapExactAmountIn(s.Ctx, s.TestAccs[0], pool, foocoin, "bar", sdk.ZeroInt(), swapFee) + _, err := s.App.GAMMKeeper.SwapExactAmountIn(s.Ctx, s.TestAccs[0], pool, foocoin, "bar", sdk.ZeroInt(), spreadFactor) s.Require().Error(err) - _, err = s.App.GAMMKeeper.SwapExactAmountOut(s.Ctx, s.TestAccs[0], pool, "bar", sdk.NewInt(1000000000000000000), foocoin, swapFee) + _, err = s.App.GAMMKeeper.SwapExactAmountOut(s.Ctx, s.TestAccs[0], pool, "bar", sdk.NewInt(1000000000000000000), foocoin, spreadFactor) s.Require().Error(err) } } diff --git a/x/gamm/pool-models/balancer/amm.go b/x/gamm/pool-models/balancer/amm.go index 832a5f90286..7c7201a1c24 100644 --- a/x/gamm/pool-models/balancer/amm.go +++ b/x/gamm/pool-models/balancer/amm.go @@ -119,12 +119,12 @@ func calcPoolSharesOutGivenSingleAssetIn( normalizedTokenWeightIn, poolShares, tokenAmountIn, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) sdk.Dec { - // deduct swapfee on the in asset. - // We don't charge swap fee on the token amount that we imagine as unswapped (the normalized weight). - // So effective_swapfee = swapfee * (1 - normalized_token_weight) - tokenAmountInAfterFee := tokenAmountIn.Mul(feeRatio(normalizedTokenWeightIn, swapFee)) + // deduct spread factor on the in asset. + // We don't charge spread factor on the token amount that we imagine as unswapped (the normalized weight). + // So effective_swapfee = spread factor * (1 - normalized_token_weight) + tokenAmountInAfterFee := tokenAmountIn.Mul(feeRatio(normalizedTokenWeightIn, spreadFactor)) // To figure out the number of shares we add, first notice that in balancer we can treat // the number of shares as linearly related to the `k` value function. This is due to the normalization. // e.g. @@ -185,9 +185,9 @@ func updateIntermediaryPoolAssetsLiquidity(liquidity sdk.Coins, poolAssetsByDeno } // feeRatio returns the fee ratio that is defined as follows: -// 1 - ((1 - normalizedTokenWeightOut) * swapFee) -func feeRatio(normalizedWeight, swapFee sdk.Dec) sdk.Dec { - return sdk.OneDec().Sub((sdk.OneDec().Sub(normalizedWeight)).Mul(swapFee)) +// 1 - ((1 - normalizedTokenWeightOut) * spreadFactor) +func feeRatio(normalizedWeight, spreadFactor sdk.Dec) sdk.Dec { + return sdk.OneDec().Sub((sdk.OneDec().Sub(normalizedWeight)).Mul(spreadFactor)) } // calcSingleAssetInGivenPoolSharesOut returns token amount in with fee included @@ -197,13 +197,13 @@ func calcSingleAssetInGivenPoolSharesOut( normalizedTokenWeightIn, totalPoolSharesSupply, sharesAmountOut, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) sdk.Dec { // delta balanceIn is negative(tokens inside the pool increases) // pool weight is always 1 tokenAmountIn := solveConstantFunctionInvariant(totalPoolSharesSupply.Add(sharesAmountOut), totalPoolSharesSupply, sdk.OneDec(), tokenBalanceIn, normalizedTokenWeightIn).Neg() - // deduct swapfee on the in asset - tokenAmountInFeeIncluded := tokenAmountIn.Quo(feeRatio(normalizedTokenWeightIn, swapFee)) + // deduct spread factor on the in asset + tokenAmountInFeeIncluded := tokenAmountIn.Quo(feeRatio(normalizedTokenWeightIn, spreadFactor)) return tokenAmountInFeeIncluded } @@ -215,10 +215,10 @@ func calcPoolSharesInGivenSingleAssetOut( normalizedTokenWeightOut, totalPoolSharesSupply, tokenAmountOut, - swapFee, + spreadFactor, exitFee sdk.Dec, ) sdk.Dec { - tokenAmountOutFeeIncluded := tokenAmountOut.Quo(feeRatio(normalizedTokenWeightOut, swapFee)) + tokenAmountOutFeeIncluded := tokenAmountOut.Quo(feeRatio(normalizedTokenWeightOut, spreadFactor)) // delta poolSupply is positive(total pool shares decreases) // pool weight is always 1 diff --git a/x/gamm/pool-models/balancer/amm_test.go b/x/gamm/pool-models/balancer/amm_test.go index fcbe2cd7634..7db021a4094 100644 --- a/x/gamm/pool-models/balancer/amm_test.go +++ b/x/gamm/pool-models/balancer/amm_test.go @@ -21,33 +21,33 @@ func TestBalancerTestSuite(t *testing.T) { } func TestBalancerPoolParams(t *testing.T) { - // Tests that creating a pool with the given pair of swapfee and exit fee + // Tests that creating a pool with the given pair of spread factor and exit fee // errors or succeeds as intended. Furthermore, it checks that // NewPool panics in the error case. tests := []struct { - SwapFee sdk.Dec - ExitFee sdk.Dec - shouldErr bool + SpreadFactor sdk.Dec + ExitFee sdk.Dec + shouldErr bool }{ // Should work - {defaultSwapFee, defaultZeroExitFee, noErr}, - // Can't set the swap fee as negative + {defaultSpreadFactor, defaultZeroExitFee, noErr}, + // Can't set the spread factor as negative {sdk.NewDecWithPrec(-1, 2), defaultZeroExitFee, wantErr}, - // Can't set the swap fee as 1 + // Can't set the spread factor as 1 {sdk.NewDec(1), defaultZeroExitFee, wantErr}, - // Can't set the swap fee above 1 + // Can't set the spread factor above 1 {sdk.NewDecWithPrec(15, 1), defaultZeroExitFee, wantErr}, // Can't set the exit fee as negative - {defaultSwapFee, sdk.NewDecWithPrec(-1, 2), wantErr}, + {defaultSpreadFactor, sdk.NewDecWithPrec(-1, 2), wantErr}, // Can't set the exit fee as 1 - {defaultSwapFee, sdk.NewDec(1), wantErr}, + {defaultSpreadFactor, sdk.NewDec(1), wantErr}, // Can't set the exit fee above 1 - {defaultSwapFee, sdk.NewDecWithPrec(15, 1), wantErr}, + {defaultSpreadFactor, sdk.NewDecWithPrec(15, 1), wantErr}, } for i, params := range tests { PoolParams := balancer.PoolParams{ - SwapFee: params.SwapFee, + SwapFee: params.SpreadFactor, ExitFee: params.ExitFee, } err := PoolParams.Validate(dummyPoolAssets) diff --git a/x/gamm/pool-models/balancer/export_test.go b/x/gamm/pool-models/balancer/export_test.go index 784c2c5350a..edff7d4b8fe 100644 --- a/x/gamm/pool-models/balancer/export_test.go +++ b/x/gamm/pool-models/balancer/export_test.go @@ -18,10 +18,10 @@ var ( EnsureDenomInPool = ensureDenomInPool ) -func (p *Pool) CalcSingleAssetJoin(tokenIn sdk.Coin, swapFee sdk.Dec, tokenInPoolAsset PoolAsset, totalShares sdk.Int) (numShares sdk.Int, err error) { - return p.calcSingleAssetJoin(tokenIn, swapFee, tokenInPoolAsset, totalShares) +func (p *Pool) CalcSingleAssetJoin(tokenIn sdk.Coin, spreadFactor sdk.Dec, tokenInPoolAsset PoolAsset, totalShares sdk.Int) (numShares sdk.Int, err error) { + return p.calcSingleAssetJoin(tokenIn, spreadFactor, tokenInPoolAsset, totalShares) } -func (p *Pool) CalcJoinSingleAssetTokensIn(tokensIn sdk.Coins, totalSharesSoFar sdk.Int, poolAssetsByDenom map[string]PoolAsset, swapFee sdk.Dec) (sdk.Int, sdk.Coins, error) { - return p.calcJoinSingleAssetTokensIn(tokensIn, totalSharesSoFar, poolAssetsByDenom, swapFee) +func (p *Pool) CalcJoinSingleAssetTokensIn(tokensIn sdk.Coins, totalSharesSoFar sdk.Int, poolAssetsByDenom map[string]PoolAsset, spreadFactor sdk.Dec) (sdk.Int, sdk.Coins, error) { + return p.calcJoinSingleAssetTokensIn(tokensIn, totalSharesSoFar, poolAssetsByDenom, spreadFactor) } diff --git a/x/gamm/pool-models/balancer/marshal_test.go b/x/gamm/pool-models/balancer/marshal_test.go index 714f3cb7735..13a67fc0c40 100644 --- a/x/gamm/pool-models/balancer/marshal_test.go +++ b/x/gamm/pool-models/balancer/marshal_test.go @@ -27,7 +27,7 @@ func TestPoolJson(t *testing.T) { }, } pacc, err := balancer.NewBalancerPool(poolId, balancer.PoolParams{ - SwapFee: defaultSwapFee, + SwapFee: defaultSpreadFactor, ExitFee: defaultZeroExitFee, }, jsonAssetTest, defaultFutureGovernor, defaultCurBlockTime) require.NoError(t, err) @@ -54,7 +54,7 @@ func TestPoolProtoMarshal(t *testing.T) { require.NoError(t, err) require.Equal(t, pool2.Id, uint64(10)) - require.Equal(t, pool2.PoolParams.SwapFee, defaultSwapFee) + require.Equal(t, pool2.PoolParams.SwapFee, defaultSpreadFactor) require.Equal(t, pool2.PoolParams.ExitFee, sdk.MustNewDecFromStr("0.025")) require.Equal(t, pool2.FuturePoolGovernor, "") require.Equal(t, pool2.TotalShares, sdk.Coin{Denom: "gamm/pool/10", Amount: sdk.ZeroInt()}) diff --git a/x/gamm/pool-models/balancer/msgs_test.go b/x/gamm/pool-models/balancer/msgs_test.go index cdd363a2fd5..2c5336c558b 100644 --- a/x/gamm/pool-models/balancer/msgs_test.go +++ b/x/gamm/pool-models/balancer/msgs_test.go @@ -149,7 +149,7 @@ func TestMsgCreateBalancerPool_ValidateBasic(t *testing.T) { expectPass: false, }, { - name: "negative swap fee with zero exit fee", + name: "negative spread factor with zero exit fee", msg: createMsg(func(msg balancer.MsgCreateBalancerPool) balancer.MsgCreateBalancerPool { msg.PoolParams = &balancer.PoolParams{ SwapFee: sdk.NewDecWithPrec(-1, 2), @@ -192,7 +192,7 @@ func TestMsgCreateBalancerPool_ValidateBasic(t *testing.T) { expectPass: true, }, { - name: "zero swap fee, zero exit fee", + name: "zero spread factor, zero exit fee", msg: createMsg(func(msg balancer.MsgCreateBalancerPool) balancer.MsgCreateBalancerPool { msg.PoolParams = &balancer.PoolParams{ ExitFee: sdk.NewDecWithPrec(0, 0), @@ -258,7 +258,7 @@ func (s *KeeperTestSuite) TestMsgCreateBalancerPool() { }, poolId: 1, }, - "error due to negative swap fee": { + "error due to negative spread factor": { msg: balancer.MsgCreateBalancerPool{ Sender: s.TestAccs[0].String(), PoolParams: &balancer.PoolParams{SwapFee: sdk.NewDecWithPrec(1, 2).Neg(), ExitFee: sdk.ZeroDec()}, diff --git a/x/gamm/pool-models/balancer/pool.go b/x/gamm/pool-models/balancer/pool.go index c2172b06bac..78d52635e1e 100644 --- a/x/gamm/pool-models/balancer/pool.go +++ b/x/gamm/pool-models/balancer/pool.go @@ -88,7 +88,7 @@ func (p Pool) GetId() uint64 { return p.Id } -func (p Pool) GetSwapFee(_ sdk.Context) sdk.Dec { +func (p Pool) GetSpreadFactor(_ sdk.Context) sdk.Dec { return p.PoolParams.SwapFee } @@ -492,18 +492,18 @@ func (p Pool) CalcOutAmtGivenIn( ctx sdk.Context, tokensIn sdk.Coins, tokenOutDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (sdk.Coin, error) { tokenIn, poolAssetIn, poolAssetOut, err := p.parsePoolAssets(tokensIn, tokenOutDenom) if err != nil { return sdk.Coin{}, err } - tokenAmountInAfterFee := tokenIn.Amount.ToDec().Mul(sdk.OneDec().Sub(swapFee)) + tokenAmountInAfterFee := tokenIn.Amount.ToDec().Mul(sdk.OneDec().Sub(spreadFactor)) poolTokenInBalance := poolAssetIn.Token.Amount.ToDec() poolPostSwapInBalance := poolTokenInBalance.Add(tokenAmountInAfterFee) - // deduct swapfee on the tokensIn + // deduct spread factor on the tokensIn // delta balanceOut is positive(tokens inside the pool decreases) tokenAmountOut := solveConstantFunctionInvariant( poolTokenInBalance, @@ -527,11 +527,11 @@ func (p *Pool) SwapOutAmtGivenIn( ctx sdk.Context, tokensIn sdk.Coins, tokenOutDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) ( tokenOut sdk.Coin, err error, ) { - tokenOutCoin, err := p.CalcOutAmtGivenIn(ctx, tokensIn, tokenOutDenom, swapFee) + tokenOutCoin, err := p.CalcOutAmtGivenIn(ctx, tokensIn, tokenOutDenom, spreadFactor) if err != nil { return sdk.Coin{}, err } @@ -546,7 +546,7 @@ func (p *Pool) SwapOutAmtGivenIn( // CalcInAmtGivenOut calculates token to be provided, fee added, // given the swapped out amount, using solveConstantFunctionInvariant. func (p Pool) CalcInAmtGivenOut( - ctx sdk.Context, tokensOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) ( + ctx sdk.Context, tokensOut sdk.Coins, tokenInDenom string, spreadFactor sdk.Dec) ( tokenIn sdk.Coin, err error, ) { tokenOut, poolAssetOut, poolAssetIn, err := p.parsePoolAssets(tokensOut, tokenInDenom) @@ -562,11 +562,11 @@ func (p Pool) CalcInAmtGivenOut( poolTokenOutBalance, poolPostSwapOutBalance, poolAssetOut.Weight.ToDec(), poolAssetIn.Token.Amount.ToDec(), poolAssetIn.Weight.ToDec()).Neg() - // We deduct a swap fee on the input asset. The swap happens by following the invariant curve on the input * (1 - swap fee) - // and then the swap fee is added to the pool. - // Thus in order to give X amount out, we solve the invariant for the invariant input. However invariant input = (1 - swapfee) * trade input. - // Therefore we divide by (1 - swapfee) here - tokenAmountInBeforeFee := tokenAmountIn.Quo(sdk.OneDec().Sub(swapFee)) + // We deduct a spread factor on the input asset. The swap happens by following the invariant curve on the input * (1 - spread factor) + // and then the spread factor is added to the pool. + // Thus in order to give X amount out, we solve the invariant for the invariant input. However invariant input = (1 - spread factor) * trade input. + // Therefore we divide by (1 - spread factor) here + tokenAmountInBeforeFee := tokenAmountIn.Quo(sdk.OneDec().Sub(spreadFactor)) // We round up tokenInAmt, as this is whats charged for the swap, for the precise amount out. // Otherwise, the pool would under-charge by this rounding error. @@ -580,10 +580,10 @@ func (p Pool) CalcInAmtGivenOut( // SwapInAmtGivenOut is a mutative method for CalcOutAmtGivenIn, which includes the actual swap. func (p *Pool) SwapInAmtGivenOut( - ctx sdk.Context, tokensOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) ( + ctx sdk.Context, tokensOut sdk.Coins, tokenInDenom string, spreadFactor sdk.Dec) ( tokenIn sdk.Coin, err error, ) { - tokenInCoin, err := p.CalcInAmtGivenOut(ctx, tokensOut, tokenInDenom, swapFee) + tokenInCoin, err := p.CalcInAmtGivenOut(ctx, tokensOut, tokenInDenom, spreadFactor) if err != nil { return sdk.Coin{}, err } @@ -648,7 +648,7 @@ func (p Pool) SpotPrice(ctx sdk.Context, quoteAsset, baseAsset string) (spotPric } // calcPoolOutGivenSingleIn - balance pAo. -func (p *Pool) calcSingleAssetJoin(tokenIn sdk.Coin, swapFee sdk.Dec, tokenInPoolAsset PoolAsset, totalShares sdk.Int) (numShares sdk.Int, err error) { +func (p *Pool) calcSingleAssetJoin(tokenIn sdk.Coin, spreadFactor sdk.Dec, tokenInPoolAsset PoolAsset, totalShares sdk.Int) (numShares sdk.Int, err error) { _, err = p.GetPoolAsset(tokenIn.Denom) if err != nil { return sdk.ZeroInt(), err @@ -664,15 +664,15 @@ func (p *Pool) calcSingleAssetJoin(tokenIn sdk.Coin, swapFee sdk.Dec, tokenInPoo normalizedWeight, totalShares.ToDec(), tokenIn.Amount.ToDec(), - swapFee, + spreadFactor, ).TruncateInt(), nil } -// JoinPool calculates the number of shares needed given tokensIn with swapFee applied. +// JoinPool calculates the number of shares needed given tokensIn with spreadFactor applied. // It updates the liquidity if the pool is joined successfully. If not, returns error. // and updates pool accordingly. -func (p *Pool) JoinPool(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, err error) { - numShares, newLiquidity, err := p.CalcJoinPoolShares(ctx, tokensIn, swapFee) +func (p *Pool) JoinPool(ctx sdk.Context, tokensIn sdk.Coins, spreadFactor sdk.Dec) (numShares sdk.Int, err error) { + numShares, newLiquidity, err := p.CalcJoinPoolShares(ctx, tokensIn, spreadFactor) if err != nil { return sdk.Int{}, err } @@ -682,10 +682,10 @@ func (p *Pool) JoinPool(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (n return numShares, nil } -// JoinPoolNoSwap calculates the number of shares needed for an all-asset join given tokensIn with swapFee applied. +// JoinPoolNoSwap calculates the number of shares needed for an all-asset join given tokensIn with spreadFactor applied. // It updates the liquidity if the pool is joined successfully. If not, returns error. -func (p *Pool) JoinPoolNoSwap(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, err error) { - numShares, tokensJoined, err := p.CalcJoinPoolNoSwapShares(ctx, tokensIn, swapFee) +func (p *Pool) JoinPoolNoSwap(ctx sdk.Context, tokensIn sdk.Coins, spreadFactor sdk.Dec) (numShares sdk.Int, err error) { + numShares, tokensJoined, err := p.CalcJoinPoolNoSwapShares(ctx, tokensIn, spreadFactor) if err != nil { return sdk.Int{}, err } @@ -702,14 +702,14 @@ func (p *Pool) JoinPoolNoSwap(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.D // // It returns the number of shares created, the amount of coins actually joined into the pool // (in case of not being able to fully join), or an error. -func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, tokensJoined sdk.Coins, err error) { +func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, spreadFactor sdk.Dec) (numShares sdk.Int, tokensJoined sdk.Coins, err error) { // 1) Get pool current liquidity + and token weights // 2) If single token provided, do single asset join and exit. // 3) If multi-asset join, first do as much of a join as we can with no swaps. // 4) Update pool shares / liquidity / remaining tokens to join accordingly // 5) For every remaining token to LP, do a single asset join, and update pool shares / liquidity. // - // Note that all single asset joins do incur swap fee. + // Note that all single asset joins do incur spread factor. // // Since CalcJoinPoolShares is non-mutative, the steps for updating pool shares / liquidity are // more complex / don't just alter the state. @@ -730,7 +730,7 @@ func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee s totalShares := p.GetTotalShares() if tokensIn.Len() == 1 { // 2) Single token provided, so do single asset join and exit. - numShares, err = p.calcSingleAssetJoin(tokensIn[0], swapFee, poolAssetsByDenom[tokensIn[0].Denom], totalShares) + numShares, err = p.calcSingleAssetJoin(tokensIn[0], spreadFactor, poolAssetsByDenom[tokensIn[0].Denom], totalShares) if err != nil { return sdk.ZeroInt(), sdk.NewCoins(), err } @@ -745,7 +745,7 @@ func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee s // * numShares is how many shares are perfectly matched. // * remainingTokensIn is how many coins we have left to join, that have not already been used. // if remaining coins is empty, logic is done (we joined all tokensIn) - numShares, tokensJoined, err = p.CalcJoinPoolNoSwapShares(ctx, tokensIn, swapFee) + numShares, tokensJoined, err = p.CalcJoinPoolNoSwapShares(ctx, tokensIn, spreadFactor) if err != nil { return sdk.ZeroInt(), sdk.NewCoins(), err } @@ -769,7 +769,7 @@ func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee s // 5) Now single asset join each remaining coin. remainingTokensIn := tokensIn.Sub(tokensJoined) - newNumSharesFromRemaining, newLiquidityFromRemaining, err := p.calcJoinSingleAssetTokensIn(remainingTokensIn, newTotalShares, poolAssetsByDenom, swapFee) + newNumSharesFromRemaining, newLiquidityFromRemaining, err := p.calcJoinSingleAssetTokensIn(remainingTokensIn, newTotalShares, poolAssetsByDenom, spreadFactor) if err != nil { return sdk.ZeroInt(), sdk.NewCoins(), err } @@ -793,7 +793,7 @@ func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee s // Since CalcJoinPoolNoSwapShares is non-mutative, the steps for updating pool shares / liquidity are // more complex / don't just alter the state. // We should simplify this logic further in the future using multi-join equations. -func (p *Pool) CalcJoinPoolNoSwapShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, tokensJoined sdk.Coins, err error) { +func (p *Pool) CalcJoinPoolNoSwapShares(ctx sdk.Context, tokensIn sdk.Coins, spreadFactor sdk.Dec) (numShares sdk.Int, tokensJoined sdk.Coins, err error) { // get all 'pool assets' (aka current pool liquidity + balancer weight) poolAssetsByDenom, err := getPoolAssetsByDenom(p.GetAllPoolAssets()) if err != nil { @@ -829,17 +829,17 @@ func (p *Pool) CalcJoinPoolNoSwapShares(ctx sdk.Context, tokensIn sdk.Coins, swa // calcJoinSingleAssetTokensIn attempts to calculate single // asset join for all tokensIn given totalShares in pool, -// poolAssetsByDenom and swapFee. totalShares is the number +// poolAssetsByDenom and spreadFactor. totalShares is the number // of shares in pool before beginnning to join any of the tokensIn. // // Returns totalNewShares and totalNewLiquidity from joining all tokensIn // by mimicking individually single asset joining each. // or error if fails to calculate join for any of the tokensIn. -func (p *Pool) calcJoinSingleAssetTokensIn(tokensIn sdk.Coins, totalShares sdk.Int, poolAssetsByDenom map[string]PoolAsset, swapFee sdk.Dec) (sdk.Int, sdk.Coins, error) { +func (p *Pool) calcJoinSingleAssetTokensIn(tokensIn sdk.Coins, totalShares sdk.Int, poolAssetsByDenom map[string]PoolAsset, spreadFactor sdk.Dec) (sdk.Int, sdk.Coins, error) { totalNewShares := sdk.ZeroInt() totalNewLiquidity := sdk.NewCoins() for _, coin := range tokensIn { - newShares, err := p.calcSingleAssetJoin(coin, swapFee, poolAssetsByDenom[coin.Denom], totalShares.Add(totalNewShares)) + newShares, err := p.calcSingleAssetJoin(coin, spreadFactor, poolAssetsByDenom[coin.Denom], totalShares.Add(totalNewShares)) if err != nil { return sdk.ZeroInt(), sdk.Coins{}, err } @@ -885,7 +885,7 @@ func (p *Pool) CalcTokenInShareAmountOut( ctx sdk.Context, tokenInDenom string, shareOutAmount sdk.Int, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (tokenInAmount sdk.Int, err error) { _, poolAssetIn, err := p.getPoolAssetAndIndex(tokenInDenom) if err != nil { @@ -901,7 +901,7 @@ func (p *Pool) CalcTokenInShareAmountOut( normalizedWeight, p.GetTotalShares().ToDec(), shareOutAmount.ToDec(), - swapFee, + spreadFactor, ).Ceil().TruncateInt() if !tokenInAmount.IsPositive() { @@ -928,7 +928,7 @@ func (p *Pool) JoinPoolTokenInMaxShareAmountOut( normalizedWeight, p.GetTotalShares().ToDec(), shareOutAmount.ToDec(), - p.GetSwapFee(ctx), + p.GetSpreadFactor(ctx), ).TruncateInt() if !tokenInAmount.IsPositive() { @@ -959,7 +959,7 @@ func (p *Pool) ExitSwapExactAmountOut( poolAssetOut.Weight.ToDec().Quo(p.TotalWeight.ToDec()), p.GetTotalShares().ToDec(), tokenOut.Amount.ToDec(), - p.GetSwapFee(ctx), + p.GetSpreadFactor(ctx), p.GetExitFee(ctx), ).TruncateInt() diff --git a/x/gamm/pool-models/balancer/pool_params.go b/x/gamm/pool-models/balancer/pool_params.go index cfbf3d0d4d3..f2bbbd2e84d 100644 --- a/x/gamm/pool-models/balancer/pool_params.go +++ b/x/gamm/pool-models/balancer/pool_params.go @@ -8,9 +8,9 @@ import ( "github.com/osmosis-labs/osmosis/v15/x/gamm/types" ) -func NewPoolParams(swapFee, exitFee sdk.Dec, params *SmoothWeightChangeParams) PoolParams { +func NewPoolParams(spreadFactor, exitFee sdk.Dec, params *SmoothWeightChangeParams) PoolParams { return PoolParams{ - SwapFee: swapFee, + SwapFee: spreadFactor, ExitFee: exitFee, SmoothWeightChangeParams: params, } @@ -26,11 +26,11 @@ func (params PoolParams) Validate(poolWeights []PoolAsset) error { } if params.SwapFee.IsNegative() { - return types.ErrNegativeSwapFee + return types.ErrNegativeSpreadFactor } if params.SwapFee.GTE(sdk.OneDec()) { - return types.ErrTooMuchSwapFee + return types.ErrTooMuchSpreadFactor } if params.SmoothWeightChangeParams != nil { @@ -69,7 +69,7 @@ func (params PoolParams) Validate(poolWeights []PoolAsset) error { return nil } -func (params PoolParams) GetPoolSwapFee() sdk.Dec { +func (params PoolParams) GetPoolSpreadFactor() sdk.Dec { return params.SwapFee } diff --git a/x/gamm/pool-models/balancer/pool_suite_test.go b/x/gamm/pool-models/balancer/pool_suite_test.go index 2a63eafdfe1..c2dde1500a3 100644 --- a/x/gamm/pool-models/balancer/pool_suite_test.go +++ b/x/gamm/pool-models/balancer/pool_suite_test.go @@ -54,7 +54,7 @@ var ( // CalcJoinPoolShares with only one tokensIn. type calcJoinSharesTestCase struct { name string - swapFee sdk.Dec + spreadFactor sdk.Dec poolAssets []balancer.PoolAsset tokensIn sdk.Coins expectShares sdk.Int @@ -79,15 +79,15 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100000000000000000000*%28%281+%2B+%2850000%2F1000000000000%29%29%5E0.5+-+1%29 // Simplified: P_issued = 2,499,999,968,750 - name: "single tokensIn - equal weights with zero swap fee", - swapFee: sdk.MustNewDecFromStr("0"), + name: "single tokensIn - equal weights with zero spread factor", + spreadFactor: sdk.MustNewDecFromStr("0"), poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000)), expectShares: sdk.NewInt(2_499_999_968_750), }, { // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) on page 10: - // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) + // P_issued = P_supply * ((1 + (A_t * spreadFactorRatio / B_t))^W_t - 1) // // 2_487_500_000_000 = 1e20 * (( 1 + (50,000 * (1 - (1 - 0.5) * 0.01) / 1e12))^0.5 - 1) // @@ -96,19 +96,19 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ // A_t = amount of deposited asset = 50,000 // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 // W_t = normalized weight of deposited asset in pool = 0.5 (equally weighted two-asset pool) - // swapFeeRatio = (1 - (1 - W_t) * swapFee) + // spreadFactorRatio = (1 - (1 - W_t) * spreadFactor) // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-0.5%29+*+0.01%29%2F1000000000000%29%29%5E0.5+-+1%29 // Simplified: P_issued = 2_487_500_000_000 - name: "single tokensIn - equal weights with 0.01 swap fee", - swapFee: sdk.MustNewDecFromStr("0.01"), + name: "single tokensIn - equal weights with 0.01 spread factor", + spreadFactor: sdk.MustNewDecFromStr("0.01"), poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000)), expectShares: sdk.NewInt(2_487_500_000_000), }, { // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) on page 10: - // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) + // P_issued = P_supply * ((1 + (A_t * spreadFactorRatio / B_t))^W_t - 1) // // 1_262_500_000_000 = 1e20 * (( 1 + (50,000 * (1 - (1 - 0.5) * 0.99) / 1e12))^0.5 - 1) // @@ -117,19 +117,19 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ // A_t = amount of deposited asset = 50,000 // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 // W_t = normalized weight of deposited asset in pool = 0.5 (equal weights) - // swapFeeRatio = (1 - (1 - W_t) * swapFee) + // spreadFactorRatio = (1 - (1 - W_t) * spreadFactor) // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=%28100+*+10%5E18+%29*+%28%28+1+%2B+%2850%2C000+*+%281+-+%281+-+0.5%29+*+0.99%29+%2F+1000000000000%29%29%5E0.5+-+1%29 // Simplified: P_issued = 1_262_500_000_000 - name: "single tokensIn - equal weights with 0.99 swap fee", - swapFee: sdk.MustNewDecFromStr("0.99"), + name: "single tokensIn - equal weights with 0.99 spread factor", + spreadFactor: sdk.MustNewDecFromStr("0.99"), poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000)), expectShares: sdk.NewInt(1_262_500_000_000), }, { // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) on page 10: - // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) + // P_issued = P_supply * ((1 + (A_t * spreadFactorRatio / B_t))^W_t - 1) // // 321_875_000_000 = 1e20 * (( 1 + (50,000 * (1 - (1 - 0.25) * 0.99) / 1e12))^0.25 - 1) // @@ -138,12 +138,12 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ // A_t = amount of deposited asset = 50,000 // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 // W_t = normalized weight of deposited asset in pool = 0.25 (asset A, uosmo, has weight 1/4 of uatom) - // swapFeeRatio = (1 - (1 - W_t) * swapFee) + // spreadFactorRatio = (1 - (1 - W_t) * spreadFactor) // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=%28100+*+10%5E18+%29*+%28%28+1+%2B+%2850%2C000+*+%281+-+%281+-+0.25%29+*+0.99%29+%2F+1000000000000%29%29%5E0.25+-+1%29 // Simplified: P_issued = 321_875_000_000 - name: "single tokensIn - unequal weights with 0.99 swap fee", - swapFee: sdk.MustNewDecFromStr("0.99"), + name: "single tokensIn - unequal weights with 0.99 spread factor", + spreadFactor: sdk.MustNewDecFromStr("0.99"), poolAssets: []balancer.PoolAsset{ defaultOsmoPoolAsset, { @@ -168,8 +168,8 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-%28500+%2F+%28100+%2B+500%29%29%29+*+0%29%2F1000000000000%29%29%5E%28500+%2F+%28100+%2B+500%29%29+-+1%29 // Simplified: P_issued = 4_159_722_200_000 - name: "single asset - token in weight is greater than the other token, with zero swap fee", - swapFee: sdk.ZeroDec(), + name: "single asset - token in weight is greater than the other token, with zero spread factor", + spreadFactor: sdk.ZeroDec(), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 1e12), @@ -194,8 +194,8 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-%28500+%2F+%28100+%2B+500%29%29%29+*+0.01%29%2F1000000000000%29%29%5E%28500+%2F+%28100+%2B+500%29%29+-+1%29 // Simplified: P_issued = 4_159_722_200_000 - name: "single asset - token in weight is greater than the other token, with non-zero swap fee", - swapFee: sdk.MustNewDecFromStr("0.01"), + name: "single asset - token in weight is greater than the other token, with non-zero spread factor", + spreadFactor: sdk.MustNewDecFromStr("0.01"), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 1e12), @@ -220,8 +220,8 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-%28200+%2F+%28200+%2B+1000%29%29%29+*+0%29%2F1000000000000%29%29%5E%28200+%2F+%28200+%2B+1000%29%29+-+1%29 // Simplified: P_issued = 833_333_315_972 - name: "single asset - token in weight is smaller than the other token, with zero swap fee", - swapFee: sdk.MustNewDecFromStr("0"), + name: "single asset - token in weight is smaller than the other token, with zero spread factor", + spreadFactor: sdk.MustNewDecFromStr("0"), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 1e12), @@ -249,8 +249,8 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-%28200+%2F+%28200+%2B+1000%29%29%29+*+0.02%29%2F1000000000000%29%29%5E%28200+%2F+%28200+%2B+1000%29%29+-+1%29 // Simplified: P_issued = 819_444_430_000 - name: "single asset - token in weight is smaller than the other token, with non-zero swap fee", - swapFee: sdk.MustNewDecFromStr("0.02"), + name: "single asset - token in weight is smaller than the other token, with non-zero spread factor", + spreadFactor: sdk.MustNewDecFromStr("0.02"), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 1e12), @@ -278,8 +278,8 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%28117552*%281+-+%281-%28200+%2F+%28200+%2B+1000%29%29%29+*+0%29%2F156736%29%29%5E%28200+%2F+%28200+%2B+1000%29%29+-+1%29 // Simplified: P_issued = 9_775_731_930_496_140_648 - name: "single asset - tokenIn is large relative to liquidity, token in weight is smaller than the other token, with zero swap fee", - swapFee: sdk.MustNewDecFromStr("0"), + name: "single asset - tokenIn is large relative to liquidity, token in weight is smaller than the other token, with zero spread factor", + spreadFactor: sdk.MustNewDecFromStr("0"), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 156_736), @@ -308,8 +308,8 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-%28200+%2F+%28200+%2B+1000%29%29%29+*+0.02%29%2F1000000000000%29%29%5E%28200+%2F+%28200+%2B+1000%29%29+-+1%29 // Simplified: P_issued = 9_644_655_900_000_000_000 - name: "single asset - tokenIn is large relative to liquidity, token in weight is smaller than the other token, with non-zero swap fee", - swapFee: sdk.MustNewDecFromStr("0.02"), + name: "single asset - tokenIn is large relative to liquidity, token in weight is smaller than the other token, with non-zero spread factor", + spreadFactor: sdk.MustNewDecFromStr("0.02"), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 156_736), @@ -338,8 +338,8 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%28499999*%281+-+%281-%28100+%2F+%28100+%2B+1000%29%29%29+*+0%29%2F500000%29%29%5E%28100+%2F+%28100+%2B+1000%29%29+-+1%29 // Simplified: P_issued = 6_504_099_261_800_144_638 - name: "single asset - (almost 1 == tokenIn / liquidity ratio), token in weight is smaller than the other token, with zero swap fee", - swapFee: sdk.MustNewDecFromStr("0"), + name: "single asset - (almost 1 == tokenIn / liquidity ratio), token in weight is smaller than the other token, with zero spread factor", + spreadFactor: sdk.MustNewDecFromStr("0"), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 500_000), @@ -359,8 +359,8 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ // The ratio of tokenIn / existing liquidity that is larger than or equal to 1 causes a panic. // This has been deemed as acceptable since it causes code complexity to fix // & only affects UX in an edge case (user has to split up single asset joins) - name: "single asset - (exactly 1 == tokenIn / liquidity ratio - failure), token in weight is smaller than the other token, with zero swap fee", - swapFee: sdk.MustNewDecFromStr("0"), + name: "single asset - (exactly 1 == tokenIn / liquidity ratio - failure), token in weight is smaller than the other token, with zero spread factor", + spreadFactor: sdk.MustNewDecFromStr("0"), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 500_000), @@ -377,7 +377,7 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ }, { name: "tokenIn asset does not exist in pool", - swapFee: sdk.MustNewDecFromStr("0"), + spreadFactor: sdk.MustNewDecFromStr("0"), poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins(sdk.NewInt64Coin(doesNotExistDenom, 50_000)), expectShares: sdk.ZeroInt(), @@ -386,8 +386,8 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ { // Pool liquidity is changed by 1e-12 / 2 // P_issued = 1e20 * 1e-12 / 2 = 1e8 / 2 = 50_000_000 - name: "minimum input single asset equal liquidity", - swapFee: sdk.MustNewDecFromStr("0"), + name: "minimum input single asset equal liquidity", + spreadFactor: sdk.MustNewDecFromStr("0"), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 1_000_000_000_000), @@ -406,8 +406,8 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ { // P_issued should be 1/10th that of the previous test // p_issued = 50_000_000 / 10 = 5_000_000 - name: "minimum input single asset imbalanced liquidity", - swapFee: sdk.MustNewDecFromStr("0"), + name: "minimum input single asset imbalanced liquidity", + spreadFactor: sdk.MustNewDecFromStr("0"), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 10_000_000_000_000), @@ -427,9 +427,9 @@ var calcSingleAssetJoinTestCases = []calcJoinSharesTestCase{ var multiAssetExactInputTestCases = []calcJoinSharesTestCase{ { - name: "swap equal weights with zero swap fee", - swapFee: sdk.MustNewDecFromStr("0"), - poolAssets: oneTrillionEvenPoolAssets, + name: "swap equal weights with zero spread factor", + spreadFactor: sdk.MustNewDecFromStr("0"), + poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins( sdk.NewInt64Coin("uosmo", 25_000), sdk.NewInt64Coin("uatom", 25_000), @@ -444,9 +444,9 @@ var multiAssetExactInputTestCases = []calcJoinSharesTestCase{ ), }, { - name: "swap equal weights with 0.001 swap fee", - swapFee: sdk.MustNewDecFromStr("0.001"), - poolAssets: oneTrillionEvenPoolAssets, + name: "swap equal weights with 0.001 spread factor", + spreadFactor: sdk.MustNewDecFromStr("0.001"), + poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins( sdk.NewInt64Coin("uosmo", 25_000), sdk.NewInt64Coin("uatom", 25_000), @@ -461,8 +461,8 @@ var multiAssetExactInputTestCases = []calcJoinSharesTestCase{ // This test doubles the liquidity in a fresh pool, so it should generate the base number of LP shares for pool creation as new shares // This is set to 1e20 (or 100 * 10^18) for Osmosis, so we should expect: // P_issued = 1e20 - name: "minimum input with two assets and minimum liquidity", - swapFee: sdk.MustNewDecFromStr("0"), + name: "minimum input with two assets and minimum liquidity", + spreadFactor: sdk.MustNewDecFromStr("0"), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 1), @@ -486,8 +486,8 @@ var multiAssetExactInputTestCases = []calcJoinSharesTestCase{ { // Pool liquidity is changed by 1e-12 // P_issued = 1e20 * 1e-12 = 1e8 - name: "minimum input two assets equal liquidity", - swapFee: sdk.MustNewDecFromStr("0"), + name: "minimum input two assets equal liquidity", + spreadFactor: sdk.MustNewDecFromStr("0"), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 1_000_000_000_000), @@ -516,7 +516,7 @@ var multiAssetUnevenInputTestCases = []calcJoinSharesTestCase{ // join pool is first done to the extent where the ratio can be preserved, which is 25,000 uosmo and 25,000 uatom // then we perfrom single asset deposit for the remaining 25,000 uatom with the equation below // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) on page 10: - // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) + // P_issued = P_supply * ((1 + (A_t * spreadFactorRatio / B_t))^W_t - 1) // 1_249_999_960_937 = (1e20 + 2.5e12) * (( 1 + (25000 * 1 / 1000000025000))^0.5 - 1) (without fee) // // where: @@ -524,14 +524,14 @@ var multiAssetUnevenInputTestCases = []calcJoinSharesTestCase{ // A_t = amount of deposited asset = 25,000 // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,025,000 // W_t = normalized weight of deposited asset in pool = 0.5 (equally weighted two-asset pool) - // swapFeeRatio = (1 - (1 - W_t) * swapFee) + // spreadFactorRatio = (1 - (1 - W_t) * spreadFactor) // Plugging all of this in, we get: // Full Solution without fees: https://www.wolframalpha.com/input?i=%28100+*+10%5E18+%2B+2.5e12+%29*+%28%28+1%2B+++++%2825000+*+%281%29+%2F+1000000025000%29%29%5E0.5+-+1%29 // Simplified: P_issued = 2_500_000_000_000 + 1_249_999_960_937 - name: "Multi-tokens In: unequal amounts, equal weights with 0 swap fee", - swapFee: sdk.ZeroDec(), - poolAssets: oneTrillionEvenPoolAssets, + name: "Multi-tokens In: unequal amounts, equal weights with 0 spread factor", + spreadFactor: sdk.ZeroDec(), + poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins( sdk.NewInt64Coin("uosmo", 25_000), sdk.NewInt64Coin("uatom", 50_000), @@ -544,7 +544,7 @@ var multiAssetUnevenInputTestCases = []calcJoinSharesTestCase{ // join pool is first done to the extent where the ratio can be preserved, which is 25,000 uosmo and 25,000 uatom // then we perfrom single asset deposit for the remaining 25,000 uatom with the equation below // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) on page 10: - // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) + // P_issued = P_supply * ((1 + (A_t * spreadFactorRatio / B_t))^W_t - 1) // 1_243_750_000_000 = (1e20 + 2.5e12)* (( 1 + (25000 * (1 - (1 - 0.5) * 0.01) / 1000000025000))^0.5 - 1) // // where: @@ -552,14 +552,14 @@ var multiAssetUnevenInputTestCases = []calcJoinSharesTestCase{ // A_t = amount of deposited asset = 25,000 // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,025,000 // W_t = normalized weight of deposited asset in pool = 0.5 (equally weighted two-asset pool) - // swapFeeRatio = (1 - (1 - W_t) * swapFee) + // spreadFactorRatio = (1 - (1 - W_t) * spreadFactor) // Plugging all of this in, we get: // Full solution with fees: https://www.wolframalpha.com/input?i=%28100+*10%5E18%2B2.5e12%29*%28%281%2B+++%2825000*%281+-+%281-0.5%29+*+0.01%29%2F1000000000000%29%29%5E0.5+-+1%29 // Simplified: P_issued = 2_500_000_000_000 + 1_243_750_000_000 - name: "Multi-tokens In: unequal amounts, equal weights with 0.01 swap fee", - swapFee: sdk.MustNewDecFromStr("0.01"), - poolAssets: oneTrillionEvenPoolAssets, + name: "Multi-tokens In: unequal amounts, equal weights with 0.01 spread factor", + spreadFactor: sdk.MustNewDecFromStr("0.01"), + poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins( sdk.NewInt64Coin("uosmo", 25_000), sdk.NewInt64Coin("uatom", 50_000), @@ -573,7 +573,7 @@ var multiAssetUnevenInputTestCases = []calcJoinSharesTestCase{ // // For uatom: // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) on page 10: - // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) + // P_issued = P_supply * ((1 + (A_t * spreadFactorRatio / B_t))^W_t - 1) // 609,374,990,000 = (1e20 + 1,250,000,000,000) * (( 1 + (37,500 * (1 - (1 - 1/6) * 0.03) / 10,000,00,025,000))^1/6 - 1) // // where: @@ -581,12 +581,12 @@ var multiAssetUnevenInputTestCases = []calcJoinSharesTestCase{ // A_t = amount of deposited asset = 37,500 // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,025,000 // W_t = normalized weight of deposited asset in pool = 0.5 (equally weighted two-asset pool) - // swapFeeRatio = (1 - (1 - W_t) * swapFee) + // spreadFactorRatio = (1 - (1 - W_t) * spreadFactor) // Plugging all of this in, we get: // Full solution with fees: https://www.wolframalpha.com/input?i=%28100+*10%5E18+%2B+1250000000000%29*%28%281%2B++++%2837500*%281+-+%281-1%2F6%29+*+0.03%29%2F1000000012500%29%29%5E%281%2F6%29+-+1%29 // Simplified: P_issued = 1,250,000,000,000 + 609,374,990,000 - name: "Multi-tokens In: unequal amounts, with unequal weights with 0.03 swap fee", - swapFee: sdk.MustNewDecFromStr("0.03"), + name: "Multi-tokens In: unequal amounts, with unequal weights with 0.03 spread factor", + spreadFactor: sdk.MustNewDecFromStr("0.03"), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 2_000_000_000_000), @@ -833,11 +833,11 @@ func (s *KeeperTestSuite) TestCalcJoinPoolShares() { tc := tc s.T().Run(tc.name, func(t *testing.T) { - pool := createTestPool(t, tc.swapFee, sdk.ZeroDec(), tc.poolAssets...) + pool := createTestPool(t, tc.spreadFactor, sdk.ZeroDec(), tc.poolAssets...) // system under test sut := func() { - shares, liquidity, err := pool.CalcJoinPoolShares(s.Ctx, tc.tokensIn, tc.swapFee) + shares, liquidity, err := pool.CalcJoinPoolShares(s.Ctx, tc.tokensIn, tc.spreadFactor) if tc.expErr != nil { require.Error(t, err) require.ErrorAs(t, tc.expErr, &err) @@ -870,12 +870,12 @@ func (s *KeeperTestSuite) TestJoinPool() { tc := tc s.T().Run(tc.name, func(t *testing.T) { - pool := createTestPool(t, tc.swapFee, sdk.ZeroDec(), tc.poolAssets...) + pool := createTestPool(t, tc.spreadFactor, sdk.ZeroDec(), tc.poolAssets...) // system under test sut := func() { preJoinAssets := pool.GetTotalPoolLiquidity(s.Ctx) - shares, err := pool.JoinPool(s.Ctx, tc.tokensIn, tc.swapFee) + shares, err := pool.JoinPool(s.Ctx, tc.tokensIn, tc.spreadFactor) postJoinAssets := pool.GetTotalPoolLiquidity(s.Ctx) if tc.expErr != nil { @@ -905,9 +905,9 @@ func (s *KeeperTestSuite) TestJoinPoolNoSwap() { testCases := []calcJoinSharesTestCase{ { // only the exact ratio portion is successfully joined - name: "Multi-tokens In: unequal amounts, equal weights with 0 swap fee", - swapFee: sdk.ZeroDec(), - poolAssets: oneTrillionEvenPoolAssets, + name: "Multi-tokens In: unequal amounts, equal weights with 0 spread factor", + spreadFactor: sdk.ZeroDec(), + poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins( sdk.NewInt64Coin("uosmo", 25_000), sdk.NewInt64Coin("uatom", 50_000), @@ -921,9 +921,9 @@ func (s *KeeperTestSuite) TestJoinPoolNoSwap() { }, { // only the exact ratio portion is successfully joined - name: "Multi-tokens In: unequal amounts, equal weights with 0.01 swap fee", - swapFee: sdk.MustNewDecFromStr("0.01"), - poolAssets: oneTrillionEvenPoolAssets, + name: "Multi-tokens In: unequal amounts, equal weights with 0.01 spread factor", + spreadFactor: sdk.MustNewDecFromStr("0.01"), + poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins( sdk.NewInt64Coin("uosmo", 25_000), sdk.NewInt64Coin("uatom", 50_000), @@ -939,8 +939,8 @@ func (s *KeeperTestSuite) TestJoinPoolNoSwap() { // Note that the ratio of the assets matter, but their weights don't // We expect a 2:1 ratio in the joined liquidity because there's a 2:1 ration in existing liquidity // Since only the exact ratio portion is successfully joined, we expect 25k uosmo and 12.5k uatom - name: "Multi-tokens In: unequal amounts, with unequal weights with 0.03 swap fee", - swapFee: sdk.MustNewDecFromStr("0.03"), + name: "Multi-tokens In: unequal amounts, with unequal weights with 0.03 spread factor", + spreadFactor: sdk.MustNewDecFromStr("0.03"), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 2_000_000_000_000), @@ -965,12 +965,12 @@ func (s *KeeperTestSuite) TestJoinPoolNoSwap() { tc := tc s.T().Run(tc.name, func(t *testing.T) { - pool := createTestPool(t, tc.swapFee, sdk.ZeroDec(), tc.poolAssets...) + pool := createTestPool(t, tc.spreadFactor, sdk.ZeroDec(), tc.poolAssets...) // system under test sut := func() { preJoinAssets := pool.GetTotalPoolLiquidity(s.Ctx) - shares, err := pool.JoinPoolNoSwap(s.Ctx, tc.tokensIn, tc.swapFee) + shares, err := pool.JoinPoolNoSwap(s.Ctx, tc.tokensIn, tc.spreadFactor) postJoinAssets := pool.GetTotalPoolLiquidity(s.Ctx) if tc.expErr != nil { @@ -1023,7 +1023,7 @@ func (s *KeeperTestSuite) TestRandomizedJoinPoolExitPoolInvariants() { return tc } - swapFeeDec := sdk.ZeroDec() + spreadFactorDec := sdk.ZeroDec() exitFeeDec := sdk.ZeroDec() // create pool with randomized initial token amounts @@ -1039,7 +1039,7 @@ func (s *KeeperTestSuite) TestRandomizedJoinPoolExitPoolInvariants() { Weight: sdk.NewInt(5), } - pool = createTestPool(s.T(), swapFeeDec, exitFeeDec, poolAssetOut, poolAssetIn) + pool = createTestPool(s.T(), spreadFactorDec, exitFeeDec, poolAssetOut, poolAssetIn) s.Require().NotNil(pool) return pool @@ -1051,7 +1051,7 @@ func (s *KeeperTestSuite) TestRandomizedJoinPoolExitPoolInvariants() { sdk.NewCoin(denomIn, sdk.NewInt(tc.initialTokensDenomIn).MulRaw(tc.percentRatio).QuoRaw(100)), sdk.NewCoin(denomOut, sdk.NewInt(tc.initialTokensDenomOut).MulRaw(tc.percentRatio).QuoRaw(100)), } - numShares, err := pool.JoinPool(s.Ctx, tokensIn, swapFeeDec) + numShares, err := pool.JoinPool(s.Ctx, tokensIn, spreadFactorDec) s.Require().NoError(err) tc.numShares = numShares } diff --git a/x/gamm/pool-models/balancer/pool_test.go b/x/gamm/pool-models/balancer/pool_test.go index 9d3fbf14947..447349f4b00 100644 --- a/x/gamm/pool-models/balancer/pool_test.go +++ b/x/gamm/pool-models/balancer/pool_test.go @@ -18,11 +18,11 @@ import ( ) var ( - defaultSwapFee = sdk.MustNewDecFromStr("0.025") + defaultSpreadFactor = sdk.MustNewDecFromStr("0.025") defaultZeroExitFee = sdk.ZeroDec() defaultPoolId = uint64(10) defaultBalancerPoolParams = balancer.PoolParams{ - SwapFee: defaultSwapFee, + SwapFee: defaultSpreadFactor, ExitFee: defaultZeroExitFee, } defaultFutureGovernor = "" @@ -136,7 +136,7 @@ func TestCalcSingleAssetJoin(t *testing.T) { for _, tc := range calcSingleAssetJoinTestCases { tc := tc t.Run(tc.name, func(t *testing.T) { - pool := createTestPool(t, tc.swapFee, sdk.MustNewDecFromStr("0"), tc.poolAssets...) + pool := createTestPool(t, tc.spreadFactor, sdk.MustNewDecFromStr("0"), tc.poolAssets...) tokenIn := tc.tokensIn[0] @@ -155,7 +155,7 @@ func TestCalcSingleAssetJoin(t *testing.T) { // system under test sut := func() { - shares, err := pool.CalcSingleAssetJoin(tokenIn, tc.swapFee, poolAssetIn, pool.GetTotalShares()) + shares, err := pool.CalcSingleAssetJoin(tokenIn, tc.spreadFactor, poolAssetIn, pool.GetTotalShares()) if tc.expErr != nil { require.Error(t, err) @@ -178,7 +178,7 @@ func TestCalcSingleAssetJoin(t *testing.T) { func TestCalcJoinSingleAssetTokensIn(t *testing.T) { testCases := []struct { name string - swapFee sdk.Dec + spreadFactor sdk.Dec poolAssets []balancer.PoolAsset tokensIn sdk.Coins expectShares sdk.Int @@ -199,8 +199,8 @@ func TestCalcJoinSingleAssetTokensIn(t *testing.T) { // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100000000000000000000*%28%281+%2B+%2850000%2F1000000000000%29%29%5E0.5+-+1%29 // Simplified: P_issued = 2,499,999,968,750 - name: "one token in - equal weights with zero swap fee", - swapFee: sdk.MustNewDecFromStr("0"), + name: "one token in - equal weights with zero spread factor", + spreadFactor: sdk.MustNewDecFromStr("0"), poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000)), expectShares: sdk.NewInt(2_499_999_968_750), @@ -219,16 +219,16 @@ func TestCalcJoinSingleAssetTokensIn(t *testing.T) { // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100000000000000000000*%28%281+%2B+%2850000%2F1000000000000%29%29%5E0.5+-+1%29 // Simplified: P_issued = 2,499,999,968,750 - name: "two tokens in - equal weights with zero swap fee", - swapFee: sdk.MustNewDecFromStr("0"), + name: "two tokens in - equal weights with zero spread factor", + spreadFactor: sdk.MustNewDecFromStr("0"), poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000), sdk.NewInt64Coin("uatom", 50_000)), expectShares: sdk.NewInt(2_499_999_968_750 * 2), }, { // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) with on page 10 - // with swapFeeRatio added: - // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) + // with spreadFactorRatio added: + // P_issued = P_supply * ((1 + (A_t * spreadFactorRatio / B_t))^W_t - 1) // // 2_487_500_000_000 = 1e20 * (( 1 + (50,000 * (1 - (1 - 0.5) * 0.01) / 1e12))^0.5 - 1) // @@ -237,20 +237,20 @@ func TestCalcJoinSingleAssetTokensIn(t *testing.T) { // A_t = amount of deposited asset = 50,000 // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 // W_t = normalized weight of deposited asset in pool = 0.5 (equally weighted two-asset pool) - // swapFeeRatio = (1 - (1 - W_t) * swapFee) + // spreadFactorRatio = (1 - (1 - W_t) * spreadFactor) // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-0.5%29+*+0.01%29%2F1000000000000%29%29%5E0.5+-+1%29 // Simplified: P_issued = 2_487_500_000_000 - name: "one token in - equal weights with swap fee of 0.01", - swapFee: sdk.MustNewDecFromStr("0.01"), + name: "one token in - equal weights with spread factor of 0.01", + spreadFactor: sdk.MustNewDecFromStr("0.01"), poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000)), expectShares: sdk.NewInt(2_487_500_000_000), }, { // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) with on page 10 - // with swapFeeRatio added: - // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) + // with spreadFactorRatio added: + // P_issued = P_supply * ((1 + (A_t * spreadFactorRatio / B_t))^W_t - 1) // // 2_487_500_000_000 = 1e20 * (( 1 + (50,000 * (1 - (1 - 0.5) * 0.01) / 1e12))^0.5 - 1) // @@ -259,12 +259,12 @@ func TestCalcJoinSingleAssetTokensIn(t *testing.T) { // A_t = amount of deposited asset = 50,000 // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 // W_t = normalized weight of deposited asset in pool = 0.5 (equally weighted two-asset pool) - // swapFeeRatio = (1 - (1 - W_t) * swapFee) + // spreadFactorRatio = (1 - (1 - W_t) * spreadFactor) // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-0.5%29+*+0.01%29%2F1000000000000%29%29%5E0.5+-+1%29 // Simplified: P_issued = 2_487_500_000_000 - name: "two tokens in - equal weights with swap fee of 0.01", - swapFee: sdk.MustNewDecFromStr("0.01"), + name: "two tokens in - equal weights with spread factor of 0.01", + spreadFactor: sdk.MustNewDecFromStr("0.01"), poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000), sdk.NewInt64Coin("uatom", 50_000)), expectShares: sdk.NewInt(2_487_500_000_000 * 2), @@ -273,8 +273,8 @@ func TestCalcJoinSingleAssetTokensIn(t *testing.T) { // For uosmo: // // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) with on page 10 - // with swapFeeRatio added: - // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) + // with spreadFactorRatio added: + // P_issued = P_supply * ((1 + (A_t * spreadFactorRatio / B_t))^W_t - 1) // // 2_072_912_400_000_000 = 1e20 * (( 1 + (50,000 * (1 - (1 - 0.83) * 0.03) / 2_000_000_000))^0.83 - 1) // @@ -283,7 +283,7 @@ func TestCalcJoinSingleAssetTokensIn(t *testing.T) { // A_t = amount of deposited asset = 50,000 // B_t = existing balance of deposited asset in the pool prior to deposit = 2_000_000_000 // W_t = normalized weight of deposited asset in pool = 500 / 500 + 100 = 0.83 - // swapFeeRatio = (1 - (1 - W_t) * swapFee) + // spreadFactorRatio = (1 - (1 - W_t) * spreadFactor) // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%2850000*%281+-+%281-%28500+%2F+%28500+%2B+100%29%29%29+*+0.03%29%2F2000000000%29%29%5E%28500+%2F+%28500+%2B+100%29%29+-+1%29 // Simplified: P_issued = 2_072_912_400_000_000 @@ -292,8 +292,8 @@ func TestCalcJoinSingleAssetTokensIn(t *testing.T) { // For uatom: // // Expected output from Balancer paper (https://balancer.fi/whitepaper.pdf) using equation (25) with on page 10 - // with swapFeeRatio added: - // P_issued = P_supply * ((1 + (A_t * swapFeeRatio / B_t))^W_t - 1) + // with spreadFactorRatio added: + // P_issued = P_supply * ((1 + (A_t * spreadFactorRatio / B_t))^W_t - 1) // // 1_624_999_900_000 = 1e20 * (( 1 + (100_000 * (1 - (1 - 0.167) * 0.03) / 1e12))^0.167 - 1) // @@ -302,12 +302,12 @@ func TestCalcJoinSingleAssetTokensIn(t *testing.T) { // A_t = amount of deposited asset = 50,000 // B_t = existing balance of deposited asset in the pool prior to deposit = 1,000,000,000,000 // W_t = normalized weight of deposited asset in pool = 100 / 500 + 100 = 0.167 - // swapFeeRatio = (1 - (1 - W_t) * swapFee) + // spreadFactorRatio = (1 - (1 - W_t) * spreadFactor) // Plugging all of this in, we get: // Full solution: https://www.wolframalpha.com/input?i=100+*10%5E18*%28%281+%2B+%28100000*%281+-+%281-%28100+%2F+%28500+%2B+100%29%29%29+*+0.03%29%2F1000000000000%29%29%5E%28100+%2F+%28500+%2B+100%29%29+-+1%29 // Simplified: P_issued = 1_624_999_900_000 - name: "two varying tokens in, varying weights, with swap fee of 0.03", - swapFee: sdk.MustNewDecFromStr("0.03"), + name: "two varying tokens in, varying weights, with spread factor of 0.03", + spreadFactor: sdk.MustNewDecFromStr("0.03"), poolAssets: []balancer.PoolAsset{ { Token: sdk.NewInt64Coin("uosmo", 2_000_000_000), @@ -323,15 +323,15 @@ func TestCalcJoinSingleAssetTokensIn(t *testing.T) { }, { name: "no tokens in", - swapFee: sdk.MustNewDecFromStr("0.03"), + spreadFactor: sdk.MustNewDecFromStr("0.03"), poolAssets: oneTrillionEvenPoolAssets, tokensIn: sdk.NewCoins(), expectShares: sdk.NewInt(0), }, { - name: "one of the tokensIn asset does not exist in pool", - swapFee: sdk.ZeroDec(), - poolAssets: oneTrillionEvenPoolAssets, + name: "one of the tokensIn asset does not exist in pool", + spreadFactor: sdk.ZeroDec(), + poolAssets: oneTrillionEvenPoolAssets, // Second tokenIn does not exist. tokensIn: sdk.NewCoins(sdk.NewInt64Coin("uosmo", 50_000), sdk.NewInt64Coin(doesNotExistDenom, 50_000)), expectShares: sdk.ZeroInt(), @@ -343,7 +343,7 @@ func TestCalcJoinSingleAssetTokensIn(t *testing.T) { tc := tc t.Run(tc.name, func(t *testing.T) { - pool := createTestPool(t, tc.swapFee, sdk.ZeroDec(), tc.poolAssets...) + pool := createTestPool(t, tc.spreadFactor, sdk.ZeroDec(), tc.poolAssets...) poolAssetsByDenom, err := balancer.GetPoolAssetsByDenom(pool.GetAllPoolAssets()) require.NoError(t, err) @@ -355,7 +355,7 @@ func TestCalcJoinSingleAssetTokensIn(t *testing.T) { } sut := func() { - totalNumShares, totalNewLiquidity, err := pool.CalcJoinSingleAssetTokensIn(tc.tokensIn, pool.GetTotalShares(), poolAssetsByDenom, tc.swapFee) + totalNumShares, totalNewLiquidity, err := pool.CalcJoinSingleAssetTokensIn(tc.tokensIn, pool.GetTotalShares(), poolAssetsByDenom, tc.spreadFactor) if tc.expErr != nil { require.Error(t, err) @@ -480,7 +480,7 @@ func (suite *BalancerTestSuite) TestBalancerCalculateAmountOutAndIn_InverseRelat initialWeightIn int64 } - // For every test case in testcases, apply a swap fee in swapFeeCases. + // For every test case in testcases, apply a spread factor in spreadFactorCases. testcases := []testcase{ { denomOut: "uosmo", @@ -534,20 +534,20 @@ func (suite *BalancerTestSuite) TestBalancerCalculateAmountOutAndIn_InverseRelat }, } - swapFeeCases := []string{"0", "0.001", "0.1", "0.5", "0.99"} + spreadFactorCases := []string{"0", "0.001", "0.1", "0.5", "0.99"} - getTestCaseName := func(tc testcase, swapFeeCase string) string { - return fmt.Sprintf("tokenOutInitial: %d, tokenInInitial: %d, initialOut: %d, swapFee: %s", + getTestCaseName := func(tc testcase, spreadFactorCase string) string { + return fmt.Sprintf("tokenOutInitial: %d, tokenInInitial: %d, initialOut: %d, spreadFactor: %s", tc.initialPoolOut, tc.initialPoolIn, tc.initialCalcOut, - swapFeeCase, + spreadFactorCase, ) } for _, tc := range testcases { - for _, swapFee := range swapFeeCases { - suite.Run(getTestCaseName(tc, swapFee), func() { + for _, spreadFactor := range spreadFactorCases { + suite.Run(getTestCaseName(tc, spreadFactor), func() { ctx := suite.CreateTestContext() poolAssetOut := balancer.PoolAsset{ @@ -560,20 +560,20 @@ func (suite *BalancerTestSuite) TestBalancerCalculateAmountOutAndIn_InverseRelat Weight: sdk.NewInt(tc.initialWeightIn), } - swapFeeDec, err := sdk.NewDecFromStr(swapFee) + spreadFactorDec, err := sdk.NewDecFromStr(spreadFactor) suite.Require().NoError(err) exitFeeDec, err := sdk.NewDecFromStr("0") suite.Require().NoError(err) - pool := createTestPool(suite.T(), swapFeeDec, exitFeeDec, poolAssetOut, poolAssetIn) + pool := createTestPool(suite.T(), spreadFactorDec, exitFeeDec, poolAssetOut, poolAssetIn) suite.Require().NotNil(pool) errTolerance := osmomath.ErrTolerance{ AdditiveTolerance: sdk.OneDec(), MultiplicativeTolerance: sdk.Dec{}, } sut := func() { - test_helpers.TestCalculateAmountOutAndIn_InverseRelationship(suite.T(), ctx, pool, poolAssetIn.Token.Denom, poolAssetOut.Token.Denom, tc.initialCalcOut, swapFeeDec, errTolerance) + test_helpers.TestCalculateAmountOutAndIn_InverseRelationship(suite.T(), ctx, pool, poolAssetIn.Token.Denom, poolAssetOut.Token.Denom, tc.initialCalcOut, spreadFactorDec, errTolerance) } assertPoolStateNotModified(suite.T(), pool, sut) @@ -590,7 +590,7 @@ func TestCalcSingleAssetInAndOut_InverseRelationship(t *testing.T) { initialWeightIn int64 } - // For every test case in testcases, apply a swap fee in swapFeeCases. + // For every test case in testcases, apply a spread factor in spreadFactorCases. testcases := []testcase{ { initialPoolOut: 1_000_000_000_000, @@ -642,22 +642,22 @@ func TestCalcSingleAssetInAndOut_InverseRelationship(t *testing.T) { }, } - swapFeeCases := []string{"0", "0.001", "0.1", "0.5", "0.99"} + spreadFactorCases := []string{"0", "0.001", "0.1", "0.5", "0.99"} - getTestCaseName := func(tc testcase, swapFeeCase string) string { - return fmt.Sprintf("initialPoolOut: %d, initialCalcOut: %d, initialWeightOut: %d, initialWeightIn: %d, swapFee: %s", + getTestCaseName := func(tc testcase, spreadFactorDec string) string { + return fmt.Sprintf("initialPoolOut: %d, initialCalcOut: %d, initialWeightOut: %d, initialWeightIn: %d, spreadFactor: %s", tc.initialPoolOut, tc.tokenOut, tc.initialWeightOut, tc.initialWeightIn, - swapFeeCase, + spreadFactorDec, ) } for _, tc := range testcases { - for _, swapFee := range swapFeeCases { - t.Run(getTestCaseName(tc, swapFee), func(t *testing.T) { - swapFeeDec, err := sdk.NewDecFromStr(swapFee) + for _, spreadFactor := range spreadFactorCases { + t.Run(getTestCaseName(tc, spreadFactor), func(t *testing.T) { + spreadFactorDec, err := sdk.NewDecFromStr(spreadFactor) require.NoError(t, err) initialPoolBalanceOut := sdk.NewInt(tc.initialPoolOut) @@ -673,7 +673,7 @@ func TestCalcSingleAssetInAndOut_InverseRelationship(t *testing.T) { initialWeightOut.ToDec().Quo(initialWeightOut.Add(initialWeightIn).ToDec()), initialTotalShares, initialCalcTokenOut.ToDec(), - swapFeeDec, + spreadFactorDec, ) inverseCalcTokenOut := balancer.CalcSingleAssetInGivenPoolSharesOut( @@ -681,7 +681,7 @@ func TestCalcSingleAssetInAndOut_InverseRelationship(t *testing.T) { initialWeightOut.ToDec().Quo(initialWeightOut.Add(initialWeightIn).ToDec()), initialTotalShares.Add(actualSharesOut), actualSharesOut, - swapFeeDec, + spreadFactorDec, ) tol := sdk.NewDec(1) @@ -968,7 +968,7 @@ func TestLBPParamsEmptyStartTime(t *testing.T) { pacc, err := balancer.NewBalancerPool(defaultPoolId, balancer.PoolParams{ SmoothWeightChangeParams: ¶ms, - SwapFee: defaultSwapFee, + SwapFee: defaultSpreadFactor, ExitFee: defaultZeroExitFee, }, initialPoolAssets, defaultFutureGovernor, defaultCurBlockTime) require.NoError(t, err) @@ -1160,7 +1160,7 @@ func TestBalancerPoolPokeTokenWeights(t *testing.T) { } // Initialize the pool pacc, err := balancer.NewBalancerPool(uint64(poolId), balancer.PoolParams{ - SwapFee: defaultSwapFee, + SwapFee: defaultSpreadFactor, ExitFee: defaultZeroExitFee, SmoothWeightChangeParams: &tc.params, }, initialPoolAssets, defaultFutureGovernor, defaultCurBlockTime) @@ -1341,13 +1341,13 @@ func TestCalcJoinPoolNoSwapShares(t *testing.T) { balancerPool := balancer.Pool{ Address: poolmanagertypes.NewPoolAddress(defaultPoolId).String(), Id: defaultPoolId, - PoolParams: balancer.PoolParams{SwapFee: defaultSwapFee, ExitFee: defaultZeroExitFee}, + PoolParams: balancer.PoolParams{SwapFee: defaultSpreadFactor, ExitFee: defaultZeroExitFee}, PoolAssets: test.poolAssets, FuturePoolGovernor: defaultFutureGovernor, TotalShares: sdk.NewCoin(types.GetPoolShareDenom(defaultPoolId), types.InitPoolSharesSupply), } - numShare, tokensJoined, err := balancerPool.CalcJoinPoolNoSwapShares(ctx, test.tokensIn, balancerPool.GetSwapFee(ctx)) + numShare, tokensJoined, err := balancerPool.CalcJoinPoolNoSwapShares(ctx, test.tokensIn, balancerPool.GetSpreadFactor(ctx)) if test.expectPass { require.NoError(t, err) diff --git a/x/gamm/pool-models/balancer/util_test.go b/x/gamm/pool-models/balancer/util_test.go index 3aae0cf9f6a..b21ddb6b948 100644 --- a/x/gamm/pool-models/balancer/util_test.go +++ b/x/gamm/pool-models/balancer/util_test.go @@ -12,11 +12,11 @@ import ( "github.com/osmosis-labs/osmosis/v15/x/gamm/pool-models/balancer" ) -func createTestPool(t *testing.T, swapFee, exitFee sdk.Dec, poolAssets ...balancer.PoolAsset) *balancer.Pool { +func createTestPool(t *testing.T, spreadFactor, exitFee sdk.Dec, poolAssets ...balancer.PoolAsset) *balancer.Pool { t.Helper() pool, err := balancer.NewBalancerPool( 1, - balancer.NewPoolParams(swapFee, exitFee, nil), + balancer.NewPoolParams(spreadFactor, exitFee, nil), poolAssets, "", time.Now(), diff --git a/x/gamm/pool-models/internal/cfmm_common/lp.go b/x/gamm/pool-models/internal/cfmm_common/lp.go index 860b3f6d1a3..6c1ad71d3a1 100644 --- a/x/gamm/pool-models/internal/cfmm_common/lp.go +++ b/x/gamm/pool-models/internal/cfmm_common/lp.go @@ -116,7 +116,7 @@ func MaximalExactRatioJoin(p types.CFMMPoolI, ctx sdk.Context, tokensIn sdk.Coin } // We binary search a number of LP shares, s.t. if we exited the pool with the updated liquidity, -// and swapped all the tokens back to the input denom, we'd get the same amount. (under 0 swap fee) +// and swapped all the tokens back to the input denom, we'd get the same amount. (under 0 spread factor) // Thanks to CFMM path-independence, we can estimate slippage with these swaps to be sure to get the right numbers here. // (by path-independence, swap all of B -> A, and then swap all of C -> A will yield same amount of A, regardless // of order and interleaving) @@ -169,14 +169,14 @@ func BinarySearchSingleAssetJoin( // SwapAllCoinsToSingleAsset iterates through each token in the input set and trades it against the same pool sequentially func SwapAllCoinsToSingleAsset(pool types.CFMMPoolI, ctx sdk.Context, inTokens sdk.Coins, swapToDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (sdk.Int, error) { tokenOutAmt := inTokens.AmountOfNoDenomValidation(swapToDenom) for _, coin := range inTokens { if coin.Denom == swapToDenom { continue } - tokenOut, err := pool.SwapOutAmtGivenIn(ctx, sdk.NewCoins(coin), swapToDenom, swapFee) + tokenOut, err := pool.SwapOutAmtGivenIn(ctx, sdk.NewCoins(coin), swapToDenom, spreadFactor) if err != nil { return sdk.Int{}, err } diff --git a/x/gamm/pool-models/internal/test_helpers/test_helpers.go b/x/gamm/pool-models/internal/test_helpers/test_helpers.go index 0df709a4ce1..d9e7c83b183 100644 --- a/x/gamm/pool-models/internal/test_helpers/test_helpers.go +++ b/x/gamm/pool-models/internal/test_helpers/test_helpers.go @@ -39,19 +39,19 @@ func TestCalculateAmountOutAndIn_InverseRelationship( assetInDenom string, assetOutDenom string, initialCalcOut int64, - swapFee sdk.Dec, + spreadFactor sdk.Dec, errTolerance osmomath.ErrTolerance, ) { initialOut := sdk.NewInt64Coin(assetOutDenom, initialCalcOut) initialOutCoins := sdk.NewCoins(initialOut) - actualTokenIn, err := pool.CalcInAmtGivenOut(ctx, initialOutCoins, assetInDenom, swapFee) + actualTokenIn, err := pool.CalcInAmtGivenOut(ctx, initialOutCoins, assetInDenom, spreadFactor) require.NoError(t, err) // we expect that any output less than 1 will always be rounded up require.True(t, actualTokenIn.Amount.GTE(sdk.OneInt())) - inverseTokenOut, err := pool.CalcOutAmtGivenIn(ctx, sdk.NewCoins(actualTokenIn), assetOutDenom, swapFee) + inverseTokenOut, err := pool.CalcOutAmtGivenIn(ctx, sdk.NewCoins(actualTokenIn), assetOutDenom, spreadFactor) require.NoError(t, err) require.Equal(t, initialOut.Denom, inverseTokenOut.Denom) @@ -63,7 +63,7 @@ func TestCalculateAmountOutAndIn_InverseRelationship( // we expect there to be drastically amplified error that will fall outside our usual bounds. // Since these cases are effectively unusable by design, we only really care about whether // they are safe i.e. round correctly. - preFeeTokenIn := actualTokenIn.Amount.ToDec().Mul((sdk.OneDec().Sub(swapFee))).Ceil().TruncateInt() + preFeeTokenIn := actualTokenIn.Amount.ToDec().Mul((sdk.OneDec().Sub(spreadFactor))).Ceil().TruncateInt() if preFeeTokenIn.Equal(sdk.OneInt()) { require.True(t, actual.GT(expected)) } else { @@ -98,7 +98,7 @@ func TestSlippageRelationOutGivenIn( swapOutDenom := initLiquidity[1].Denom curPool := createPoolWithLiquidity(ctx, initLiquidity) - fee := curPool.GetSwapFee(ctx) + fee := curPool.GetSpreadFactor(ctx) curLiquidity := initLiquidity curOutAmount, err := curPool.CalcOutAmtGivenIn(ctx, swapInAmt, swapOutDenom, fee) @@ -131,7 +131,7 @@ func TestSlippageRelationInGivenOut( swapInDenom := initLiquidity[1].Denom curPool := createPoolWithLiquidity(ctx, initLiquidity) - fee := curPool.GetSwapFee(ctx) + fee := curPool.GetSpreadFactor(ctx) // we first ensure that the pool has sufficient liquidity to accommodate // a swap that yields `swapOutAmt` without more than doubling input reserves @@ -164,14 +164,14 @@ func TestSlippageRelationInGivenOut( } // returns true if the pool can accommodate an InGivenOut swap with `tokenOut` amount out, false otherwise -func isWithinBounds(ctx sdk.Context, pool types.CFMMPoolI, tokenOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) (b bool) { +func isWithinBounds(ctx sdk.Context, pool types.CFMMPoolI, tokenOut sdk.Coins, tokenInDenom string, spreadFactor sdk.Dec) (b bool) { b = true defer func() { if r := recover(); r != nil { b = false } }() - _, err := pool.CalcInAmtGivenOut(ctx, tokenOut, tokenInDenom, swapFee) + _, err := pool.CalcInAmtGivenOut(ctx, tokenOut, tokenInDenom, spreadFactor) if err != nil { b = false } diff --git a/x/gamm/pool-models/stableswap/README.md b/x/gamm/pool-models/stableswap/README.md index 714f83e1873..5cfb48047b7 100644 --- a/x/gamm/pool-models/stableswap/README.md +++ b/x/gamm/pool-models/stableswap/README.md @@ -48,13 +48,13 @@ We detail rounding modes and scaling details as pseudocode in the relevant secti The AMM pool interfaces requires implementing the following stateful methods: ```golang - SwapOutAmtGivenIn(tokenIn sdk.Coins, tokenOutDenom string, swapFee sdk.Dec) (tokenOut sdk.Coin, err error) - SwapInAmtGivenOut(tokenOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) (tokenIn sdk.Coin, err error) + SwapOutAmtGivenIn(tokenIn sdk.Coins, tokenOutDenom string, spreadFactor sdk.Dec) (tokenOut sdk.Coin, err error) + SwapInAmtGivenOut(tokenOut sdk.Coins, tokenInDenom string, spreadFactor sdk.Dec) (tokenIn sdk.Coin, err error) SpotPrice(baseAssetDenom string, quoteAssetDenom string) (sdk.Dec, error) - JoinPool(tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, err error) - JoinPoolNoSwap(tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, err error) + JoinPool(tokensIn sdk.Coins, spreadFactor sdk.Dec) (numShares sdk.Int, err error) + JoinPoolNoSwap(tokensIn sdk.Coins, spreadFactor sdk.Dec) (numShares sdk.Int, err error) ExitPool(numShares sdk.Int, exitFee sdk.Dec) (exitedCoins sdk.Coins, err error) ``` @@ -109,7 +109,7 @@ First we note the direct way of solving this, its limitation, and then an iterat #### Direct swap solution -The method to compute this under 0 swap fee is implied by the CFMM equation itself, since the constant refers to: +The method to compute this under 0 spread factor is implied by the CFMM equation itself, since the constant refers to: $g(x_0, y_0, v, w) = k = g(x_0 + a, y_0 - b, v, w)$. As $k$ is linearly related to $v$, and $v$ is unchanged throughout the swap, we can simplify the equation to be reasoning about $k' = \frac{k}{v}$ as the constant, and $h$ instead of $g$ We then model the solution by finding a function $\text{solve cfmm}(x, w, k') = y\text{ s.t. }h(x, y, w) = k'$. @@ -241,7 +241,7 @@ def binary_search(lowerbound, upperbound, approximation_fn, target, max_iteratio What remains is setting the error tolerance. We need two properties: - The returned value to be within some correctness threshold of the true value -- The returned value to be rounded correctly (always ending with the user having fewer funds to avoid pool drain attacks). Mitigated by swap fees for normal swaps, but needed for 0-fee to be safe. +- The returned value to be rounded correctly (always ending with the user having fewer funds to avoid pool drain attacks). Mitigated by spread factors for normal swaps, but needed for 0-fee to be safe. The error tolerance we set is defined in terms of error in `k`, which itself implies some error in `y`. An error of `e_k` in `k`, implies an error `e_y` in `y` that is less than `e_k`. We prove this [here](#err_proof) (and show that `e_y` is actually much less than the error in `e_k`, but for simplicity ignore this fact). We want `y` to be within a factor of `10^(-12)` of its true value. @@ -272,17 +272,17 @@ When we scale liquidity, we round down, as lower reserves -> higher slippage. Similarly when we scale the token in, we round down as well. These both ensure no risk of over payment. -The amount of tokens that we treat as going into the "0-swap fee" pool we defined equations off of is: `amm_in = in_amt_scaled * (1 - swapfee)`. (With `swapfee * in_amt_scaled` just being added to pool liquidity) +The amount of tokens that we treat as going into the "0-spread factor" pool we defined equations off of is: `amm_in = in_amt_scaled * (1 - spread factor)`. (With `spread factor * in_amt_scaled` just being added to pool liquidity) Then we simply call `solve_y` with the input reserves, and `amm_in`. ```python -def CalcOutAmountGivenExactAmountIn(pool, in_coin, out_denom, swap_fee): +def CalcOutAmountGivenExactAmountIn(pool, in_coin, out_denom, spread_factor): in_reserve, out_reserve, rem_reserves = pool.ScaledLiquidity(in_coin, out_denom, RoundingMode.RoundDown) in_amt_scaled = pool.ScaleToken(in_coin, RoundingMode.RoundDown) - amm_in = in_amt_scaled * (1 - swap_fee) + amm_in = in_amt_scaled * (1 - spread_factor) out_amt_scaled = solve_y(in_reserve, out_reserve, remReserves, amm_in) out_amt = pool.DescaleToken(out_amt_scaled, out_denom) return out_amt @@ -296,23 +296,23 @@ When we scale liquidity, we round down, as lower reserves -> higher slippage. Similarly when we scale the exact token out, we round up to increase required token in. We model the `solve_y` call as we are doing a known change to the `out_reserve`, and solving for the implied unknown change to `in_reserve`. -To handle the swapfee, we apply the swapfee on the resultant needed input amount. -We do this by having `token_in = amm_in / (1 - swapfee)`. +To handle the spread factor, we apply the spread factor on the resultant needed input amount. +We do this by having `token_in = amm_in / (1 - spread factor)`. ```python -def CalcInAmountGivenExactAmountOut(pool, out_coin, in_denom, swap_fee): +def CalcInAmountGivenExactAmountOut(pool, out_coin, in_denom, spread_factor): in_reserve, out_reserve, rem_reserves = pool.ScaledLiquidity(in_denom, out_coin, RoundingMode.RoundDown) out_amt_scaled = pool.ScaleToken(out_coin, RoundingMode.RoundUp) amm_in_scaled = solve_y(out_reserve, in_reserve, remReserves, -out_amt_scaled) - swap_in_scaled = ceil(amm_in_scaled / (1 - swapfee)) + swap_in_scaled = ceil(amm_in_scaled / (1 - spread factor)) in_amt = pool.DescaleToken(swap_in_scaled, in_denom) return in_amt ``` -We see correctness of the swap fee, by imagining what happens if we took this resultant input amount, and ran `SwapExactAmountIn (seai)`. Namely, that `seai_amm_in = amm_in * (1 - swapfee) = amm_in`, as desired! +We see correctness of the spread factor, by imagining what happens if we took this resultant input amount, and ran `SwapExactAmountIn (seai)`. Namely, that `seai_amm_in = amm_in * (1 - spread factor) = amm_in`, as desired! #### Precision handling @@ -398,24 +398,24 @@ The JoinPool API only supports JoinPoolNoSwap if #### Join pool single asset in -There are a couple ways to define `JoinPoolSingleAssetIn`. The simplest way is to define it from its intended relation from the CFMM, with Exit pool. We describe this below under the zero swap fee case. +There are a couple ways to define `JoinPoolSingleAssetIn`. The simplest way is to define it from its intended relation from the CFMM, with Exit pool. We describe this below under the zero spread factor case. Let `pool_{L, S}` represent a pool with liquidity `L`, and `S` total LP shares. If we call `pool_{L, S}.JoinPoolSingleAssetIn(tokensIn) -> (N, pool_{L + tokensIn, S + N})`, or in others we get out `N` new LP shares, and a pool with with tokensIn added to liquidity. It must then be the case that `pool_{L+tokensIn, S+N}.ExitPool(N) -> (tokensExited, pool_{L + tokensIn - tokensExited, S})`. -Then if we swap all of `tokensExited` back to tokensIn, under 0 swap fee, we should get back to `pool_{L, S}` under the CFMM property. +Then if we swap all of `tokensExited` back to tokensIn, under 0 spread factor, we should get back to `pool_{L, S}` under the CFMM property. -In other words, if we single asset join pool, and then exit pool, we should return back to the same CFMM `k` value we started with. Then if we swap back to go entirely back into our input asset, we should have exactly many tokens as we started with, under 0 swap fee. +In other words, if we single asset join pool, and then exit pool, we should return back to the same CFMM `k` value we started with. Then if we swap back to go entirely back into our input asset, we should have exactly many tokens as we started with, under 0 spread factor. We can solve this relation with a binary search over the amount of LP shares to give! -Thus we are left with how to account swap fee. We currently account for swap fee, by considering the asset ratio in the pool. If post scaling factors, the pool liquidity is say 60:20:20, where 60 is the asset were bringing in, then we consider "only (1 - 60%) = 40%" of the input as getting swapped. So we charge the swap fee on 40% of our single asset join in input. So the pseudocode for this is roughly: +Thus we are left with how to account spread factor. We currently account for spread factor, by considering the asset ratio in the pool. If post scaling factors, the pool liquidity is say 60:20:20, where 60 is the asset were bringing in, then we consider "only (1 - 60%) = 40%" of the input as getting swapped. So we charge the spread factor on 40% of our single asset join in input. So the pseudocode for this is roughly: ```python def JoinPoolSingleAssetIn(pool, tokenIn): - swapFeeApplicableFraction = 1 - (pool.ScaledLiquidityOf(tokenIn.Denom) / pool.SumOfAllScaledLiquidity()) - effectiveSwapFee = pool.SwapFee * swapFeeApplicableFraction - effectiveTokenIn = RoundDown(tokenIn * (1 - effectiveSwapFee)) + spreadFactorApplicableFraction = 1 - (pool.ScaledLiquidityOf(tokenIn.Denom) / pool.SumOfAllScaledLiquidity()) + effectiveSpreadFactor = pool.SwapFee * spreadFactorApplicableFraction + effectiveTokenIn = RoundDown(tokenIn * (1 - effectiveSpreadFactor)) return BinarySearchSingleJoinLpShares(pool, effectiveTokenIn) ``` diff --git a/x/gamm/pool-models/stableswap/amm.go b/x/gamm/pool-models/stableswap/amm.go index 1805d858443..cd9f69a6cdf 100644 --- a/x/gamm/pool-models/stableswap/amm.go +++ b/x/gamm/pool-models/stableswap/amm.go @@ -157,7 +157,7 @@ func solveCFMMBinarySearchMulti(xReserve, yReserve, wSumSquares, yIn osmomath.Bi func (p Pool) spotPrice(quoteDenom, baseDenom string) (spotPrice sdk.Dec, err error) { // Define f_{y -> x}(a) as the function that outputs the amount of tokens X you'd get by - // trading "a" units of Y against the pool, assuming 0 swap fee, at the current liquidity. + // trading "a" units of Y against the pool, assuming 0 spread factor, at the current liquidity. // The spot price of the pool is then lim a -> 0, f_{y -> x}(a) / a // For uniswap f_{y -> x}(a) = x - xy/(y + a), // The spot price equation of y in terms of x is X_SUPPLY/Y_SUPPLY. @@ -176,12 +176,12 @@ func (p Pool) spotPrice(quoteDenom, baseDenom string) (spotPrice sdk.Dec, err er return res, err } -func oneMinus(swapFee sdk.Dec) osmomath.BigDec { - return osmomath.BigDecFromSDKDec(sdk.OneDec().Sub(swapFee)) +func oneMinus(spreadFactor sdk.Dec) osmomath.BigDec { + return osmomath.BigDecFromSDKDec(sdk.OneDec().Sub(spreadFactor)) } // calcOutAmtGivenIn calculate amount of specified denom to output from a pool in sdk.Dec given the input `tokenIn` -func (p Pool) calcOutAmtGivenIn(tokenIn sdk.Coin, tokenOutDenom string, swapFee sdk.Dec) (sdk.Dec, error) { +func (p Pool) calcOutAmtGivenIn(tokenIn sdk.Coin, tokenOutDenom string, spreadFactor sdk.Dec) (sdk.Dec, error) { // round liquidity down, and round token in down reserves, err := p.scaledSortedPoolReserves(tokenIn.Denom, tokenOutDenom, osmomath.RoundDown) if err != nil { @@ -193,8 +193,8 @@ func (p Pool) calcOutAmtGivenIn(tokenIn sdk.Coin, tokenOutDenom string, swapFee return sdk.Dec{}, err } - // amm input = tokenIn * (1 - swap fee) - ammIn := tokenInDec.Mul(oneMinus(swapFee)) + // amm input = tokenIn * (1 - spread factor) + ammIn := tokenInDec.Mul(oneMinus(spreadFactor)) // We are solving for the amount of token out, hence x = tokenOutSupply, y = tokenInSupply // fmt.Printf("outSupply %s, inSupply %s, remReservs %s, ammIn %s\n ", tokenOutSupply, tokenInSupply, remReserves, ammIn) cfmmOut := solveCfmm(tokenOutSupply, tokenInSupply, remReserves, ammIn) @@ -204,7 +204,7 @@ func (p Pool) calcOutAmtGivenIn(tokenIn sdk.Coin, tokenOutDenom string, swapFee } // calcInAmtGivenOut calculates exact input amount given the desired output and return as a decimal -func (p *Pool) calcInAmtGivenOut(tokenOut sdk.Coin, tokenInDenom string, swapFee sdk.Dec) (sdk.Dec, error) { +func (p *Pool) calcInAmtGivenOut(tokenOut sdk.Coin, tokenInDenom string, spreadFactor sdk.Dec) (sdk.Dec, error) { // round liquidity down, and round token out up reserves, err := p.scaledSortedPoolReserves(tokenInDenom, tokenOut.Denom, osmomath.RoundDown) if err != nil { @@ -222,43 +222,43 @@ func (p *Pool) calcInAmtGivenOut(tokenOut sdk.Coin, tokenInDenom string, swapFee // returned cfmmIn is negative, representing we need to add this many tokens to pool. // We invert that negative here. cfmmIn = cfmmIn.Neg() - // divide by (1 - swapfee) to force a corresponding increase in input asset - inAmt := cfmmIn.QuoRoundUp(oneMinus(swapFee)) + // divide by (1 - spread factor) to force a corresponding increase in input asset + inAmt := cfmmIn.QuoRoundUp(oneMinus(spreadFactor)) inCoinAmt := p.getDescaledPoolAmt(tokenInDenom, inAmt) return inCoinAmt, nil } // calcSingleAssetJoinShares calculates the number of LP shares that // should be granted given the passed in single-token input (non-mutative) -func (p *Pool) calcSingleAssetJoinShares(tokenIn sdk.Coin, swapFee sdk.Dec) (sdk.Int, error) { +func (p *Pool) calcSingleAssetJoinShares(tokenIn sdk.Coin, spreadFactor sdk.Dec) (sdk.Int, error) { poolWithAddedLiquidityAndShares := func(newLiquidity sdk.Coin, newShares sdk.Int) types.CFMMPoolI { paCopy := p.Copy() paCopy.updatePoolForJoin(sdk.NewCoins(newLiquidity), newShares) return &paCopy } - // We apply the swap fee by multiplying by: - // 1) getting what % of the input the swap fee should apply to - // 2) multiplying that by swap fee - // 3) oneMinusSwapFee := (1 - swap_fee * swap_fee_applicable_percent) - // 4) Multiplying token in by one minus swap fee. - swapFeeApplicableRatio, err := p.singleAssetJoinSwapFeeRatio(tokenIn.Denom) + // We apply the spread factor by multiplying by: + // 1) getting what % of the input the spread factor should apply to + // 2) multiplying that by spread factor + // 3) oneMinusSpreadFactor := (1 - spread_factor * spread_factor_applicable_percent) + // 4) Multiplying token in by one minus spread factor. + spreadFactorApplicableRatio, err := p.singleAssetJoinSpreadFactorRatio(tokenIn.Denom) if err != nil { return sdk.Int{}, err } - oneMinusSwapFee := sdk.OneDec().Sub(swapFee.Mul(swapFeeApplicableRatio)) - tokenInAmtAfterFee := tokenIn.Amount.ToDec().Mul(oneMinusSwapFee).TruncateInt() + oneMinusSpreadFactor := sdk.OneDec().Sub(spreadFactor.Mul(spreadFactorApplicableRatio)) + tokenInAmtAfterFee := tokenIn.Amount.ToDec().Mul(oneMinusSpreadFactor).TruncateInt() return cfmm_common.BinarySearchSingleAssetJoin(p, sdk.NewCoin(tokenIn.Denom, tokenInAmtAfterFee), poolWithAddedLiquidityAndShares) } // returns the ratio of input asset liquidity, to total liquidity in pool, post-scaling. -// We use this as the portion of input liquidity to apply a swap fee too, for single asset joins. +// We use this as the portion of input liquidity to apply a spread factor too, for single asset joins. // So if a pool is currently comprised of 80% of asset A, and 20% of asset B (post-scaling), // and we input asset A, this function will return 20%. -// Note that this will over-estimate swap fee for single asset joins slightly, +// Note that this will over-estimate spread factor for single asset joins slightly, // as in the swapping process into the pool, the A to B ratio would decrease the relative supply of B. -func (p *Pool) singleAssetJoinSwapFeeRatio(tokenInDenom string) (sdk.Dec, error) { +func (p *Pool) singleAssetJoinSpreadFactorRatio(tokenInDenom string) (sdk.Dec, error) { // get a second denom in pool tokenOut := p.PoolLiquidity[0] if tokenOut.Denom == tokenInDenom { @@ -282,13 +282,13 @@ func (p *Pool) singleAssetJoinSwapFeeRatio(tokenInDenom string) (sdk.Dec, error) // Route a pool join attempt to either a single-asset join or all-asset join (mutates pool state) // Eventually, we intend to switch this to a COW wrapped pa for better performance -func (p *Pool) joinPoolSharesInternal(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, tokensJoined sdk.Coins, err error) { +func (p *Pool) joinPoolSharesInternal(ctx sdk.Context, tokensIn sdk.Coins, spreadFactor sdk.Dec) (numShares sdk.Int, tokensJoined sdk.Coins, err error) { if !tokensIn.DenomsSubsetOf(p.GetTotalPoolLiquidity(ctx)) { return sdk.ZeroInt(), sdk.NewCoins(), errors.New("attempted joining pool with assets that do not exist in pool") } if len(tokensIn) == 1 && tokensIn[0].Amount.GT(sdk.OneInt()) { - numShares, err = p.calcSingleAssetJoinShares(tokensIn[0], swapFee) + numShares, err = p.calcSingleAssetJoinShares(tokensIn[0], spreadFactor) if err != nil { return sdk.ZeroInt(), sdk.NewCoins(), err } diff --git a/x/gamm/pool-models/stableswap/amm_test.go b/x/gamm/pool-models/stableswap/amm_test.go index 6a3a412c048..294d0fd4dea 100644 --- a/x/gamm/pool-models/stableswap/amm_test.go +++ b/x/gamm/pool-models/stableswap/amm_test.go @@ -722,7 +722,7 @@ func (suite *StableSwapTestSuite) Test_StableSwap_CalculateAmountOutAndIn_Invers scalingFactors []uint64 } - // For every test case in testcases, apply a swap fee in swapFeeCases. + // For every test case in testcases, apply a spread factor in spreadFactorCases. testcases := map[string]testcase{ // two-asset pools "even pool": { @@ -889,34 +889,34 @@ func (suite *StableSwapTestSuite) Test_StableSwap_CalculateAmountOutAndIn_Invers } } - swapFeeCases := []string{"0", "0.001", "0.1", "0.5", "0.99"} + spreadFactorCases := []string{"0", "0.001", "0.1", "0.5", "0.99"} - getTestCaseName := func(name string, tc testcase, swapFeeCase string) string { - return fmt.Sprintf("%s: initialOut: %d, swapFee: %s", + getTestCaseName := func(name string, tc testcase, spreadFactorCase string) string { + return fmt.Sprintf("%s: initialOut: %d, spreadFactor: %s", name, tc.initialCalcOut, - swapFeeCase, + spreadFactorCase, ) } for name, tc := range testcases { - for _, swapFee := range swapFeeCases { - suite.Run(getTestCaseName(name, tc, swapFee), func() { + for _, spreadFactor := range spreadFactorCases { + suite.Run(getTestCaseName(name, tc, spreadFactor), func() { ctx := suite.CreateTestContext() - swapFeeDec, err := sdk.NewDecFromStr(swapFee) + spreadFactorDec, err := sdk.NewDecFromStr(spreadFactor) suite.Require().NoError(err) exitFeeDec, err := sdk.NewDecFromStr("0") suite.Require().NoError(err) // TODO: add scaling factors into inverse relationship tests - pool := createTestPool(suite.T(), tc.poolLiquidity, swapFeeDec, exitFeeDec, tc.scalingFactors) + pool := createTestPool(suite.T(), tc.poolLiquidity, spreadFactorDec, exitFeeDec, tc.scalingFactors) suite.Require().NotNil(pool) errTolerance := osmomath.ErrTolerance{ AdditiveTolerance: sdk.Dec{}, MultiplicativeTolerance: sdk.NewDecWithPrec(1, 12), } - test_helpers.TestCalculateAmountOutAndIn_InverseRelationship(suite.T(), ctx, pool, tc.denomIn, tc.denomOut, tc.initialCalcOut, swapFeeDec, errTolerance) + test_helpers.TestCalculateAmountOutAndIn_InverseRelationship(suite.T(), ctx, pool, tc.denomIn, tc.denomOut, tc.initialCalcOut, spreadFactorDec, errTolerance) }) } } @@ -941,11 +941,11 @@ func (suite *StableSwapTestSuite) Test_StableSwap_Slippage_LiquidityRelation() { scalingFactors: []uint64{3, 2}, }, } - swapFeeCases := []string{"0", "0.001", "0.1", "0.5", "0.99"} + spreadFactorCases := []string{"0", "0.001", "0.1", "0.5", "0.99"} for name, tc := range testcases { - for _, swapFee := range swapFeeCases { + for _, spreadFactor := range spreadFactorCases { createPoolFn := func(ctx sdk.Context, liq sdk.Coins) types.CFMMPoolI { - return createTestPool(suite.T(), liq, sdk.MustNewDecFromStr(swapFee), sdk.ZeroDec(), tc.scalingFactors) + return createTestPool(suite.T(), liq, sdk.MustNewDecFromStr(spreadFactor), sdk.ZeroDec(), tc.scalingFactors) } ctx := sdk.Context{} test_helpers.TestSlippageRelationWithLiquidityIncrease(name, suite.T(), ctx, createPoolFn, tc.initialLiquidity) @@ -974,82 +974,82 @@ func TestCalcSingleAssetJoinShares(t *testing.T) { tokenIn sdk.Coin poolAssets sdk.Coins scalingFactors []uint64 - swapFee sdk.Dec + spreadFactor sdk.Dec expectedOut sdk.Int } tests := map[string]testcase{ - // no swap fees - "even two asset pool, no swap fee": { + // no spread factors + "even two asset pool, no spread factor": { tokenIn: sdk.NewCoin("foo", sdk.NewInt(100)), poolAssets: twoEvenStablePoolAssets, scalingFactors: defaultTwoAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectedOut: sdk.NewInt(100), }, - "uneven two asset pool, no swap fee": { + "uneven two asset pool, no spread factor": { tokenIn: sdk.NewCoin("foo", sdk.NewInt(100)), poolAssets: twoUnevenStablePoolAssets, scalingFactors: defaultTwoAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectedOut: sdk.NewInt(100), }, - "even 3-asset pool, no swap fee": { + "even 3-asset pool, no spread factor": { tokenIn: sdk.NewCoin("asset/a", sdk.NewInt(1000)), poolAssets: threeEvenStablePoolAssets, scalingFactors: defaultThreeAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectedOut: sdk.NewInt(1000), }, - "uneven 3-asset pool, no swap fee": { + "uneven 3-asset pool, no spread factor": { tokenIn: sdk.NewCoin("asset/a", sdk.NewInt(100)), poolAssets: threeUnevenStablePoolAssets, scalingFactors: defaultThreeAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expectedOut: sdk.NewInt(100), }, - // with swap fees - "even two asset pool, default swap fee": { + // with spread factors + "even two asset pool, default spread factor": { tokenIn: sdk.NewCoin("foo", sdk.NewInt(100)), poolAssets: twoEvenStablePoolAssets, scalingFactors: defaultTwoAssetScalingFactors, - swapFee: defaultSwapFee, + spreadFactor: defaultSpreadFactor, expectedOut: sdk.NewInt(100 - 3), }, - "uneven two asset pool, default swap fee": { + "uneven two asset pool, default spread factor": { tokenIn: sdk.NewCoin("foo", sdk.NewInt(100)), poolAssets: twoUnevenStablePoolAssets, scalingFactors: defaultTwoAssetScalingFactors, - swapFee: defaultSwapFee, + spreadFactor: defaultSpreadFactor, expectedOut: sdk.NewInt(100 - 3), }, - "even 3-asset pool, default swap fee": { + "even 3-asset pool, default spread factor": { tokenIn: sdk.NewCoin("asset/a", sdk.NewInt(100)), poolAssets: threeEvenStablePoolAssets, scalingFactors: defaultThreeAssetScalingFactors, - swapFee: defaultSwapFee, + spreadFactor: defaultSpreadFactor, expectedOut: sdk.NewInt(100 - 3), }, - "uneven 3-asset pool, default swap fee": { + "uneven 3-asset pool, default spread factor": { tokenIn: sdk.NewCoin("asset/a", sdk.NewInt(100)), poolAssets: threeUnevenStablePoolAssets, scalingFactors: defaultThreeAssetScalingFactors, - swapFee: defaultSwapFee, + spreadFactor: defaultSpreadFactor, expectedOut: sdk.NewInt(100 - 3), }, - "even 3-asset pool, 0.03 swap fee": { + "even 3-asset pool, 0.03 spread factor": { tokenIn: sdk.NewCoin("asset/a", sdk.NewInt(100)), poolAssets: threeEvenStablePoolAssets, scalingFactors: defaultThreeAssetScalingFactors, - swapFee: sdk.MustNewDecFromStr("0.03"), + spreadFactor: sdk.MustNewDecFromStr("0.03"), expectedOut: sdk.NewInt(100 - 3), }, - "uneven 3-asset pool, 0.03 swap fee": { + "uneven 3-asset pool, 0.03 spread factor": { tokenIn: sdk.NewCoin("asset/a", sdk.NewInt(100)), poolAssets: threeUnevenStablePoolAssets, scalingFactors: defaultThreeAssetScalingFactors, - swapFee: sdk.MustNewDecFromStr("0.03"), + spreadFactor: sdk.MustNewDecFromStr("0.03"), expectedOut: sdk.NewInt(100 - 3), }, } @@ -1059,7 +1059,7 @@ func TestCalcSingleAssetJoinShares(t *testing.T) { ctx := sdk.Context{} p := poolStructFromAssets(tc.poolAssets, tc.scalingFactors) - shares, err := p.calcSingleAssetJoinShares(tc.tokenIn, tc.swapFee) + shares, err := p.calcSingleAssetJoinShares(tc.tokenIn, tc.spreadFactor) require.NoError(t, err, "test: %s", name) p.updatePoolForJoin(sdk.Coins{tc.tokenIn}, shares) @@ -1085,7 +1085,7 @@ func TestJoinPoolSharesInternal(t *testing.T) { tokensIn sdk.Coins poolAssets sdk.Coins scalingFactors []uint64 - swapFee sdk.Dec + spreadFactor sdk.Dec expNumShare sdk.Int expTokensJoined sdk.Coins expPoolAssets sdk.Coins @@ -1097,7 +1097,7 @@ func TestJoinPoolSharesInternal(t *testing.T) { tokensIn: tenPercentOfTwoPoolCoins, poolAssets: twoEvenStablePoolAssets, scalingFactors: defaultTwoAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expNumShare: sdk.NewIntFromUint64(10000000000000000000), expTokensJoined: tenPercentOfTwoPoolCoins, expPoolAssets: twoAssetPlusTenPercent, @@ -1107,7 +1107,7 @@ func TestJoinPoolSharesInternal(t *testing.T) { tokensIn: sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(tenPercentOfTwoPoolRaw)), sdk.NewCoin("bar", sdk.NewInt(10+tenPercentOfTwoPoolRaw))), poolAssets: twoEvenStablePoolAssets, scalingFactors: defaultTwoAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expNumShare: sdk.NewIntFromUint64(10000000000000000000), expTokensJoined: sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(tenPercentOfTwoPoolRaw)), sdk.NewCoin("bar", sdk.NewInt(tenPercentOfTwoPoolRaw))), expPoolAssets: twoAssetPlusTenPercent, @@ -1123,7 +1123,7 @@ func TestJoinPoolSharesInternal(t *testing.T) { sdk.NewCoin("bar", types.StableswapMaxScaledAmtPerAsset), ), scalingFactors: defaultTwoAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expNumShare: sdk.ZeroInt(), expTokensJoined: sdk.Coins{}, expPoolAssets: sdk.NewCoins( @@ -1141,7 +1141,7 @@ func TestJoinPoolSharesInternal(t *testing.T) { sdk.NewCoin("bar", types.StableswapMaxScaledAmtPerAsset), ), scalingFactors: defaultTwoAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expNumShare: sdk.ZeroInt(), expTokensJoined: sdk.Coins{}, expPoolAssets: sdk.NewCoins( @@ -1160,7 +1160,7 @@ func TestJoinPoolSharesInternal(t *testing.T) { sdk.NewCoin("bar", types.StableswapMaxScaledAmtPerAsset.Sub(sdk.NewInt(1))), ), scalingFactors: defaultTwoAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expNumShare: types.InitPoolSharesSupply.Quo(types.StableswapMaxScaledAmtPerAsset), expTokensJoined: sdk.NewCoins( sdk.NewInt64Coin("foo", 1), @@ -1179,7 +1179,7 @@ func TestJoinPoolSharesInternal(t *testing.T) { ctx := sdk.Context{} p := poolStructFromAssets(tc.poolAssets, tc.scalingFactors) - shares, joinedLiquidity, err := p.joinPoolSharesInternal(ctx, tc.tokensIn, tc.swapFee) + shares, joinedLiquidity, err := p.joinPoolSharesInternal(ctx, tc.tokensIn, tc.spreadFactor) if tc.expectPass { require.Equal(t, tc.expNumShare, shares) @@ -1191,7 +1191,7 @@ func TestJoinPoolSharesInternal(t *testing.T) { } } -func TestSingleAssetJoinSwapFeeRatio(t *testing.T) { +func TestSingleAssetJoinSpreadFactorRatio(t *testing.T) { largeInt, ok := sdk.NewIntFromString("123456789012345678") require.True(t, ok) type testcase struct { @@ -1240,7 +1240,7 @@ func TestSingleAssetJoinSwapFeeRatio(t *testing.T) { t.Run(name, func(t *testing.T) { p := poolStructFromAssets(tc.poolLiquidity, tc.scalingFactors) - ratio, err := p.singleAssetJoinSwapFeeRatio(tc.tokenInDenom) + ratio, err := p.singleAssetJoinSpreadFactorRatio(tc.tokenInDenom) require.NoError(t, err) require.Equal(t, tc.expectedRatio, ratio) }) diff --git a/x/gamm/pool-models/stableswap/msgs_test.go b/x/gamm/pool-models/stableswap/msgs_test.go index 869242e1ae2..3afeec3732e 100644 --- a/x/gamm/pool-models/stableswap/msgs_test.go +++ b/x/gamm/pool-models/stableswap/msgs_test.go @@ -118,7 +118,7 @@ func TestMsgCreateStableswapPoolValidateBasic(t *testing.T) { expectPass: false, }, { - name: "negative swap fee with zero exit fee", + name: "negative spread factor with zero exit fee", msg: updateMsg(func(msg stableswap.MsgCreateStableswapPool) stableswap.MsgCreateStableswapPool { msg.PoolParams = &stableswap.PoolParams{ SwapFee: sdk.NewDecWithPrec(-1, 2), @@ -193,7 +193,7 @@ func TestMsgCreateStableswapPoolValidateBasic(t *testing.T) { expectPass: true, }, { - name: "zero swap fee, zero exit fee", + name: "zero spread factor, zero exit fee", msg: updateMsg(func(msg stableswap.MsgCreateStableswapPool) stableswap.MsgCreateStableswapPool { msg.PoolParams = &stableswap.PoolParams{ ExitFee: sdk.NewDecWithPrec(0, 0), diff --git a/x/gamm/pool-models/stableswap/pool.go b/x/gamm/pool-models/stableswap/pool.go index c0d324ee4f8..8d47b9c9c8d 100644 --- a/x/gamm/pool-models/stableswap/pool.go +++ b/x/gamm/pool-models/stableswap/pool.go @@ -86,7 +86,7 @@ func (p Pool) GetId() uint64 { return p.Id } -func (p Pool) GetSwapFee(ctx sdk.Context) sdk.Dec { +func (p Pool) GetSpreadFactor(ctx sdk.Context) sdk.Dec { return p.PoolParams.SwapFee } @@ -239,11 +239,11 @@ func (p *Pool) updatePoolForJoin(tokensIn sdk.Coins, newShares sdk.Int) { // TODO: These should all get moved to amm.go // CalcOutAmtGivenIn calculates expected output amount given input token -func (p Pool) CalcOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDenom string, swapFee sdk.Dec) (tokenOut sdk.Coin, err error) { +func (p Pool) CalcOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDenom string, spreadFactor sdk.Dec) (tokenOut sdk.Coin, err error) { if tokenIn.Len() != 1 { return sdk.Coin{}, errors.New("stableswap CalcOutAmtGivenIn: tokenIn is of wrong length") } - outAmtDec, err := p.calcOutAmtGivenIn(tokenIn[0], tokenOutDenom, swapFee) + outAmtDec, err := p.calcOutAmtGivenIn(tokenIn[0], tokenOutDenom, spreadFactor) if err != nil { return sdk.Coin{}, err } @@ -258,12 +258,12 @@ func (p Pool) CalcOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDeno } // SwapOutAmtGivenIn executes a swap given a desired input amount -func (p *Pool) SwapOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDenom string, swapFee sdk.Dec) (tokenOut sdk.Coin, err error) { +func (p *Pool) SwapOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDenom string, spreadFactor sdk.Dec) (tokenOut sdk.Coin, err error) { if err = validatePoolLiquidity(p.PoolLiquidity.Add(tokenIn...), p.ScalingFactors); err != nil { return sdk.Coin{}, err } - tokenOut, err = p.CalcOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, swapFee) + tokenOut, err = p.CalcOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, spreadFactor) if err != nil { return sdk.Coin{}, err } @@ -274,12 +274,12 @@ func (p *Pool) SwapOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDen } // CalcInAmtGivenOut calculates input amount needed to receive given output -func (p Pool) CalcInAmtGivenOut(ctx sdk.Context, tokenOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) (tokenIn sdk.Coin, err error) { +func (p Pool) CalcInAmtGivenOut(ctx sdk.Context, tokenOut sdk.Coins, tokenInDenom string, spreadFactor sdk.Dec) (tokenIn sdk.Coin, err error) { if tokenOut.Len() != 1 { return sdk.Coin{}, errors.New("stableswap CalcInAmtGivenOut: tokenOut is of wrong length") } - amt, err := p.calcInAmtGivenOut(tokenOut[0], tokenInDenom, swapFee) + amt, err := p.calcInAmtGivenOut(tokenOut[0], tokenInDenom, spreadFactor) if err != nil { return sdk.Coin{}, err } @@ -295,8 +295,8 @@ func (p Pool) CalcInAmtGivenOut(ctx sdk.Context, tokenOut sdk.Coins, tokenInDeno } // SwapInAmtGivenOut executes a swap given a desired output amount -func (p *Pool) SwapInAmtGivenOut(ctx sdk.Context, tokenOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) (tokenIn sdk.Coin, err error) { - tokenIn, err = p.CalcInAmtGivenOut(ctx, tokenOut, tokenInDenom, swapFee) +func (p *Pool) SwapInAmtGivenOut(ctx sdk.Context, tokenOut sdk.Coins, tokenInDenom string, spreadFactor sdk.Dec) (tokenIn sdk.Coin, err error) { + tokenIn, err = p.CalcInAmtGivenOut(ctx, tokenOut, tokenInDenom, spreadFactor) if err != nil { return sdk.Coin{}, err } @@ -322,9 +322,9 @@ func (p Pool) Copy() Pool { return p2 } -func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, newLiquidity sdk.Coins, err error) { +func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, spreadFactor sdk.Dec) (numShares sdk.Int, newLiquidity sdk.Coins, err error) { pCopy := p.Copy() - return pCopy.joinPoolSharesInternal(ctx, tokensIn, swapFee) + return pCopy.joinPoolSharesInternal(ctx, tokensIn, spreadFactor) } // CalcJoinPoolNoSwapShares calculates the number of shares created to execute an all-asset pool join with the provided amount of `tokensIn`. @@ -332,7 +332,7 @@ func (p *Pool) CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee s // // Returns the number of shares created, the amount of coins actually joined into the pool as not all may tokens may be joinable. // If an all-asset join is not possible, returns an error. -func (p Pool) CalcJoinPoolNoSwapShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, tokensJoined sdk.Coins, err error) { +func (p Pool) CalcJoinPoolNoSwapShares(ctx sdk.Context, tokensIn sdk.Coins, spreadFactor sdk.Dec) (numShares sdk.Int, tokensJoined sdk.Coins, err error) { // ensure that there aren't too many or too few assets in `tokensIn` if tokensIn.Len() != p.NumAssets() || !tokensIn.DenomsSubsetOf(p.GetTotalPoolLiquidity(ctx)) { return sdk.ZeroInt(), sdk.NewCoins(), errors.New("no-swap joins require LP'ing with all assets in pool") @@ -355,13 +355,13 @@ func (p Pool) CalcJoinPoolNoSwapShares(ctx sdk.Context, tokensIn sdk.Coins, swap return numShares, tokensJoined, nil } -func (p *Pool) JoinPool(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (sdk.Int, error) { - numShares, _, err := p.joinPoolSharesInternal(ctx, tokensIn, swapFee) +func (p *Pool) JoinPool(ctx sdk.Context, tokensIn sdk.Coins, spreadFactor sdk.Dec) (sdk.Int, error) { + numShares, _, err := p.joinPoolSharesInternal(ctx, tokensIn, spreadFactor) return numShares, err } -func (p *Pool) JoinPoolNoSwap(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (sdk.Int, error) { - newShares, tokensJoined, err := p.CalcJoinPoolNoSwapShares(ctx, tokensIn, swapFee) +func (p *Pool) JoinPoolNoSwap(ctx sdk.Context, tokensIn sdk.Coins, spreadFactor sdk.Dec) (sdk.Int, error) { + newShares, tokensJoined, err := p.CalcJoinPoolNoSwapShares(ctx, tokensIn, spreadFactor) if err != nil { return sdk.Int{}, err } diff --git a/x/gamm/pool-models/stableswap/pool_params.go b/x/gamm/pool-models/stableswap/pool_params.go index f118ab0bd1d..48478a19eca 100644 --- a/x/gamm/pool-models/stableswap/pool_params.go +++ b/x/gamm/pool-models/stableswap/pool_params.go @@ -16,11 +16,11 @@ func (params PoolParams) Validate() error { } if params.SwapFee.IsNegative() { - return types.ErrNegativeSwapFee + return types.ErrNegativeSpreadFactor } if params.SwapFee.GTE(sdk.OneDec()) { - return types.ErrTooMuchSwapFee + return types.ErrTooMuchSpreadFactor } return nil } diff --git a/x/gamm/pool-models/stableswap/pool_test.go b/x/gamm/pool-models/stableswap/pool_test.go index f9634c89a9a..02131aa333d 100644 --- a/x/gamm/pool-models/stableswap/pool_test.go +++ b/x/gamm/pool-models/stableswap/pool_test.go @@ -17,11 +17,11 @@ import ( ) var ( - defaultSwapFee = sdk.MustNewDecFromStr("0.025") + defaultSpreadFactor = sdk.MustNewDecFromStr("0.025") defaultExitFee = sdk.ZeroDec() defaultPoolId = uint64(1) defaultStableswapPoolParams = PoolParams{ - SwapFee: defaultSwapFee, + SwapFee: defaultSpreadFactor, ExitFee: defaultExitFee, } defaultTwoAssetScalingFactors = []uint64{1, 1} @@ -675,7 +675,7 @@ func TestCalcJoinPoolNoSwapShares(t *testing.T) { t.Run(name, func(t *testing.T) { ctx := sdk.Context{} pool := poolStructFromAssets(test.poolAssets, test.scalingFactors) - numShare, tokensJoined, err := pool.CalcJoinPoolNoSwapShares(ctx, test.tokensIn, pool.GetSwapFee(ctx)) + numShare, tokensJoined, err := pool.CalcJoinPoolNoSwapShares(ctx, test.tokensIn, pool.GetSpreadFactor(ctx)) if test.expectPass { require.NoError(t, err) @@ -699,7 +699,7 @@ func TestSwapOutAmtGivenIn(t *testing.T) { tokenIn sdk.Coins expectedTokenOut sdk.Coin expectedPoolLiquidity sdk.Coins - swapFee sdk.Dec + spreadFactor sdk.Dec expError bool }{ "even pool basic trade": { @@ -708,7 +708,7 @@ func TestSwapOutAmtGivenIn(t *testing.T) { tokenIn: sdk.NewCoins(sdk.NewInt64Coin("foo", 100)), expectedTokenOut: sdk.NewInt64Coin("bar", 99), expectedPoolLiquidity: twoEvenStablePoolAssets.Add(sdk.NewInt64Coin("foo", 100)).Sub(sdk.NewCoins(sdk.NewInt64Coin("bar", 99))), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expError: false, }, "100:1 scaling factor ratio, even swap": { @@ -723,12 +723,12 @@ func TestSwapOutAmtGivenIn(t *testing.T) { sdk.NewInt64Coin("bar", 1000000000).SubAmount(sdk.NewIntFromUint64(9999)), sdk.NewInt64Coin("foo", 10000000).AddAmount(sdk.NewIntFromUint64(100)), ), - swapFee: sdk.ZeroDec(), - expError: false, + spreadFactor: sdk.ZeroDec(), + expError: false, }, // TODO: Add test cases here, where they're off 1-1 ratio // * (we just need to verify that the further off they are, further slippage is) - // * Add test cases with non-zero swap fee. + // * Add test cases with non-zero spread factor. // looks like its really an error due to slippage at limit "trade hits max pool capacity for asset": { poolAssets: sdk.NewCoins( @@ -742,8 +742,8 @@ func TestSwapOutAmtGivenIn(t *testing.T) { sdk.NewInt64Coin("foo", 9_999_999_999), sdk.NewInt64Coin("bar", 9_999_999_997), ), - swapFee: sdk.ZeroDec(), - expError: true, + spreadFactor: sdk.ZeroDec(), + expError: true, }, "trade exceeds max pool capacity for asset": { poolAssets: sdk.NewCoins( @@ -757,8 +757,8 @@ func TestSwapOutAmtGivenIn(t *testing.T) { sdk.NewInt64Coin("foo", 10_000_000_000), sdk.NewInt64Coin("bar", 10_000_000_000), ), - swapFee: sdk.ZeroDec(), - expError: true, + spreadFactor: sdk.ZeroDec(), + expError: true, }, } @@ -767,7 +767,7 @@ func TestSwapOutAmtGivenIn(t *testing.T) { ctx := sdk.Context{} p := poolStructFromAssets(tc.poolAssets, tc.scalingFactors) - tokenOut, err := p.SwapOutAmtGivenIn(ctx, tc.tokenIn, tc.expectedTokenOut.Denom, tc.swapFee) + tokenOut, err := p.SwapOutAmtGivenIn(ctx, tc.tokenIn, tc.expectedTokenOut.Denom, tc.spreadFactor) osmoassert.ConditionalError(t, tc.expError, err) if !tc.expError { require.Equal(t, tc.expectedTokenOut.Amount, tokenOut.Amount) @@ -786,7 +786,7 @@ func TestSwapInAmtGivenOut(t *testing.T) { tokenOut sdk.Coins expectedTokenIn sdk.Coin expectedPoolLiquidity sdk.Coins - swapFee sdk.Dec + spreadFactor sdk.Dec expError bool }{ "even pool basic trade": { @@ -795,7 +795,7 @@ func TestSwapInAmtGivenOut(t *testing.T) { tokenOut: sdk.NewCoins(sdk.NewInt64Coin("bar", 100)), expectedTokenIn: sdk.NewInt64Coin("foo", 100), expectedPoolLiquidity: twoEvenStablePoolAssets.Add(sdk.NewInt64Coin("foo", 100)).Sub(sdk.NewCoins(sdk.NewInt64Coin("bar", 100))), - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), expError: false, }, "trade hits max pool capacity for asset": { @@ -810,8 +810,8 @@ func TestSwapInAmtGivenOut(t *testing.T) { sdk.NewInt64Coin("foo", 9_999_999_998*types.ScalingFactorMultiplier), sdk.NewInt64Coin("bar", 9_999_999_996*types.ScalingFactorMultiplier), ), - swapFee: sdk.ZeroDec(), - expError: false, + spreadFactor: sdk.ZeroDec(), + expError: false, }, "trade exceeds max pool capacity for asset": { poolAssets: sdk.NewCoins( @@ -825,8 +825,8 @@ func TestSwapInAmtGivenOut(t *testing.T) { sdk.NewInt64Coin("foo", 10_000_000_000*types.ScalingFactorMultiplier), sdk.NewInt64Coin("bar", 10_000_000_000*types.ScalingFactorMultiplier), ), - swapFee: sdk.ZeroDec(), - expError: true, + spreadFactor: sdk.ZeroDec(), + expError: true, }, } @@ -835,7 +835,7 @@ func TestSwapInAmtGivenOut(t *testing.T) { ctx := sdk.Context{} p := poolStructFromAssets(tc.poolAssets, tc.scalingFactors) - tokenIn, err := p.SwapInAmtGivenOut(ctx, tc.tokenOut, tc.expectedTokenIn.Denom, tc.swapFee) + tokenIn, err := p.SwapInAmtGivenOut(ctx, tc.tokenOut, tc.expectedTokenIn.Denom, tc.spreadFactor) if !tc.expError { require.True(t, tokenIn.Amount.GTE(tc.expectedTokenIn.Amount)) require.True(t, p.PoolLiquidity.IsAllGTE(tc.expectedPoolLiquidity)) @@ -855,94 +855,94 @@ func TestInverseJoinPoolExitPool(t *testing.T) { poolAssets sdk.Coins unevenJoinedTokens sdk.Coins scalingFactors []uint64 - swapFee sdk.Dec + spreadFactor sdk.Dec } tests := map[string]testcase{ - "[single asset join] even two asset pool, no swap fee": { + "[single asset join] even two asset pool, no spread factor": { tokensIn: hundredFoo, poolAssets: twoEvenStablePoolAssets, scalingFactors: defaultTwoAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), }, - "[single asset join] uneven two asset pool, no swap fee": { + "[single asset join] uneven two asset pool, no spread factor": { tokensIn: hundredFoo, poolAssets: twoUnevenStablePoolAssets, scalingFactors: defaultTwoAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), }, - "[single asset join] even 3-asset pool, no swap fee": { + "[single asset join] even 3-asset pool, no spread factor": { tokensIn: thousandAssetA, poolAssets: threeEvenStablePoolAssets, scalingFactors: defaultThreeAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), }, - "[single asset join] uneven 3-asset pool, no swap fee": { + "[single asset join] uneven 3-asset pool, no spread factor": { tokensIn: thousandAssetA, poolAssets: threeUnevenStablePoolAssets, scalingFactors: defaultThreeAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), }, - "[single asset join] even two asset pool, default swap fee": { + "[single asset join] even two asset pool, default spread factor": { tokensIn: hundredFoo, poolAssets: twoEvenStablePoolAssets, scalingFactors: defaultTwoAssetScalingFactors, - swapFee: defaultSwapFee, + spreadFactor: defaultSpreadFactor, }, - "[single asset join] uneven two asset pool, default swap fee": { + "[single asset join] uneven two asset pool, default spread factor": { tokensIn: hundredFoo, poolAssets: twoUnevenStablePoolAssets, scalingFactors: defaultTwoAssetScalingFactors, - swapFee: defaultSwapFee, + spreadFactor: defaultSpreadFactor, }, - "[single asset join] even 3-asset pool, default swap fee": { + "[single asset join] even 3-asset pool, default spread factor": { tokensIn: thousandAssetA, poolAssets: threeEvenStablePoolAssets, scalingFactors: defaultThreeAssetScalingFactors, - swapFee: defaultSwapFee, + spreadFactor: defaultSpreadFactor, }, - "[single asset join] uneven 3-asset pool, default swap fee": { + "[single asset join] uneven 3-asset pool, default spread factor": { tokensIn: thousandAssetA, poolAssets: threeUnevenStablePoolAssets, scalingFactors: defaultThreeAssetScalingFactors, - swapFee: defaultSwapFee, + spreadFactor: defaultSpreadFactor, }, - "[single asset join] even 3-asset pool, 0.03 swap fee": { + "[single asset join] even 3-asset pool, 0.03 spread factor": { tokensIn: thousandAssetA, poolAssets: threeEvenStablePoolAssets, scalingFactors: defaultThreeAssetScalingFactors, - swapFee: sdk.MustNewDecFromStr("0.03"), + spreadFactor: sdk.MustNewDecFromStr("0.03"), }, - "[single asset join] uneven 3-asset pool, 0.03 swap fee": { + "[single asset join] uneven 3-asset pool, 0.03 spread factor": { tokensIn: thousandAssetA, poolAssets: threeUnevenStablePoolAssets, scalingFactors: defaultThreeAssetScalingFactors, - swapFee: sdk.MustNewDecFromStr("0.03"), + spreadFactor: sdk.MustNewDecFromStr("0.03"), }, "[all asset join] even two asset pool, same tokenIn ratio": { tokensIn: tenPercentOfTwoPoolCoins, poolAssets: twoEvenStablePoolAssets, scalingFactors: defaultTwoAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), }, "[all asset join] even two asset pool, different tokenIn ratio with pool": { tokensIn: sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(tenPercentOfTwoPoolRaw)), sdk.NewCoin("bar", sdk.NewInt(10+tenPercentOfTwoPoolRaw))), poolAssets: twoEvenStablePoolAssets, scalingFactors: defaultTwoAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), }, - "[all asset join] even two asset pool, different tokenIn ratio with pool, nonzero swap fee": { + "[all asset join] even two asset pool, different tokenIn ratio with pool, nonzero spread factor": { tokensIn: sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(tenPercentOfTwoPoolRaw)), sdk.NewCoin("bar", sdk.NewInt(10+tenPercentOfTwoPoolRaw))), poolAssets: twoEvenStablePoolAssets, scalingFactors: defaultTwoAssetScalingFactors, - swapFee: defaultSwapFee, + spreadFactor: defaultSpreadFactor, }, "[all asset join] even two asset pool, no tokens in": { tokensIn: sdk.NewCoins(), poolAssets: twoEvenStablePoolAssets, scalingFactors: defaultTwoAssetScalingFactors, - swapFee: sdk.ZeroDec(), + spreadFactor: sdk.ZeroDec(), }, } @@ -955,12 +955,12 @@ func TestInverseJoinPoolExitPool(t *testing.T) { var swapRatio sdk.Dec var err error if len(tc.tokensIn) == 1 { - swapRatio, err = p.singleAssetJoinSwapFeeRatio(tc.tokensIn[0].Denom) + swapRatio, err = p.singleAssetJoinSpreadFactorRatio(tc.tokensIn[0].Denom) require.NoError(t, err) } // we join then exit the pool - shares, _ := p.JoinPool(ctx, tc.tokensIn, tc.swapFee) + shares, _ := p.JoinPool(ctx, tc.tokensIn, tc.spreadFactor) tokenOut, err := p.ExitPool(ctx, shares, defaultExitFee) require.NoError(t, err) @@ -975,8 +975,8 @@ func TestInverseJoinPoolExitPool(t *testing.T) { // to be smaller by swap ratio * 2 var expectedTokenOut sdk.Coins if len(tc.tokensIn) == 1 { - oneMinusSingleSwapFee := sdk.OneDec().Sub((swapRatio.Mul(tc.swapFee))) - expectedAmt := (tc.tokensIn[0].Amount.ToDec().Mul(oneMinusSingleSwapFee)).TruncateInt() + oneMinusSingleSpreadFactor := sdk.OneDec().Sub((swapRatio.Mul(tc.spreadFactor))) + expectedAmt := (tc.tokensIn[0].Amount.ToDec().Mul(oneMinusSingleSpreadFactor)).TruncateInt() expectedTokenOut = sdk.NewCoins(sdk.NewCoin(tc.tokensIn[0].Denom, expectedAmt)) } else { expectedTokenOut = tc.tokensIn diff --git a/x/gamm/pool-models/stableswap/util_test.go b/x/gamm/pool-models/stableswap/util_test.go index be7dfb6c464..70b6216d1c3 100644 --- a/x/gamm/pool-models/stableswap/util_test.go +++ b/x/gamm/pool-models/stableswap/util_test.go @@ -9,13 +9,13 @@ import ( "github.com/osmosis-labs/osmosis/v15/x/gamm/types" ) -func createTestPool(t *testing.T, poolLiquidity sdk.Coins, swapFee, exitFee sdk.Dec, scalingFactors []uint64) types.CFMMPoolI { +func createTestPool(t *testing.T, poolLiquidity sdk.Coins, spreadFactor, exitFee sdk.Dec, scalingFactors []uint64) types.CFMMPoolI { t.Helper() scalingFactors, _ = applyScalingFactorMultiplier(scalingFactors) pool, err := NewStableswapPool(1, PoolParams{ - SwapFee: swapFee, - ExitFee: exitFee, + SwapFee: spreadFactor, + ExitFee: exitFee, }, poolLiquidity, scalingFactors, "", "") require.NoError(t, err) diff --git a/x/gamm/simulation/sim_msgs.go b/x/gamm/simulation/sim_msgs.go index 691c643fdbe..6e355ba3d73 100644 --- a/x/gamm/simulation/sim_msgs.go +++ b/x/gamm/simulation/sim_msgs.go @@ -145,7 +145,7 @@ func RandomSwapExactAmountIn(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Cont randomCoinSubset := sim.RandSubsetCoins(sdk.NewCoins(sdk.NewCoin(accCoinIn.Denom, accCoinIn.Amount))) // calculate the minimum number of tokens received from input of tokenIn - tokenOutMin, err := pool.CalcOutAmtGivenIn(ctx, randomCoinSubset, coinOut.Denom, pool.GetSwapFee(ctx)) + tokenOutMin, err := pool.CalcOutAmtGivenIn(ctx, randomCoinSubset, coinOut.Denom, pool.GetSpreadFactor(ctx)) if err != nil { return nil, err } @@ -183,11 +183,11 @@ func RandomSwapExactAmountOut(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Con randomCoinInSubset := osmoutils.MinCoins(sdk.NewCoins(coinIn), sdk.NewCoins(accCoin)) // utilize CalcOutAmtGivenIn to calculate tokenOut and use tokenOut to calculate tokenInMax - tokenOut, err := pool.CalcOutAmtGivenIn(ctx, randomCoinInSubset, coinOut.Denom, pool.GetSwapFee(ctx)) + tokenOut, err := pool.CalcOutAmtGivenIn(ctx, randomCoinInSubset, coinOut.Denom, pool.GetSpreadFactor(ctx)) if err != nil { return nil, err } - tokenInMax, err := pool.CalcInAmtGivenOut(ctx, sdk.NewCoins(tokenOut), coinIn.Denom, pool.GetSwapFee(ctx)) + tokenInMax, err := pool.CalcInAmtGivenOut(ctx, sdk.NewCoins(tokenOut), coinIn.Denom, pool.GetSpreadFactor(ctx)) if err != nil { return nil, err } @@ -219,7 +219,7 @@ func RandomJoinSwapExternAmountIn(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk newTokenIn := osmoutils.MinCoins(sdk.NewCoins(coinIn), sdk.NewCoins(tokenIn)) // calc shares out with tokenIn - minShareOutAmt, _, err := pool.CalcJoinPoolShares(ctx, newTokenIn, pool.GetSwapFee(ctx)) + minShareOutAmt, _, err := pool.CalcJoinPoolShares(ctx, newTokenIn, pool.GetSpreadFactor(ctx)) if err != nil { return nil, err } @@ -251,7 +251,7 @@ func RandomJoinSwapShareAmountOut(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk newTokenIn := osmoutils.MinCoins(sdk.NewCoins(coinIn), sdk.NewCoins(tokenIn)) // calc shares out with tokenIn - minShareOutAmt, _, err := pool.CalcJoinPoolShares(ctx, newTokenIn, pool.GetSwapFee(ctx)) + minShareOutAmt, _, err := pool.CalcJoinPoolShares(ctx, newTokenIn, pool.GetSpreadFactor(ctx)) if err != nil { return nil, err } @@ -261,7 +261,7 @@ func RandomJoinSwapShareAmountOut(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk if !ok { return nil, fmt.Errorf("pool with id %d does not support this kind of join", pool_id) } - tokenInAmount, err := extendedPool.CalcTokenInShareAmountOut(ctx, tokenIn.Denom, minShareOutAmt, pool.GetSwapFee(ctx)) + tokenInAmount, err := extendedPool.CalcTokenInShareAmountOut(ctx, tokenIn.Denom, minShareOutAmt, pool.GetSpreadFactor(ctx)) if err != nil { return nil, err } @@ -306,7 +306,7 @@ func RandomExitSwapExternAmountOut(k keeper.Keeper, sim *simtypes.SimCtx, ctx sd // get amount of coinIn from exitedCoins and calculate how much of tokenOut you should get from that exitedCoinsIn := exitedCoins.AmountOf(coinIn.Denom) - tokenOut, err := pool.CalcOutAmtGivenIn(ctx, sdk.NewCoins(sdk.NewCoin(coinIn.Denom, exitedCoinsIn)), coinOut.Denom, pool.GetSwapFee(ctx)) + tokenOut, err := pool.CalcOutAmtGivenIn(ctx, sdk.NewCoins(sdk.NewCoin(coinIn.Denom, exitedCoinsIn)), coinOut.Denom, pool.GetSpreadFactor(ctx)) if err != nil { return nil, err } @@ -348,7 +348,7 @@ func RandomExitSwapShareAmountIn(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk. // get amount of coinIn from exitedCoins and calculate how much of tokenOut you should get from that exitedCoinsIn := exitedCoins.AmountOf(coinIn.Denom) - tokenOut, err := pool.CalcOutAmtGivenIn(ctx, sdk.NewCoins(sdk.NewCoin(coinIn.Denom, exitedCoinsIn)), coinOut.Denom, pool.GetSwapFee(ctx)) + tokenOut, err := pool.CalcOutAmtGivenIn(ctx, sdk.NewCoins(sdk.NewCoin(coinIn.Denom, exitedCoinsIn)), coinOut.Denom, pool.GetSpreadFactor(ctx)) if err != nil { return nil, err } @@ -367,7 +367,7 @@ func RandomExitSwapShareAmountIn(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk. // TODO: Fix CalcJoinPoolShares API so we don't have to do this func deriveRealMinShareOutAmt(ctx sdk.Context, tokenIn sdk.Coins, pool types.CFMMPoolI) (sdk.Int, error) { - minShareOutAmt, _, err := pool.CalcJoinPoolShares(ctx, tokenIn, pool.GetSwapFee(ctx)) + minShareOutAmt, _, err := pool.CalcJoinPoolShares(ctx, tokenIn, pool.GetSpreadFactor(ctx)) if err != nil { return sdk.Int{}, err } diff --git a/x/gamm/types/constants.go b/x/gamm/types/constants.go index 7abe5647a52..8cc43273661 100644 --- a/x/gamm/types/constants.go +++ b/x/gamm/types/constants.go @@ -38,8 +38,8 @@ var ( // It is limited by sdk.Dec's precision. MinSpotPrice = sdk.SmallestDec() - // MultihopSwapFeeMultiplierForOsmoPools if a swap fees multiplier for trades consists of just two OSMO pools during a single transaction. - MultihopSwapFeeMultiplierForOsmoPools = sdk.NewDecWithPrec(5, 1) // 0.5 + // MultihopSpreadFactorMultiplierForOsmoPools if a spread factor multiplier for trades consists of just two OSMO pools during a single transaction. + MultihopSpreadFactorMultiplierForOsmoPools = sdk.NewDecWithPrec(5, 1) // 0.5 // Maximum amount per asset after the application of scaling factors should be 10e34. StableswapMaxScaledAmtPerAsset = sdk.NewDec(10).Power(34).TruncateInt() diff --git a/x/gamm/types/errors.go b/x/gamm/types/errors.go index 8a97103e6f0..b36dcc8a6fb 100644 --- a/x/gamm/types/errors.go +++ b/x/gamm/types/errors.go @@ -67,9 +67,9 @@ var ( ErrEmptyRoutes = errorsmod.Register(ModuleName, 21, "routes not defined") ErrEmptyPoolAssets = errorsmod.Register(ModuleName, 22, "PoolAssets not defined") - ErrNegativeSwapFee = errorsmod.Register(ModuleName, 23, "swap fee is negative") + ErrNegativeSpreadFactor = errorsmod.Register(ModuleName, 23, "spread factor is negative") ErrNegativeExitFee = errorsmod.Register(ModuleName, 24, "exit fee is negative") - ErrTooMuchSwapFee = errorsmod.Register(ModuleName, 25, "swap fee should be lesser than 1 (100%)") + ErrTooMuchSpreadFactor = errorsmod.Register(ModuleName, 25, "spread factor should be lesser than 1 (100%)") ErrTooMuchExitFee = errorsmod.Register(ModuleName, 26, "exit fee should be lesser than 1 (100%)") ErrNotPositiveWeight = errorsmod.Register(ModuleName, 27, "token weight should be greater than 0") ErrWeightTooLarge = errorsmod.Register(ModuleName, 28, "user specified token weight should be less than 2^20") diff --git a/x/gamm/types/pool.go b/x/gamm/types/pool.go index 890dccecc39..6c9fce10153 100644 --- a/x/gamm/types/pool.go +++ b/x/gamm/types/pool.go @@ -18,11 +18,11 @@ type CFMMPoolI interface { // This function is mutative and updates the pool's internal state if there is no error. // It is up to pool implementation if they support LP'ing at arbitrary ratios, or a subset of ratios. // Pools are expected to guarantee LP'ing at the exact ratio, and single sided LP'ing. - JoinPool(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, err error) + JoinPool(ctx sdk.Context, tokensIn sdk.Coins, spreadFactor sdk.Dec) (numShares sdk.Int, err error) // JoinPoolNoSwap joins the pool with an all-asset join using the maximum amount possible given the tokensIn provided. // This function is mutative and updates the pool's internal state if there is no error. // Pools are expected to guarantee LP'ing at the exact ratio. - JoinPoolNoSwap(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, err error) + JoinPoolNoSwap(ctx sdk.Context, tokensIn sdk.Coins, spreadFactor sdk.Dec) (numShares sdk.Int, err error) // ExitPool exits #numShares LP shares from the pool, decreases its internal liquidity & LP share totals, // and returns the number of coins that are being returned. @@ -30,26 +30,26 @@ type CFMMPoolI interface { ExitPool(ctx sdk.Context, numShares sdk.Int, exitFee sdk.Dec) (exitedCoins sdk.Coins, err error) // CalcJoinPoolNoSwapShares returns how many LP shares JoinPoolNoSwap would return on these arguments. // This does not mutate the pool, or state. - CalcJoinPoolNoSwapShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, newLiquidity sdk.Coins, err error) + CalcJoinPoolNoSwapShares(ctx sdk.Context, tokensIn sdk.Coins, spreadFactor sdk.Dec) (numShares sdk.Int, newLiquidity sdk.Coins, err error) // CalcExitPoolCoinsFromShares returns how many coins ExitPool would return on these arguments. // This does not mutate the pool, or state. CalcExitPoolCoinsFromShares(ctx sdk.Context, numShares sdk.Int, exitFee sdk.Dec) (exitedCoins sdk.Coins, err error) // CalcJoinPoolShares returns how many LP shares JoinPool would return on these arguments. // This does not mutate the pool, or state. - CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, newLiquidity sdk.Coins, err error) - // SwapOutAmtGivenIn swaps 'tokenIn' against the pool, for tokenOutDenom, with the provided swapFee charged. + CalcJoinPoolShares(ctx sdk.Context, tokensIn sdk.Coins, spreadFactor sdk.Dec) (numShares sdk.Int, newLiquidity sdk.Coins, err error) + // SwapOutAmtGivenIn swaps 'tokenIn' against the pool, for tokenOutDenom, with the provided spreadFactor charged. // Balance transfers are done in the keeper, but this method updates the internal pool state. - SwapOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDenom string, swapFee sdk.Dec) (tokenOut sdk.Coin, err error) + SwapOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDenom string, spreadFactor sdk.Dec) (tokenOut sdk.Coin, err error) // CalcOutAmtGivenIn returns how many coins SwapOutAmtGivenIn would return on these arguments. // This does not mutate the pool, or state. - CalcOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDenom string, swapFee sdk.Dec) (tokenOut sdk.Coin, err error) + CalcOutAmtGivenIn(ctx sdk.Context, tokenIn sdk.Coins, tokenOutDenom string, spreadFactor sdk.Dec) (tokenOut sdk.Coin, err error) // SwapInAmtGivenOut swaps exactly enough tokensIn against the pool, to get the provided tokenOut amount out of the pool. // Balance transfers are done in the keeper, but this method updates the internal pool state. - SwapInAmtGivenOut(ctx sdk.Context, tokenOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) (tokenIn sdk.Coin, err error) + SwapInAmtGivenOut(ctx sdk.Context, tokenOut sdk.Coins, tokenInDenom string, spreadFactor sdk.Dec) (tokenIn sdk.Coin, err error) // CalcInAmtGivenOut returns how many coins SwapInAmtGivenOut would return on these arguments. // This does not mutate the pool, or state. - CalcInAmtGivenOut(ctx sdk.Context, tokenOut sdk.Coins, tokenInDenom string, swapFee sdk.Dec) (tokenIn sdk.Coin, err error) + CalcInAmtGivenOut(ctx sdk.Context, tokenOut sdk.Coins, tokenInDenom string, spreadFactor sdk.Dec) (tokenIn sdk.Coin, err error) // GetTotalShares returns the total number of LP shares in the pool GetTotalShares() sdk.Int // GetTotalPoolLiquidity returns the coins in the pool owned by all LPs @@ -77,7 +77,7 @@ type PoolAmountOutExtension interface { ctx sdk.Context, tokenInDenom string, shareOutAmount sdk.Int, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (tokenInAmount sdk.Int, err error) // JoinPoolTokenInMaxShareAmountOut add liquidity to a specified pool with a maximum amount of tokens in (tokenInMaxAmount) diff --git a/x/poolmanager/README.md b/x/poolmanager/README.md index 5b6f07f5dcc..f5bb0a82f26 100644 --- a/x/poolmanager/README.md +++ b/x/poolmanager/README.md @@ -247,7 +247,7 @@ type SwapI interface { tokenIn sdk.Coin, tokenOutDenom string, tokenOutMinAmount sdk.Int, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (sdk.Int, error) } ``` @@ -261,7 +261,7 @@ For example, in the context of balancer pools, given a `tokenIn`, the following calculations are done to calculate how many tokens are to be swapped into and removed from the pool: -`tokenBalanceOut * [1 - { tokenBalanceIn / (tokenBalanceIn + (1 - swapFee) * tokenAmountIn)} ^ (tokenWeightIn / tokenWeightOut)]` +`tokenBalanceOut * [1 - { tokenBalanceIn / (tokenBalanceIn + (1 - spreadFactor) * tokenAmountIn)} ^ (tokenWeightIn / tokenWeightOut)]` The calculation is also able to be reversed, the case where user provides `tokenOut`. The calculation for the amount of tokens that the @@ -300,9 +300,9 @@ The most cost-efficient route is determined offline and the list of the pools is At the moment of execution, the provided route may not be the most cost-efficient one anymore. When a trade consists of just two OSMO-included routes during a single transaction, -the swap fees on each hop would be automatically halved. -Example: for converting `ATOM -> OSMO -> LUNA` using two pools with swap fees `0.3% + 0.2%`, -instead `0.15% + 0.1%` fees will be applied. +the spread factors on each hop would be automatically halved. +Example: for converting `ATOM -> OSMO -> LUNA` using two pools with spread factors `0.3% + 0.2%`, +instead `0.15% + 0.1%` spread factors will be applied. [Multi-Hop](https://github.com/osmosis-labs/osmosis/blob/f26ceb958adaaf31510e17ed88f5eab47e2bac03/x/poolmanager/router.go#L16) @@ -311,7 +311,7 @@ instead `0.15% + 0.1%` fees will be applied. Each route can be thought of as a separate multi-hop swap. Splitting swaps across multiple pools for the same token pair can be beneficial for several reasons, -primarily relating to reduced slippage, price impact, and potentially lower fees. +primarily relating to reduced slippage, price impact, and potentially lower spreads. Here's a detailed explanation of these advantages: @@ -320,12 +320,12 @@ Here's a detailed explanation of these advantages: - **Lower price impact**: When executing a large trade in a single pool, the price impact can be substantial, leading to a less favorable exchange rate for the trader. By splitting the swap across multiple pools, the price impact in each pool is minimized, resulting in a better overall exchange rate. -- **Improved liquidity utilization**: Different pools may have varying levels of liquidity, fees, and price curves. By splitting swaps across multiple pools, +- **Improved liquidity utilization**: Different pools may have varying levels of liquidity, spreads, and price curves. By splitting swaps across multiple pools, the router can utilize liquidity from various sources, allowing for more efficient execution of trades. This is particularly useful when the liquidity in a single pool is not sufficient to handle a large trade or when the price curve of one pool becomes less favorable as the trade size increases. -- **Potentially lower fees**: In some cases, splitting swaps across multiple pools may result in lower overall fees. This can happen when different pools -have different fee structures, or when the total fee paid across multiple pools is lower than the fee for executing the entire trade in a single pool with +- **Potentially lower spreads**: In some cases, splitting swaps across multiple pools may result in lower overall spreads. This can happen when different pools +have different spread structures, or when the total spread paid across multiple pools is lower than the spread for executing the entire trade in a single pool with higher slippage. Note, that the actual split happens off-chain. The router is only responsible for executing the swaps in the order and quantities of token in provided diff --git a/x/poolmanager/client/cli/tx.go b/x/poolmanager/client/cli/tx.go index a8c2bc198f2..fd480976d44 100644 --- a/x/poolmanager/client/cli/tx.go +++ b/x/poolmanager/client/cli/tx.go @@ -166,7 +166,7 @@ func NewBuildCreateBalancerPoolMsg(clientCtx client.Context, txf tx.Factory, fs return txf, nil, errors.New("deposit tokens and token weights should have same length") } - swapFee, err := sdk.NewDecFromStr(pool.SwapFee) + spreadFactor, err := sdk.NewDecFromStr(pool.SwapFee) if err != nil { return txf, nil, err } @@ -189,7 +189,7 @@ func NewBuildCreateBalancerPoolMsg(clientCtx client.Context, txf tx.Factory, fs } poolParams := &balancer.PoolParams{ - SwapFee: swapFee, + SwapFee: spreadFactor, ExitFee: exitFee, } @@ -257,7 +257,7 @@ func NewBuildCreateStableswapPoolMsg(clientCtx client.Context, txf tx.Factory, f return txf, nil, err } - swapFee, err := sdk.NewDecFromStr(flags.SwapFee) + spreadFactor, err := sdk.NewDecFromStr(flags.SwapFee) if err != nil { return txf, nil, err } @@ -268,7 +268,7 @@ func NewBuildCreateStableswapPoolMsg(clientCtx client.Context, txf tx.Factory, f } poolParams := &stableswap.PoolParams{ - SwapFee: swapFee, + SwapFee: spreadFactor, ExitFee: exitFee, } diff --git a/x/poolmanager/client/testutil/test_helpers.go b/x/poolmanager/client/testutil/test_helpers.go index b583cd9268c..15db7730229 100644 --- a/x/poolmanager/client/testutil/test_helpers.go +++ b/x/poolmanager/client/testutil/test_helpers.go @@ -31,7 +31,7 @@ func MsgCreatePool( owner fmt.Stringer, tokenWeights string, initialDeposit string, - swapFee string, + spreadFactor string, exitFee string, futureGovernor string, extraArgs ...string, @@ -53,7 +53,7 @@ func MsgCreatePool( poolmanagercli.PoolFileInitialDeposit, initialDeposit, poolmanagercli.PoolFileSwapFee, - swapFee, + spreadFactor, poolmanagercli.PoolFileExitFee, exitFee, poolmanagercli.PoolFileExitFee, diff --git a/x/poolmanager/create_pool_test.go b/x/poolmanager/create_pool_test.go index 464cf8dddff..01398a0ba72 100644 --- a/x/poolmanager/create_pool_test.go +++ b/x/poolmanager/create_pool_test.go @@ -148,7 +148,7 @@ func (s *KeeperTestSuite) TestCreatePool() { invalidStableswapPoolMsg = stableswap.NewMsgCreateStableswapPool(s.TestAccs[0], stableswap.PoolParams{SwapFee: sdk.NewDec(0), ExitFee: sdk.NewDecWithPrec(1, 2)}, DefaultStableswapLiquidity, []uint64{}, "") - validConcentratedPoolMsg = clmodel.NewMsgCreateConcentratedPool(s.TestAccs[0], foo, bar, 1, defaultPoolSwapFee) + validConcentratedPoolMsg = clmodel.NewMsgCreateConcentratedPool(s.TestAccs[0], foo, bar, 1, defaultPoolSpreadFactor) defaultFundAmount = sdk.NewCoins(sdk.NewCoin(foo, defaultInitPoolAmount.Mul(sdk.NewInt(2))), sdk.NewCoin(bar, defaultInitPoolAmount.Mul(sdk.NewInt(2)))) ) @@ -266,7 +266,7 @@ func (s *KeeperTestSuite) TestCreatePoolZeroLiquidityNoCreationFee() { }, }, "") - concentratedPoolMsg := clmodel.NewMsgCreateConcentratedPool(poolManagerModuleAcc.GetAddress(), foo, bar, 1, defaultPoolSwapFee) + concentratedPoolMsg := clmodel.NewMsgCreateConcentratedPool(poolManagerModuleAcc.GetAddress(), foo, bar, 1, defaultPoolSpreadFactor) tests := []struct { name string diff --git a/x/poolmanager/export_test.go b/x/poolmanager/export_test.go index 2aa856a9f79..e0498ec4f97 100644 --- a/x/poolmanager/export_test.go +++ b/x/poolmanager/export_test.go @@ -12,10 +12,10 @@ func (k Keeper) GetNextPoolIdAndIncrement(ctx sdk.Context) uint64 { return k.getNextPoolIdAndIncrement(ctx) } -func (k Keeper) GetOsmoRoutedMultihopTotalSwapFee(ctx sdk.Context, route types.MultihopRoute) ( - totalPathSwapFee sdk.Dec, sumOfSwapFees sdk.Dec, err error, +func (k Keeper) GetOsmoRoutedMultihopTotalSpreadFactor(ctx sdk.Context, route types.MultihopRoute) ( + totalPathSpreadFactor sdk.Dec, sumOfSpreadFactors sdk.Dec, err error, ) { - return k.getOsmoRoutedMultihopTotalSwapFee(ctx, route) + return k.getOsmoRoutedMultihopTotalSpreadFactor(ctx, route) } // SetPoolRoutesUnsafe sets the given routes to the poolmanager keeper diff --git a/x/poolmanager/keeper_test.go b/x/poolmanager/keeper_test.go index 30ec917e275..a43f1e7a231 100644 --- a/x/poolmanager/keeper_test.go +++ b/x/poolmanager/keeper_test.go @@ -39,14 +39,14 @@ func (s *KeeperTestSuite) SetupTest() { s.Setup() } -// createBalancerPoolsFromCoinsWithSwapFee creates balancer pools from given sets of coins and respective swap fees. +// createBalancerPoolsFromCoinsWithSpreadFactor creates balancer pools from given sets of coins and respective spread factors. // Where element 1 of the input corresponds to the first pool created, // element 2 to the second pool created, up until the last element. -func (s *KeeperTestSuite) createBalancerPoolsFromCoinsWithSwapFee(poolCoins []sdk.Coins, swapFee []sdk.Dec) { +func (s *KeeperTestSuite) createBalancerPoolsFromCoinsWithSpreadFactor(poolCoins []sdk.Coins, spreadFactor []sdk.Dec) { for i, curPoolCoins := range poolCoins { s.FundAcc(s.TestAccs[0], curPoolCoins) s.PrepareCustomBalancerPoolFromCoins(curPoolCoins, balancer.PoolParams{ - SwapFee: swapFee[i], + SwapFee: spreadFactor[i], ExitFee: sdk.ZeroDec(), }) } diff --git a/x/poolmanager/router.go b/x/poolmanager/router.go index baf882033ee..008917c0b33 100644 --- a/x/poolmanager/router.go +++ b/x/poolmanager/router.go @@ -29,9 +29,9 @@ func (k Keeper) RouteExactAmountIn( tokenOutMinAmount sdk.Int, ) (tokenOutAmount sdk.Int, err error) { var ( - isMultiHopRouted bool - routeSwapFee sdk.Dec - sumOfSwapFees sdk.Dec + isMultiHopRouted bool + routeSpreadFactor sdk.Dec + sumOfSpreadFactors sdk.Dec ) // Ensure that provided route is not empty and has valid denom format. @@ -48,11 +48,11 @@ func (k Keeper) RouteExactAmountIn( // // If all of the above is true, then we collect the additive and max fee between the // two pools to later calculate the following: - // total_swap_fee = max(swapfee1, swapfee2) - // fee_per_pool = total_swap_fee * ((pool_fee) / (swapfee1 + swapfee2)) + // total_spread_factor = max(spread_factor1, spread_factor2) + // fee_per_pool = total_spread_factor * ((pool_fee) / (spread_factor1 + spread_factor2)) if k.isOsmoRoutedMultihop(ctx, routeStep, route[0].TokenOutDenom, tokenIn.Denom) { isMultiHopRouted = true - routeSwapFee, sumOfSwapFees, err = k.getOsmoRoutedMultihopTotalSwapFee(ctx, routeStep) + routeSpreadFactor, sumOfSpreadFactors, err = k.getOsmoRoutedMultihopTotalSpreadFactor(ctx, routeStep) if err != nil { return sdk.Int{}, err } @@ -84,15 +84,15 @@ func (k Keeper) RouteExactAmountIn( return sdk.Int{}, types.InactivePoolError{PoolId: pool.GetId()} } - swapFee := pool.GetSwapFee(ctx) + spreadFactor := pool.GetSpreadFactor(ctx) - // If we determined the routeStep is an osmo multi-hop and both route are incentivized, - // we modify the swap fee accordingly. + // If we determined the route is an osmo multi-hop and both routes are incentivized, + // we modify the spread factor accordingly. if isMultiHopRouted { - swapFee = routeSwapFee.MulRoundUp((swapFee.QuoRoundUp(sumOfSwapFees))) + spreadFactor = routeSpreadFactor.MulRoundUp((spreadFactor.QuoRoundUp(sumOfSpreadFactors))) } - tokenOutAmount, err = swapModule.SwapExactAmountIn(ctx, sender, pool, tokenIn, routeStep.TokenOutDenom, _outMinAmount, swapFee) + tokenOutAmount, err = swapModule.SwapExactAmountIn(ctx, sender, pool, tokenIn, routeStep.TokenOutDenom, _outMinAmount, spreadFactor) if err != nil { return sdk.Int{}, err } @@ -203,10 +203,10 @@ func (k Keeper) SwapExactAmountIn( return sdk.Int{}, fmt.Errorf("pool %d is not active", pool.GetId()) } - swapFee := pool.GetSwapFee(ctx) + spreadFactor := pool.GetSpreadFactor(ctx) // routeStep to the pool-specific SwapExactAmountIn implementation. - tokenOutAmount, err = swapModule.SwapExactAmountIn(ctx, sender, pool, tokenIn, tokenOutDenom, tokenOutMinAmount, swapFee) + tokenOutAmount, err = swapModule.SwapExactAmountIn(ctx, sender, pool, tokenIn, tokenOutDenom, tokenOutMinAmount, spreadFactor) if err != nil { return sdk.Int{}, err } @@ -220,9 +220,9 @@ func (k Keeper) MultihopEstimateOutGivenExactAmountIn( tokenIn sdk.Coin, ) (tokenOutAmount sdk.Int, err error) { var ( - isMultiHopRouted bool - routeSwapFee sdk.Dec - sumOfSwapFees sdk.Dec + isMultiHopRouted bool + routeSpreadFactor sdk.Dec + sumOfSpreadFactors sdk.Dec ) // recover from panic @@ -240,7 +240,7 @@ func (k Keeper) MultihopEstimateOutGivenExactAmountIn( if k.isOsmoRoutedMultihop(ctx, routeStep, route[0].TokenOutDenom, tokenIn.Denom) { isMultiHopRouted = true - routeSwapFee, sumOfSwapFees, err = k.getOsmoRoutedMultihopTotalSwapFee(ctx, routeStep) + routeSpreadFactor, sumOfSpreadFactors, err = k.getOsmoRoutedMultihopTotalSpreadFactor(ctx, routeStep) if err != nil { return sdk.Int{}, err } @@ -258,15 +258,15 @@ func (k Keeper) MultihopEstimateOutGivenExactAmountIn( return sdk.Int{}, poolErr } - swapFee := poolI.GetSwapFee(ctx) + spreadFactor := poolI.GetSpreadFactor(ctx) // If we determined the routeStep is an osmo multi-hop and both route are incentivized, // we modify the swap fee accordingly. if isMultiHopRouted { - swapFee = routeSwapFee.Mul((swapFee.Quo(sumOfSwapFees))) + spreadFactor = routeSpreadFactor.Mul((spreadFactor.Quo(sumOfSpreadFactors))) } - tokenOut, err := swapModule.CalcOutAmtGivenIn(ctx, poolI, tokenIn, routeStep.TokenOutDenom, swapFee) + tokenOut, err := swapModule.CalcOutAmtGivenIn(ctx, poolI, tokenIn, routeStep.TokenOutDenom, spreadFactor) if err != nil { return sdk.Int{}, err } @@ -294,7 +294,7 @@ func (k Keeper) RouteExactAmountOut(ctx sdk.Context, tokenInMaxAmount sdk.Int, tokenOut sdk.Coin, ) (tokenInAmount sdk.Int, err error) { - isMultiHopRouted, routeSwapFee, sumOfSwapFees := false, sdk.Dec{}, sdk.Dec{} + isMultiHopRouted, routeSpreadFactor, sumOfSpreadFactors := false, sdk.Dec{}, sdk.Dec{} // Ensure that provided route is not empty and has valid denom format. routeStep := types.SwapAmountOutRoutes(route) if err := routeStep.Validate(); err != nil { @@ -315,8 +315,8 @@ func (k Keeper) RouteExactAmountOut(ctx sdk.Context, // - both routeStep 1 and routeStep 2 are incentivized pools // // if all of the above is true, then we collect the additive and max fee between the two pools to later calculate the following: - // total_swap_fee = max(swapfee1, swapfee2) - // fee_per_pool = total_swap_fee * ((pool_fee) / (swapfee1 + swapfee2)) + // total_spread_factor = total_spread_factor = max(spread_factor1, spread_factor2) + // fee_per_pool = total_spread_factor * ((pool_fee) / (spread_factor1 + spread_factor2)) var insExpected []sdk.Int isMultiHopRouted = k.isOsmoRoutedMultihop(ctx, routeStep, route[0].TokenInDenom, tokenOut.Denom) @@ -324,11 +324,11 @@ func (k Keeper) RouteExactAmountOut(ctx sdk.Context, // if we determined the routeStep is an osmo multi-hop and both route are incentivized, // we utilize a separate function that calculates the discounted swap fees if isMultiHopRouted { - routeSwapFee, sumOfSwapFees, err = k.getOsmoRoutedMultihopTotalSwapFee(ctx, routeStep) + routeSpreadFactor, sumOfSpreadFactors, err = k.getOsmoRoutedMultihopTotalSpreadFactor(ctx, routeStep) if err != nil { return sdk.Int{}, err } - insExpected, err = k.createOsmoMultihopExpectedSwapOuts(ctx, route, tokenOut, routeSwapFee, sumOfSwapFees) + insExpected, err = k.createOsmoMultihopExpectedSwapOuts(ctx, route, tokenOut, routeSpreadFactor, sumOfSpreadFactors) } else { insExpected, err = k.createMultihopExpectedSwapOuts(ctx, route, tokenOut) } @@ -370,14 +370,14 @@ func (k Keeper) RouteExactAmountOut(ctx sdk.Context, return sdk.Int{}, types.InactivePoolError{PoolId: pool.GetId()} } - swapFee := pool.GetSwapFee(ctx) + spreadFactor := pool.GetSpreadFactor(ctx) // If we determined the routeStep is an osmo multi-hop and both route are incentivized, // we modify the swap fee accordingly. if isMultiHopRouted { - swapFee = routeSwapFee.Mul((swapFee.Quo(sumOfSwapFees))) + spreadFactor = routeSpreadFactor.Mul((spreadFactor.Quo(sumOfSpreadFactors))) } - _tokenInAmount, swapErr := swapModule.SwapExactAmountOut(ctx, sender, pool, routeStep.TokenInDenom, insExpected[i], _tokenOut, swapFee) + _tokenInAmount, swapErr := swapModule.SwapExactAmountOut(ctx, sender, pool, routeStep.TokenInDenom, insExpected[i], _tokenOut, spreadFactor) if swapErr != nil { return sdk.Int{}, swapErr } @@ -503,7 +503,7 @@ func (k Keeper) MultihopEstimateInGivenExactAmountOut( route []types.SwapAmountOutRoute, tokenOut sdk.Coin, ) (tokenInAmount sdk.Int, err error) { - isMultiHopRouted, routeSwapFee, sumOfSwapFees := false, sdk.Dec{}, sdk.Dec{} + isMultiHopRouted, routeSpreadFactor, sumOfSpreadFactors := false, sdk.Dec{}, sdk.Dec{} var insExpected []sdk.Int // recover from panic @@ -521,17 +521,17 @@ func (k Keeper) MultihopEstimateInGivenExactAmountOut( if k.isOsmoRoutedMultihop(ctx, routeStep, route[0].TokenInDenom, tokenOut.Denom) { isMultiHopRouted = true - routeSwapFee, sumOfSwapFees, err = k.getOsmoRoutedMultihopTotalSwapFee(ctx, routeStep) + routeSpreadFactor, sumOfSpreadFactors, err = k.getOsmoRoutedMultihopTotalSpreadFactor(ctx, routeStep) if err != nil { return sdk.Int{}, err } } - // Determine what the estimated input would be for each pool along the multi-hop routeStep - // if we determined the routeStep is an osmo multi-hop and both route are incentivized, - // we utilize a separate function that calculates the discounted swap fees + // Determine what the estimated input would be for each pool along the multi-hop route + // if we determined the route is an osmo multi-hop and both routes are incentivized, + // we utilize a separate function that calculates the discounted spread factors if isMultiHopRouted { - insExpected, err = k.createOsmoMultihopExpectedSwapOuts(ctx, route, tokenOut, routeSwapFee, sumOfSwapFees) + insExpected, err = k.createOsmoMultihopExpectedSwapOuts(ctx, route, tokenOut, routeSpreadFactor, sumOfSpreadFactors) } else { insExpected, err = k.createMultihopExpectedSwapOuts(ctx, route, tokenOut) } @@ -605,14 +605,14 @@ func (k Keeper) isOsmoRoutedMultihop(ctx sdk.Context, route types.MultihopRoute, return route0Incentivized && route1Incentivized } -// getOsmoRoutedMultihopTotalSwapFee calculates and returns the average swap fee and the sum of swap fees for +// getOsmoRoutedMultihopTotalSpreadFactor calculates and returns the average swap fee and the sum of swap fees for // a given route. For the former, it sets a lower bound of the highest swap fee pool in the route to ensure total // swap fees for a route are never more than halved. -func (k Keeper) getOsmoRoutedMultihopTotalSwapFee(ctx sdk.Context, route types.MultihopRoute) ( - totalPathSwapFee sdk.Dec, sumOfSwapFees sdk.Dec, err error, +func (k Keeper) getOsmoRoutedMultihopTotalSpreadFactor(ctx sdk.Context, route types.MultihopRoute) ( + totalPathSpreadFactor sdk.Dec, sumOfSpreadFactors sdk.Dec, err error, ) { - additiveSwapFee := sdk.ZeroDec() - highestSwapFee := sdk.ZeroDec() + additiveSpreadFactor := sdk.ZeroDec() + maxSpreadFactor := sdk.ZeroDec() for _, poolId := range route.PoolIds() { swapModule, err := k.GetPoolModule(ctx, poolId) @@ -624,19 +624,19 @@ func (k Keeper) getOsmoRoutedMultihopTotalSwapFee(ctx sdk.Context, route types.M if poolErr != nil { return sdk.Dec{}, sdk.Dec{}, poolErr } - swapFee := pool.GetSwapFee(ctx) - additiveSwapFee = additiveSwapFee.Add(swapFee) - highestSwapFee = sdk.MaxDec(highestSwapFee, swapFee) + SpreadFactor := pool.GetSpreadFactor(ctx) + additiveSpreadFactor = additiveSpreadFactor.Add(SpreadFactor) + maxSpreadFactor = sdk.MaxDec(maxSpreadFactor, SpreadFactor) } // We divide by 2 to get the average since OSMO-routed multihops always have exactly 2 pools. - averageSwapFee := additiveSwapFee.QuoInt64(2) + averageSpreadFactor := additiveSpreadFactor.QuoInt64(2) // We take the max here as a guardrail to ensure that there is a lowerbound on the swap fee for the // whole route equivalent to the highest fee pool - routeSwapFee := sdk.MaxDec(highestSwapFee, averageSwapFee) + routeSpreadFactor := sdk.MaxDec(maxSpreadFactor, averageSpreadFactor) - return routeSwapFee, additiveSwapFee, nil + return routeSpreadFactor, additiveSpreadFactor, nil } // createMultihopExpectedSwapOuts defines the output denom and output amount for the last pool in @@ -663,7 +663,7 @@ func (k Keeper) createMultihopExpectedSwapOuts( return nil, err } - tokenIn, err := swapModule.CalcInAmtGivenOut(ctx, poolI, tokenOut, routeStep.TokenInDenom, poolI.GetSwapFee(ctx)) + tokenIn, err := swapModule.CalcInAmtGivenOut(ctx, poolI, tokenOut, routeStep.TokenInDenom, poolI.GetSpreadFactor(ctx)) if err != nil { return nil, err } @@ -680,7 +680,7 @@ func (k Keeper) createOsmoMultihopExpectedSwapOuts( ctx sdk.Context, route []types.SwapAmountOutRoute, tokenOut sdk.Coin, - cumulativeRouteSwapFee, sumOfSwapFees sdk.Dec, + cumulativeRouteSpreadFactor, sumOfSpreadFactors sdk.Dec, ) ([]sdk.Int, error) { insExpected := make([]sdk.Int, len(route)) for i := len(route) - 1; i >= 0; i-- { @@ -696,8 +696,8 @@ func (k Keeper) createOsmoMultihopExpectedSwapOuts( return nil, err } - swapFee := poolI.GetSwapFee(ctx) - tokenIn, err := swapModule.CalcInAmtGivenOut(ctx, poolI, tokenOut, routeStep.TokenInDenom, cumulativeRouteSwapFee.Mul((swapFee.Quo(sumOfSwapFees)))) + spreadFactor := poolI.GetSpreadFactor(ctx) + tokenIn, err := swapModule.CalcInAmtGivenOut(ctx, poolI, tokenOut, routeStep.TokenInDenom, cumulativeRouteSpreadFactor.Mul((spreadFactor.Quo(sumOfSpreadFactors)))) if err != nil { return nil, err } diff --git a/x/poolmanager/router_test.go b/x/poolmanager/router_test.go index 7955fa6d96b..57bd7b5c56b 100644 --- a/x/poolmanager/router_test.go +++ b/x/poolmanager/router_test.go @@ -33,11 +33,11 @@ const ( ) var ( - defaultInitPoolAmount = sdk.NewInt(1000000000000) - defaultPoolSwapFee = sdk.NewDecWithPrec(1, 3) // 0.1% pool swap fee default - defaultSwapAmount = sdk.NewInt(1000000) - gammKeeperType = reflect.TypeOf(&gamm.Keeper{}) - concentratedKeeperType = reflect.TypeOf(&cl.Keeper{}) + defaultInitPoolAmount = sdk.NewInt(1000000000000) + defaultPoolSpreadFactor = sdk.NewDecWithPrec(1, 3) // 0.1% pool spread factor default + defaultSwapAmount = sdk.NewInt(1000000) + gammKeeperType = reflect.TypeOf(&gamm.Keeper{}) + concentratedKeeperType = reflect.TypeOf(&cl.Keeper{}) defaultPoolInitAmount = sdk.NewInt(10_000_000_000) twentyFiveBaseUnitsAmount = sdk.NewInt(25_000_000) @@ -348,7 +348,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountIn() { incentivizedGauges []uint64 tokenIn sdk.Coin tokenOutMinAmount sdk.Int - swapFee sdk.Dec + spreadFactor sdk.Dec isConcentrated bool expectError bool expectReducedFeeApplied bool @@ -356,7 +356,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountIn() { { name: "One route: Swap - [foo -> bar], 1 percent fee", poolCoins: []sdk.Coins{sdk.NewCoins(sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(bar, defaultInitPoolAmount))}, - poolFee: []sdk.Dec{defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor}, routes: []types.SwapAmountInRoute{ { PoolId: 1, @@ -372,7 +372,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountIn() { sdk.NewCoins(sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(bar, defaultInitPoolAmount)), // pool 1. sdk.NewCoins(sdk.NewCoin(bar, defaultInitPoolAmount), sdk.NewCoin(baz, defaultInitPoolAmount)), // pool 2. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor}, routes: []types.SwapAmountInRoute{ { PoolId: 1, @@ -393,7 +393,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountIn() { sdk.NewCoins(sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 1. sdk.NewCoins(sdk.NewCoin(baz, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 2. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor}, routes: []types.SwapAmountInRoute{ { PoolId: 1, @@ -415,7 +415,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountIn() { sdk.NewCoins(sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 1. sdk.NewCoins(sdk.NewCoin(baz, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 2. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, sdk.NewDecWithPrec(1, 1)}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, sdk.NewDecWithPrec(1, 1)}, routes: []types.SwapAmountInRoute{ { PoolId: 1, @@ -438,7 +438,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountIn() { sdk.NewCoins(sdk.NewCoin(baz, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 2. sdk.NewCoins(sdk.NewCoin(bar, defaultInitPoolAmount), sdk.NewCoin(baz, defaultInitPoolAmount)), // pool 3. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee, defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor, defaultPoolSpreadFactor}, routes: []types.SwapAmountInRoute{ { PoolId: 1, @@ -466,7 +466,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountIn() { sdk.NewCoins(sdk.NewCoin(bar, defaultInitPoolAmount), sdk.NewCoin(baz, defaultInitPoolAmount), sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 2. // pool 3. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor}, routes: []types.SwapAmountInRoute{ { PoolId: 1, @@ -490,7 +490,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountIn() { sdk.NewCoins(sdk.NewCoin(bar, defaultInitPoolAmount), sdk.NewCoin(baz, defaultInitPoolAmount), sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 2. // pool 3. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor}, routes: []types.SwapAmountInRoute{ { PoolId: 1, @@ -516,7 +516,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountIn() { sdk.NewCoins(sdk.NewCoin(bar, defaultInitPoolAmount), sdk.NewCoin(baz, defaultInitPoolAmount), sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 3. // pool 3. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee, defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor, defaultPoolSpreadFactor}, routes: []types.SwapAmountInRoute{ { PoolId: 1, @@ -542,7 +542,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountIn() { poolDenoms: [][]string{ {foo, bar}, }, - poolFee: []sdk.Dec{defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor}, routes: []types.SwapAmountInRoute{ { PoolId: 1, @@ -560,7 +560,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountIn() { {baz, uosmo}, // pool 2. {bar, baz}, // pool 3. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee, defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor, defaultPoolSpreadFactor}, routes: []types.SwapAmountInRoute{ { PoolId: 1, @@ -595,9 +595,9 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountIn() { if tc.isConcentrated { // create a concentrated pool with a full range position - s.CreateConcentratedPoolsAndFullRangePositionWithSwapFee(tc.poolDenoms, tc.poolFee) + s.CreateConcentratedPoolsAndFullRangePositionWithSpreadFactor(tc.poolDenoms, tc.poolFee) } else { - s.createBalancerPoolsFromCoinsWithSwapFee(tc.poolCoins, tc.poolFee) + s.createBalancerPoolsFromCoinsWithSpreadFactor(tc.poolCoins, tc.poolFee) } // if test specifies incentivized gauges, set them here @@ -637,14 +637,14 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountOut() { incentivizedGauges []uint64 tokenOut sdk.Coin tokenInMaxAmount sdk.Int - swapFee sdk.Dec + spreadFactor sdk.Dec expectError bool expectReducedFeeApplied bool }{ { name: "One route: Swap - [foo -> bar], 1 percent fee", poolCoins: []sdk.Coins{sdk.NewCoins(sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(bar, defaultInitPoolAmount))}, - poolFee: []sdk.Dec{defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor}, routes: []types.SwapAmountOutRoute{ { PoolId: 1, @@ -660,7 +660,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountOut() { sdk.NewCoins(sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(bar, defaultInitPoolAmount)), // pool 1. sdk.NewCoins(sdk.NewCoin(bar, defaultInitPoolAmount), sdk.NewCoin(baz, defaultInitPoolAmount)), // pool 2. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor}, routes: []types.SwapAmountOutRoute{ { PoolId: 1, @@ -682,7 +682,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountOut() { sdk.NewCoins(sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 1. sdk.NewCoins(sdk.NewCoin(baz, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 2. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor}, routes: []types.SwapAmountOutRoute{ { PoolId: 1, @@ -704,7 +704,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountOut() { sdk.NewCoins(sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 1. sdk.NewCoins(sdk.NewCoin(baz, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 2. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, sdk.NewDecWithPrec(1, 1)}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, sdk.NewDecWithPrec(1, 1)}, routes: []types.SwapAmountOutRoute{ { PoolId: 1, @@ -727,7 +727,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountOut() { sdk.NewCoins(sdk.NewCoin(baz, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 2. sdk.NewCoins(sdk.NewCoin(bar, defaultInitPoolAmount), sdk.NewCoin(baz, defaultInitPoolAmount)), // pool 3. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee, defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor, defaultPoolSpreadFactor}, routes: []types.SwapAmountOutRoute{ { PoolId: 1, @@ -755,7 +755,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountOut() { sdk.NewCoins(sdk.NewCoin(bar, defaultInitPoolAmount), sdk.NewCoin(baz, defaultInitPoolAmount), sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 2. // pool 3. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor}, routes: []types.SwapAmountOutRoute{ { PoolId: 1, @@ -779,7 +779,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountOut() { sdk.NewCoins(sdk.NewCoin(bar, defaultInitPoolAmount), sdk.NewCoin(baz, defaultInitPoolAmount), sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 2. // pool 3. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor}, routes: []types.SwapAmountOutRoute{ { PoolId: 1, @@ -805,7 +805,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountOut() { sdk.NewCoins(sdk.NewCoin(bar, defaultInitPoolAmount), sdk.NewCoin(baz, defaultInitPoolAmount), sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 3. // pool 3. }, - poolFee: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee, defaultPoolSwapFee}, + poolFee: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor, defaultPoolSpreadFactor}, routes: []types.SwapAmountOutRoute{ { PoolId: 1, @@ -840,7 +840,7 @@ func (s *KeeperTestSuite) TestMultihopSwapExactAmountOut() { s.SetupTest() poolmanagerKeeper := s.App.PoolManagerKeeper - s.createBalancerPoolsFromCoinsWithSwapFee(tc.poolCoins, tc.poolFee) + s.createBalancerPoolsFromCoinsWithSpreadFactor(tc.poolCoins, tc.poolFee) // if test specifies incentivized gauges, set them here if len(tc.incentivizedGauges) > 0 { @@ -1005,7 +1005,7 @@ func (s *KeeperTestSuite) TestEstimateMultihopSwapExactAmountIn() { s.Run(test.name, func() { poolmanagerKeeper := s.App.PoolManagerKeeper - firstEstimatePoolId, secondEstimatePoolId := s.setupPools(test.poolType, defaultPoolSwapFee) + firstEstimatePoolId, secondEstimatePoolId := s.setupPools(test.poolType, defaultPoolSpreadFactor) firstEstimatePool, err := s.App.GAMMKeeper.GetPoolAndPoke(s.Ctx, firstEstimatePoolId) s.Require().NoError(err) @@ -1187,7 +1187,7 @@ func (s *KeeperTestSuite) TestEstimateMultihopSwapExactAmountOut() { s.Run(test.name, func() { poolmanagerKeeper := s.App.PoolManagerKeeper - firstEstimatePoolId, secondEstimatePoolId := s.setupPools(test.poolType, defaultPoolSwapFee) + firstEstimatePoolId, secondEstimatePoolId := s.setupPools(test.poolType, defaultPoolSpreadFactor) firstEstimatePool, err := s.App.GAMMKeeper.GetPoolAndPoke(s.Ctx, firstEstimatePoolId) s.Require().NoError(err) @@ -1245,10 +1245,10 @@ func (s *KeeperTestSuite) calcOutAmountAsSeparateSwaps(osmoFeeReduced bool, rout if osmoFeeReduced { // extract route from swap route := types.SwapAmountOutRoutes(routes) - // utilizing the extracted route, determine the routeSwapFee and sumOfSwapFees + // utilizing the extracted route, determine the routeSpreadFactor and sumOfspreadFactors // these two variables are used to calculate the overall swap fee utilizing the following formula - // swapFee = routeSwapFee * ((pool_fee) / (sumOfSwapFees)) - routeSwapFee, sumOfSwapFees, err := s.App.PoolManagerKeeper.GetOsmoRoutedMultihopTotalSwapFee(s.Ctx, route) + // spreadFactor = routeSpreadFactor * ((pool_fee) / (sumOfspreadFactors)) + routeSpreadFactor, sumOfSpreadFactors, err := s.App.PoolManagerKeeper.GetOsmoRoutedMultihopTotalSpreadFactor(s.Ctx, route) s.Require().NoError(err) nextTokenOut := tokenOut for i := len(routes) - 1; i >= 0; i-- { @@ -1256,11 +1256,11 @@ func (s *KeeperTestSuite) calcOutAmountAsSeparateSwaps(osmoFeeReduced bool, rout // extract the current pool's swap fee hopPool, err := s.App.GAMMKeeper.GetPoolAndPoke(cacheCtx, hop.PoolId) s.Require().NoError(err) - currentPoolSwapFee := hopPool.GetSwapFee(cacheCtx) - // utilize the routeSwapFee, sumOfSwapFees, and current pool swap fee to calculate the new reduced swap fee - swapFee := routeSwapFee.Mul((currentPoolSwapFee.Quo(sumOfSwapFees))) + currentPoolSpreadFactor := hopPool.GetSpreadFactor(cacheCtx) + // utilize the routeSpreadFactor, sumOfSpreadFactors, and current pool swap fee to calculate the new reduced swap fee + spreadFactor := routeSpreadFactor.Mul((currentPoolSpreadFactor.Quo(sumOfSpreadFactors))) // we then do individual swaps until we reach the end of the swap route - tokenOut, err := s.App.GAMMKeeper.SwapExactAmountOut(cacheCtx, s.TestAccs[0], hopPool, hop.TokenInDenom, sdk.NewInt(100000000), nextTokenOut, swapFee) + tokenOut, err := s.App.GAMMKeeper.SwapExactAmountOut(cacheCtx, s.TestAccs[0], hopPool, hop.TokenInDenom, sdk.NewInt(100000000), nextTokenOut, spreadFactor) s.Require().NoError(err) nextTokenOut = sdk.NewCoin(hop.TokenInDenom, tokenOut) } @@ -1271,8 +1271,8 @@ func (s *KeeperTestSuite) calcOutAmountAsSeparateSwaps(osmoFeeReduced bool, rout hop := routes[i] hopPool, err := s.App.GAMMKeeper.GetPoolAndPoke(cacheCtx, hop.PoolId) s.Require().NoError(err) - updatedPoolSwapFee := hopPool.GetSwapFee(cacheCtx) - tokenOut, err := s.App.GAMMKeeper.SwapExactAmountOut(cacheCtx, s.TestAccs[0], hopPool, hop.TokenInDenom, sdk.NewInt(100000000), nextTokenOut, updatedPoolSwapFee) + updatedPoolSpreadFactor := hopPool.GetSpreadFactor(cacheCtx) + tokenOut, err := s.App.GAMMKeeper.SwapExactAmountOut(cacheCtx, s.TestAccs[0], hopPool, hop.TokenInDenom, sdk.NewInt(100000000), nextTokenOut, updatedPoolSpreadFactor) s.Require().NoError(err) nextTokenOut = sdk.NewCoin(hop.TokenInDenom, tokenOut) } @@ -1288,10 +1288,10 @@ func (s *KeeperTestSuite) calcInAmountAsSeparatePoolSwaps(osmoFeeReduced bool, r if osmoFeeReduced { // extract route from swap route := types.SwapAmountInRoutes(routes) - // utilizing the extracted route, determine the routeSwapFee and sumOfSwapFees + // utilizing the extracted route, determine the routeSpreadFactor and sumOfSpreadFactors // these two variables are used to calculate the overall swap fee utilizing the following formula - // swapFee = routeSwapFee * ((pool_fee) / (sumOfSwapFees)) - routeSwapFee, sumOfSwapFees, err := s.App.PoolManagerKeeper.GetOsmoRoutedMultihopTotalSwapFee(s.Ctx, route) + // spreadFactor = routeSpreadFactor * ((pool_fee) / (sumOfSpreadFactors)) + routeSpreadFactor, sumOfSpreadFactors, err := s.App.PoolManagerKeeper.GetOsmoRoutedMultihopTotalSpreadFactor(s.Ctx, route) s.Require().NoError(err) nextTokenIn := tokenIn @@ -1302,11 +1302,11 @@ func (s *KeeperTestSuite) calcInAmountAsSeparatePoolSwaps(osmoFeeReduced bool, r pool, err := swapModule.GetPool(s.Ctx, hop.PoolId) s.Require().NoError(err) - // utilize the routeSwapFee, sumOfSwapFees, and current pool swap fee to calculate the new reduced swap fee - swapFee := routeSwapFee.Mul(pool.GetSwapFee(cacheCtx).Quo(sumOfSwapFees)) + // utilize the routeSpreadFactor, sumOfSpreadFactors, and current pool swap fee to calculate the new reduced swap fee + spreadFactor := routeSpreadFactor.Mul(pool.GetSpreadFactor(cacheCtx).Quo(sumOfSpreadFactors)) // we then do individual swaps until we reach the end of the swap route - tokenOut, err := swapModule.SwapExactAmountIn(cacheCtx, s.TestAccs[0], pool, nextTokenIn, hop.TokenOutDenom, sdk.OneInt(), swapFee) + tokenOut, err := swapModule.SwapExactAmountIn(cacheCtx, s.TestAccs[0], pool, nextTokenIn, hop.TokenOutDenom, sdk.OneInt(), spreadFactor) s.Require().NoError(err) nextTokenIn = sdk.NewCoin(hop.TokenOutDenom, tokenOut) @@ -1321,11 +1321,11 @@ func (s *KeeperTestSuite) calcInAmountAsSeparatePoolSwaps(osmoFeeReduced bool, r pool, err := swapModule.GetPool(s.Ctx, hop.PoolId) s.Require().NoError(err) - // utilize the routeSwapFee, sumOfSwapFees, and current pool swap fee to calculate the new reduced swap fee - swapFee := pool.GetSwapFee(cacheCtx) + // utilize the routeSpreadFactor, sumOfSpreadFactors, and current pool swap fee to calculate the new reduced swap fee + spreadFactor := pool.GetSpreadFactor(cacheCtx) // we then do individual swaps until we reach the end of the swap route - tokenOut, err := swapModule.SwapExactAmountIn(cacheCtx, s.TestAccs[0], pool, nextTokenIn, hop.TokenOutDenom, sdk.OneInt(), swapFee) + tokenOut, err := swapModule.SwapExactAmountIn(cacheCtx, s.TestAccs[0], pool, nextTokenIn, hop.TokenOutDenom, sdk.OneInt(), spreadFactor) s.Require().NoError(err) nextTokenIn = sdk.NewCoin(hop.TokenOutDenom, tokenOut) @@ -1351,7 +1351,7 @@ func (s *KeeperTestSuite) TestSingleSwapExactAmountIn() { // We have: // - foo: 1000000000000 // - bar: 1000000000000 - // - swapFee: 0.1% + // - spreadFactor: 0.1% // - foo in: 100000 // - bar amount out will be calculated according to the formula // https://www.wolframalpha.com/input?i=solve+%2810%5E12+%2B+10%5E5+x+0.999%29%2810%5E12+-+x%29+%3D+10%5E24 @@ -1360,7 +1360,7 @@ func (s *KeeperTestSuite) TestSingleSwapExactAmountIn() { name: "Swap - [foo -> bar], 0.1 percent fee", poolId: 1, poolCoins: sdk.NewCoins(sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(bar, defaultInitPoolAmount)), - poolFee: defaultPoolSwapFee, + poolFee: defaultPoolSpreadFactor, tokenIn: sdk.NewCoin(foo, sdk.NewInt(100000)), tokenOutMinAmount: sdk.NewInt(1), tokenOutDenom: bar, @@ -1370,7 +1370,7 @@ func (s *KeeperTestSuite) TestSingleSwapExactAmountIn() { name: "Wrong pool id", poolId: 2, poolCoins: sdk.NewCoins(sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(bar, defaultInitPoolAmount)), - poolFee: defaultPoolSwapFee, + poolFee: defaultPoolSpreadFactor, tokenIn: sdk.NewCoin(foo, sdk.NewInt(100000)), tokenOutMinAmount: sdk.NewInt(1), tokenOutDenom: bar, @@ -1380,7 +1380,7 @@ func (s *KeeperTestSuite) TestSingleSwapExactAmountIn() { name: "In denom not exist", poolId: 1, poolCoins: sdk.NewCoins(sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(bar, defaultInitPoolAmount)), - poolFee: defaultPoolSwapFee, + poolFee: defaultPoolSpreadFactor, tokenIn: sdk.NewCoin(baz, sdk.NewInt(100000)), tokenOutMinAmount: sdk.NewInt(1), tokenOutDenom: bar, @@ -1390,7 +1390,7 @@ func (s *KeeperTestSuite) TestSingleSwapExactAmountIn() { name: "Out denom not exist", poolId: 1, poolCoins: sdk.NewCoins(sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(bar, defaultInitPoolAmount)), - poolFee: defaultPoolSwapFee, + poolFee: defaultPoolSpreadFactor, tokenIn: sdk.NewCoin(foo, sdk.NewInt(100000)), tokenOutMinAmount: sdk.NewInt(1), tokenOutDenom: baz, @@ -1619,7 +1619,7 @@ func (s *KeeperTestSuite) TestAllPools_RealPools() { } // sets *KeeperTestSuiteof desired type and returns their IDs -func (s *KeeperTestSuite) setupPools(poolType types.PoolType, poolDefaultSwapFee sdk.Dec) (firstEstimatePoolId, secondEstimatePoolId uint64) { +func (s *KeeperTestSuite) setupPools(poolType types.PoolType, poolDefaultSpreadFactor sdk.Dec) (firstEstimatePoolId, secondEstimatePoolId uint64) { switch poolType { case types.Stableswap: // Prepare 4 pools, @@ -1637,21 +1637,21 @@ func (s *KeeperTestSuite) setupPools(poolType types.PoolType, poolDefaultSwapFee // Two pools for calculating `MultihopSwapExactAmountOut` // and two pools for calculating `EstimateMultihopSwapExactAmountOut` s.PrepareBalancerPoolWithPoolParams(balancer.PoolParams{ - SwapFee: poolDefaultSwapFee, // 1% + SwapFee: poolDefaultSpreadFactor, // 1% ExitFee: sdk.NewDec(0), }) s.PrepareBalancerPoolWithPoolParams(balancer.PoolParams{ - SwapFee: poolDefaultSwapFee, + SwapFee: poolDefaultSpreadFactor, ExitFee: sdk.NewDec(0), }) firstEstimatePoolId = s.PrepareBalancerPoolWithPoolParams(balancer.PoolParams{ - SwapFee: poolDefaultSwapFee, // 1% + SwapFee: poolDefaultSpreadFactor, // 1% ExitFee: sdk.NewDec(0), }) secondEstimatePoolId = s.PrepareBalancerPoolWithPoolParams(balancer.PoolParams{ - SwapFee: poolDefaultSwapFee, + SwapFee: poolDefaultSpreadFactor, ExitFee: sdk.NewDec(0), }) return @@ -2298,8 +2298,8 @@ func (s *KeeperTestSuite) TestIsOsmoRoutedMultihop() { } } -// TestGetOsmoRoutedMultihopTotalSwapFee tests the GetOsmoRoutedMultihopTotalSwapFee function -func (s *KeeperTestSuite) TestGetOsmoRoutedMultihopTotalSwapFee() { +// TestGetOsmoRoutedMultihopTotalSpreadFactor tests the GetOsmoRoutedMultihopTotalSpreadFactor function +func (s *KeeperTestSuite) TestGetOsmoRoutedMultihopTotalSpreadFactor() { tests := map[string]struct { route types.MultihopRoute balancerPoolCoins []sdk.Coins @@ -2321,14 +2321,14 @@ func (s *KeeperTestSuite) TestGetOsmoRoutedMultihopTotalSwapFee() { TokenOutDenom: bar, }, }), - poolFees: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee}, + poolFees: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor}, balancerPoolCoins: []sdk.Coins{ sdk.NewCoins(sdk.NewCoin(foo, defaultInitPoolAmount), sdk.NewCoin(uosmo, defaultInitPoolAmount)), // pool 1. sdk.NewCoins(sdk.NewCoin(uosmo, defaultInitPoolAmount), sdk.NewCoin(bar, defaultInitPoolAmount)), // pool 2. }, - expectedRouteFee: defaultPoolSwapFee, - expectedTotalFee: defaultPoolSwapFee.Add(defaultPoolSwapFee), + expectedRouteFee: defaultPoolSpreadFactor, + expectedTotalFee: defaultPoolSpreadFactor.Add(defaultPoolSpreadFactor), }, "concentrated route": { route: types.SwapAmountInRoutes([]types.SwapAmountInRoute{ @@ -2341,14 +2341,14 @@ func (s *KeeperTestSuite) TestGetOsmoRoutedMultihopTotalSwapFee() { TokenOutDenom: bar, }, }), - poolFees: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee}, + poolFees: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor}, concentratedPoolDenoms: [][]string{ {foo, uosmo}, // pool 1. {uosmo, baz}, // pool 2. }, - expectedRouteFee: defaultPoolSwapFee, - expectedTotalFee: defaultPoolSwapFee.Add(defaultPoolSwapFee), + expectedRouteFee: defaultPoolSpreadFactor, + expectedTotalFee: defaultPoolSpreadFactor.Add(defaultPoolSpreadFactor), }, "mixed concentrated and balancer route": { route: types.SwapAmountInRoutes([]types.SwapAmountInRoute{ @@ -2361,7 +2361,7 @@ func (s *KeeperTestSuite) TestGetOsmoRoutedMultihopTotalSwapFee() { TokenOutDenom: bar, }, }), - poolFees: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee}, + poolFees: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor}, concentratedPoolDenoms: [][]string{ {foo, uosmo}, // pool 1. }, @@ -2369,8 +2369,8 @@ func (s *KeeperTestSuite) TestGetOsmoRoutedMultihopTotalSwapFee() { sdk.NewCoins(sdk.NewCoin(uosmo, defaultInitPoolAmount), sdk.NewCoin(bar, defaultInitPoolAmount)), // pool 2. }, - expectedRouteFee: defaultPoolSwapFee, - expectedTotalFee: defaultPoolSwapFee.Add(defaultPoolSwapFee), + expectedRouteFee: defaultPoolSpreadFactor, + expectedTotalFee: defaultPoolSpreadFactor.Add(defaultPoolSpreadFactor), }, "edge case: average fee is lower than highest pool fee": { route: types.SwapAmountInRoutes([]types.SwapAmountInRoute{ @@ -2384,14 +2384,14 @@ func (s *KeeperTestSuite) TestGetOsmoRoutedMultihopTotalSwapFee() { }, }), // Note that pool 2 has 5x the swap fee of pool 1 - poolFees: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee.Mul(sdk.NewDec(5))}, + poolFees: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor.Mul(sdk.NewDec(5))}, concentratedPoolDenoms: [][]string{ {foo, uosmo}, // pool 1. {uosmo, baz}, // pool 2. }, - expectedRouteFee: defaultPoolSwapFee.Mul(sdk.NewDec(5)), - expectedTotalFee: defaultPoolSwapFee.Mul(sdk.NewDec(6)), + expectedRouteFee: defaultPoolSpreadFactor.Mul(sdk.NewDec(5)), + expectedTotalFee: defaultPoolSpreadFactor.Mul(sdk.NewDec(6)), }, "error: pool does not exist": { route: types.SwapAmountInRoutes([]types.SwapAmountInRoute{ @@ -2404,7 +2404,7 @@ func (s *KeeperTestSuite) TestGetOsmoRoutedMultihopTotalSwapFee() { TokenOutDenom: bar, }, }), - poolFees: []sdk.Dec{defaultPoolSwapFee, defaultPoolSwapFee}, + poolFees: []sdk.Dec{defaultPoolSpreadFactor, defaultPoolSpreadFactor}, expectedError: types.FailedToFindRouteError{PoolId: 1}, }, @@ -2417,15 +2417,15 @@ func (s *KeeperTestSuite) TestGetOsmoRoutedMultihopTotalSwapFee() { // Create pools for test route if tc.concentratedPoolDenoms != nil { - s.CreateConcentratedPoolsAndFullRangePositionWithSwapFee(tc.concentratedPoolDenoms, tc.poolFees) + s.CreateConcentratedPoolsAndFullRangePositionWithSpreadFactor(tc.concentratedPoolDenoms, tc.poolFees) } if tc.balancerPoolCoins != nil { - s.createBalancerPoolsFromCoinsWithSwapFee(tc.balancerPoolCoins, tc.poolFees) + s.createBalancerPoolsFromCoinsWithSpreadFactor(tc.balancerPoolCoins, tc.poolFees) } // System under test - routeFee, totalFee, err := poolManagerKeeper.GetOsmoRoutedMultihopTotalSwapFee(s.Ctx, tc.route) + routeFee, totalFee, err := poolManagerKeeper.GetOsmoRoutedMultihopTotalSpreadFactor(s.Ctx, tc.route) // Assertions if tc.expectedError != nil { @@ -2445,13 +2445,13 @@ func (s *KeeperTestSuite) TestGetOsmoRoutedMultihopTotalSwapFee() { func (suite *KeeperTestSuite) TestCreateMultihopExpectedSwapOuts() { tests := map[string]struct { - route []types.SwapAmountOutRoute - tokenOut sdk.Coin - balancerPoolCoins []sdk.Coins - concentratedPoolDenoms [][]string - poolCoins []sdk.Coins - cumulativeRouteSwapFee sdk.Dec - sumOfSwapFees sdk.Dec + route []types.SwapAmountOutRoute + tokenOut sdk.Coin + balancerPoolCoins []sdk.Coins + concentratedPoolDenoms [][]string + poolCoins []sdk.Coins + cumulativeRouteSpreadFactor sdk.Dec + sumOfSpreadFactors sdk.Dec expectedSwapIns []sdk.Int expectedError bool @@ -2499,9 +2499,9 @@ func (suite *KeeperTestSuite) TestCreateMultihopExpectedSwapOuts() { TokenInDenom: bar, }, }, - poolCoins: []sdk.Coins{sdk.NewCoins(sdk.NewCoin(uosmo, sdk.NewInt(100)), sdk.NewCoin(bar, sdk.NewInt(100)))}, - cumulativeRouteSwapFee: sdk.NewDec(100), - sumOfSwapFees: sdk.NewDec(500), + poolCoins: []sdk.Coins{sdk.NewCoins(sdk.NewCoin(uosmo, sdk.NewInt(100)), sdk.NewCoin(bar, sdk.NewInt(100)))}, + cumulativeRouteSpreadFactor: sdk.NewDec(100), + sumOfSpreadFactors: sdk.NewDec(500), tokenOut: sdk.NewCoin(uosmo, sdk.NewInt(10)), expectedSwapIns: []sdk.Int{sdk.NewInt(12)}, @@ -2522,8 +2522,8 @@ func (suite *KeeperTestSuite) TestCreateMultihopExpectedSwapOuts() { sdk.NewCoins(sdk.NewCoin(foo, sdk.NewInt(100)), sdk.NewCoin(bar, sdk.NewInt(100))), // pool 1. sdk.NewCoins(sdk.NewCoin(bar, sdk.NewInt(100)), sdk.NewCoin(uosmo, sdk.NewInt(100))), // pool 2. }, - cumulativeRouteSwapFee: sdk.NewDec(100), - sumOfSwapFees: sdk.NewDec(500), + cumulativeRouteSpreadFactor: sdk.NewDec(100), + sumOfSpreadFactors: sdk.NewDec(500), tokenOut: sdk.NewCoin(uosmo, sdk.NewInt(10)), expectedSwapIns: []sdk.Int{sdk.NewInt(14), sdk.NewInt(12)}, @@ -2568,8 +2568,8 @@ func (suite *KeeperTestSuite) TestCreateMultihopExpectedSwapOuts() { var actualSwapOuts []sdk.Int var err error - if !tc.sumOfSwapFees.IsNil() && !tc.cumulativeRouteSwapFee.IsNil() { - actualSwapOuts, err = suite.App.PoolManagerKeeper.CreateOsmoMultihopExpectedSwapOuts(suite.Ctx, tc.route, tc.tokenOut, tc.cumulativeRouteSwapFee, tc.sumOfSwapFees) + if !tc.sumOfSpreadFactors.IsNil() && !tc.cumulativeRouteSpreadFactor.IsNil() { + actualSwapOuts, err = suite.App.PoolManagerKeeper.CreateOsmoMultihopExpectedSwapOuts(suite.Ctx, tc.route, tc.tokenOut, tc.cumulativeRouteSpreadFactor, tc.sumOfSpreadFactors) } else { actualSwapOuts, err = suite.App.PoolManagerKeeper.CreateMultihopExpectedSwapOuts(suite.Ctx, tc.route, tc.tokenOut) } diff --git a/x/poolmanager/types/pool.go b/x/poolmanager/types/pool.go index cf113beb246..006374432a9 100644 --- a/x/poolmanager/types/pool.go +++ b/x/poolmanager/types/pool.go @@ -14,11 +14,11 @@ type PoolI interface { GetAddress() sdk.AccAddress String() string GetId() uint64 - // GetSwapFee returns the pool's swap fee, based on the current state. - // Pools may choose to make their swap fees dependent upon state + // GetSpreadFactor returns the pool's spread factor, based on the current state. + // Pools may choose to make their spread factors dependent upon state // (prior TWAPs, network downtime, other pool states, etc.) // hence Context is provided as an argument. - GetSwapFee(ctx sdk.Context) sdk.Dec + GetSpreadFactor(ctx sdk.Context) sdk.Dec // Returns whether the pool has swaps enabled at the moment IsActive(ctx sdk.Context) bool diff --git a/x/poolmanager/types/routes.go b/x/poolmanager/types/routes.go index d7163a19432..3f80fc32d84 100644 --- a/x/poolmanager/types/routes.go +++ b/x/poolmanager/types/routes.go @@ -54,7 +54,7 @@ type PoolModuleI interface { tokenIn sdk.Coin, tokenOutDenom string, tokenOutMinAmount sdk.Int, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (sdk.Int, error) // CalcOutAmtGivenIn calculates the amount of tokenOut given tokenIn and the pool's current state. // Returns error if the given pool is not a CFMM pool. Returns error on internal calculations. @@ -63,7 +63,7 @@ type PoolModuleI interface { poolI PoolI, tokenIn sdk.Coin, tokenOutDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (tokenOut sdk.Coin, err error) SwapExactAmountOut( @@ -73,7 +73,7 @@ type PoolModuleI interface { tokenInDenom string, tokenInMaxAmount sdk.Int, tokenOut sdk.Coin, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (tokenInAmount sdk.Int, err error) // CalcInAmtGivenOut calculates the amount of tokenIn given tokenOut and the pool's current state. // Returns error if the given pool is not a CFMM pool. Returns error on internal calculations. @@ -82,7 +82,7 @@ type PoolModuleI interface { poolI PoolI, tokenOut sdk.Coin, tokenInDenom string, - swapFee sdk.Dec, + spreadFactor sdk.Dec, ) (tokenIn sdk.Coin, err error) // GetTotalPoolLiquidity returns the coins in the pool owned by all LPs diff --git a/x/protorev/keeper/keeper_test.go b/x/protorev/keeper/keeper_test.go index 6446af951ba..d55fa73750f 100644 --- a/x/protorev/keeper/keeper_test.go +++ b/x/protorev/keeper/keeper_test.go @@ -34,14 +34,14 @@ type KeeperTestSuite struct { } type Pool struct { - PoolAssets []balancer.PoolAsset - Asset1 string - Asset2 string - Amount1 sdk.Int - Amount2 sdk.Int - SwapFee sdk.Dec - ExitFee sdk.Dec - PoolId uint64 + PoolAssets []balancer.PoolAsset + Asset1 string + Asset2 string + Amount1 sdk.Int + Amount2 sdk.Int + SpreadFactor sdk.Dec + ExitFee sdk.Dec + PoolId uint64 } type StableSwapPool struct { @@ -183,9 +183,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 1, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 1, }, { // Pool 2 PoolAssets: []balancer.PoolAsset{ @@ -198,9 +198,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 2, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 2, }, { // Pool 3 PoolAssets: []balancer.PoolAsset{ @@ -213,9 +213,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 3, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 3, }, { // Pool 4 PoolAssets: []balancer.PoolAsset{ @@ -228,9 +228,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 4, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 4, }, { // Pool 5 PoolAssets: []balancer.PoolAsset{ @@ -243,9 +243,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 5, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 5, }, { // Pool 6 PoolAssets: []balancer.PoolAsset{ @@ -258,9 +258,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 6, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 6, }, { // Pool 7 PoolAssets: []balancer.PoolAsset{ @@ -273,9 +273,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 7, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 7, }, { // Pool 8 PoolAssets: []balancer.PoolAsset{ @@ -288,9 +288,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 8, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 8, }, { // Pool 9 PoolAssets: []balancer.PoolAsset{ @@ -303,9 +303,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 9, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 9, }, { // Pool 10 PoolAssets: []balancer.PoolAsset{ @@ -318,9 +318,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 10, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 10, }, { // Pool 11 PoolAssets: []balancer.PoolAsset{ @@ -333,9 +333,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 11, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 11, }, { // Pool 12 PoolAssets: []balancer.PoolAsset{ @@ -348,9 +348,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 12, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 12, }, { // Pool 13 PoolAssets: []balancer.PoolAsset{ @@ -363,9 +363,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 13, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 13, }, { // Pool 14 PoolAssets: []balancer.PoolAsset{ @@ -378,9 +378,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 14, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 14, }, { // Pool 15 PoolAssets: []balancer.PoolAsset{ @@ -393,9 +393,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 15, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 15, }, { // Pool 16 PoolAssets: []balancer.PoolAsset{ @@ -408,9 +408,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 16, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 16, }, { // Pool 17 PoolAssets: []balancer.PoolAsset{ @@ -423,9 +423,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 17, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 17, }, { // Pool 18 PoolAssets: []balancer.PoolAsset{ @@ -438,9 +438,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 18, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 18, }, { // Pool 19 PoolAssets: []balancer.PoolAsset{ @@ -453,9 +453,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 19, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 19, }, { // Pool 20 PoolAssets: []balancer.PoolAsset{ @@ -468,9 +468,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 20, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 20, }, { // Pool 21 PoolAssets: []balancer.PoolAsset{ @@ -483,9 +483,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(0, 2), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 21, + SpreadFactor: sdk.NewDecWithPrec(0, 2), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 21, }, { // Pool 22 PoolAssets: []balancer.PoolAsset{ @@ -498,9 +498,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(2, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 22, + SpreadFactor: sdk.NewDecWithPrec(2, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 22, }, { // Pool 23 PoolAssets: []balancer.PoolAsset{ @@ -513,9 +513,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(535, 5), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 23, + SpreadFactor: sdk.NewDecWithPrec(535, 5), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 23, }, { // Pool 24 PoolAssets: []balancer.PoolAsset{ @@ -528,9 +528,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(2, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 24, + SpreadFactor: sdk.NewDecWithPrec(2, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 24, }, { // Pool 25 PoolAssets: []balancer.PoolAsset{ @@ -543,9 +543,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(2, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 25, + SpreadFactor: sdk.NewDecWithPrec(2, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 25, }, { // Pool 26 PoolAssets: []balancer.PoolAsset{ @@ -558,9 +558,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(50), }, }, - SwapFee: sdk.NewDecWithPrec(2, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 26, + SpreadFactor: sdk.NewDecWithPrec(2, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 26, }, { // Pool 27 PoolAssets: []balancer.PoolAsset{ @@ -573,9 +573,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(50), }, }, - SwapFee: sdk.NewDecWithPrec(2, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 27, + SpreadFactor: sdk.NewDecWithPrec(2, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 27, }, { // Pool 28 PoolAssets: []balancer.PoolAsset{ @@ -596,9 +596,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(25), }, }, - SwapFee: sdk.NewDecWithPrec(4, 4), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 28, + SpreadFactor: sdk.NewDecWithPrec(4, 4), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 28, }, { // Pool 29 PoolAssets: []balancer.PoolAsset{ @@ -611,9 +611,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(2, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 29, + SpreadFactor: sdk.NewDecWithPrec(2, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 29, }, { // Pool 30 PoolAssets: []balancer.PoolAsset{ @@ -626,9 +626,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(2, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 30, + SpreadFactor: sdk.NewDecWithPrec(2, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 30, }, { // Pool 31 PoolAssets: []balancer.PoolAsset{ @@ -649,9 +649,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(25), }, }, - SwapFee: sdk.NewDecWithPrec(4, 4), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 31, + SpreadFactor: sdk.NewDecWithPrec(4, 4), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 31, }, { // Pool 32 PoolAssets: []balancer.PoolAsset{ @@ -664,9 +664,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(30), }, }, - SwapFee: sdk.NewDecWithPrec(3, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 32, + SpreadFactor: sdk.NewDecWithPrec(3, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 32, }, { // Pool 33 PoolAssets: []balancer.PoolAsset{ @@ -679,9 +679,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(30), }, }, - SwapFee: sdk.NewDecWithPrec(3, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 33, + SpreadFactor: sdk.NewDecWithPrec(3, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 33, }, { // Pool 34 PoolAssets: []balancer.PoolAsset{ @@ -694,9 +694,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(3, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 34, + SpreadFactor: sdk.NewDecWithPrec(3, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 34, }, { // Pool 35 PoolAssets: []balancer.PoolAsset{ @@ -709,9 +709,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(2, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 35, + SpreadFactor: sdk.NewDecWithPrec(2, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 35, }, { // Pool 36 PoolAssets: []balancer.PoolAsset{ @@ -724,9 +724,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(3, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 36, + SpreadFactor: sdk.NewDecWithPrec(3, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 36, }, { // Pool 37 PoolAssets: []balancer.PoolAsset{ @@ -739,9 +739,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(3, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 37, + SpreadFactor: sdk.NewDecWithPrec(3, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 37, }, { // Pool 38 PoolAssets: []balancer.PoolAsset{ @@ -754,9 +754,9 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(2, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 38, + SpreadFactor: sdk.NewDecWithPrec(2, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 38, }, { // Pool 39 PoolAssets: []balancer.PoolAsset{ @@ -769,14 +769,14 @@ func (s *KeeperTestSuite) setUpPools() { Weight: sdk.NewInt(1), }, }, - SwapFee: sdk.NewDecWithPrec(2, 3), - ExitFee: sdk.NewDecWithPrec(0, 2), - PoolId: 39, + SpreadFactor: sdk.NewDecWithPrec(2, 3), + ExitFee: sdk.NewDecWithPrec(0, 2), + PoolId: 39, }, } for _, pool := range s.pools { - s.createGAMMPool(pool.PoolAssets, pool.SwapFee, pool.ExitFee) + s.createGAMMPool(pool.PoolAssets, pool.SpreadFactor, pool.ExitFee) } s.stableSwapPools = []StableSwapPool{ @@ -909,9 +909,9 @@ func (s *KeeperTestSuite) createStableswapPool(initialLiquidity sdk.Coins, poolP } // createGAMMPool creates a balancer pool with the given pool assets and params -func (s *KeeperTestSuite) createGAMMPool(poolAssets []balancer.PoolAsset, swapFee, exitFee sdk.Dec) uint64 { +func (s *KeeperTestSuite) createGAMMPool(poolAssets []balancer.PoolAsset, spreadFactor, exitFee sdk.Dec) uint64 { poolParams := balancer.PoolParams{ - SwapFee: swapFee, + SwapFee: spreadFactor, ExitFee: exitFee, } diff --git a/x/protorev/keeper/rebalance.go b/x/protorev/keeper/rebalance.go index 7f260eb96ab..a30847ba6e9 100644 --- a/x/protorev/keeper/rebalance.go +++ b/x/protorev/keeper/rebalance.go @@ -77,7 +77,7 @@ func (k Keeper) ConvertProfits(ctx sdk.Context, inputCoin sdk.Coin, profit sdk.I conversionPool, sdk.NewCoin(inputCoin.Denom, profit), types.OsmosisDenomination, - conversionPool.GetSwapFee(ctx), + conversionPool.GetSpreadFactor(ctx), ) if err != nil { return profit, err diff --git a/x/txfees/keeper/feetokens.go b/x/txfees/keeper/feetokens.go index 1e137ac7eed..cd41902077f 100644 --- a/x/txfees/keeper/feetokens.go +++ b/x/txfees/keeper/feetokens.go @@ -35,7 +35,7 @@ func (k Keeper) ConvertToBaseToken(ctx sdk.Context, inputFee sdk.Coin) (sdk.Coin } // CalcFeeSpotPrice converts the provided tx fees into their equivalent value in the base denomination. -// Spot Price Calculation: spotPrice / (1 - swapFee), +// Spot Price Calculation: spotPrice / (1 - spreadFactor), // where spotPrice is defined as: // (tokenBalanceIn / tokenWeightIn) / (tokenBalanceOut / tokenWeightOut) func (k Keeper) CalcFeeSpotPrice(ctx sdk.Context, inputDenom string) (sdk.Dec, error) { diff --git a/x/txfees/keeper/hooks_test.go b/x/txfees/keeper/hooks_test.go index 3dededb49a7..bbc783731f8 100644 --- a/x/txfees/keeper/hooks_test.go +++ b/x/txfees/keeper/hooks_test.go @@ -40,29 +40,29 @@ func (s *KeeperTestSuite) TestTxFeesAfterEpochEnd() { _, ustPool := s.preparePool(ust) tests := []struct { - name string - coins sdk.Coins - baseDenom string - denoms []string - poolTypes []poolmanagertypes.PoolI - swapFee sdk.Dec - expectPass bool + name string + coins sdk.Coins + baseDenom string + denoms []string + poolTypes []poolmanagertypes.PoolI + spreadFactor sdk.Dec + expectPass bool }{ { - name: "One non-osmo fee token (uion): TxFees AfterEpochEnd", - coins: sdk.Coins{sdk.NewInt64Coin(uion, 10)}, - baseDenom: baseDenom, - denoms: []string{uion}, - poolTypes: []poolmanagertypes.PoolI{uionPool}, - swapFee: sdk.MustNewDecFromStr("0"), + name: "One non-osmo fee token (uion): TxFees AfterEpochEnd", + coins: sdk.Coins{sdk.NewInt64Coin(uion, 10)}, + baseDenom: baseDenom, + denoms: []string{uion}, + poolTypes: []poolmanagertypes.PoolI{uionPool}, + spreadFactor: sdk.MustNewDecFromStr("0"), }, { - name: "Multiple non-osmo fee token: TxFees AfterEpochEnd", - coins: sdk.Coins{sdk.NewInt64Coin(atom, 20), sdk.NewInt64Coin(ust, 30)}, - baseDenom: baseDenom, - denoms: []string{atom, ust}, - poolTypes: []poolmanagertypes.PoolI{atomPool, ustPool}, - swapFee: sdk.MustNewDecFromStr("0"), + name: "Multiple non-osmo fee token: TxFees AfterEpochEnd", + coins: sdk.Coins{sdk.NewInt64Coin(atom, 20), sdk.NewInt64Coin(ust, 30)}, + baseDenom: baseDenom, + denoms: []string{atom, ust}, + poolTypes: []poolmanagertypes.PoolI{atomPool, ustPool}, + spreadFactor: sdk.MustNewDecFromStr("0"), }, } @@ -80,7 +80,7 @@ func (s *KeeperTestSuite) TestTxFeesAfterEpochEnd() { expectedOutput, err := pool.CalcOutAmtGivenIn(s.Ctx, sdk.Coins{sdk.Coin{Denom: tc.denoms[i], Amount: coin.Amount}}, tc.baseDenom, - tc.swapFee) + tc.spreadFactor) s.NoError(err) // sanity check for the expectedAmount s.True(coin.Amount.GTE(expectedOutput.Amount))