-
Notifications
You must be signed in to change notification settings - Fork 607
/
pool_service.go
321 lines (280 loc) · 11 KB
/
pool_service.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
package keeper
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/osmosis-labs/osmosis/v12/osmomath"
"github.com/osmosis-labs/osmosis/v12/x/gamm/types"
)
// CalculateSpotPrice returns the spot price of the quote asset in terms of the base asset,
// using the specified pool.
// E.g. if pool 1 trades 2 atom for 3 osmo, the quote asset was atom, and the base asset was osmo,
// this would return 1.5. (Meaning that 1 atom costs 1.5 osmo)
//
// This function is guaranteed to not panic, but may return an error if:
// * An internal error within the pool occurs for calculating the spot price
// * The returned spot price is greater than max spot price
func (k Keeper) CalculateSpotPrice(
ctx sdk.Context,
poolID uint64,
baseAssetDenom string,
quoteAssetDenom string,
) (spotPrice sdk.Dec, err error) {
pool, err := k.GetPoolAndPoke(ctx, poolID)
if err != nil {
return sdk.Dec{}, err
}
// defer to catch panics, in case something internal overflows.
defer func() {
if r := recover(); r != nil {
spotPrice = sdk.Dec{}
err = types.ErrSpotPriceInternal
}
}()
spotPrice, err = pool.SpotPrice(ctx, baseAssetDenom, quoteAssetDenom)
if err != nil {
return sdk.Dec{}, err
}
// if spotPrice greater than max spot price, return an error
if spotPrice.GT(types.MaxSpotPrice) {
return types.MaxSpotPrice, types.ErrSpotPriceOverflow
} else if !spotPrice.IsPositive() {
return sdk.Dec{}, types.ErrSpotPriceInternal
}
// we want to round this to `SpotPriceSigFigs` of precision
spotPrice = osmomath.SigFigRound(spotPrice, types.SpotPriceSigFigs)
return spotPrice, err
}
// JoinPoolNoSwap aims to LP exactly enough to pool #{poolId} to get shareOutAmount number of LP shares.
// If the required tokens is greater than tokenInMaxs, returns an error & the message reverts.
// Leftover tokens that weren't LP'd (due to being at inexact ratios) remain in the sender account.
//
// JoinPoolNoSwap determines the maximum amount that can be LP'd without any swap,
// by looking at the ratio of the total LP'd assets. (e.g. 2 osmo : 1 atom)
// It then finds the maximal amount that can be LP'd.
func (k Keeper) JoinPoolNoSwap(
ctx sdk.Context,
sender sdk.AccAddress,
poolId uint64,
shareOutAmount sdk.Int,
tokenInMaxs sdk.Coins,
) (tokenIn sdk.Coins, sharesOut sdk.Int, err error) {
// all pools handled within this method are pointer references, `JoinPool` directly updates the pools
pool, err := k.GetPoolAndPoke(ctx, poolId)
if err != nil {
return nil, sdk.ZeroInt(), err
}
// we do an abstract calculation on the lp liquidity coins needed to have
// the designated amount of given shares of the pool without performing swap
neededLpLiquidity, err := getMaximalNoSwapLPAmount(ctx, pool, shareOutAmount)
if err != nil {
return nil, sdk.ZeroInt(), err
}
// check that needed lp liquidity does not exceed the given `tokenInMaxs` parameter. Return error if so.
// if tokenInMaxs == 0, don't do this check.
if tokenInMaxs.Len() != 0 {
if !(neededLpLiquidity.DenomsSubsetOf(tokenInMaxs) && tokenInMaxs.IsAllGTE(neededLpLiquidity)) {
return nil, sdk.ZeroInt(), sdkerrors.Wrapf(types.ErrLimitMaxAmount, "TokenInMaxs is less than the needed LP liquidity to this JoinPoolNoSwap,"+
" upperbound: %v, needed %v", tokenInMaxs, neededLpLiquidity)
} else if !(tokenInMaxs.DenomsSubsetOf(neededLpLiquidity)) {
return nil, sdk.ZeroInt(), sdkerrors.Wrapf(types.ErrDenomNotFoundInPool, "TokenInMaxs includes tokens that are not part of the target pool,"+
" input tokens: %v, pool tokens %v", tokenInMaxs, neededLpLiquidity)
}
}
sharesOut, err = pool.JoinPoolNoSwap(ctx, neededLpLiquidity, pool.GetSwapFee(ctx))
if err != nil {
return nil, sdk.ZeroInt(), err
}
// sanity check, don't return error as not worth halting the LP. We know its not too much.
if sharesOut.LT(shareOutAmount) {
ctx.Logger().Error(fmt.Sprintf("Expected to JoinPoolNoSwap >= %s shares, actually did %s shares",
shareOutAmount, sharesOut))
}
err = k.applyJoinPoolStateChange(ctx, pool, sender, sharesOut, neededLpLiquidity)
return neededLpLiquidity, sharesOut, err
}
// getMaximalNoSwapLPAmount returns the coins(lp liquidity) needed to get the specified amount of shares in the pool.
// Steps to getting the needed lp liquidity coins needed for the share of the pools are
// 1. calculate how much percent of the pool does given share account for(# of input shares / # of current total shares)
// 2. since we know how much % of the pool we want, iterate through all pool liquidity to calculate how much coins we need for
// each pool asset.
func getMaximalNoSwapLPAmount(ctx sdk.Context, pool types.TraditionalAmmInterface, shareOutAmount sdk.Int) (neededLpLiquidity sdk.Coins, err error) {
totalSharesAmount := pool.GetTotalShares()
// shareRatio is the desired number of shares, divided by the total number of
// shares currently in the pool. It is intended to be used in scenarios where you want
shareRatio := shareOutAmount.ToDec().QuoInt(totalSharesAmount)
if shareRatio.LTE(sdk.ZeroDec()) {
return sdk.Coins{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, "share ratio is zero or negative")
}
poolLiquidity := pool.GetTotalPoolLiquidity(ctx)
neededLpLiquidity = sdk.Coins{}
for _, coin := range poolLiquidity {
// (coin.Amt * shareRatio).Ceil()
neededAmt := coin.Amount.ToDec().Mul(shareRatio).Ceil().RoundInt()
if neededAmt.LTE(sdk.ZeroInt()) {
return sdk.Coins{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, "Too few shares out wanted")
}
neededCoin := sdk.Coin{Denom: coin.Denom, Amount: neededAmt}
neededLpLiquidity = neededLpLiquidity.Add(neededCoin)
}
return neededLpLiquidity, nil
}
// JoinSwapExactAmountIn is an LP transaction, that will LP all of the provided
// tokensIn coins. The underlying pool is responsible for swapping any non-even
// LP proportions to the correct ratios. An error is returned if the amount of
// LP shares obtained at the end is less than shareOutMinAmount. Otherwise, we
// return the total amount of shares outgoing from joining the pool.
func (k Keeper) JoinSwapExactAmountIn(
ctx sdk.Context,
sender sdk.AccAddress,
poolId uint64,
tokensIn sdk.Coins,
shareOutMinAmount sdk.Int,
) (sdk.Int, error) {
pool, err := k.getPoolForSwap(ctx, poolId)
if err != nil {
return sdk.Int{}, err
}
sharesOut, err := pool.JoinPool(ctx, tokensIn, pool.GetSwapFee(ctx))
switch {
case err != nil:
return sdk.ZeroInt(), err
case sharesOut.LT(shareOutMinAmount):
return sdk.ZeroInt(), sdkerrors.Wrapf(
types.ErrLimitMinAmount,
"too much slippage; needed a minimum of %s shares to pass, got %s",
shareOutMinAmount, sharesOut,
)
case sharesOut.LTE(sdk.ZeroInt()):
return sdk.ZeroInt(), sdkerrors.Wrapf(types.ErrInvalidMathApprox, "share amount is zero or negative")
}
if err := k.applyJoinPoolStateChange(ctx, pool, sender, sharesOut, tokensIn); err != nil {
return sdk.ZeroInt(), err
}
return sharesOut, nil
}
func (k Keeper) JoinSwapShareAmountOut(
ctx sdk.Context,
sender sdk.AccAddress,
poolId uint64,
tokenInDenom string,
shareOutAmount sdk.Int,
tokenInMaxAmount sdk.Int,
) (tokenInAmount sdk.Int, err error) {
pool, err := k.getPoolForSwap(ctx, poolId)
if err != nil {
return sdk.Int{}, err
}
extendedPool, ok := pool.(types.PoolAmountOutExtension)
if !ok {
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))
if err != nil {
return sdk.Int{}, err
}
if tokenInAmount.GT(tokenInMaxAmount) {
return sdk.Int{}, sdkerrors.Wrapf(types.ErrLimitMaxAmount, "%d resulted tokens is larger than the max amount of %d", tokenInAmount.Int64(), tokenInMaxAmount.Int64())
}
tokenIn := sdk.NewCoins(sdk.NewCoin(tokenInDenom, tokenInAmount))
// Not using generic JoinPool because we want to guarantee exact shares out
extendedPool.IncreaseLiquidity(shareOutAmount, tokenIn)
err = k.applyJoinPoolStateChange(ctx, pool, sender, shareOutAmount, tokenIn)
if err != nil {
return sdk.ZeroInt(), err
}
return tokenInAmount, nil
}
func (k Keeper) ExitPool(
ctx sdk.Context,
sender sdk.AccAddress,
poolId uint64,
shareInAmount sdk.Int,
tokenOutMins sdk.Coins,
) (exitCoins sdk.Coins, err error) {
pool, err := k.GetPoolAndPoke(ctx, poolId)
if err != nil {
return sdk.Coins{}, err
}
totalSharesAmount := pool.GetTotalShares()
if shareInAmount.GTE(totalSharesAmount) || shareInAmount.LTE(sdk.ZeroInt()) {
return sdk.Coins{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, "share ratio is zero or negative")
}
exitFee := pool.GetExitFee(ctx)
exitCoins, err = pool.ExitPool(ctx, shareInAmount, exitFee)
if err != nil {
return sdk.Coins{}, err
}
if !tokenOutMins.DenomsSubsetOf(exitCoins) || tokenOutMins.IsAnyGT(exitCoins) {
return sdk.Coins{}, sdkerrors.Wrapf(types.ErrLimitMinAmount,
"Exit pool returned %s , minimum tokens out specified as %s",
exitCoins, tokenOutMins)
}
err = k.applyExitPoolStateChange(ctx, pool, sender, shareInAmount, exitCoins)
if err != nil {
return sdk.Coins{}, err
}
return exitCoins, nil
}
// ExitSwapShareAmountIn is an Exit Pool transaction, that will exit all of the provided LP shares,
// and then swap it all against the pool into tokenOutDenom.
// If the amount of tokens gotten out after the swap is less than tokenOutMinAmount, return an error.
func (k Keeper) ExitSwapShareAmountIn(
ctx sdk.Context,
sender sdk.AccAddress,
poolId uint64,
tokenOutDenom string,
shareInAmount sdk.Int,
tokenOutMinAmount sdk.Int,
) (tokenOutAmount sdk.Int, err error) {
exitCoins, err := k.ExitPool(ctx, sender, poolId, shareInAmount, sdk.Coins{})
if err != nil {
return sdk.Int{}, err
}
tokenOutAmount = exitCoins.AmountOf(tokenOutDenom)
pool, err := k.GetPool(ctx, poolId)
if err != nil {
return sdk.Int{}, err
}
swapFee := pool.GetSwapFee(ctx)
for _, coin := range exitCoins {
if coin.Denom == tokenOutDenom {
continue
}
swapOut, err := k.SwapExactAmountIn(ctx, sender, pool, coin, tokenOutDenom, sdk.ZeroInt(), swapFee)
if err != nil {
return sdk.Int{}, err
}
tokenOutAmount = tokenOutAmount.Add(swapOut)
}
if tokenOutAmount.LT(tokenOutMinAmount) {
return sdk.Int{}, sdkerrors.Wrapf(types.ErrLimitMinAmount,
"Provided LP shares yield %s tokens out, wanted a minimum of %s for it to work",
tokenOutAmount, tokenOutMinAmount)
}
return tokenOutAmount, nil
}
func (k Keeper) ExitSwapExactAmountOut(
ctx sdk.Context,
sender sdk.AccAddress,
poolId uint64,
tokenOut sdk.Coin,
shareInMaxAmount sdk.Int,
) (shareInAmount sdk.Int, err error) {
pool, err := k.getPoolForSwap(ctx, poolId)
if err != nil {
return sdk.Int{}, err
}
extendedPool, ok := pool.(types.PoolAmountOutExtension)
if !ok {
return sdk.Int{}, fmt.Errorf("pool with id %d does not support this kind of exit", poolId)
}
shareInAmount, err = extendedPool.ExitSwapExactAmountOut(ctx, tokenOut, shareInMaxAmount)
if err != nil {
return sdk.Int{}, err
}
if err := k.applyExitPoolStateChange(ctx, pool, sender, shareInAmount, sdk.Coins{tokenOut}); err != nil {
return sdk.Int{}, err
}
return shareInAmount, nil
}