-
Notifications
You must be signed in to change notification settings - Fork 559
/
amm.go
486 lines (418 loc) · 17.2 KB
/
amm.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
package balancer
import (
"errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/osmosis-labs/osmosis/v9/osmomath"
"github.com/osmosis-labs/osmosis/v9/x/gamm/pool-models/internal/cfmm_common"
"github.com/osmosis-labs/osmosis/v9/x/gamm/types"
)
const (
errMsgFormatSharesAmountNotPositive = "shares amount must be positive, was %d"
errMsgFormatTokenAmountNotPositive = "token amount must be positive, was %d"
errMsgFormatTokensLargerThanMax = "%d resulted tokens is larger than the max amount of %d"
errMsgFormatSharesLargerThanMax = "%d resulted shares is larger than the max amount of %d"
)
// solveConstantFunctionInvariant solves the constant function of an AMM
// that determines the relationship between the differences of two sides
// of assets inside the pool.
// For fixed balanceXBefore, balanceXAfter, weightX, balanceY, weightY,
// we could deduce the balanceYDelta, calculated by:
// balanceYDelta = balanceY * (1 - (balanceXBefore/balanceXAfter)^(weightX/weightY))
// balanceYDelta is positive when the balance liquidity decreases.
// balanceYDelta is negative when the balance liquidity increases.
//
// panics if tokenWeightUnknown is 0.
func solveConstantFunctionInvariant(
tokenBalanceFixedBefore,
tokenBalanceFixedAfter,
tokenWeightFixed,
tokenBalanceUnknownBefore,
tokenWeightUnknown sdk.Dec,
) sdk.Dec {
// weightRatio = (weightX/weightY)
weightRatio := tokenWeightFixed.Quo(tokenWeightUnknown)
// y = balanceXBefore/balanceXAfter
y := tokenBalanceFixedBefore.Quo(tokenBalanceFixedAfter)
// amountY = balanceY * (1 - (y ^ weightRatio))
yToWeightRatio := osmomath.Pow(y, weightRatio)
paranthetical := sdk.OneDec().Sub(yToWeightRatio)
amountY := tokenBalanceUnknownBefore.Mul(paranthetical)
return amountY
}
// CalcOutAmtGivenIn calculates tokens to be swapped out given the provided
// amount and fee deducted, using solveConstantFunctionInvariant.
func (p Pool) CalcOutAmtGivenIn(
ctx sdk.Context,
tokensIn sdk.Coins,
tokenOutDenom string,
swapFee 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))
poolTokenInBalance := poolAssetIn.Token.Amount.ToDec()
poolPostSwapInBalance := poolTokenInBalance.Add(tokenAmountInAfterFee)
// deduct swapfee on the tokensIn
// delta balanceOut is positive(tokens inside the pool decreases)
tokenAmountOut := solveConstantFunctionInvariant(
poolTokenInBalance,
poolPostSwapInBalance,
poolAssetIn.Weight.ToDec(),
poolAssetOut.Token.Amount.ToDec(),
poolAssetOut.Weight.ToDec(),
)
// We ignore the decimal component, as we round down the token amount out.
tokenAmountOutInt := tokenAmountOut.TruncateInt()
if !tokenAmountOutInt.IsPositive() {
return sdk.Coin{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, "token amount must be positive")
}
return sdk.NewCoin(tokenOutDenom, tokenAmountOutInt), nil
}
// SwapOutAmtGivenIn is a mutative method for CalcOutAmtGivenIn, which includes the actual swap.
func (p *Pool) SwapOutAmtGivenIn(
ctx sdk.Context,
tokensIn sdk.Coins,
tokenOutDenom string,
swapFee sdk.Dec,
) (
tokenOut sdk.Coin, err error,
) {
tokenOutCoin, err := p.CalcOutAmtGivenIn(ctx, tokensIn, tokenOutDenom, swapFee)
if err != nil {
return sdk.Coin{}, err
}
err = p.applySwap(ctx, tokensIn, sdk.Coins{tokenOutCoin})
if err != nil {
return sdk.Coin{}, err
}
return tokenOutCoin, nil
}
// 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) (
tokenIn sdk.Coin, err error,
) {
tokenOut, poolAssetOut, poolAssetIn, err := p.parsePoolAssets(tokensOut, tokenInDenom)
if err != nil {
return sdk.Coin{}, err
}
// delta balanceOut is positive(tokens inside the pool decreases)
poolTokenOutBalance := poolAssetOut.Token.Amount.ToDec()
poolPostSwapOutBalance := poolTokenOutBalance.Sub(tokenOut.Amount.ToDec())
// (x_0)(y_0) = (x_0 + in)(y_0 - out)
tokenAmountIn := solveConstantFunctionInvariant(
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 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.
tokenInAmt := tokenAmountInBeforeFee.Ceil().TruncateInt()
if !tokenInAmt.IsPositive() {
return sdk.Coin{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, "token amount must be positive")
}
return sdk.NewCoin(tokenInDenom, tokenInAmt), nil
}
// 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) (
tokenIn sdk.Coin, err error,
) {
tokenInCoin, err := p.CalcInAmtGivenOut(ctx, tokensOut, tokenInDenom, swapFee)
if err != nil {
return sdk.Coin{}, err
}
err = p.applySwap(ctx, sdk.Coins{tokenInCoin}, tokensOut)
if err != nil {
return sdk.Coin{}, err
}
return tokenInCoin, nil
}
// ApplySwap.
func (p *Pool) applySwap(ctx sdk.Context, tokensIn sdk.Coins, tokensOut sdk.Coins) error {
// Also ensures that len(tokensIn) = 1 = len(tokensOut)
inPoolAsset, outPoolAsset, err := p.parsePoolAssetsCoins(tokensIn, tokensOut)
if err != nil {
return err
}
inPoolAsset.Token.Amount = inPoolAsset.Token.Amount.Add(tokensIn[0].Amount)
outPoolAsset.Token.Amount = outPoolAsset.Token.Amount.Sub(tokensOut[0].Amount)
return p.UpdatePoolAssetBalances(sdk.NewCoins(
inPoolAsset.Token,
outPoolAsset.Token,
))
}
// SpotPrice returns the spot price of the pool
// This is the weight-adjusted balance of the tokens in the pool.
// In order reduce the propagated effect of incorrect trailing digits,
// we take the ratio of weights and divide this by ratio of supplies
// this is equivalent to spot_price = (Base_supply / Weight_base) / (Quote_supply / Weight_quote)
// but cancels out the common term in weight.
//
// panics if pool is misconfigured and has any weight as 0.
func (p Pool) SpotPrice(ctx sdk.Context, baseAsset, quoteAsset string) (sdk.Dec, error) {
quote, base, err := p.parsePoolAssetsByDenoms(quoteAsset, baseAsset)
if err != nil {
return sdk.Dec{}, err
}
if base.Weight.IsZero() || quote.Weight.IsZero() {
return sdk.Dec{}, errors.New("pool is misconfigured, got 0 weight")
}
// spot_price = (Base_supply / Weight_base) / (Quote_supply / Weight_quote)
// spot_price = (weight_quote / weight_base) * (base_supply / quote_supply)
invWeightRatio := quote.Weight.ToDec().Quo(base.Weight.ToDec())
supplyRatio := base.Token.Amount.ToDec().Quo(quote.Token.Amount.ToDec())
fullRatio := supplyRatio.Mul(invWeightRatio)
ratio := (fullRatio.Mul(types.SigFigs).RoundInt()).ToDec().Quo(types.SigFigs)
return ratio, nil
}
// balancer notation: pAo - pool shares amount out, given single asset in
// the second argument requires the tokenWeightIn / total token weight.
func calcPoolSharesOutGivenSingleAssetIn(
tokenBalanceIn,
normalizedTokenWeightIn,
poolShares,
tokenAmountIn,
swapFee 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))
// 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.
// if x^.5 y^.5 = k, then we `n` x the liquidity to `(nx)^.5 (ny)^.5 = nk = k'`
// We generalize this linear relation to do the liquidity add for the not-all-asset case.
// Suppose we increase the supply of x by x', so we want to solve for `k'/k`.
// This is `(x + x')^{weight} * old_terms / (x^{weight} * old_terms) = (x + x')^{weight} / (x^{weight})`
// The number of new shares we need to make is then `old_shares * ((k'/k) - 1)`
// Whats very cool, is that this turns out to be the exact same `solveConstantFunctionInvariant` code
// with the answer's sign reversed.
poolAmountOut := solveConstantFunctionInvariant(
tokenBalanceIn.Add(tokenAmountInAfterFee),
tokenBalanceIn,
normalizedTokenWeightIn,
poolShares,
sdk.OneDec()).Neg()
return poolAmountOut
}
// calcPoolOutGivenSingleIn - balance pAo.
func (p *Pool) calcSingleAssetJoin(tokenIn sdk.Coin, swapFee sdk.Dec, tokenInPoolAsset PoolAsset, totalShares sdk.Int) (numShares sdk.Int, err error) {
totalWeight := p.GetTotalWeight()
if totalWeight.IsZero() {
return sdk.ZeroInt(), errors.New("pool misconfigured, total weight = 0")
}
normalizedWeight := tokenInPoolAsset.Weight.ToDec().Quo(totalWeight.ToDec())
return calcPoolSharesOutGivenSingleAssetIn(
tokenInPoolAsset.Token.Amount.ToDec(),
normalizedWeight,
totalShares.ToDec(),
tokenIn.Amount.ToDec(),
swapFee,
).TruncateInt(), nil
}
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)
if err != nil {
return sdk.Int{}, err
}
p.IncreaseLiquidity(numShares, newLiquidity)
return numShares, nil
}
func (p *Pool) CalcJoinPoolShares(_ sdk.Context, tokensIn sdk.Coins, swapFee sdk.Dec) (numShares sdk.Int, newLiquidity sdk.Coins, err error) {
poolAssets := p.GetAllPoolAssets()
poolAssetsByDenom := make(map[string]PoolAsset)
for _, poolAsset := range poolAssets {
poolAssetsByDenom[poolAsset.Token.Denom] = poolAsset
}
totalShares := p.GetTotalShares()
if tokensIn.Len() == 1 {
numShares, err = p.calcSingleAssetJoin(tokensIn[0], swapFee, poolAssetsByDenom[tokensIn[0].Denom], totalShares)
if err != nil {
return sdk.ZeroInt(), sdk.NewCoins(), err
}
newLiquidity = tokensIn
return numShares, newLiquidity, nil
} else if tokensIn.Len() != p.NumAssets() {
return sdk.ZeroInt(), sdk.NewCoins(), errors.New("balancer pool only supports LP'ing with one asset or all assets in pool")
}
// Add all exact coins we can (no swap). ctx arg doesn't matter for Balancer.
numShares, remCoins, err := cfmm_common.MaximalExactRatioJoin(p, sdk.Context{}, tokensIn)
if err != nil {
return sdk.ZeroInt(), sdk.NewCoins(), err
}
// update liquidity for accurate calcSingleAssetJoin calculation
newLiquidity = tokensIn.Sub(remCoins)
for _, coin := range newLiquidity {
poolAsset := poolAssetsByDenom[coin.Denom]
poolAsset.Token.Amount = poolAssetsByDenom[coin.Denom].Token.Amount.Add(coin.Amount)
poolAssetsByDenom[coin.Denom] = poolAsset
}
totalShares = totalShares.Add(numShares)
// If there are coins that couldn't be perfectly joined, do single asset joins
// for each of them.
if !remCoins.Empty() {
for _, coin := range remCoins {
newShares, err := p.calcSingleAssetJoin(coin, swapFee, poolAssetsByDenom[coin.Denom], totalShares)
if err != nil {
return sdk.ZeroInt(), sdk.NewCoins(), err
}
newLiquidity = newLiquidity.Add(coin)
numShares = numShares.Add(newShares)
}
}
return numShares, newLiquidity, nil
}
func (p *Pool) ExitPool(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitingCoins sdk.Coins, err error) {
exitingCoins, err = p.CalcExitPoolShares(ctx, exitingShares, exitFee)
if err != nil {
return sdk.Coins{}, err
}
if err := p.exitPool(ctx, exitingCoins, exitingShares); err != nil {
return sdk.Coins{}, err
}
return exitingCoins, nil
}
// exitPool exits the pool given exitingCoins and exitingShares.
// updates the pool's liquidity and totalShares.
func (p *Pool) exitPool(ctx sdk.Context, exitingCoins sdk.Coins, exitingShares sdk.Int) error {
balances := p.GetTotalPoolLiquidity(ctx).Sub(exitingCoins)
if err := p.UpdatePoolAssetBalances(balances); err != nil {
return err
}
totalShares := p.GetTotalShares()
p.TotalShares = sdk.NewCoin(p.TotalShares.Denom, totalShares.Sub(exitingShares))
return nil
}
func (p *Pool) CalcExitPoolShares(ctx sdk.Context, exitingShares sdk.Int, exitFee sdk.Dec) (exitedCoins sdk.Coins, err error) {
return cfmm_common.CalcExitPool(ctx, p, exitingShares, exitFee)
}
// 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))
}
// calcSingleAssetInGivenPoolSharesOut returns token amount in with fee included
// given the swapped out shares amount, using solveConstantFunctionInvariant
func calcSingleAssetInGivenPoolSharesOut(
tokenBalanceIn,
normalizedTokenWeightIn,
totalPoolSharesSupply,
sharesAmountOut,
swapFee 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))
return tokenAmountInFeeIncluded
}
func (p *Pool) CalcTokenInShareAmountOut(
ctx sdk.Context,
tokenInDenom string,
shareOutAmount sdk.Int,
swapFee sdk.Dec,
) (tokenInAmount sdk.Int, err error) {
_, poolAssetIn, err := p.getPoolAssetAndIndex(tokenInDenom)
if err != nil {
return sdk.Int{}, err
}
normalizedWeight := poolAssetIn.Weight.ToDec().Quo(p.GetTotalWeight().ToDec())
// We round up tokenInAmount, as this is whats charged for the swap, for the precise amount out.
// Otherwise, the pool would under-charge by this rounding error.
tokenInAmount = calcSingleAssetInGivenPoolSharesOut(
poolAssetIn.Token.Amount.ToDec(),
normalizedWeight,
p.GetTotalShares().ToDec(),
shareOutAmount.ToDec(),
swapFee,
).Ceil().TruncateInt()
if !tokenInAmount.IsPositive() {
return sdk.Int{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, errMsgFormatTokenAmountNotPositive, tokenInAmount.Int64())
}
return tokenInAmount, nil
}
func (p *Pool) JoinPoolTokenInMaxShareAmountOut(
ctx sdk.Context,
tokenInDenom string,
shareOutAmount sdk.Int,
) (tokenInAmount sdk.Int, err error) {
_, poolAssetIn, err := p.getPoolAssetAndIndex(tokenInDenom)
if err != nil {
return sdk.Int{}, err
}
normalizedWeight := poolAssetIn.Weight.ToDec().Quo(p.GetTotalWeight().ToDec())
tokenInAmount = calcSingleAssetInGivenPoolSharesOut(
poolAssetIn.Token.Amount.ToDec(),
normalizedWeight,
p.GetTotalShares().ToDec(),
shareOutAmount.ToDec(),
p.GetSwapFee(ctx),
).TruncateInt()
if !tokenInAmount.IsPositive() {
return sdk.Int{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, errMsgFormatTokenAmountNotPositive, tokenInAmount.Int64())
}
poolAssetIn.Token.Amount = poolAssetIn.Token.Amount.Add(tokenInAmount)
err = p.UpdatePoolAssetBalance(poolAssetIn.Token)
if err != nil {
return sdk.Int{}, err
}
return tokenInAmount, nil
}
// calcPoolSharesInGivenSingleAssetOut returns pool shares amount in, given single asset out.
// the returned shares in have the fee included in them.
// the second argument requires the tokenWeightOut / total token weight.
func calcPoolSharesInGivenSingleAssetOut(
tokenBalanceOut,
normalizedTokenWeightOut,
totalPoolSharesSupply,
tokenAmountOut,
swapFee,
exitFee sdk.Dec,
) sdk.Dec {
tokenAmountOutFeeIncluded := tokenAmountOut.Quo(feeRatio(normalizedTokenWeightOut, swapFee))
// delta poolSupply is positive(total pool shares decreases)
// pool weight is always 1
sharesIn := solveConstantFunctionInvariant(tokenBalanceOut.Sub(tokenAmountOutFeeIncluded), tokenBalanceOut, normalizedTokenWeightOut, totalPoolSharesSupply, sdk.OneDec())
// charge exit fee on the pool token side
// pAi = pAiAfterExitFee/(1-exitFee)
sharesInFeeIncluded := sharesIn.Quo(sdk.OneDec().Sub(exitFee))
return sharesInFeeIncluded
}
func (p *Pool) ExitSwapExactAmountOut(
ctx sdk.Context,
tokenOut sdk.Coin,
shareInMaxAmount sdk.Int,
) (shareInAmount sdk.Int, err error) {
_, poolAssetOut, err := p.getPoolAssetAndIndex(tokenOut.Denom)
if err != nil {
return sdk.Int{}, err
}
sharesIn := calcPoolSharesInGivenSingleAssetOut(
poolAssetOut.Token.Amount.ToDec(),
poolAssetOut.Weight.ToDec().Quo(p.TotalWeight.ToDec()),
p.GetTotalShares().ToDec(),
tokenOut.Amount.ToDec(),
p.GetSwapFee(ctx),
p.GetExitFee(ctx),
).TruncateInt()
if !sharesIn.IsPositive() {
return sdk.Int{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, errMsgFormatSharesAmountNotPositive, sharesIn.Int64())
}
if sharesIn.GT(shareInMaxAmount) {
return sdk.Int{}, sdkerrors.Wrapf(types.ErrLimitMaxAmount, errMsgFormatSharesLargerThanMax, sharesIn.Int64(), shareInMaxAmount.Uint64())
}
if err := p.exitPool(ctx, sdk.NewCoins(tokenOut), sharesIn); err != nil {
return sdk.Int{}, err
}
return sharesIn, nil
}