Skip to content

Commit

Permalink
refactor(CL): change tick API from sdk.Dec to osmomath.BigDec (#6033)
Browse files Browse the repository at this point in the history
* refactor(CL): change tick API from sdk.Dec to osmomath.BigDec

* changelog

(cherry picked from commit 36e7201)
  • Loading branch information
p0mvn authored and mergify[bot] committed Aug 23, 2023
1 parent 94c91d7 commit d000417
Show file tree
Hide file tree
Showing 31 changed files with 290 additions and 309 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* [#5983](https://github.com/osmosis-labs/osmosis/pull/5983) refactor(CL): 6 return values in CL CreatePosition with a struct
* [#6004](https://github.com/osmosis-labs/osmosis/pull/6004) reduce number of returns for creating full range position
* [#6018](https://github.com/osmosis-labs/osmosis/pull/6018) golangci: add unused parameters linter
* [#6033](https://github.com/osmosis-labs/osmosis/pull/6033) change tick API from sdk.Dec to osmomath.BigDec

### Features

Expand Down
4 changes: 2 additions & 2 deletions tests/cl-genesis-positions/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ func ConvertSubgraphToOsmosisGenesis(positionCreatorAddresses []sdk.AccAddress,
if err != nil {
panic(err)
}
lowerTickOsmosis, err := math.SqrtPriceToTickRoundDownSpacing(sqrtPriceLower, pool.GetTickSpacing())
lowerTickOsmosis, err := math.SqrtPriceToTickRoundDownSpacing(osmomath.BigDecFromSDKDec(sqrtPriceLower), pool.GetTickSpacing())
if err != nil {
panic(err)
}
Expand All @@ -147,7 +147,7 @@ func ConvertSubgraphToOsmosisGenesis(positionCreatorAddresses []sdk.AccAddress,
if err != nil {
panic(err)
}
upperTickOsmosis, err := math.SqrtPriceToTickRoundDownSpacing(sqrtPriceUpper, pool.GetTickSpacing())
upperTickOsmosis, err := math.SqrtPriceToTickRoundDownSpacing(osmomath.BigDecFromSDKDec(sqrtPriceUpper), pool.GetTickSpacing())
if err != nil {
panic(err)
}
Expand Down
8 changes: 4 additions & 4 deletions tests/e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -491,8 +491,8 @@ func (s *IntegrationTestSuite) ConcentratedLiquidity() {
s.Require().NoError(err)
_, sqrtPriceAtNextInitializedTick, err := clmath.TickToSqrtPrice(nextInitTick)
s.Require().NoError(err)
sqrtPriceAfterNextInitializedTickBigDec := osmomath.BigDecFromSDKDec(sqrtPriceAfterNextInitializedTick)
sqrtPriceAtNextInitializedTickBigDec := osmomath.BigDecFromSDKDec(sqrtPriceAtNextInitializedTick)
sqrtPriceAfterNextInitializedTickBigDec := sqrtPriceAfterNextInitializedTick
sqrtPriceAtNextInitializedTickBigDec := sqrtPriceAtNextInitializedTick

// Calculate Δ(sqrtPrice):
// deltaSqrtPriceAfterNextInitializedTick = ΔsqrtP(40300) - ΔsqrtP(40000)
Expand Down Expand Up @@ -635,7 +635,7 @@ func (s *IntegrationTestSuite) ConcentratedLiquidity() {
s.Require().NoError(err)
_, sqrtPriceAtNextInitializedTick, err = clmath.TickToSqrtPrice(nextInitTick)
s.Require().NoError(err)
sqrtPriceAtNextInitializedTickBigDec = osmomath.BigDecFromSDKDec(sqrtPriceAtNextInitializedTick)
sqrtPriceAtNextInitializedTickBigDec = sqrtPriceAtNextInitializedTick

// Calculate numerators
numeratorBelowNextInitializedTick := sqrtPriceAtNextInitializedTick.Sub(sqrtPricebBelowNextInitializedTick)
Expand All @@ -650,7 +650,7 @@ func (s *IntegrationTestSuite) ConcentratedLiquidity() {
fractionAtNextInitializedTick := numeratorNextInitializedTick.Quo(denominatorNextInitializedTick)

// Calculate amounts of uionIn needed
amountInToGetToTickBelowInitialized := liquidityBeforeSwap.Add(positionsAddress1[0].Position.Liquidity).Mul(fractionBelowNextInitializedTick)
amountInToGetToTickBelowInitialized := liquidityBeforeSwap.Add(positionsAddress1[0].Position.Liquidity).Mul(fractionBelowNextInitializedTick.SDKDec())
amountInToGetToNextInitTick = liquidityBeforeSwap.Mul(fractionAtNextInitializedTick.SDKDec())

var (
Expand Down
5 changes: 3 additions & 2 deletions x/concentrated-liquidity/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (

sdk "github.com/cosmos/cosmos-sdk/types"

"github.com/osmosis-labs/osmosis/osmomath"
"github.com/osmosis-labs/osmosis/osmoutils/accum"
"github.com/osmosis-labs/osmosis/v17/x/concentrated-liquidity/model"
"github.com/osmosis-labs/osmosis/v17/x/concentrated-liquidity/swapstrategy"
Expand Down Expand Up @@ -162,7 +163,7 @@ func (k Keeper) SetPositionIdToLock(ctx sdk.Context, positionId, underlyingLockI
k.setPositionIdToLock(ctx, positionId, underlyingLockId)
}

func RoundTickToCanonicalPriceTick(lowerTick, upperTick int64, priceTickLower, priceTickUpper sdk.Dec, tickSpacing uint64) (int64, int64, error) {
func RoundTickToCanonicalPriceTick(lowerTick, upperTick int64, priceTickLower, priceTickUpper osmomath.BigDec, tickSpacing uint64) (int64, int64, error) {
return roundTickToCanonicalPriceTick(lowerTick, upperTick, priceTickLower, priceTickUpper, tickSpacing)
}

Expand Down Expand Up @@ -328,7 +329,7 @@ func (k Keeper) GetLargestSupportedUptimeDuration(ctx sdk.Context) time.Duration

func (k Keeper) SetupSwapStrategy(ctx sdk.Context, p types.ConcentratedPoolExtension,
spreadFactor sdk.Dec, tokenInDenom string,
priceLimit sdk.Dec) (strategy swapstrategy.SwapStrategy, sqrtPriceLimit sdk.Dec, err error) {
priceLimit sdk.Dec) (strategy swapstrategy.SwapStrategy, sqrtPriceLimit osmomath.BigDec, err error) {
return k.setupSwapStrategy(p, spreadFactor, tokenInDenom, priceLimit)
}

Expand Down
2 changes: 1 addition & 1 deletion x/concentrated-liquidity/fuzz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ func (s *KeeperTestSuite) swapNearNextTickBoundary(r *rand.Rand, pool types.Conc
func (s *KeeperTestSuite) swapNearInitializedTickBoundary(r *rand.Rand, pool types.ConcentratedPoolExtension, zfo bool) (didSwap bool, fatalErr bool) {
fmt.Println("swap type: near initialized tick boundary")

ss := swapstrategy.New(zfo, sdk.ZeroDec(), s.App.GetKey(types.ModuleName), sdk.ZeroDec())
ss := swapstrategy.New(zfo, osmomath.ZeroDec(), s.App.GetKey(types.ModuleName), sdk.ZeroDec())

iter := ss.InitializeNextTickIterator(s.Ctx, pool.GetId(), pool.GetCurrentTick())
defer iter.Close()
Expand Down
3 changes: 2 additions & 1 deletion x/concentrated-liquidity/incentives.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/cosmos/cosmos-sdk/types/query"
"golang.org/x/exp/slices"

"github.com/osmosis-labs/osmosis/osmomath"
"github.com/osmosis-labs/osmosis/osmoutils"
"github.com/osmosis-labs/osmosis/osmoutils/accum"
"github.com/osmosis-labs/osmosis/v17/x/concentrated-liquidity/math"
Expand Down Expand Up @@ -200,7 +201,7 @@ func (k Keeper) prepareBalancerPoolAsFullRange(ctx sdk.Context, clPoolId uint64,
// Calculate the amount of liquidity the Balancer amounts qualify in the CL pool. Note that since we use the CL spot price, this is
// safe against prices drifting apart between the two pools (we take the lower bound on the qualifying liquidity in this case).
// The `sqrtPriceLowerTick` and `sqrtPriceUpperTick` fields are set to the appropriate values for a full range position.
qualifyingFullRangeSharesPreDiscount := math.GetLiquidityFromAmounts(clPool.GetCurrentSqrtPrice(), types.MinSqrtPrice, types.MaxSqrtPrice, asset0Amount, asset1Amount)
qualifyingFullRangeSharesPreDiscount := math.GetLiquidityFromAmounts(clPool.GetCurrentSqrtPrice(), osmomath.BigDecFromSDKDec(types.MinSqrtPrice), osmomath.BigDecFromSDKDec(types.MaxSqrtPrice), asset0Amount, asset1Amount)

// Get discount ratio from governance-set discount rate.
// Note that discount rate is the amount that is being discounted by (e.g. 0.05 for a 5% discount), while discount ratio is what
Expand Down
5 changes: 3 additions & 2 deletions x/concentrated-liquidity/incentives_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/cosmos/cosmos-sdk/types/query"
distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types"

"github.com/osmosis-labs/osmosis/osmomath"
"github.com/osmosis-labs/osmosis/osmoutils/accum"
cl "github.com/osmosis-labs/osmosis/v17/x/concentrated-liquidity"
"github.com/osmosis-labs/osmosis/v17/x/concentrated-liquidity/math"
Expand Down Expand Up @@ -1056,7 +1057,7 @@ func (s *KeeperTestSuite) TestUpdateUptimeAccumulatorsToNow() {
clPool, err = clKeeper.GetPoolById(s.Ctx, clPool.GetId())
s.Require().NoError(err)
if tc.canonicalBalancerPoolAssets != nil {
qualifyingBalancerLiquidityPreDiscount := math.GetLiquidityFromAmounts(clPool.GetCurrentSqrtPrice(), types.MinSqrtPrice, types.MaxSqrtPrice, tc.canonicalBalancerPoolAssets[0].Token.Amount, tc.canonicalBalancerPoolAssets[1].Token.Amount)
qualifyingBalancerLiquidityPreDiscount := math.GetLiquidityFromAmounts(clPool.GetCurrentSqrtPrice(), osmomath.BigDecFromSDKDec(types.MinSqrtPrice), osmomath.BigDecFromSDKDec(types.MaxSqrtPrice), tc.canonicalBalancerPoolAssets[0].Token.Amount, tc.canonicalBalancerPoolAssets[1].Token.Amount)
qualifyingBalancerLiquidity = (sdk.OneDec().Sub(types.DefaultBalancerSharesDiscount)).Mul(qualifyingBalancerLiquidityPreDiscount)
qualifyingLiquidity = qualifyingLiquidity.Add(qualifyingBalancerLiquidity)

Expand Down Expand Up @@ -3591,7 +3592,7 @@ func (s *KeeperTestSuite) TestPrepareBalancerPoolAsFullRange() {
s.Require().NoError(err)
asset0BalancerAmount := tc.balancerPoolAssets[0].Token.Amount.ToDec().Mul(tc.portionOfSharesBonded).TruncateInt()
asset1BalancerAmount := tc.balancerPoolAssets[1].Token.Amount.ToDec().Mul(tc.portionOfSharesBonded).TruncateInt()
qualifyingSharesPreDiscount := math.GetLiquidityFromAmounts(updatedClPool.GetCurrentSqrtPrice(), types.MinSqrtPrice, types.MaxSqrtPrice, asset1BalancerAmount, asset0BalancerAmount)
qualifyingSharesPreDiscount := math.GetLiquidityFromAmounts(updatedClPool.GetCurrentSqrtPrice(), osmomath.BigDecFromSDKDec(types.MinSqrtPrice), osmomath.BigDecFromSDKDec(types.MaxSqrtPrice), asset1BalancerAmount, asset0BalancerAmount)
qualifyingShares := (sdk.OneDec().Sub(types.DefaultBalancerSharesDiscount)).Mul(qualifyingSharesPreDiscount)

// TODO: clean this check up (will likely require refactoring the whole test)
Expand Down
10 changes: 5 additions & 5 deletions x/concentrated-liquidity/keeper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,10 @@ var (
sqrt4999 = sdk.MustNewDecFromStr("70.703606697254136613")
sqrt5500 = sdk.MustNewDecFromStr("74.161984870956629488")
sqrt6250 = sdk.MustNewDecFromStr("79.056941504209483300")
DefaultExponentConsecutivePositionLowerTick, _ = math.SqrtPriceToTickRoundDownSpacing(sqrt5500, DefaultTickSpacing)
DefaultExponentConsecutivePositionUpperTick, _ = math.SqrtPriceToTickRoundDownSpacing(sqrt6250, DefaultTickSpacing)
DefaultExponentOverlappingPositionLowerTick, _ = math.SqrtPriceToTickRoundDownSpacing(sqrt4000, DefaultTickSpacing)
DefaultExponentOverlappingPositionUpperTick, _ = math.SqrtPriceToTickRoundDownSpacing(sqrt4999, DefaultTickSpacing)
DefaultExponentConsecutivePositionLowerTick, _ = math.SqrtPriceToTickRoundDownSpacing(osmomath.BigDecFromSDKDec(sqrt5500), DefaultTickSpacing)
DefaultExponentConsecutivePositionUpperTick, _ = math.SqrtPriceToTickRoundDownSpacing(osmomath.BigDecFromSDKDec(sqrt6250), DefaultTickSpacing)
DefaultExponentOverlappingPositionLowerTick, _ = math.SqrtPriceToTickRoundDownSpacing(osmomath.BigDecFromSDKDec(sqrt4000), DefaultTickSpacing)
DefaultExponentOverlappingPositionUpperTick, _ = math.SqrtPriceToTickRoundDownSpacing(osmomath.BigDecFromSDKDec(sqrt4999), DefaultTickSpacing)
BAR = "bar"
FOO = "foo"
InsufficientFundsError = fmt.Errorf("insufficient funds")
Expand All @@ -82,7 +82,7 @@ func TestConstants(t *testing.T) {
lowerSqrtPrice, _ := osmomath.MonotonicSqrt(DefaultLowerPrice)
upperSqrtPrice, _ := osmomath.MonotonicSqrt(DefaultUpperPrice)
liq := math.GetLiquidityFromAmounts(DefaultCurrSqrtPrice,
lowerSqrtPrice, upperSqrtPrice, DefaultAmt0, DefaultAmt1)
osmomath.BigDecFromSDKDec(lowerSqrtPrice), osmomath.BigDecFromSDKDec(upperSqrtPrice), DefaultAmt0, DefaultAmt1)
require.Equal(t, DefaultLiquidityAmt, liq)
}

Expand Down
2 changes: 1 addition & 1 deletion x/concentrated-liquidity/lp.go
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,7 @@ func (k Keeper) initializeInitialPositionForPool(ctx sdk.Context, pool types.Con
// Calculate the initial tick from the initial spot price
// We round down here so that the tick is rounded to
// the nearest possible value given the tick spacing.
initialTick, err := math.SqrtPriceToTickRoundDownSpacing(initialCurSqrtPrice, pool.GetTickSpacing())
initialTick, err := math.SqrtPriceToTickRoundDownSpacing(osmomath.BigDecFromSDKDec(initialCurSqrtPrice), pool.GetTickSpacing())
if err != nil {
return err
}
Expand Down
21 changes: 9 additions & 12 deletions x/concentrated-liquidity/math/math.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,28 +173,25 @@ func GetNextSqrtPriceFromAmount1OutRoundingDown(sqrtPriceCurrent, liquidity, amo

// GetLiquidityFromAmounts takes the current sqrtPrice and the sqrtPrice for the upper and lower ticks as well as the amounts of asset0 and asset1
// and returns the resulting liquidity from these inputs.
func GetLiquidityFromAmounts(sqrtPrice osmomath.BigDec, sqrtPriceA, sqrtPriceB sdk.Dec, amount0, amount1 sdk.Int) (liquidity sdk.Dec) {
sqrtPriceABigDec := osmomath.BigDecFromSDKDec(sqrtPriceA)
sqrtPriceBBigDec := osmomath.BigDecFromSDKDec(sqrtPriceB)

func GetLiquidityFromAmounts(sqrtPrice osmomath.BigDec, sqrtPriceA, sqrtPriceB osmomath.BigDec, amount0, amount1 sdk.Int) (liquidity sdk.Dec) {
// Reorder the prices so that sqrtPriceA is the smaller of the two.
// todo: Remove this.
if sqrtPriceABigDec.GT(sqrtPriceBBigDec) {
sqrtPriceABigDec, sqrtPriceBBigDec = sqrtPriceBBigDec, sqrtPriceABigDec
if sqrtPriceA.GT(sqrtPriceB) {
sqrtPriceA, sqrtPriceB = sqrtPriceB, sqrtPriceA
}

if sqrtPrice.LTE(sqrtPriceABigDec) {
if sqrtPrice.LTE(sqrtPriceA) {
// If the current price is less than or equal to the lower tick, then we use the liquidity0 formula.
liquidity = Liquidity0(amount0, sqrtPriceABigDec, sqrtPriceBBigDec)
} else if sqrtPrice.LT(sqrtPriceBBigDec) {
liquidity = Liquidity0(amount0, sqrtPriceA, sqrtPriceB)
} else if sqrtPrice.LT(sqrtPriceB) {
// If the current price is between the lower and upper ticks (exclusive of both the lower and upper ticks,
// as both would trigger a division by zero), then we use the minimum of the liquidity0 and liquidity1 formulas.
liquidity0 := Liquidity0(amount0, sqrtPrice, sqrtPriceBBigDec)
liquidity1 := Liquidity1(amount1, sqrtPrice, sqrtPriceABigDec)
liquidity0 := Liquidity0(amount0, sqrtPrice, sqrtPriceB)
liquidity1 := Liquidity1(amount1, sqrtPrice, sqrtPriceA)
liquidity = sdk.MinDec(liquidity0, liquidity1)
} else {
// If the current price is greater than the upper tick, then we use the liquidity1 formula.
liquidity = Liquidity1(amount1, sqrtPriceBBigDec, sqrtPriceABigDec)
liquidity = Liquidity1(amount1, sqrtPriceB, sqrtPriceA)
}

return liquidity
Expand Down
36 changes: 18 additions & 18 deletions x/concentrated-liquidity/math/math_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,8 @@ func TestGetLiquidityFromAmounts(t *testing.T) {

testCases := map[string]struct {
currentSqrtP osmomath.BigDec
sqrtPHigh sdk.Dec
sqrtPLow sdk.Dec
sqrtPHigh osmomath.BigDec
sqrtPLow osmomath.BigDec
// the amount of token0 that will need to be sold to move the price from P_cur to P_low
amount0Desired sdk.Int
// the amount of token 1 that will need to be sold to move the price from P_cur to P_high.
Expand All @@ -283,40 +283,40 @@ func TestGetLiquidityFromAmounts(t *testing.T) {
}{
"happy path (case A)": {
currentSqrtP: osmomath.MustNewDecFromStr("67"), // 4489
sqrtPHigh: sqrt5500, // 5500
sqrtPLow: sqrt4545, // 4545
sqrtPHigh: sqrt5500BigDec, // 5500
sqrtPLow: sqrt4545BigDec, // 4545
amount0Desired: sdk.NewInt(1000000),
amount1Desired: sdk.ZeroInt(),
expectedLiquidity: "741212151.448720111852782017",
},
"happy path (case A, but with sqrtPriceA greater than sqrtPriceB)": {
currentSqrtP: osmomath.MustNewDecFromStr("67"), // 4489
sqrtPHigh: sqrt4545, // 4545
sqrtPLow: sqrt5500, // 5500
sqrtPHigh: sqrt4545BigDec, // 4545
sqrtPLow: sqrt5500BigDec, // 5500
amount0Desired: sdk.NewInt(1000000),
amount1Desired: sdk.ZeroInt(),
expectedLiquidity: "741212151.448720111852782017",
},
"happy path (case B)": {
currentSqrtP: sqrt5000BigDec, // 5000
sqrtPHigh: sqrt5500, // 5500
sqrtPLow: sqrt4545, // 4545
sqrtPHigh: sqrt5500BigDec, // 5500
sqrtPLow: sqrt4545BigDec, // 4545
amount0Desired: sdk.NewInt(1000000),
amount1Desired: sdk.NewInt(5000000000),
expectedLiquidity: "1517882343.751510418088349649",
},
"happy path (case C)": {
currentSqrtP: osmomath.MustNewDecFromStr("75"), // 5625
sqrtPHigh: sqrt5500, // 5500
sqrtPLow: sqrt4545, // 4545
sqrtPHigh: sqrt5500BigDec, // 5500
sqrtPLow: sqrt4545BigDec, // 4545
amount0Desired: sdk.ZeroInt(),
amount1Desired: sdk.NewInt(5000000000),
expectedLiquidity: "741249214.836069764856625637",
},
"full range, price proportional to amounts, equal liquidities (some rounding error) price of 4": {
currentSqrtP: sqrt(sdk.NewDec(4)),
sqrtPHigh: cltypes.MaxSqrtPrice,
sqrtPLow: cltypes.MinSqrtPrice,
sqrtPHigh: osmomath.BigDecFromSDKDec(cltypes.MaxSqrtPrice),
sqrtPLow: osmomath.BigDecFromSDKDec(cltypes.MinSqrtPrice),
amount0Desired: sdk.NewInt(4),
amount1Desired: sdk.NewInt(16),

Expand All @@ -326,8 +326,8 @@ func TestGetLiquidityFromAmounts(t *testing.T) {
},
"full range, price proportional to amounts, equal liquidities (some rounding error) price of 2": {
currentSqrtP: sqrt(sdk.NewDec(2)),
sqrtPHigh: cltypes.MaxSqrtPrice,
sqrtPLow: cltypes.MinSqrtPrice,
sqrtPHigh: osmomath.BigDecFromSDKDec(cltypes.MaxSqrtPrice),
sqrtPLow: osmomath.BigDecFromSDKDec(cltypes.MinSqrtPrice),
amount0Desired: sdk.NewInt(1),
amount1Desired: sdk.NewInt(2),

Expand All @@ -337,8 +337,8 @@ func TestGetLiquidityFromAmounts(t *testing.T) {
},
"not full range, price proportional to amounts, non equal liquidities": {
currentSqrtP: sqrt(sdk.NewDec(2)),
sqrtPHigh: sqrt(sdk.NewDec(3)).SDKDec(),
sqrtPLow: sqrt(sdk.NewDec(1)).SDKDec(),
sqrtPHigh: sqrt(sdk.NewDec(3)),
sqrtPLow: sqrt(sdk.NewDec(1)),
amount0Desired: sdk.NewInt(1),
amount1Desired: sdk.NewInt(2),

Expand All @@ -348,8 +348,8 @@ func TestGetLiquidityFromAmounts(t *testing.T) {
},
"current sqrt price on upper bound": {
currentSqrtP: sqrt5500BigDec,
sqrtPHigh: sqrt5500,
sqrtPLow: sqrt4545,
sqrtPHigh: sqrt5500BigDec,
sqrtPLow: sqrt4545BigDec,
amount0Desired: sdk.ZeroInt(),
amount1Desired: sdk.NewInt(1000000),
// Liquidity1 = amount1 / (sqrtPriceB - sqrtPriceA)
Expand Down
Loading

0 comments on commit d000417

Please sign in to comment.