Skip to content

Commit

Permalink
Add some more code comments for functions discussed with @alexanderbez (
Browse files Browse the repository at this point in the history
#1126)

* Add some more code comments for functions discussed with @alexanderbez

* Try to simplify the BeginEpoch logic
  • Loading branch information
ValarDragon authored Mar 23, 2022
1 parent f1389ee commit 196a644
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 45 deletions.
55 changes: 29 additions & 26 deletions x/epochs/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,39 +20,42 @@ func BeginBlocker(ctx sdk.Context, k keeper.Keeper) {
shouldInitialEpochStart := !epochInfo.EpochCountingStarted && !epochInfo.StartTime.After(ctx.BlockTime())

epochEndTime := epochInfo.CurrentEpochStartTime.Add(epochInfo.Duration)
shouldEpochStart := ctx.BlockTime().After(epochEndTime) && !shouldInitialEpochStart && !epochInfo.StartTime.After(ctx.BlockTime())

if shouldInitialEpochStart || shouldEpochStart {
epochInfo.CurrentEpochStartHeight = ctx.BlockHeight()

if shouldInitialEpochStart {
epochInfo.EpochCountingStarted = true
epochInfo.CurrentEpoch = 1
epochInfo.CurrentEpochStartTime = epochInfo.StartTime
logger.Info(fmt.Sprintf("Starting new epoch with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch))
} else {
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeEpochEnd,
sdk.NewAttribute(types.AttributeEpochNumber, fmt.Sprintf("%d", epochInfo.CurrentEpoch)),
),
)
k.AfterEpochEnd(ctx, epochInfo.Identifier, epochInfo.CurrentEpoch)
epochInfo.CurrentEpoch += 1
epochInfo.CurrentEpochStartTime = epochInfo.CurrentEpochStartTime.Add(epochInfo.Duration)
logger.Info(fmt.Sprintf("Starting epoch with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch))
}
k.SetEpochInfo(ctx, epochInfo)
shouldEpochStart := (ctx.BlockTime().After(epochEndTime) && !epochInfo.StartTime.After(ctx.BlockTime())) || shouldInitialEpochStart

if !shouldEpochStart {
return false
}
epochInfo.CurrentEpochStartHeight = ctx.BlockHeight()

if shouldInitialEpochStart {
epochInfo.EpochCountingStarted = true
epochInfo.CurrentEpoch = 1
epochInfo.CurrentEpochStartTime = epochInfo.StartTime
logger.Info(fmt.Sprintf("Starting new epoch with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch))
} else {
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeEpochStart,
types.EventTypeEpochEnd,
sdk.NewAttribute(types.AttributeEpochNumber, fmt.Sprintf("%d", epochInfo.CurrentEpoch)),
sdk.NewAttribute(types.AttributeEpochStartTime, fmt.Sprintf("%d", epochInfo.CurrentEpochStartTime.Unix())),
),
)
k.BeforeEpochStart(ctx, epochInfo.Identifier, epochInfo.CurrentEpoch)
k.AfterEpochEnd(ctx, epochInfo.Identifier, epochInfo.CurrentEpoch)
epochInfo.CurrentEpoch += 1
epochInfo.CurrentEpochStartTime = epochInfo.CurrentEpochStartTime.Add(epochInfo.Duration)
logger.Info(fmt.Sprintf("Starting epoch with identifier %s epoch number %d", epochInfo.Identifier, epochInfo.CurrentEpoch))
}

// emit new epoch start event, set epoch info, and run BeforeEpochStart hook
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeEpochStart,
sdk.NewAttribute(types.AttributeEpochNumber, fmt.Sprintf("%d", epochInfo.CurrentEpoch)),
sdk.NewAttribute(types.AttributeEpochStartTime, fmt.Sprintf("%d", epochInfo.CurrentEpochStartTime.Unix())),
),
)
k.SetEpochInfo(ctx, epochInfo)
k.BeforeEpochStart(ctx, epochInfo.Identifier, epochInfo.CurrentEpoch)

return false
})
}
65 changes: 46 additions & 19 deletions x/gamm/keeper/pool_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ import (
"github.com/osmosis-labs/osmosis/v7/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 traded 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)
func (k Keeper) CalculateSpotPrice(
ctx sdk.Context,
poolID uint64,
Expand Down Expand Up @@ -109,6 +113,13 @@ func (k Keeper) CreateBalancerPool(
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,
Expand All @@ -121,27 +132,11 @@ func (k Keeper) JoinPoolNoSwap(
return err
}

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
// (tokens per share) * number of shares out = # tokens * (# shares out / cur total shares)
shareRatio := shareOutAmount.ToDec().QuoInt(totalSharesAmount)
if shareRatio.LTE(sdk.ZeroDec()) {
return sdkerrors.Wrapf(types.ErrInvalidMathApprox, "share ratio is zero or negative")
neededLpLiquidity, err := getMaximalNoSwapLPAmount(ctx, pool, shareOutAmount)
if err != nil {
return err
}

poolLiquidity := pool.GetTotalLpBalances(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 sdkerrors.Wrapf(types.ErrInvalidMathApprox, "Too few shares out wanted")
}
neededCoin := sdk.Coin{Denom: coin.Denom, Amount: neededAmt}
neededLpLiquidity = neededLpLiquidity.Add(neededCoin)
}
// if neededLPLiquidity >= tokenInMaxs, return err
// if tokenInMaxs == 0, don't do this check.
if tokenInMaxs.Len() != 0 {
Expand All @@ -165,6 +160,35 @@ func (k Keeper) JoinPoolNoSwap(
return err
}

func getMaximalNoSwapLPAmount(ctx sdk.Context, pool types.PoolI, 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
// (tokens per share) * number of shares out = # tokens * (# shares out / cur total shares)
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.GetTotalLpBalances(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.
// If the amount of LP shares obtained at the end is less than shareOutMinAmount,
// then return an error and revert the message.
func (k Keeper) JoinSwapExactAmountIn(
ctx sdk.Context,
sender sdk.AccAddress,
Expand Down Expand Up @@ -271,6 +295,9 @@ func (k Keeper) ExitPool(
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,
Expand Down
2 changes: 2 additions & 0 deletions x/txfees/keeper/feedecorator.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ func (mfd MempoolFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate b
return next(ctx, tx, simulate)
}

// IsSufficientFee checks if the feeCoin provided (in any asset), is worth enough osmo at current spot prices
// to pay the gas cost of this tx.
func (k Keeper) IsSufficientFee(ctx sdk.Context, minBaseGasPrice sdk.Dec, gasRequested uint64, feeCoin sdk.Coin) error {
baseDenom, err := k.GetBaseDenom(ctx)
if err != nil {
Expand Down

0 comments on commit 196a644

Please sign in to comment.