-
Notifications
You must be signed in to change notification settings - Fork 609
/
swaps.go
540 lines (467 loc) · 22 KB
/
swaps.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
package concentrated_liquidity
import (
fmt "fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
events "github.com/osmosis-labs/osmosis/v13/x/swaprouter/events"
"github.com/osmosis-labs/osmosis/v13/x/concentrated-liquidity/internal/math"
"github.com/osmosis-labs/osmosis/v13/x/concentrated-liquidity/internal/swapstrategy"
"github.com/osmosis-labs/osmosis/v13/x/concentrated-liquidity/types"
gammtypes "github.com/osmosis-labs/osmosis/v13/x/gamm/types"
swaproutertypes "github.com/osmosis-labs/osmosis/v13/x/swaprouter/types"
)
type SwapState struct {
amountSpecifiedRemaining sdk.Dec // remaining amount of tokens that need to be bought by the pool
amountCalculated sdk.Dec // amount out
sqrtPrice sdk.Dec // new current price when swap is done
tick sdk.Int // new tick when swap is done
liquidity sdk.Dec // new liquidity when swap is done
}
func (k Keeper) SwapExactAmountIn(
ctx sdk.Context,
sender sdk.AccAddress,
poolI swaproutertypes.PoolI,
tokenIn sdk.Coin,
tokenOutDenom string,
tokenOutMinAmount sdk.Int,
swapFee sdk.Dec,
) (tokenOutAmount sdk.Int, err error) {
if tokenIn.Denom == tokenOutDenom {
return sdk.Int{}, types.DenomDuplicatedError{TokenInDenom: tokenIn.Denom, TokenOutDenom: tokenOutDenom}
}
// type cast PoolI to ConcentratedPoolExtension
pool, ok := poolI.(types.ConcentratedPoolExtension)
if !ok {
return sdk.Int{}, fmt.Errorf("pool type (%T) cannot be cast to ConcentratedPoolExtension", poolI)
}
// determine if we are swapping asset0 for asset1 or vice versa
asset0 := pool.GetToken0()
zeroForOne := tokenIn.Denom == asset0
// change priceLimit based on which direction we are swapping
var priceLimit sdk.Dec
if zeroForOne {
priceLimit = types.LowerPriceLimit
} else {
priceLimit = types.UpperPriceLimit
}
tokenIn, tokenOut, newCurrentTick, newLiquidity, newSqrtPrice, err := k.SwapOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, swapFee, priceLimit, pool.GetId())
if err != nil {
return sdk.Int{}, err
}
// check that the tokenOut calculated is both valid and less than specified limit
tokenOutAmount = tokenOut.Amount
if !tokenOutAmount.IsPositive() {
return sdk.Int{}, fmt.Errorf("token amount must be positive: got %v", tokenOutAmount)
}
if tokenOutAmount.LT(tokenOutMinAmount) {
return sdk.Int{}, types.AmountLessThanMinError{TokenAmount: tokenOutAmount, TokenMin: tokenOutMinAmount}
}
// Settles balances between the tx sender and the pool to match the swap that was executed earlier.
// Also emits swap event and updates related liquidity metrics
if err := k.updatePoolForSwap(ctx, poolI, sender, tokenIn, tokenOut, newCurrentTick, newLiquidity, newSqrtPrice); err != nil {
return sdk.Int{}, err
}
return tokenOutAmount, nil
}
func (k Keeper) SwapExactAmountOut(
ctx sdk.Context,
sender sdk.AccAddress,
poolI swaproutertypes.PoolI,
tokenInDenom string,
tokenInMaxAmount sdk.Int,
tokenOut sdk.Coin,
swapFee sdk.Dec,
) (tokenInAmount sdk.Int, err error) {
if tokenOut.Denom == tokenInDenom {
return sdk.Int{}, types.DenomDuplicatedError{TokenInDenom: tokenInDenom, TokenOutDenom: tokenOut.Denom}
}
// type cast PoolI to ConcentratedPoolExtension
pool, ok := poolI.(types.ConcentratedPoolExtension)
if !ok {
return sdk.Int{}, fmt.Errorf("pool type (%T) cannot be cast to ConcentratedPoolExtension", poolI)
}
// determine if we are swapping asset0 for asset1 or vice versa
asset0 := pool.GetToken0()
zeroForOne := tokenOut.Denom == asset0
// change priceLimit based on which direction we are swapping
var priceLimit sdk.Dec
if zeroForOne {
priceLimit = types.LowerPriceLimit
} else {
priceLimit = types.UpperPriceLimit
}
tokenIn, tokenOut, newCurrentTick, newLiquidity, newSqrtPrice, err := k.SwapInAmtGivenOut(ctx, tokenOut, tokenInDenom, swapFee, priceLimit, pool.GetId())
if err != nil {
return sdk.Int{}, err
}
// check that the tokenOut calculated is both valid and less than specified limit
tokenInAmount = tokenIn.Amount
if !tokenInAmount.IsPositive() {
return sdk.Int{}, fmt.Errorf("token amount must be positive: got %v", tokenInAmount)
}
if tokenInAmount.GT(tokenInMaxAmount) {
return sdk.Int{}, types.AmountGreaterThanMaxError{TokenAmount: tokenInAmount, TokenMax: tokenInMaxAmount}
}
// Settles balances between the tx sender and the pool to match the swap that was executed earlier.
// Also emits swap event and updates related liquidity metrics
if err := k.updatePoolForSwap(ctx, poolI, sender, tokenIn, tokenOut, newCurrentTick, newLiquidity, newSqrtPrice); err != nil {
return sdk.Int{}, err
}
return tokenInAmount, nil
}
// SwapOutAmtGivenIn is the internal mutative method for CalcOutAmtGivenIn. Utilizing CalcOutAmtGivenIn's output, this function applies the
// new tick, liquidity, and sqrtPrice to the respective pool
func (k Keeper) SwapOutAmtGivenIn(
ctx sdk.Context,
tokenIn sdk.Coin,
tokenOutDenom string,
swapFee sdk.Dec,
priceLimit sdk.Dec,
poolId uint64,
) (calcTokenIn, calcTokenOut sdk.Coin, currentTick sdk.Int, liquidity, sqrtPrice sdk.Dec, err error) {
tokenIn, tokenOut, newCurrentTick, newLiquidity, newSqrtPrice, err := k.calcOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, swapFee, priceLimit, poolId)
if err != nil {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, err
}
err = k.applySwap(ctx, tokenIn, tokenOut, poolId, newLiquidity, newCurrentTick, newSqrtPrice)
if err != nil {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, err
}
return tokenIn, tokenOut, newCurrentTick, newLiquidity, newSqrtPrice, nil
}
func (k *Keeper) SwapInAmtGivenOut(
ctx sdk.Context,
desiredTokenOut sdk.Coin,
tokenInDenom string,
swapFee sdk.Dec,
priceLimit sdk.Dec,
poolId uint64,
) (calcTokenIn, calcTokenOut sdk.Coin, currentTick sdk.Int, liquidity, sqrtPrice sdk.Dec, err error) {
tokenIn, tokenOut, newCurrentTick, newLiquidity, newSqrtPrice, err := k.calcInAmtGivenOut(ctx, desiredTokenOut, tokenInDenom, swapFee, priceLimit, poolId)
if err != nil {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, err
}
err = k.applySwap(ctx, tokenIn, tokenOut, poolId, newLiquidity, newCurrentTick, newSqrtPrice)
if err != nil {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, err
}
return tokenIn, tokenOut, newCurrentTick, newLiquidity, newSqrtPrice, nil
}
func (k Keeper) CalcOutAmtGivenIn(
ctx sdk.Context,
poolI swaproutertypes.PoolI,
tokenIn sdk.Coin,
tokenOutDenom string,
swapFee sdk.Dec,
) (tokenOut sdk.Coin, err error) {
_, tokenOut, _, _, _, err = k.calcOutAmtGivenIn(ctx, tokenIn, tokenOutDenom, swapFee, sdk.ZeroDec(), poolI.GetId())
if err != nil {
return sdk.Coin{}, err
}
return tokenOut, nil
}
func (k Keeper) CalcInAmtGivenOut(
ctx sdk.Context,
poolI swaproutertypes.PoolI,
tokenOut sdk.Coin,
tokenInDenom string,
swapFee sdk.Dec,
) (tokenIn sdk.Coin, err error) {
tokenIn, _, _, _, _, err = k.calcInAmtGivenOut(ctx, tokenOut, tokenInDenom, swapFee, sdk.ZeroDec(), poolI.GetId())
if err != nil {
return sdk.Coin{}, err
}
return tokenIn, nil
}
// calcOutAmtGivenIn calculates tokens to be swapped out given the provided amount and fee deducted. It also returns
// what the updated tick, liquidity, and currentSqrtPrice for the pool would be after this swap.
// Note this method is non-mutative, so the values returned by CalcOutAmtGivenIn do not get stored
func (k Keeper) calcOutAmtGivenIn(ctx sdk.Context,
tokenInMin sdk.Coin,
tokenOutDenom string,
swapFee sdk.Dec,
priceLimit sdk.Dec,
poolId uint64,
) (tokenIn, tokenOut sdk.Coin, updatedTick sdk.Int, updatedLiquidity, updatedSqrtPrice sdk.Dec, err error) {
p, err := k.getPoolById(ctx, poolId)
if err != nil {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, err
}
asset0 := p.GetToken0()
asset1 := p.GetToken1()
tokenAmountInAfterFee := tokenInMin.Amount.ToDec().Mul(sdk.OneDec().Sub(swapFee))
// if swapping asset0 for asset1, zeroForOne is true
zeroForOne := tokenInMin.Denom == asset0
// if priceLimit not set, set to max/min value based on swap direction
if zeroForOne && priceLimit.Equal(sdk.ZeroDec()) {
priceLimit = types.LowerPriceLimit
} else if !zeroForOne && priceLimit.Equal(sdk.ZeroDec()) {
priceLimit = types.UpperPriceLimit
}
// take provided price limit and turn this into a sqrt price limit since formulas use sqrtPrice
sqrtPriceLimit, err := priceLimit.ApproxSqrt()
if err != nil {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, fmt.Errorf("issue calculating square root of price limit")
}
// set the swap strategy
swapStrategy := swapstrategy.New(zeroForOne, sqrtPriceLimit, k.storeKey)
// get current sqrt price from pool
curSqrtPrice := p.GetCurrentSqrtPrice()
if err := swapStrategy.ValidatePriceLimit(sqrtPriceLimit, curSqrtPrice); err != nil {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, err
}
// check that the specified tokenIn matches one of the assets in the specified pool
if tokenInMin.Denom != asset0 && tokenInMin.Denom != asset1 {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, types.TokenInDenomNotInPoolError{TokenInDenom: tokenInMin.Denom}
}
// check that the specified tokenOut matches one of the assets in the specified pool
if tokenOutDenom != asset0 && tokenOutDenom != asset1 {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, types.TokenOutDenomNotInPoolError{TokenOutDenom: tokenOutDenom}
}
// check that token in and token out are different denominations
if tokenInMin.Denom == tokenOutDenom {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, types.DenomDuplicatedError{TokenInDenom: tokenInMin.Denom, TokenOutDenom: tokenOutDenom}
}
// initialize swap state with the following parameters:
// as we iterate through the following for loop, this swap state will get updated after each required iteration
swapState := SwapState{
amountSpecifiedRemaining: tokenAmountInAfterFee, // tokenIn
amountCalculated: sdk.ZeroDec(), // tokenOut
sqrtPrice: curSqrtPrice,
tick: swapStrategy.InitializeTickValue(p.GetCurrentTick()),
liquidity: p.GetLiquidity(),
}
// iterate and update swapState until we swap all tokenIn or we reach the specific sqrtPriceLimit
// TODO: for now, we check if amountSpecifiedRemaining is GT 0.0000001. This is because there are times when the remaining
// amount may be extremely small, and that small amount cannot generate and amountIn/amountOut and we are therefore left
// in an infinite loop.
for swapState.amountSpecifiedRemaining.GT(sdk.MustNewDecFromStr("0.0000001")) && !swapState.sqrtPrice.Equal(sqrtPriceLimit) {
// log the sqrtPrice we start the iteration with
sqrtPriceStart := swapState.sqrtPrice
// we first check to see what the position of the nearest initialized tick is
// if zeroForOneStrategy, we look to the left of the tick the current sqrt price is at
// if oneForZeroStrategy, we look to the right of the tick the current sqrt price is at
// if no ticks are initialized (no users have created liquidity positions) then we return an error
nextTick, ok := swapStrategy.NextInitializedTick(ctx, poolId, swapState.tick.Int64())
if !ok {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, fmt.Errorf("there are no more ticks initialized to fill the swap")
}
// utilizing the next initialized tick, we find the corresponding nextSqrtPrice (the target sqrtPrice)
nextSqrtPrice, err := math.TickToSqrtPrice(nextTick)
if err != nil {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, fmt.Errorf("could not convert next tick (%v) to nextSqrtPrice", nextTick)
}
// utilizing the bucket's liquidity and knowing the price target, we calculate the how much tokenOut we get from the tokenIn
// we also calculate the swap state's new sqrtPrice after this swap
sqrtPrice, amountIn, amountOut := swapStrategy.ComputeSwapStep(
swapState.sqrtPrice,
nextSqrtPrice,
swapState.liquidity,
swapState.amountSpecifiedRemaining,
)
// update the swapState with the new sqrtPrice from the above swap
swapState.sqrtPrice = sqrtPrice
// we deduct the amount of tokens we input in the computeSwapStep above from the user's defined tokenIn amount
swapState.amountSpecifiedRemaining = swapState.amountSpecifiedRemaining.Sub(amountIn)
// we add the amount of tokens we received (amountOut) from the computeSwapStep above to the amountCalculated accumulator
swapState.amountCalculated = swapState.amountCalculated.Add(amountOut)
// if the computeSwapStep calculated a sqrtPrice that is equal to the nextSqrtPrice, this means all liquidity in the current
// tick has been consumed and we must move on to the next tick to complete the swap
if nextSqrtPrice.Equal(sqrtPrice) {
// retrieve the liquidity held in the next closest initialized tick
liquidityNet, err := k.crossTick(ctx, p.GetId(), nextTick.Int64())
if err != nil {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, err
}
liquidityNet = swapStrategy.SetLiquidityDeltaSign(liquidityNet)
// update the swapState's liquidity with the new tick's liquidity
newLiquidity := math.AddLiquidity(swapState.liquidity, liquidityNet)
swapState.liquidity = newLiquidity
// update the swapState's tick with the tick we retrieved liquidity from
swapState.tick = nextTick
} else if !sqrtPriceStart.Equal(sqrtPrice) {
// otherwise if the sqrtPrice calculated from computeSwapStep does not equal the sqrtPrice we started with at the
// beginning of this iteration, we set the swapState tick to the corresponding tick of the sqrtPrice calculated from computeSwapStep
swapState.tick = math.PriceToTick(sqrtPrice.Power(2))
}
}
// coin amounts require int values
// round amountIn up to avoid under charging
amt0 := tokenAmountInAfterFee.Sub(swapState.amountSpecifiedRemaining).RoundInt()
amt1 := swapState.amountCalculated.TruncateInt()
tokenIn = sdk.NewCoin(tokenInMin.Denom, amt0)
tokenOut = sdk.NewCoin(tokenOutDenom, amt1)
return tokenIn, tokenOut, swapState.tick, swapState.liquidity, swapState.sqrtPrice, nil
}
func (k Keeper) calcInAmtGivenOut(
ctx sdk.Context,
desiredTokenOut sdk.Coin,
tokenInDenom string,
swapFee sdk.Dec,
priceLimit sdk.Dec,
poolId uint64,
) (tokenIn, tokenOut sdk.Coin, updatedTick sdk.Int, updatedLiquidity, updatedSqrtPrice sdk.Dec, err error) {
p, err := k.getPoolById(ctx, poolId)
if err != nil {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, err
}
asset0 := p.GetToken0()
asset1 := p.GetToken1()
// if swapping asset0 for asset1, zeroForOne is true
zeroForOne := desiredTokenOut.Denom == asset0
// if priceLimit not set, set to max/min value based on swap direction
if zeroForOne && priceLimit.Equal(sdk.ZeroDec()) {
priceLimit = types.LowerPriceLimit
} else if !zeroForOne && priceLimit.Equal(sdk.ZeroDec()) {
priceLimit = types.UpperPriceLimit
}
// take provided price limit and turn this into a sqrt price limit since formulas use sqrtPrice
sqrtPriceLimit, err := priceLimit.ApproxSqrt()
if err != nil {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, fmt.Errorf("issue calculating square root of price limit")
}
// set the swap strategy
swapStrategy := swapstrategy.New(zeroForOne, sqrtPriceLimit, k.storeKey) // TODO: correct price limit when in given out is refactored.
// get current sqrt price from pool
curSqrtPrice := p.GetCurrentSqrtPrice()
if err := swapStrategy.ValidatePriceLimit(sqrtPriceLimit, curSqrtPrice); err != nil {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, err
}
// check that the specified tokenOut matches one of the assets in the specified pool
if desiredTokenOut.Denom != asset0 && desiredTokenOut.Denom != asset1 {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, types.TokenOutDenomNotInPoolError{TokenOutDenom: desiredTokenOut.Denom}
}
// check that the specified tokenIn matches one of the assets in the specified pool
if tokenInDenom != asset0 && tokenInDenom != asset1 {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, types.TokenInDenomNotInPoolError{TokenInDenom: tokenInDenom}
}
// check that token in and token out are different denominations
if desiredTokenOut.Denom == tokenInDenom {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, types.DenomDuplicatedError{TokenInDenom: tokenInDenom, TokenOutDenom: desiredTokenOut.Denom}
}
// initialize swap state with the following parameters:
// as we iterate through the following for loop, this swap state will get updated after each required iteration
swapState := SwapState{
amountSpecifiedRemaining: desiredTokenOut.Amount.ToDec(), // tokenOut
amountCalculated: sdk.ZeroDec(), // tokenIn
sqrtPrice: curSqrtPrice,
tick: swapStrategy.InitializeTickValue(p.GetCurrentTick()),
liquidity: p.GetLiquidity(),
}
// TODO: This should be GT 0 but some instances have very small remainder
// need to look into fixing this
for swapState.amountSpecifiedRemaining.GT(sdk.MustNewDecFromStr("0.0000001")) && !swapState.sqrtPrice.Equal(sqrtPriceLimit) {
// log the sqrtPrice we start the iteration with
sqrtPriceStart := swapState.sqrtPrice
// we first check to see what the position of the nearest initialized tick is
// if zeroForOne is false, we look to the left of the tick the current sqrt price is at
// if zeroForOne is true, we look to the right of the tick the current sqrt price is at
// if no ticks are initialized (no users have created liquidity positions) then we return an error
nextTick, ok := swapStrategy.NextInitializedTick(ctx, poolId, swapState.tick.Int64())
if !ok {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, fmt.Errorf("there are no more ticks initialized to fill the swap")
}
// utilizing the next initialized tick, we find the corresponding nextSqrtPrice (the target sqrtPrice)
nextSqrtPrice, err := math.TickToSqrtPrice(nextTick)
if err != nil {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, fmt.Errorf("could not convert next tick (%v) to nextSqrtPrice", nextTick)
}
// utilizing the bucket's liquidity and knowing the price target, we calculate the how much tokenOut we get from the tokenIn
// we also calculate the swap state's new sqrtPrice after this swap
sqrtPrice, amountIn, amountOut := swapStrategy.ComputeSwapStep(
swapState.sqrtPrice,
nextSqrtPrice,
swapState.liquidity,
swapState.amountSpecifiedRemaining,
)
// update the swapState with the new sqrtPrice from the above swap
swapState.sqrtPrice = sqrtPrice
swapState.amountSpecifiedRemaining = swapState.amountSpecifiedRemaining.Sub(amountIn)
swapState.amountCalculated = swapState.amountCalculated.Add(amountOut.Quo(sdk.OneDec().Sub(swapFee)))
// if the computeSwapStep calculated a sqrtPrice that is equal to the nextSqrtPrice, this means all liquidity in the current
// tick has been consumed and we must move on to the next tick to complete the swap
if nextSqrtPrice.Equal(sqrtPrice) {
// retrieve the liquidity held in the next closest initialized tick
liquidityNet, err := k.crossTick(ctx, p.GetId(), nextTick.Int64())
if err != nil {
return sdk.Coin{}, sdk.Coin{}, sdk.Int{}, sdk.Dec{}, sdk.Dec{}, err
}
liquidityNet = swapStrategy.SetLiquidityDeltaSign(liquidityNet)
// update the swapState's liquidity with the new tick's liquidity
newLiquidity := math.AddLiquidity(swapState.liquidity, liquidityNet)
swapState.liquidity = newLiquidity
// update the swapState's tick with the tick we retrieved liquidity from
swapState.tick = nextTick
} else if !sqrtPriceStart.Equal(sqrtPrice) {
// otherwise if the sqrtPrice calculated from computeSwapStep does not equal the sqrtPrice we started with at the
// beginning of this iteration, we set the swapState tick to the corresponding tick of the sqrtPrice calculated from computeSwapStep
swapState.tick = math.PriceToTick(sqrtPrice.Power(2))
}
// coin amounts require int values
// round amountIn up to avoid under charging
amt0 := swapState.amountCalculated.TruncateInt()
amt1 := desiredTokenOut.Amount.ToDec().Sub(swapState.amountSpecifiedRemaining).RoundInt()
tokenIn = sdk.NewCoin(tokenInDenom, amt0)
tokenOut = sdk.NewCoin(desiredTokenOut.Denom, amt1)
}
return tokenIn, tokenOut, swapState.tick, swapState.liquidity, swapState.sqrtPrice, nil
}
// applySwap persists the swap state and charges gas fees.
// TODO: test this and make sure that gas consumption is taken
func (k *Keeper) applySwap(
ctx sdk.Context,
tokenIn sdk.Coin,
tokenOut sdk.Coin,
poolId uint64,
newLiquidity sdk.Dec,
newCurrentTick sdk.Int,
newCurrentSqrtPrice sdk.Dec,
) error {
// Fixed gas consumption per swap to prevent spam
ctx.GasMeter().ConsumeGas(gammtypes.BalancerGasFeeForSwap, "cl pool swap computation")
pool, err := k.getPoolById(ctx, poolId)
if err != nil {
return err
}
if err := pool.ApplySwap(newLiquidity, newCurrentTick, newCurrentSqrtPrice); err != nil {
return err
}
if err := k.setPool(ctx, pool); err != nil {
return err
}
return nil
}
// updatePoolForSwap takes a pool, sender, and tokenIn, tokenOut amounts
// It then updates the pool's balances to the new reserve amounts, and
// sends the in tokens from the sender to the pool, and the out tokens from the pool to the sender.
func (k Keeper) updatePoolForSwap(
ctx sdk.Context,
pool swaproutertypes.PoolI,
sender sdk.AccAddress,
tokenIn sdk.Coin,
tokenOut sdk.Coin,
newCurrentTick sdk.Int,
newLiquidity sdk.Dec,
newSqrtPrice sdk.Dec,
) error {
// applySwap mutates the pool state to apply the new tick, liquidity and sqrtPrice
err := k.applySwap(ctx, tokenIn, tokenOut, pool.GetId(), newLiquidity, newCurrentTick, newSqrtPrice)
if err != nil {
return err
}
err = k.bankKeeper.SendCoins(ctx, sender, pool.GetAddress(), sdk.Coins{
tokenIn,
})
if err != nil {
return err
}
err = k.bankKeeper.SendCoins(ctx, pool.GetAddress(), sender, sdk.Coins{
tokenOut,
})
if err != nil {
return err
}
// TODO: implement hooks
events.EmitSwapEvent(ctx, sender, pool.GetId(), sdk.Coins{tokenIn}, sdk.Coins{tokenOut})
// k.hooks.AfterSwap(ctx, sender, pool.GetId(), tokenIn, tokenOut)
return err
}