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

[Feature][market] swap constant product #233

Merged
merged 13 commits into from
Oct 15, 2019
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
2 changes: 2 additions & 0 deletions .codecov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@ ignore:
- "docs"
- "*.md"
- "*.rst"
- "**/cli"
- "**/rest"
6 changes: 3 additions & 3 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ func NewTerraApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest
// register the staking hooks
// NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks
app.stakingKeeper = *stakingKeeper.SetHooks(
staking.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks(), app.oracleKeeper.Hooks()))
staking.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks(), app.oracleKeeper.StakingHooks()))

app.mm = module.NewManager(
genaccounts.NewAppModule(app.accountKeeper),
Expand Down Expand Up @@ -217,8 +217,8 @@ func NewTerraApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest
// initialized with tokens from genesis accounts.
app.mm.SetOrderInitGenesis(genaccounts.ModuleName, distr.ModuleName,
staking.ModuleName, auth.ModuleName, bank.ModuleName, slashing.ModuleName,
oracle.ModuleName, market.ModuleName, treasury.ModuleName, gov.ModuleName,
supply.ModuleName, crisis.ModuleName, genutil.ModuleName)
supply.ModuleName, oracle.ModuleName, treasury.ModuleName, gov.ModuleName,
market.ModuleName, crisis.ModuleName, genutil.ModuleName)

app.mm.RegisterInvariants(&app.crisisKeeper)
app.mm.RegisterRoutes(app.Router(), app.QueryRouter())
Expand Down
12 changes: 12 additions & 0 deletions app/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,16 @@ func (app *TerraApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []s
return false
},
)

/* Handle market state. */

// clear all market pools
app.marketKeeper.SetTerraPoolDelta(ctx, sdk.ZeroDec())

/* Handle treasury state. */

// clear all historical issuance info
app.treasuryKeeper.ClearHistoricalIssuance(ctx)
// clear all tax proceeds
app.treasuryKeeper.ClearTaxProceeds(ctx)
}
12 changes: 6 additions & 6 deletions client/lcd/swagger-ui/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2104,9 +2104,9 @@ paths:
$ref: "#/definitions/Coin"
500:
description: Internal Server Error
/market/prev_day_issuance:
/market/terra_pool_delta:
get:
summary: Get prev day issuance
summary: Get Terra pool delta, which is the gap between TerraPool and BasePool
tags:
- Market
produces:
Expand All @@ -2115,9 +2115,9 @@ paths:
200:
description: OK
schema:
type: array
items:
$ref: "#/definitions/Coin"
type: number
format: float
example: "10000000.00"
400:
description: Bad Request
500:
Expand Down Expand Up @@ -3565,4 +3565,4 @@ definitions:
gas:
type: number
format: integer
example: 10000
example: "10000"
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ github.com/tendermint/iavl v0.12.4/go.mod h1:8LHakzt8/0G3/I8FUU0ReNx98S/EP6eyPJk
github.com/tendermint/tendermint v0.32.1/go.mod h1:jmPDAKuNkev9793/ivn/fTBnfpA9mGBww8MPRNPNxnU=
github.com/tendermint/tendermint v0.32.2 h1:FvZWdksfDg/65vKKr5Lgo57keARFnmhrUEXHwyrV1QY=
github.com/tendermint/tendermint v0.32.2/go.mod h1:NwMyx58S8VJ7tEpFKqRVlVWKO9N9zjTHu+Dx96VsnOE=
github.com/tendermint/tendermint v0.32.3 h1:GEnWpGQ795h5oTFNbfBLsY0LW/CW2j6p6HtiYNfxsgg=
github.com/tendermint/tm-db v0.1.1 h1:G3Xezy3sOk9+ekhjZ/kjArYIs1SmwV+1OUgNkj7RgV0=
github.com/tendermint/tm-db v0.1.1/go.mod h1:0cPKWu2Mou3IlxecH+MEUSYc1Ch537alLe6CpFrKzgw=
github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
Expand Down
1 change: 1 addition & 0 deletions x/auth/client/utils/feeutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ type (
}
)

// String implements fmt.Stringer interface
func (r EstimateFeeResp) String() string {
return fmt.Sprintf(`EstimateFeeResp
fees: %s,
Expand Down
5 changes: 3 additions & 2 deletions x/auth/internal/types/lazy_vesting.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func (s LazySchedule) GetRatio() sdk.Dec {
return s.Ratio
}

// String implements the fmt.Stringer interface
// String implements fmt.Stringer interface
func (s LazySchedule) String() string {
return fmt.Sprintf(`LazySchedule:
StartTime: %v,
Expand Down Expand Up @@ -121,7 +121,7 @@ func (vs VestingSchedule) IsValid() bool {
return sumRatio.Equal(sdk.OneDec())
}

// String implements the fmt.Stringer interface
// String implements fmt.Stringer interface
func (vs VestingSchedule) String() string {
return fmt.Sprintf(`VestingSchedule:
Denom: %v,
Expand Down Expand Up @@ -233,6 +233,7 @@ func (lgva BaseLazyGradedVestingAccount) GetEndTime() int64 {
return 0
}

// String implements fmt.Stringer interface
func (lgva BaseLazyGradedVestingAccount) String() string {
var pubkey string

Expand Down
16 changes: 2 additions & 14 deletions x/market/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,12 @@ package market

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

core "github.com/terra-project/core/types"
"github.com/terra-project/core/x/market/internal/types"
)

// EndBlocker is called at the end of every block
func EndBlocker(ctx sdk.Context, k Keeper) {
if !core.IsPeriodLastBlock(ctx, core.BlocksPerDay) {
return
}

// update luna issuance at last block of a day
updatedIssuance := k.UpdatePrevDayIssuance(ctx)
// Replenishes each pools towards equilibrium
k.ReplenishPools(ctx)

ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventDaliyIssuanceUpdate,
sdk.NewAttribute(types.AttributeKeyIssuance, updatedIssuance.String()),
),
)
}
16 changes: 7 additions & 9 deletions x/market/abci_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,18 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require"

core "github.com/terra-project/core/types"
"github.com/terra-project/core/x/market/internal/keeper"
)

func TestOracleThreshold(t *testing.T) {
func TestReplenishPools(t *testing.T) {
input := keeper.CreateTestInput(t)

targetIssuance := sdk.NewInt(1000000)
supply := input.SupplyKeeper.GetSupply(input.Ctx)
supply = supply.SetTotal(sdk.NewCoins(sdk.NewCoin(core.MicroLunaDenom, targetIssuance)))
input.SupplyKeeper.SetSupply(input.Ctx, supply)
delta := sdk.NewDec(1000000)
regressionAmt := delta.QuoInt64(input.MarketKeeper.PoolRecoveryPeriod(input.Ctx))
input.MarketKeeper.SetTerraPoolDelta(input.Ctx, delta)

input.Ctx = input.Ctx.WithBlockHeight(core.BlocksPerDay - 1)
EndBlocker(input.Ctx, input.MarketKeeper)
issuance := input.MarketKeeper.GetPrevDayIssuance(input.Ctx).AmountOf(core.MicroLunaDenom)
require.Equal(t, targetIssuance, issuance)

terraPoolDelta := input.MarketKeeper.GetTerraPoolDelta(input.Ctx)
require.Equal(t, delta.Sub(regressionAmt), terraPoolDelta)
}
25 changes: 14 additions & 11 deletions x/market/alias.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ const (
CodeInsufficientSwap = types.CodeInsufficientSwap
CodeNoEffectivePrice = types.CodeNoEffectivePrice
CodeRecursiveSwap = types.CodeRecursiveSwap
CodeExceedsSwapLimit = types.CodeExceedsSwapLimit
CodeInactive = types.CodeInactive
ModuleName = types.ModuleName
StoreKey = types.StoreKey
RouterKey = types.RouterKey
QuerierRoute = types.QuerierRoute
DefaultParamspace = types.DefaultParamspace
QuerySwap = types.QuerySwap
QueryPrevDayIssuance = types.QueryPrevDayIssuance
QueryTerraPoolDelta = types.QueryTerraPoolDelta
QueryParameters = types.QueryParameters
)

Expand All @@ -32,7 +32,7 @@ var (
ErrNoEffectivePrice = types.ErrNoEffectivePrice
ErrInsufficientSwapCoins = types.ErrInsufficientSwapCoins
ErrRecursiveSwap = types.ErrRecursiveSwap
ErrExceedsDailySwapLimit = types.ErrExceedsDailySwapLimit
ErrInactive = types.ErrInactive
NewGenesisState = types.NewGenesisState
DefaultGenesisState = types.DefaultGenesisState
ValidateGenesis = types.ValidateGenesis
Expand All @@ -44,14 +44,17 @@ var (
NewQuerier = keeper.NewQuerier

// variable aliases
ModuleCdc = types.ModuleCdc
PrevDayIssuanceKey = types.PrevDayIssuanceKey
ParamStoreKeyDailyLunaDeltaCap = types.ParamStoreKeyDailyLunaDeltaCap
ParamStoreKeyMaxSwapSpread = types.ParamStoreKeyMaxSwapSpread
ParamStoreKeyMinSwapSpread = types.ParamStoreKeyMinSwapSpread
DefaultDailyLunaDeltaCap = types.DefaultDailyLunaDeltaCap
DefaultMaxSwapSpread = types.DefaultMaxSwapSpread
DefaultMinSwapSpread = types.DefaultMinSwapSpread
ModuleCdc = types.ModuleCdc
TerraPoolDeltaKey = types.TerraPoolDeltaKey
ParamStoreKeyBasePool = types.ParamStoreKeyBasePool
ParamStoreKeyPoolRecoveryPeriod = types.ParamStoreKeyPoolRecoveryPeriod
ParamStoreKeyMinSpread = types.ParamStoreKeyMinSpread
ParmamStoreKeyTobinTax = types.ParmamStoreKeyTobinTax
DefaultBasePool = types.DefaultBasePool
DefaultPoolRecoveryPeriod = types.DefaultPoolRecoveryPeriod
DefaultTerraLiquidityRatio = types.DefaultTerraLiquidityRatio
DefaultMinSpread = types.DefaultMinSpread
DefaultTobinTax = types.DefaultTobinTax
)

type (
Expand Down
26 changes: 15 additions & 11 deletions x/market/client/cli/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command {

marketQueryCmd.AddCommand(client.GetCommands(
GetCmdQuerySwap(queryRoute, cdc),
GetCmdQueryTerraPoolDelta(queryRoute, cdc),
GetCmdQueryParams(queryRoute, cdc),
GetCmdQueryPrevDayIssuance(queryRoute, cdc),
)...)

return marketQueryCmd
Expand Down Expand Up @@ -64,31 +64,35 @@ $ terracli query query swap 5000000uluna usdr
}

var retCoin sdk.Coin
cdc.MustUnmarshalBinaryLengthPrefixed(res, &retCoin)
cdc.MustUnmarshalJSON(res, &retCoin)
return cliCtx.PrintOutput(retCoin)
},
}

return cmd
}

// GetCmdQueryPrevDayIssuance implements the query params command.
func GetCmdQueryPrevDayIssuance(queryRoute string, cdc *codec.Codec) *cobra.Command {
// GetCmdQueryTerraPoolDelta implements the query params command.
func GetCmdQueryTerraPoolDelta(queryRoute string, cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: "prev-day-issuance",
Args: cobra.ExactArgs(1),
Short: "Query the prev day issuance",
Use: "terra-pool-delta",
Args: cobra.NoArgs,
Short: "Query terra pool delta",
Long: `Query terra pool delta, which is the gap between TerraPool and BasePool.

$ terracli query market terra-pool-delta
`,
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)

res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryPrevDayIssuance), nil)
res, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", queryRoute, types.QueryTerraPoolDelta), nil)
if err != nil {
return err
}

var prevDayIssuance sdk.Coins
cdc.MustUnmarshalJSON(res, &prevDayIssuance)
return cliCtx.PrintOutput(prevDayIssuance)
var poolDelta sdk.Dec
cdc.MustUnmarshalJSON(res, &poolDelta)
return cliCtx.PrintOutput(poolDelta)
},
}

Expand Down
10 changes: 5 additions & 5 deletions x/market/client/rest/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (

func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) {
r.HandleFunc("/market/swap", querySwapHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/market/prev_day_issuance", queryPrevDayIssuanceHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/market/terra_pool_delta", queryTerraPoolDeltaHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/market/parameters", queryParamsHandlerFn(cliCtx)).Methods("GET")
}

Expand Down Expand Up @@ -63,14 +63,14 @@ func querySwapHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
}
}

func queryParamsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
func queryTerraPoolDeltaHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r)
if !ok {
return
}

res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParameters), nil)
res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryTerraPoolDelta), nil)
if err != nil {
rest.WriteErrorResponse(w, http.StatusNotFound, err.Error())
return
Expand All @@ -81,14 +81,14 @@ func queryParamsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
}
}

func queryPrevDayIssuanceHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
func queryParamsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r)
if !ok {
return
}

res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryPrevDayIssuance), nil)
res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryParameters), nil)
if err != nil {
rest.WriteErrorResponse(w, http.StatusNotFound, err.Error())
return
Expand Down
4 changes: 3 additions & 1 deletion x/market/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ import (
// and the keeper's address to pubkey map
func InitGenesis(ctx sdk.Context, keeper Keeper, data GenesisState) {
keeper.SetParams(ctx, data.Params)
keeper.SetTerraPoolDelta(ctx, data.TerraPoolDelta)
}

// ExportGenesis writes the current store values
// to a genesis file, which can be imported again
// with InitGenesis
func ExportGenesis(ctx sdk.Context, keeper Keeper) (data GenesisState) {
params := keeper.GetParams(ctx)
terraPoolDelta := keeper.GetTerraPoolDelta(ctx)

return NewGenesisState(params)
return NewGenesisState(terraPoolDelta, params)
}
22 changes: 22 additions & 0 deletions x/market/genesis_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package market

import (
"testing"

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require"

"github.com/terra-project/core/x/market/internal/keeper"
)

func TestExportInitGenesis(t *testing.T) {
input := keeper.CreateTestInput(t)
input.MarketKeeper.SetTerraPoolDelta(input.Ctx, sdk.NewDec(1123))
genesis := ExportGenesis(input.Ctx, input.MarketKeeper)

newInput := keeper.CreateTestInput(t)
InitGenesis(newInput.Ctx, newInput.MarketKeeper, genesis)
newGenesis := ExportGenesis(newInput.Ctx, newInput.MarketKeeper)

require.Equal(t, genesis, newGenesis)
}
Loading