Skip to content

Commit

Permalink
feat(CL): swaprouter types and barebones keeper (merge to main #2)
Browse files Browse the repository at this point in the history
  • Loading branch information
p0mvn committed Nov 22, 2022
1 parent f6a9bde commit d7ff622
Show file tree
Hide file tree
Showing 27 changed files with 1,222 additions and 19 deletions.
2 changes: 1 addition & 1 deletion app/apptesting/test_suite.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ func (s *KeeperTestHelper) SwapAndSetSpotPrice(poolId uint64, fromAsset sdk.Coin
coins := sdk.Coins{sdk.NewInt64Coin(fromAsset.Denom, 100000000000000)}
s.FundAcc(acc1, coins)

_, err := s.App.GAMMKeeper.SwapExactAmountOut(
_, err := s.App.GAMMKeeper.SwapExactAmountOutLegacy(
s.Ctx,
acc1,
poolId,
Expand Down
16 changes: 16 additions & 0 deletions app/keepers/keepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ import (
// IBC Transfer: Defines the "transfer" IBC port
transfer "github.com/cosmos/ibc-go/v3/modules/apps/transfer"

"github.com/osmosis-labs/osmosis/v13/x/swaprouter"

_ "github.com/osmosis-labs/osmosis/v13/client/docs/statik"
owasm "github.com/osmosis-labs/osmosis/v13/wasmbinding"
epochskeeper "github.com/osmosis-labs/osmosis/v13/x/epochs/keeper"
Expand All @@ -70,6 +72,7 @@ import (
"github.com/osmosis-labs/osmosis/v13/x/superfluid"
superfluidkeeper "github.com/osmosis-labs/osmosis/v13/x/superfluid/keeper"
superfluidtypes "github.com/osmosis-labs/osmosis/v13/x/superfluid/types"
swaproutertypes "github.com/osmosis-labs/osmosis/v13/x/swaprouter/types"
tokenfactorykeeper "github.com/osmosis-labs/osmosis/v13/x/tokenfactory/keeper"
tokenfactorytypes "github.com/osmosis-labs/osmosis/v13/x/tokenfactory/types"
"github.com/osmosis-labs/osmosis/v13/x/twap"
Expand Down Expand Up @@ -119,6 +122,7 @@ type AppKeepers struct {
WasmKeeper *wasm.Keeper
ContractKeeper *wasmkeeper.PermissionedKeeper
TokenFactoryKeeper *tokenfactorykeeper.Keeper
SwapRouterKeeper *swaprouter.Keeper
ValidatorSetPreferenceKeeper *valsetpref.Keeper

// IBC modules
Expand Down Expand Up @@ -251,6 +255,16 @@ func (appKeepers *AppKeepers) InitNormalKeepers(
appKeepers.GetSubspace(twaptypes.ModuleName),
appKeepers.GAMMKeeper)

appKeepers.SwapRouterKeeper = swaprouter.NewKeeper(
appKeepers.keys[swaproutertypes.StoreKey],
appKeepers.GetSubspace(swaproutertypes.ModuleName),
appKeepers.GAMMKeeper,
nil, // TODO: set CL keeper once it is merged.
appKeepers.BankKeeper,
appKeepers.AccountKeeper,
appKeepers.DistrKeeper,
)

appKeepers.LockupKeeper = lockupkeeper.NewKeeper(
appKeepers.keys[lockuptypes.StoreKey],
// TODO: Visit why this needs to be deref'd
Expand Down Expand Up @@ -509,6 +523,7 @@ func (appKeepers *AppKeepers) initParamsKeeper(appCodec codec.BinaryCodec, legac
paramsKeeper.Subspace(wasm.ModuleName)
paramsKeeper.Subspace(tokenfactorytypes.ModuleName)
paramsKeeper.Subspace(twaptypes.ModuleName)
paramsKeeper.Subspace(swaproutertypes.ModuleName)
paramsKeeper.Subspace(ibcratelimittypes.ModuleName)

return paramsKeeper
Expand Down Expand Up @@ -594,6 +609,7 @@ func KVStoreKeys() []string {
capabilitytypes.StoreKey,
gammtypes.StoreKey,
twaptypes.StoreKey,
swaproutertypes.StoreKey,
lockuptypes.StoreKey,
incentivestypes.StoreKey,
epochstypes.StoreKey,
Expand Down
2 changes: 2 additions & 0 deletions app/keepers/modules.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import (
poolincentivesclient "github.com/osmosis-labs/osmosis/v13/x/pool-incentives/client"
superfluid "github.com/osmosis-labs/osmosis/v13/x/superfluid"
superfluidclient "github.com/osmosis-labs/osmosis/v13/x/superfluid/client"
swaproutermodule "github.com/osmosis-labs/osmosis/v13/x/swaprouter/module"
"github.com/osmosis-labs/osmosis/v13/x/tokenfactory"
"github.com/osmosis-labs/osmosis/v13/x/twap/twapmodule"
"github.com/osmosis-labs/osmosis/v13/x/txfees"
Expand Down Expand Up @@ -80,6 +81,7 @@ var AppModuleBasics = []module.AppModuleBasic{
vesting.AppModuleBasic{},
gamm.AppModuleBasic{},
twapmodule.AppModuleBasic{},
swaproutermodule.AppModuleBasic{},
txfees.AppModuleBasic{},
incentives.AppModuleBasic{},
lockup.AppModuleBasic{},
Expand Down
4 changes: 2 additions & 2 deletions x/gamm/keeper/multihop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ func (suite *KeeperTestSuite) TestBalancerPoolMultihopSwapExactAmountIn() {
nextTokenIn := test.param.tokenIn
// we then do individual swaps until we reach the end of the swap route
for _, hop := range test.param.routes {
tokenOut, err := keeper.SwapExactAmountIn(cacheCtx, suite.TestAccs[0], hop.PoolId, nextTokenIn, hop.TokenOutDenom, sdk.OneInt())
tokenOut, err := keeper.SwapExactAmountInLegacy(cacheCtx, suite.TestAccs[0], hop.PoolId, nextTokenIn, hop.TokenOutDenom, sdk.OneInt())
suite.Require().NoError(err)
nextTokenIn = sdk.NewCoin(hop.TokenOutDenom, tokenOut)
}
Expand Down Expand Up @@ -533,7 +533,7 @@ func (suite *KeeperTestSuite) TestBalancerPoolMultihopSwapExactAmountOut() {
// we then do individual swaps until we reach the end of the swap route
for i := len(test.param.routes) - 1; i >= 0; i-- {
hop := test.param.routes[i]
tokenOut, err := keeper.SwapExactAmountOut(cacheCtx, suite.TestAccs[0], hop.PoolId, hop.TokenInDenom, sdk.NewInt(100000000), nextTokenOut)
tokenOut, err := keeper.SwapExactAmountOutLegacy(cacheCtx, suite.TestAccs[0], hop.PoolId, hop.TokenInDenom, sdk.NewInt(100000000), nextTokenOut)
suite.Require().NoError(err)
nextTokenOut = sdk.NewCoin(hop.TokenInDenom, tokenOut)
}
Expand Down
10 changes: 10 additions & 0 deletions x/gamm/keeper/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ import (
"github.com/osmosis-labs/osmosis/v13/x/gamm/types"
)

// TODO spec and tests
func (k Keeper) InitializePool(ctx sdk.Context, pool types.PoolI, creatorAddress sdk.AccAddress) error {
panic("not implemented")
}

func (k Keeper) MarshalPool(pool types.PoolI) ([]byte, error) {
return k.cdc.MarshalInterface(pool)
}
Expand All @@ -23,6 +28,11 @@ func (k Keeper) UnmarshalPool(bz []byte) (types.PoolI, error) {
return acc, k.cdc.UnmarshalInterface(bz, &acc)
}

// GetPool returns a pool with a given id.
func (k Keeper) GetPool(ctx sdk.Context, poolId uint64) (types.PoolI, error) {
return k.getPoolForSwap(ctx, poolId)
}

// 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.
Expand Down
2 changes: 1 addition & 1 deletion x/gamm/keeper/pool_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ func (k Keeper) ExitSwapShareAmountIn(
if coin.Denom == tokenOutDenom {
continue
}
swapOut, err := k.SwapExactAmountIn(ctx, sender, poolId, coin, tokenOutDenom, sdk.ZeroInt())
swapOut, err := k.SwapExactAmountInLegacy(ctx, sender, poolId, coin, tokenOutDenom, sdk.ZeroInt())
if err != nil {
return sdk.Int{}, err
}
Expand Down
40 changes: 38 additions & 2 deletions x/gamm/keeper/swap.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,31 @@ import (
"github.com/osmosis-labs/osmosis/v13/x/gamm/types"
)

// SwapExactAmountIn attempts to swap one asset, tokenIn, for another asset
// swapExactAmountIn is an internal method for swapping an exact amount of tokens
// as input to a pool, using the provided swapFee. This is intended to allow
// different swap fees as determined by multi-hops, or when recovering from
// chain liveness failures.
// TODO: investigate if swapFee can be unexported
// https://github.com/osmosis-labs/osmosis/issues/3130
func (k Keeper) SwapExactAmountIn(
ctx sdk.Context,
sender sdk.AccAddress,
pool types.PoolI,
tokenIn sdk.Coin,
tokenOutDenom string,
tokenOutMinAmount sdk.Int,
swapFee sdk.Dec,
) (tokenOutAmount sdk.Int, err error) {
panic("not implemented")
}

// SwapExactAmountInLegacy attempts to swap one asset, tokenIn, for another asset
// denominated via tokenOutDenom through a pool denoted by poolId specifying that
// tokenOutMinAmount must be returned in the resulting asset returning an error
// upon failure. Upon success, the resulting tokens swapped for are returned. A
// swap fee is applied determined by the pool's parameters.
func (k Keeper) SwapExactAmountIn(
// TODO: to be removed in future merges.
func (k Keeper) SwapExactAmountInLegacy(
ctx sdk.Context,
sender sdk.AccAddress,
poolId uint64,
Expand Down Expand Up @@ -84,7 +103,24 @@ func (k Keeper) swapExactAmountIn(
return tokenOutAmount, nil
}

// SwapExactAmountOut is a method for swapping by providing an exact amount of tokens out.
// Returns the amount of tokenIn consumed to performed the swap. Otherwise, returns error.
// Consumes swapFee. This is intended to allow different swap fees as determined by multi-hops,
// or when recovering from chain liveness failures.
func (k Keeper) SwapExactAmountOut(
ctx sdk.Context,
sender sdk.AccAddress,
pool types.PoolI,
tokenInDenom string,
tokenInMaxAmount sdk.Int,
tokenOut sdk.Coin,
swapFee sdk.Dec,
) (tokenInAmount sdk.Int, err error) {
panic("not implemented")
}

//
func (k Keeper) SwapExactAmountOutLegacy(
ctx sdk.Context,
sender sdk.AccAddress,
poolId uint64,
Expand Down
20 changes: 10 additions & 10 deletions x/gamm/keeper/swap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func (suite *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountIn() {
suite.NoError(err, "test: %v", test.name)

prevGasConsumed := suite.Ctx.GasMeter().GasConsumed()
tokenOutAmount, err := keeper.SwapExactAmountIn(ctx, suite.TestAccs[0], poolId, test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount)
tokenOutAmount, err := keeper.SwapExactAmountInLegacy(ctx, suite.TestAccs[0], poolId, test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount)
suite.NoError(err, "test: %v", test.name)
suite.True(tokenOutAmount.Equal(test.param.expectedTokenOut), "test: %v", test.name)
gasConsumedForSwap := suite.Ctx.GasMeter().GasConsumed() - prevGasConsumed
Expand All @@ -114,7 +114,7 @@ func (suite *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountIn() {
tradeAvgPrice := test.param.tokenIn.Amount.ToDec().Quo(tokenOutAmount.ToDec())
suite.True(tradeAvgPrice.GT(spotPriceBefore) && tradeAvgPrice.LT(spotPriceAfter), "test: %v", test.name)
} else {
_, err := keeper.SwapExactAmountIn(ctx, suite.TestAccs[0], poolId, test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount)
_, err := keeper.SwapExactAmountInLegacy(ctx, suite.TestAccs[0], poolId, test.param.tokenIn, test.param.tokenOutDenom, test.param.tokenOutMinAmount)
suite.Error(err, "test: %v", test.name)
}
})
Expand Down Expand Up @@ -206,7 +206,7 @@ func (suite *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountOut() {
suite.NoError(err, "test: %v", test.name)

prevGasConsumed := suite.Ctx.GasMeter().GasConsumed()
tokenInAmount, err := keeper.SwapExactAmountOut(ctx, suite.TestAccs[0], poolId, test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut)
tokenInAmount, err := keeper.SwapExactAmountOutLegacy(ctx, suite.TestAccs[0], poolId, test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut)
suite.NoError(err, "test: %v", test.name)
suite.True(tokenInAmount.Equal(test.param.expectedTokenInAmount),
"test: %v\n expect_eq actual: %s, expected: %s",
Expand All @@ -224,7 +224,7 @@ func (suite *KeeperTestSuite) TestBalancerPoolSimpleSwapExactAmountOut() {
tradeAvgPrice := tokenInAmount.ToDec().Quo(test.param.tokenOut.Amount.ToDec())
suite.True(tradeAvgPrice.GT(spotPriceBefore) && tradeAvgPrice.LT(spotPriceAfter), "test: %v", test.name)
} else {
_, err := keeper.SwapExactAmountOut(suite.Ctx, suite.TestAccs[0], poolId, test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut)
_, err := keeper.SwapExactAmountOutLegacy(suite.Ctx, suite.TestAccs[0], poolId, test.param.tokenInDenom, test.param.tokenInMaxAmount, test.param.tokenOut)
suite.Error(err, "test: %v", test.name)
}
})
Expand Down Expand Up @@ -259,14 +259,14 @@ func (suite *KeeperTestSuite) TestActiveBalancerPoolSwap() {
foocoin := sdk.NewCoin("foo", sdk.NewInt(10))

if tc.expectPass {
_, err := suite.App.GAMMKeeper.SwapExactAmountIn(suite.Ctx, suite.TestAccs[0], poolId, foocoin, "bar", sdk.ZeroInt())
_, err := suite.App.GAMMKeeper.SwapExactAmountInLegacy(suite.Ctx, suite.TestAccs[0], poolId, foocoin, "bar", sdk.ZeroInt())
suite.Require().NoError(err)
_, err = suite.App.GAMMKeeper.SwapExactAmountOut(suite.Ctx, suite.TestAccs[0], poolId, "bar", sdk.NewInt(1000000000000000000), foocoin)
_, err = suite.App.GAMMKeeper.SwapExactAmountOutLegacy(suite.Ctx, suite.TestAccs[0], poolId, "bar", sdk.NewInt(1000000000000000000), foocoin)
suite.Require().NoError(err)
} else {
_, err := suite.App.GAMMKeeper.SwapExactAmountIn(suite.Ctx, suite.TestAccs[0], poolId, foocoin, "bar", sdk.ZeroInt())
_, err := suite.App.GAMMKeeper.SwapExactAmountInLegacy(suite.Ctx, suite.TestAccs[0], poolId, foocoin, "bar", sdk.ZeroInt())
suite.Require().Error(err)
_, err = suite.App.GAMMKeeper.SwapExactAmountOut(suite.Ctx, suite.TestAccs[0], poolId, "bar", sdk.NewInt(1000000000000000000), foocoin)
_, err = suite.App.GAMMKeeper.SwapExactAmountOutLegacy(suite.Ctx, suite.TestAccs[0], poolId, "bar", sdk.NewInt(1000000000000000000), foocoin)
suite.Require().Error(err)
}
}
Expand Down Expand Up @@ -313,8 +313,8 @@ func (suite *KeeperTestSuite) TestInactivePoolFreezeSwaps() {
for _, test := range testCases {
suite.Run(test.name, func() {
// Check swaps
_, swapInErr := gammKeeper.SwapExactAmountIn(suite.Ctx, suite.TestAccs[0], test.poolId, testCoin, "bar", sdk.ZeroInt())
_, swapOutErr := gammKeeper.SwapExactAmountOut(suite.Ctx, suite.TestAccs[0], test.poolId, "bar", sdk.NewInt(1000000000000000000), testCoin)
_, swapInErr := gammKeeper.SwapExactAmountInLegacy(suite.Ctx, suite.TestAccs[0], test.poolId, testCoin, "bar", sdk.ZeroInt())
_, swapOutErr := gammKeeper.SwapExactAmountOutLegacy(suite.Ctx, suite.TestAccs[0], test.poolId, "bar", sdk.NewInt(1000000000000000000), testCoin)
if test.expectPass {
suite.Require().NoError(swapInErr)
suite.Require().NoError(swapOutErr)
Expand Down
9 changes: 9 additions & 0 deletions x/swaprouter/export_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package swaprouter

import (
sdk "github.com/cosmos/cosmos-sdk/types"
)

func (k Keeper) GetNextPoolIdAndIncrement(ctx sdk.Context) uint64 {
return k.getNextPoolIdAndIncrement(ctx)
}
110 changes: 110 additions & 0 deletions x/swaprouter/keeper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package swaprouter

import (
sdk "github.com/cosmos/cosmos-sdk/types"
gogotypes "github.com/gogo/protobuf/types"

"github.com/osmosis-labs/osmosis/v13/osmoutils"
"github.com/osmosis-labs/osmosis/v13/x/swaprouter/types"

paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
)

type Keeper struct {
storeKey sdk.StoreKey

gammKeeper types.SwapI
concentratedKeeper types.SwapI
poolIncentivesKeeper types.PoolIncentivesKeeperI
bankKeeper types.BankI
accountKeeper types.AccountI
communityPoolKeeper types.CommunityPoolI

poolCreationListeners types.PoolCreationListeners

routes map[types.PoolType]types.SwapI

paramSpace paramtypes.Subspace
}

func NewKeeper(storeKey sdk.StoreKey, paramSpace paramtypes.Subspace, gammKeeper types.SwapI, concentratedKeeper types.SwapI, bankKeeper types.BankI, accountKeeper types.AccountI, communityPoolKeeper types.CommunityPoolI) *Keeper {
// set KeyTable if it has not already been set
if !paramSpace.HasKeyTable() {
paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable())
}

routes := map[types.PoolType]types.SwapI{
types.Balancer: gammKeeper,
types.StableSwap: gammKeeper,
types.Concentrated: concentratedKeeper,
}

return &Keeper{storeKey: storeKey, paramSpace: paramSpace, gammKeeper: gammKeeper, concentratedKeeper: concentratedKeeper, bankKeeper: bankKeeper, accountKeeper: accountKeeper, communityPoolKeeper: communityPoolKeeper, routes: routes}
}

// GetParams returns the total set of swaprouter parameters.
func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) {
k.paramSpace.GetParamSet(ctx, &params)
return params
}

// SetParams sets the total set of swaprouter parameters.
func (k Keeper) SetParams(ctx sdk.Context, params types.Params) {
k.paramSpace.SetParamSet(ctx, &params)
}

// InitGenesis initializes the swaprouter module's state from a provided genesis
// state.
func (k Keeper) InitGenesis(ctx sdk.Context, genState *types.GenesisState) {
k.SetNextPoolId(ctx, genState.NextPoolId)
if err := genState.Validate(); err != nil {
panic(err)
}

k.SetParams(ctx, genState.Params)
}

// ExportGenesis returns the swaprouter module's exported genesis.
func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState {
return &types.GenesisState{
Params: k.GetParams(ctx),
NextPoolId: k.GetNextPoolId(ctx),
}
}

// GetNextPoolId returns the next pool id.
func (k Keeper) GetNextPoolId(ctx sdk.Context) uint64 {
store := ctx.KVStore(k.storeKey)
nextPoolId := gogotypes.UInt64Value{}
osmoutils.MustGet(store, types.KeyNextGlobalPoolId, &nextPoolId)
return nextPoolId.Value
}

// SetPoolCreationListeners sets the pool creation listeners.
func (k *Keeper) SetPoolCreationListeners(listeners types.PoolCreationListeners) *Keeper {
if k.poolCreationListeners != nil {
panic("cannot set pool creation listeners twice")
}

k.poolCreationListeners = listeners

return k
}

// SetNextPoolId sets next pool Id.
func (k Keeper) SetNextPoolId(ctx sdk.Context, poolId uint64) {
store := ctx.KVStore(k.storeKey)
osmoutils.MustSet(store, types.KeyNextGlobalPoolId, &gogotypes.UInt64Value{Value: poolId})
}

// SetPoolIncentivesKeeper sets pool incentives keeper
func (k *Keeper) SetPoolIncentivesKeeper(poolIncentivesKeeper types.PoolIncentivesKeeperI) {
k.poolIncentivesKeeper = poolIncentivesKeeper
}

// getNextPoolIdAndIncrement returns the next pool Id, and increments the corresponding state entry.
func (k Keeper) getNextPoolIdAndIncrement(ctx sdk.Context) uint64 {
nextPoolId := k.GetNextPoolId(ctx)
k.SetNextPoolId(ctx, nextPoolId+1)
return nextPoolId
}
Loading

0 comments on commit d7ff622

Please sign in to comment.