Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(CL): TraditionalAmmInterface gamm refactor #3038

Merged
merged 3 commits into from
Oct 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions cmd/osmosisd/cmd/balances_from_state_export.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func newDerivedAccount(address string) DerivedAccount {
}

// underlyingCoins returns liquidity pool's underlying coin balances.
func underlyingCoins(originCoins sdk.Coins, pools map[string]gammtypes.PoolI) sdk.Coins {
func underlyingCoins(originCoins sdk.Coins, pools map[string]gammtypes.TraditionalAmmInterface) sdk.Coins {
balances := sdk.Coins{}
convertAgain := false
for _, coin := range originCoins {
Expand Down Expand Up @@ -85,7 +85,7 @@ func underlyingCoins(originCoins sdk.Coins, pools map[string]gammtypes.PoolI) sd
// TODO: Make a separate type for this.
func underlyingCoinsForSelectPools(
originCoins sdk.Coins,
pools map[string]gammtypes.PoolI,
pools map[string]gammtypes.TraditionalAmmInterface,
selectPoolIDs []uint64,
) map[uint64]sdk.Coins {
balancesByPool := make(map[uint64]sdk.Coins)
Expand Down Expand Up @@ -263,9 +263,9 @@ Example:
}

// collect gamm pools
pools := make(map[string]gammtypes.PoolI)
pools := make(map[string]gammtypes.TraditionalAmmInterface)
for _, any := range gammGenesis.Pools {
var pool gammtypes.PoolI
var pool gammtypes.TraditionalAmmInterface
err := clientCtx.InterfaceRegistry.UnpackAny(any, &pool)
if err != nil {
panic(err)
Expand Down
2 changes: 1 addition & 1 deletion x/gamm/keeper/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState, unpack
// Also adds each genesis state pool to the x/gamm module's state
liquidity := sdk.Coins{}
for _, any := range genState.Pools {
var pool types.PoolI
var pool types.TraditionalAmmInterface
err := unpacker.UnpackAny(any, &pool)
if err != nil {
panic(err)
Expand Down
10 changes: 5 additions & 5 deletions x/gamm/keeper/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ func (k Keeper) MarshalPool(pool types.PoolI) ([]byte, error) {
return k.cdc.MarshalInterface(pool)
}

func (k Keeper) UnmarshalPool(bz []byte) (types.PoolI, error) {
var acc types.PoolI
func (k Keeper) UnmarshalPool(bz []byte) (types.TraditionalAmmInterface, error) {
var acc types.TraditionalAmmInterface
return acc, k.cdc.UnmarshalInterface(bz, &acc)
}

// GetPoolAndPoke returns a PoolI based on it's identifier if one exists. If poolId corresponds
// to a pool with weights (e.g. balancer), the weights of the pool are updated via PokePool prior to returning.
// TODO: Consider rename to GetPool due to downstream API confusion.
func (k Keeper) GetPoolAndPoke(ctx sdk.Context, poolId uint64) (types.PoolI, error) {
func (k Keeper) GetPoolAndPoke(ctx sdk.Context, poolId uint64) (types.TraditionalAmmInterface, error) {
store := ctx.KVStore(k.storeKey)
poolKey := types.GetKeyPrefixPools(poolId)
if !store.Has(poolKey) {
Expand All @@ -47,7 +47,7 @@ func (k Keeper) GetPoolAndPoke(ctx sdk.Context, poolId uint64) (types.PoolI, err
}

// Get pool and check if the pool is active, i.e. allowed to be swapped against.
func (k Keeper) getPoolForSwap(ctx sdk.Context, poolId uint64) (types.PoolI, error) {
func (k Keeper) getPoolForSwap(ctx sdk.Context, poolId uint64) (types.TraditionalAmmInterface, error) {
pool, err := k.GetPoolAndPoke(ctx, poolId)
if err != nil {
return &balancer.Pool{}, err
Expand All @@ -64,7 +64,7 @@ func (k Keeper) iterator(ctx sdk.Context, prefix []byte) sdk.Iterator {
return sdk.KVStorePrefixIterator(store, prefix)
}

func (k Keeper) GetPoolsAndPoke(ctx sdk.Context) (res []types.PoolI, err error) {
func (k Keeper) GetPoolsAndPoke(ctx sdk.Context) (res []types.TraditionalAmmInterface, err error) {
iter := k.iterator(ctx, types.KeyPrefixPools)
defer iter.Close()

Expand Down
4 changes: 2 additions & 2 deletions x/gamm/keeper/pool_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func (k Keeper) validateCreatedPool(
ctx sdk.Context,
initialPoolLiquidity sdk.Coins,
poolId uint64,
pool types.PoolI,
pool types.TraditionalAmmInterface,
) error {
if pool.GetId() != poolId {
return sdkerrors.Wrapf(types.ErrInvalidPool,
Expand Down Expand Up @@ -246,7 +246,7 @@ func (k Keeper) JoinPoolNoSwap(
// 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.PoolI, shareOutAmount sdk.Int) (neededLpLiquidity sdk.Coins, err error) {
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
Expand Down
2 changes: 1 addition & 1 deletion x/gamm/keeper/swap.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func (k Keeper) SwapExactAmountOut(
func (k Keeper) swapExactAmountOut(
ctx sdk.Context,
sender sdk.AccAddress,
pool types.PoolI,
pool types.TraditionalAmmInterface,
tokenInDenom string,
tokenInMaxAmount sdk.Int,
tokenOut sdk.Coin,
Expand Down
5 changes: 5 additions & 0 deletions x/gamm/pool-models/balancer/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
(*types.PoolI)(nil),
&Pool{},
)
registry.RegisterInterface(
"osmosis.gamm.v1beta1.TraditionalAmmInterface",
(*types.TraditionalAmmInterface)(nil),
&Pool{},
)
registry.RegisterImplementations(
(*sdk.Msg)(nil),
&MsgCreateBalancerPool{},
Expand Down
2 changes: 1 addition & 1 deletion x/gamm/pool-models/balancer/msgs.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (msg MsgCreateBalancerPool) InitialLiquidity() sdk.Coins {
return coins
}

func (msg MsgCreateBalancerPool) CreatePool(ctx sdk.Context, poolID uint64) (types.PoolI, error) {
func (msg MsgCreateBalancerPool) CreatePool(ctx sdk.Context, poolID uint64) (types.TraditionalAmmInterface, error) {
poolI, err := NewBalancerPool(poolID, *msg.PoolParams, msg.PoolAssets, msg.FuturePoolGovernor, ctx.BlockTime())
return &poolI, err
}
7 changes: 4 additions & 3 deletions x/gamm/pool-models/balancer/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ const (
)

var (
_ types.PoolI = &Pool{}
_ types.PoolAmountOutExtension = &Pool{}
_ types.WeightedPoolExtension = &Pool{}
_ types.PoolI = &Pool{}
_ types.PoolAmountOutExtension = &Pool{}
_ types.WeightedPoolExtension = &Pool{}
_ types.TraditionalAmmInterface = &Pool{}
)

// NewPool returns a weighted CPMM pool with the provided parameters, and initial assets.
Expand Down
4 changes: 2 additions & 2 deletions x/gamm/pool-models/balancer/pool_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1033,7 +1033,7 @@ func (suite *KeeperTestSuite) TestRandomizedJoinPoolExitPoolInvariants() {
}

// joins with predetermined ratio
joinPool := func(pool types.PoolI, tc *testCase) {
joinPool := func(pool types.TraditionalAmmInterface, tc *testCase) {
tokensIn := sdk.Coins{
sdk.NewCoin(denomIn, sdk.NewInt(tc.initialTokensDenomIn).MulRaw(tc.percentRatio).QuoRaw(100)),
sdk.NewCoin(denomOut, sdk.NewInt(tc.initialTokensDenomOut).MulRaw(tc.percentRatio).QuoRaw(100)),
Expand All @@ -1044,7 +1044,7 @@ func (suite *KeeperTestSuite) TestRandomizedJoinPoolExitPoolInvariants() {
}

// exits for same amount of shares minted
exitPool := func(pool types.PoolI, tc *testCase) {
exitPool := func(pool types.TraditionalAmmInterface, tc *testCase) {
_, err := pool.ExitPool(suite.Ctx, tc.numShares, exitFeeDec)
suite.Require().NoError(err)
}
Expand Down
2 changes: 1 addition & 1 deletion x/gamm/pool-models/balancer/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
"github.com/osmosis-labs/osmosis/v12/x/gamm/types"
)

func createTestPool(t *testing.T, swapFee, exitFee sdk.Dec, poolAssets ...balancer.PoolAsset) types.PoolI {
func createTestPool(t *testing.T, swapFee, exitFee sdk.Dec, poolAssets ...balancer.PoolAsset) types.TraditionalAmmInterface {
pool, err := balancer.NewBalancerPool(
1,
balancer.NewPoolParams(swapFee, exitFee, nil),
Expand Down
8 changes: 4 additions & 4 deletions x/gamm/pool-models/internal/cfmm_common/lp.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
const errMsgFormatSharesLargerThanMax = "%s resulted shares is larger than the max amount of %s"

// CalcExitPool returns how many tokens should come out, when exiting k LP shares against a "standard" CFMM
func CalcExitPool(ctx sdk.Context, pool types.PoolI, exitingShares sdk.Int, exitFee sdk.Dec) (sdk.Coins, error) {
func CalcExitPool(ctx sdk.Context, pool types.TraditionalAmmInterface, exitingShares sdk.Int, exitFee sdk.Dec) (sdk.Coins, error) {
totalShares := pool.GetTotalShares()
if exitingShares.GTE(totalShares) {
return sdk.Coins{}, sdkerrors.Wrapf(types.ErrLimitMaxAmount, errMsgFormatSharesLargerThanMax, exitingShares, totalShares)
Expand Down Expand Up @@ -62,7 +62,7 @@ func CalcExitPool(ctx sdk.Context, pool types.PoolI, exitingShares sdk.Int, exit
// 1. iterate through all the tokens provided as an argument, calculate how much ratio it accounts for the asset in the pool
// 2. get the minimal share ratio that would work as the benchmark for all tokens.
// 3. calculate the number of shares that could be joined (total share * min share ratio), return the remaining coins
func MaximalExactRatioJoin(p types.PoolI, ctx sdk.Context, tokensIn sdk.Coins) (numShares sdk.Int, remCoins sdk.Coins, err error) {
func MaximalExactRatioJoin(p types.TraditionalAmmInterface, ctx sdk.Context, tokensIn sdk.Coins) (numShares sdk.Int, remCoins sdk.Coins, err error) {
coinShareRatios := make([]sdk.Dec, len(tokensIn))
minShareRatio := sdk.MaxSortableDec
maxShareRatio := sdk.ZeroDec()
Expand Down Expand Up @@ -127,9 +127,9 @@ var singleAssetJoinCorrectnessThreshold = sdk.NewInt(1)
// This implementation requires each of pool.GetTotalPoolLiquidity, pool.ExitPool, and pool.SwapExactAmountIn
// to not update or read from state, and instead only do updates based upon the pool struct.
func BinarySearchSingleAssetJoin(
pool types.PoolI,
pool types.TraditionalAmmInterface,
tokenIn sdk.Coin,
poolWithAddedLiquidityAndShares func(newLiquidity sdk.Coin, newShares sdk.Int) types.PoolI,
poolWithAddedLiquidityAndShares func(newLiquidity sdk.Coin, newShares sdk.Int) types.TraditionalAmmInterface,
) (numLPShares sdk.Int, err error) {
// use dummy context
ctx := sdk.Context{}
Expand Down
2 changes: 1 addition & 1 deletion x/gamm/pool-models/internal/cfmm_common/lp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func TestCalcExitPool(t *testing.T) {

tests := []struct {
name string
pool gammtypes.PoolI
pool gammtypes.TraditionalAmmInterface
exitingShares sdk.Int
expError bool
}{
Expand Down
2 changes: 1 addition & 1 deletion x/gamm/pool-models/stableswap/amm.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ func (p *Pool) calcInAmtGivenOut(tokenOut sdk.Coin, tokenInDenom string, swapFee
}

func (p *Pool) calcSingleAssetJoinShares(tokenIn sdk.Coin, swapFee sdk.Dec) (sdk.Int, error) {
poolWithAddedLiquidityAndShares := func(newLiquidity sdk.Coin, newShares sdk.Int) types.PoolI {
poolWithAddedLiquidityAndShares := func(newLiquidity sdk.Coin, newShares sdk.Int) types.TraditionalAmmInterface {
paCopy := p.Copy()
paCopy.updatePoolForJoin(sdk.NewCoins(tokenIn), newShares)
return &paCopy
Expand Down
5 changes: 5 additions & 0 deletions x/gamm/pool-models/stableswap/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
(*types.PoolI)(nil),
&Pool{},
)
registry.RegisterInterface(
"osmosis.gamm.v1beta1.TraditionalAmmInterface",
(*types.TraditionalAmmInterface)(nil),
&Pool{},
)
registry.RegisterImplementations(
(*sdk.Msg)(nil),
&MsgCreateStableswapPool{},
Expand Down
2 changes: 1 addition & 1 deletion x/gamm/pool-models/stableswap/msgs.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func (msg MsgCreateStableswapPool) InitialLiquidity() sdk.Coins {
return msg.InitialPoolLiquidity
}

func (msg MsgCreateStableswapPool) CreatePool(ctx sdk.Context, poolId uint64) (types.PoolI, error) {
func (msg MsgCreateStableswapPool) CreatePool(ctx sdk.Context, poolId uint64) (types.TraditionalAmmInterface, error) {
stableswapPool, err := NewStableswapPool(poolId, *msg.PoolParams, msg.InitialPoolLiquidity,
msg.ScalingFactors, msg.ScalingFactorController, msg.FuturePoolGovernor)
if err != nil {
Expand Down
5 changes: 4 additions & 1 deletion x/gamm/pool-models/stableswap/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ import (
"github.com/osmosis-labs/osmosis/v12/x/gamm/types"
)

var _ types.PoolI = &Pool{}
var (
_ types.PoolI = &Pool{}
_ types.TraditionalAmmInterface = &Pool{}
)

// NewStableswapPool returns a stableswap pool
// Invariants that are assumed to be satisfied and not checked:
Expand Down
4 changes: 2 additions & 2 deletions x/gamm/simulation/sim_msgs.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ func RandomExitSwapShareAmountIn(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.
}

// TODO: Fix CalcJoinPoolShares API so we don't have to do this
func deriveRealMinShareOutAmt(ctx sdk.Context, tokenIn sdk.Coins, pool types.PoolI) (sdk.Int, error) {
func deriveRealMinShareOutAmt(ctx sdk.Context, tokenIn sdk.Coins, pool types.TraditionalAmmInterface) (sdk.Int, error) {
minShareOutAmt, _, err := pool.CalcJoinPoolShares(ctx, tokenIn, pool.GetSwapFee(ctx))
if err != nil {
return sdk.Int{}, err
Expand Down Expand Up @@ -408,7 +408,7 @@ func createPoolRestriction(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Contex
}
}

func getRandPool(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (uint64, types.PoolI, sdk.Coin, sdk.Coin, []string, string, error) {
func getRandPool(k keeper.Keeper, sim *simtypes.SimCtx, ctx sdk.Context) (uint64, types.TraditionalAmmInterface, sdk.Coin, sdk.Coin, []string, string, error) {
// select a pseudo-random pool ID, max bound by the upcoming pool ID
pool_id := simtypes.RandLTBound(sim, k.GetNextPoolId(ctx))
pool, err := k.GetPoolAndPoke(ctx, pool_id)
Expand Down
5 changes: 5 additions & 0 deletions x/gamm/types/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
// on the provided LegacyAmino codec. These types are used for Amino JSON serialization.
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cdc.RegisterInterface((*PoolI)(nil), nil)
cdc.RegisterInterface((*TraditionalAmmInterface)(nil), nil)
cdc.RegisterConcrete(&MsgJoinPool{}, "osmosis/gamm/join-pool", nil)
cdc.RegisterConcrete(&MsgExitPool{}, "osmosis/gamm/exit-pool", nil)
cdc.RegisterConcrete(&MsgSwapExactAmountIn{}, "osmosis/gamm/swap-exact-amount-in", nil)
Expand All @@ -27,6 +28,10 @@ func RegisterInterfaces(registry types.InterfaceRegistry) {
"osmosis.gamm.v1beta1.PoolI",
(*PoolI)(nil),
)
registry.RegisterInterface(
"osmosis.gamm.v1beta1.TraditionalAmmInterface",
(*TraditionalAmmInterface)(nil),
)

registry.RegisterImplementations(
(*sdk.Msg)(nil),
Expand Down
2 changes: 1 addition & 1 deletion x/gamm/types/msg_create_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ type CreatePoolMsg interface {
// Initial Liquidity for the pool that the sender is required to send to the pool account
InitialLiquidity() sdk.Coins
// CreatePool creates a pool implementing PoolI, using data from the message.
CreatePool(ctx sdk.Context, poolID uint64) (PoolI, error)
CreatePool(ctx sdk.Context, poolID uint64) (TraditionalAmmInterface, error)
}
14 changes: 10 additions & 4 deletions x/gamm/types/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ type PoolI interface {
GetExitFee(ctx sdk.Context) sdk.Dec
// Returns whether the pool has swaps enabled at the moment
IsActive(ctx sdk.Context) bool
// GetTotalPoolLiquidity returns the coins in the pool owned by all LPs
GetTotalPoolLiquidity(ctx sdk.Context) sdk.Coins
// GetTotalShares returns the total number of LP shares in the pool
GetTotalShares() sdk.Int

Expand All @@ -51,6 +49,14 @@ type PoolI interface {
// For example, if this was a UniV2 50-50 pool, with 2 ETH, and 8000 UST
// pool.SpotPrice(ctx, "eth", "ust") = 4000.00
SpotPrice(ctx sdk.Context, baseAssetDenom string, quoteAssetDenom string) (sdk.Dec, error)
}

// TraditionalAmmInterface defines an interface for pools representing traditional AMM.
type TraditionalAmmInterface interface {
PoolI

// GetTotalPoolLiquidity returns the coins in the pool owned by all LPs
GetTotalPoolLiquidity(ctx sdk.Context) sdk.Coins

// JoinPool joins the pool using all of the tokensIn provided.
// The AMM swaps to the correct internal ratio should be and returns the number of shares created.
Expand Down Expand Up @@ -88,7 +94,7 @@ type PoolI interface {
// amount of coins to get out.
// See definitions below.
type PoolAmountOutExtension interface {
PoolI
TraditionalAmmInterface

// CalcTokenInShareAmountOut returns the number of tokenInDenom tokens
// that would be returned if swapped for an exact number of shares (shareOutAmount).
Expand Down Expand Up @@ -125,7 +131,7 @@ type PoolAmountOutExtension interface {
// WeightedPoolExtension is an extension of the PoolI interface
// That defines an additional API for handling the pool's weights.
type WeightedPoolExtension interface {
PoolI
TraditionalAmmInterface

// PokePool determines if a pool's weights need to be updated and updates
// them if so.
Expand Down
4 changes: 2 additions & 2 deletions x/superfluid/types/expected_keepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ type LockupMsgServer interface {

// GammKeeper defines the expected interface needed for superfluid module.
type GammKeeper interface {
GetPoolAndPoke(ctx sdk.Context, poolId uint64) (gammtypes.PoolI, error)
GetPoolsAndPoke(ctx sdk.Context) (res []gammtypes.PoolI, err error)
GetPoolAndPoke(ctx sdk.Context, poolId uint64) (gammtypes.TraditionalAmmInterface, error)
GetPoolsAndPoke(ctx sdk.Context) (res []gammtypes.TraditionalAmmInterface, err error)
ExitPool(ctx sdk.Context, sender sdk.AccAddress, poolId uint64, shareInAmount sdk.Int, tokenOutMins sdk.Coins) (exitCoins sdk.Coins, err error)
}

Expand Down