-
Notifications
You must be signed in to change notification settings - Fork 608
/
pool_service.go
476 lines (420 loc) · 16.2 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
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
package keeper
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/osmosis-labs/osmosis/v13/osmomath"
"github.com/osmosis-labs/osmosis/v13/osmoutils"
"github.com/osmosis-labs/osmosis/v13/x/gamm/types"
swaproutertypes "github.com/osmosis-labs/osmosis/v13/x/swaprouter/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,
quoteAssetDenom string,
baseAssetDenom 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, quoteAssetDenom, baseAssetDenom)
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
}
func validateCreatePoolMsg(ctx sdk.Context, msg swaproutertypes.CreatePoolMsg) error {
err := msg.Validate(ctx)
if err != nil {
return err
}
initialPoolLiquidity := msg.InitialLiquidity()
numAssets := initialPoolLiquidity.Len()
if numAssets < swaproutertypes.MinPoolAssets {
return types.ErrTooFewPoolAssets
}
if numAssets > swaproutertypes.MaxPoolAssets {
return sdkerrors.Wrapf(
types.ErrTooManyPoolAssets,
"pool has too many PoolAssets (%d)", numAssets,
)
}
return nil
}
func (k Keeper) validateCreatedPool(
ctx sdk.Context,
initialPoolLiquidity sdk.Coins,
poolId uint64,
pool swaproutertypes.PoolI,
) error {
if pool.GetId() != poolId {
return sdkerrors.Wrapf(types.ErrInvalidPool,
"Pool was attempted to be created with incorrect pool ID.")
}
if !pool.GetAddress().Equals(types.NewPoolAddress(poolId)) {
return sdkerrors.Wrapf(types.ErrInvalidPool,
"Pool was attempted to be created with incorrect pool address.")
}
// Notably we use the initial pool liquidity at the start of the messages definition
// just in case CreatePool was mutative.
if !pool.GetTotalPoolLiquidity(ctx).IsEqual(initialPoolLiquidity) {
return sdkerrors.Wrapf(types.ErrInvalidPool,
"Pool was attempted to be created, with initial liquidity not equal to what was specified.")
}
// This check can be removed later, and replaced with a minimum.
if !pool.GetTotalShares().Equal(types.InitPoolSharesSupply) {
return sdkerrors.Wrapf(types.ErrInvalidPool,
"Pool was attempted to be created with incorrect number of initial shares.")
}
return nil
}
// CreatePool attempts to create a pool returning the newly created pool ID or
// an error upon failure. The pool creation fee is used to fund the community
// pool. It will create a dedicated module account for the pool and sends the
// initial liquidity to the created module account.
//
// After the initial liquidity is sent to the pool's account, shares are minted
// and sent to the pool creator. The shares are created using a denomination in
// the form of gamm/pool/{poolID}. In addition, the x/bank metadata is updated
// to reflect the newly created GAMM share denomination.
func (k Keeper) CreatePool(ctx sdk.Context, msg swaproutertypes.CreatePoolMsg) (uint64, error) {
err := validateCreatePoolMsg(ctx, msg)
if err != nil {
return 0, err
}
sender := msg.PoolCreator()
initialPoolLiquidity := msg.InitialLiquidity()
// send pool creation fee to community pool
params := k.GetParams(ctx)
if err := k.communityPoolKeeper.FundCommunityPool(ctx, params.PoolCreationFee, sender); err != nil {
return 0, err
}
poolId := k.getNextPoolIdAndIncrement(ctx)
pool, err := msg.CreatePool(ctx, poolId)
if err != nil {
return 0, err
}
if err := k.validateCreatedPool(ctx, initialPoolLiquidity, poolId, pool); err != nil {
return 0, err
}
// create and save the pool's module account to the account keeper
if err := osmoutils.CreateModuleAccount(ctx, k.accountKeeper, pool.GetAddress()); err != nil {
return 0, fmt.Errorf("creating pool module account for id %d: %w", poolId, err)
}
// send initial liquidity to the pool
err = k.bankKeeper.SendCoins(ctx, sender, pool.GetAddress(), initialPoolLiquidity)
if err != nil {
return 0, err
}
// Mint the initial pool shares share token to the sender
err = k.MintPoolShareToAccount(ctx, pool, sender, pool.GetTotalShares())
if err != nil {
return 0, err
}
// Finally, add the share token's meta data to the bank keeper.
poolShareBaseDenom := types.GetPoolShareDenom(pool.GetId())
poolShareDisplayDenom := fmt.Sprintf("GAMM-%d", pool.GetId())
k.bankKeeper.SetDenomMetaData(ctx, banktypes.Metadata{
Description: fmt.Sprintf("The share token of the gamm pool %d", pool.GetId()),
DenomUnits: []*banktypes.DenomUnit{
{
Denom: poolShareBaseDenom,
Exponent: 0,
Aliases: []string{
"attopoolshare",
},
},
{
Denom: poolShareDisplayDenom,
Exponent: types.OneShareExponent,
Aliases: nil,
},
},
Base: poolShareBaseDenom,
Display: poolShareDisplayDenom,
})
if err := k.setPool(ctx, pool); err != nil {
return 0, err
}
k.hooks.AfterPoolCreated(ctx, sender, pool.GetId())
k.RecordTotalLiquidityIncrease(ctx, initialPoolLiquidity)
return pool.GetId(), nil
}
// 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) {
// defer to catch panics, in case something internal overflows.
defer func() {
if r := recover(); r != nil {
tokenIn = sdk.Coins{}
sharesOut = sdk.Int{}
err = fmt.Errorf("function JoinPoolNoSwap failed due to internal reason: %v", r)
}
}()
// 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.CFMMPoolI, 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, "Too few shares out wanted. "+
"(debug: getMaximalNoSwapLPAmount 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,
) (sharesOut sdk.Int, err error) {
// defer to catch panics, in case something internal overflows.
defer func() {
if r := recover(); r != nil {
sharesOut = sdk.Int{}
err = fmt.Errorf("function JoinSwapExactAmountIn failed due to internal reason: %v", r)
}
}()
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) {
// defer to catch panics, in case something internal overflows.
defer func() {
if r := recover(); r != nil {
tokenInAmount = sdk.Int{}
err = fmt.Errorf("function JoinSwapShareAmountOut failed due to internal reason: %v", r)
}
}()
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, "%s resulted tokens is larger than the max amount of %s", tokenInAmount, tokenInMaxAmount)
}
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) {
return sdk.Coins{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, "Trying to exit >= the number of shares contained in the pool.")
} else if shareInAmount.LTE(sdk.ZeroInt()) {
return sdk.Coins{}, sdkerrors.Wrapf(types.ErrInvalidMathApprox, "Trying to exit a negative amount of shares")
}
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)
for _, coin := range exitCoins {
if coin.Denom == tokenOutDenom {
continue
}
swapOut, err := k.SwapExactAmountIn(ctx, sender, poolId, coin, tokenOutDenom, sdk.ZeroInt())
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
}