From 18981b7da064086972423dfbabb8ea2765a08b87 Mon Sep 17 00:00:00 2001 From: Walter White <101130700+NibiruHeisenberg@users.noreply.github.com> Date: Mon, 11 Jul 2022 09:50:25 -0700 Subject: [PATCH] refactor(pricefeed): Rename keeper methods (#697) * Rename SetPrice to PostRawPrice * Rename SetCurrentPrices to GatherRawPrices * Remove redundant acronym syndrome on TWAP * Update CHANGELOG.md * Fix pricefeed names in clearing house integration tests * Add pricefeed keeper method comments * Fix pricefeed keeper method names Co-authored-by: Mat-Cosmos <97468149+matthiasmatt@users.noreply.github.com> --- CHANGELOG.md | 3 +- app/ibc_test.go | 4 +- .../keeper/clearing_house_integration_test.go | 8 +-- x/perp/keeper/hooks.go | 10 ++-- x/perp/keeper/hooks_test.go | 4 +- x/perp/keeper/margin.go | 6 +-- x/perp/keeper/msg_server_test.go | 4 +- x/perp/types/expected_keepers.go | 30 +++++++++-- x/pricefeed/abci.go | 2 +- x/pricefeed/abci_test.go | 8 +-- x/pricefeed/client/cli/cli_test.go | 8 ++- x/pricefeed/genesis.go | 4 +- x/pricefeed/keeper/keeper.go | 47 ++++++++++++----- x/pricefeed/keeper/keeper_test.go | 42 +++++++-------- x/pricefeed/keeper/msg_server.go | 2 +- x/pricefeed/types/keys.go | 10 ++-- x/stablecoin/abci.go | 2 +- x/stablecoin/abci_test.go | 10 ++-- x/stablecoin/keeper/collateral_ratio.go | 2 +- x/stablecoin/keeper/collateral_ratio_test.go | 44 ++++++++-------- x/stablecoin/keeper/mint_burn_stable_test.go | 24 ++++----- x/stablecoin/types/expected_keepers.go | 4 +- x/testutil/mock/perp_interfaces.go | 52 +++++++++---------- x/vpool/keeper/prices.go | 14 ++--- x/vpool/keeper/prices_test.go | 26 +++++----- x/vpool/module.go | 2 +- x/vpool/types/keys.go | 8 +-- 27 files changed, 211 insertions(+), 169 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e4b03a6d..0c5168f52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,9 +54,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * [#687](https://github.com/NibiruChain/nibiru/pull/687) Emit `PositionChangedEvent` upon changing margin. * [#685](https://github.com/NibiruChain/nibiru/pull/685) Represent `PositionChangedEvent` bad debt as Coin. +* [#697](https://github.com/NibiruChain/nibiru/pull/697) Rename pricefeed keeper methods. +* [#689](https://github.com/NibiruChain/nibiru/pull/689) Change liquidation params to 2.5% liquidation fee ratio and 25% partial liquidation ratio. ### Testing * [#695](https://github.com/NibiruChain/nibiru/pull/695) Add `OpenPosition` integration tests. * [#692](https://github.com/NibiruChain/nibiru/pull/692) Add test coverage for Perp MsgServer methods. -* [#689](https://github.com/NibiruChain/nibiru/pull/689) Change liquidation params to 2.5% liquidation fee ratio and 25% partial liquidation ratio. diff --git a/app/ibc_test.go b/app/ibc_test.go index 4b8ffd925..03db29c2d 100644 --- a/app/ibc_test.go +++ b/app/ibc_test.go @@ -43,7 +43,7 @@ func SetupNibiruTestingApp() ( }) nibiruApp.PricefeedKeeper.WhitelistOracles(ctx, []sdk.AccAddress{oracle}) - _, err = nibiruApp.PricefeedKeeper.SetPrice( + _, err = nibiruApp.PricefeedKeeper.PostRawPrice( ctx, oracle, pair.String(), sdk.OneDec(), ctx.BlockTime().Add(time.Hour), ) @@ -51,7 +51,7 @@ func SetupNibiruTestingApp() ( return nil, defaultGenesis } - err = nibiruApp.PricefeedKeeper.SetCurrentPrices(ctx, pair.Token0, pair.Token1) + err = nibiruApp.PricefeedKeeper.GatherRawPrices(ctx, pair.Token0, pair.Token1) if err != nil { return nil, defaultGenesis } diff --git a/x/perp/keeper/clearing_house_integration_test.go b/x/perp/keeper/clearing_house_integration_test.go index eabbe9976..26df6a365 100644 --- a/x/perp/keeper/clearing_house_integration_test.go +++ b/x/perp/keeper/clearing_house_integration_test.go @@ -184,9 +184,9 @@ func TestOpenPositionSuccess(t *testing.T) { t.Log("set pricefeed oracle") nibiruApp.PricefeedKeeper.WhitelistOracles(ctx, []sdk.AccAddress{oracle}) - _, err := nibiruApp.PricefeedKeeper.SetPrice(ctx, oracle, common.PairBTCStable.String(), sdk.OneDec(), time.Now().Add(time.Hour)) + _, err := nibiruApp.PricefeedKeeper.PostRawPrice(ctx, oracle, common.PairBTCStable.String(), sdk.OneDec(), time.Now().Add(time.Hour)) require.NoError(t, err) - require.NoError(t, nibiruApp.PricefeedKeeper.SetCurrentPrices(ctx, common.DenomAxlBTC, common.DenomStable)) + require.NoError(t, nibiruApp.PricefeedKeeper.GatherRawPrices(ctx, common.DenomAxlBTC, common.DenomStable)) t.Log("initialize vpool") nibiruApp.VpoolKeeper.CreatePool( @@ -302,9 +302,9 @@ func TestOpenPositionError(t *testing.T) { t.Log("set pricefeed oracle") nibiruApp.PricefeedKeeper.WhitelistOracles(ctx, []sdk.AccAddress{oracle}) - _, err := nibiruApp.PricefeedKeeper.SetPrice(ctx, oracle, common.PairBTCStable.String(), sdk.OneDec(), time.Now().Add(time.Hour)) + _, err := nibiruApp.PricefeedKeeper.PostRawPrice(ctx, oracle, common.PairBTCStable.String(), sdk.OneDec(), time.Now().Add(time.Hour)) require.NoError(t, err) - require.NoError(t, nibiruApp.PricefeedKeeper.SetCurrentPrices(ctx, common.DenomAxlBTC, common.DenomStable)) + require.NoError(t, nibiruApp.PricefeedKeeper.GatherRawPrices(ctx, common.DenomAxlBTC, common.DenomStable)) t.Log("initialize vpool") nibiruApp.VpoolKeeper.CreatePool( diff --git a/x/perp/keeper/hooks.go b/x/perp/keeper/hooks.go index 802fbb561..f410de0a1 100644 --- a/x/perp/keeper/hooks.go +++ b/x/perp/keeper/hooks.go @@ -21,27 +21,27 @@ func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, _ int64) ctx.Logger().Error("no pool for pair found", "pairMetadata.Pair", pairMetadata.Pair) continue } - indexTWAPPrice, err := k.PricefeedKeeper.GetCurrentTWAPPrice(ctx, pairMetadata.Pair.Token0, pairMetadata.Pair.Token1) + indexTWAP, err := k.PricefeedKeeper.GetCurrentTWAP(ctx, pairMetadata.Pair.Token0, pairMetadata.Pair.Token1) if err != nil { ctx.Logger().Error("failed to fetch twap index price", "pairMetadata.Pair", pairMetadata.Pair, "error", err) continue } - if indexTWAPPrice.Price.IsZero() { + if indexTWAP.Price.IsZero() { ctx.Logger().Error("index price is zero", "pairMetadata.Pair", pairMetadata.Pair) continue } - markTWAPPrice, err := k.VpoolKeeper.GetCurrentTWAPPrice(ctx, pairMetadata.Pair) + markTWAP, err := k.VpoolKeeper.GetCurrentTWAP(ctx, pairMetadata.Pair) if err != nil { ctx.Logger().Error("failed to fetch twap mark price", "pairMetadata.Pair", pairMetadata.Pair, "error", err) continue } - if markTWAPPrice.Price.IsZero() { + if markTWAP.Price.IsZero() { ctx.Logger().Error("mark price is zero", "pairMetadata.Pair", pairMetadata.Pair) continue } epochInfo := k.EpochKeeper.GetEpochInfo(ctx, epochIdentifier) intervalsPerDay := (24 * time.Hour) / epochInfo.Duration - fundingRate := markTWAPPrice.Price.Sub(indexTWAPPrice.Price).QuoInt64(int64(intervalsPerDay)) + fundingRate := markTWAP.Price.Sub(indexTWAP.Price).QuoInt64(int64(intervalsPerDay)) if len(pairMetadata.CumulativePremiumFractions) > 0 { fundingRate = pairMetadata.CumulativePremiumFractions[len(pairMetadata.CumulativePremiumFractions)-1].Add(fundingRate) diff --git a/x/perp/keeper/hooks_test.go b/x/perp/keeper/hooks_test.go index 3fb0eac6f..e42f2cf14 100644 --- a/x/perp/keeper/hooks_test.go +++ b/x/perp/keeper/hooks_test.go @@ -97,13 +97,13 @@ func setMockPrices(ctx sdk.Context, mocks mockedDependencies, indexPrice, markPr ) } mocks.mockPricefeedKeeper.EXPECT(). - GetCurrentTWAPPrice(ctx, common.PairBTCStable.Token0, common.PairBTCStable.Token1). + GetCurrentTWAP(ctx, common.PairBTCStable.Token0, common.PairBTCStable.Token1). Return(pftypes.CurrentTWAP{ PairID: common.PairBTCStable.String(), Price: sdk.NewDec(indexPrice), }, nil).MaxTimes(1) mocks.mockVpoolKeeper.EXPECT(). - GetCurrentTWAPPrice(ctx, common.PairBTCStable). + GetCurrentTWAP(ctx, common.PairBTCStable). Return(vpooltypes.CurrentTWAP{ PairID: common.PairBTCStable.String(), Price: sdk.NewDec(markPrice), diff --git a/x/perp/keeper/margin.go b/x/perp/keeper/margin.go index 9efaf0611..6d4c88b5e 100644 --- a/x/perp/keeper/margin.go +++ b/x/perp/keeper/margin.go @@ -438,7 +438,7 @@ func (k Keeper) getPreferencePositionNotionalAndUnrealizedPnL( return sdk.Dec{}, sdk.Dec{}, err } - twapPositionNotional, twapPricePnL, err := k.getPositionNotionalAndUnrealizedPnL( + twapPositionNotional, twapPnl, err := k.getPositionNotionalAndUnrealizedPnL( ctx, position, types.PnLCalcOption_TWAP, @@ -457,10 +457,10 @@ func (k Keeper) getPreferencePositionNotionalAndUnrealizedPnL( switch pnLPreferenceOption { case types.PnLPreferenceOption_MAX: positionNotional = sdk.MaxDec(spotPositionNotional, twapPositionNotional) - unrealizedPnl = sdk.MaxDec(spotPricePnl, twapPricePnL) + unrealizedPnl = sdk.MaxDec(spotPricePnl, twapPnl) case types.PnLPreferenceOption_MIN: positionNotional = sdk.MinDec(spotPositionNotional, twapPositionNotional) - unrealizedPnl = sdk.MinDec(spotPricePnl, twapPricePnL) + unrealizedPnl = sdk.MinDec(spotPricePnl, twapPnl) default: panic("invalid pnl preference option " + pnLPreferenceOption.String()) } diff --git a/x/perp/keeper/msg_server_test.go b/x/perp/keeper/msg_server_test.go index b560c1a2e..7392a0a11 100644 --- a/x/perp/keeper/msg_server_test.go +++ b/x/perp/keeper/msg_server_test.go @@ -219,9 +219,9 @@ func TestMsgServerLiquidate(t *testing.T) { t.Log("set pricefeed oracle price") oracle := sample.AccAddress() app.PricefeedKeeper.WhitelistOracles(ctx, []sdk.AccAddress{oracle}) - _, err = app.PricefeedKeeper.SetPrice(ctx, oracle, pair.String(), sdk.OneDec(), time.Now().Add(time.Hour)) + _, err = app.PricefeedKeeper.PostRawPrice(ctx, oracle, pair.String(), sdk.OneDec(), time.Now().Add(time.Hour)) require.NoError(t, err) - require.NoError(t, app.PricefeedKeeper.SetCurrentPrices(ctx, pair.GetBaseTokenDenom(), pair.GetQuoteTokenDenom())) + require.NoError(t, app.PricefeedKeeper.GatherRawPrices(ctx, pair.GetBaseTokenDenom(), pair.GetQuoteTokenDenom())) t.Log("create position") require.NoError(t, app.PerpKeeper.PositionsState(ctx).Create(&types.Position{ diff --git a/x/perp/types/expected_keepers.go b/x/perp/types/expected_keepers.go index 2635a8508..262111cab 100644 --- a/x/perp/types/expected_keepers.go +++ b/x/perp/types/expected_keepers.go @@ -49,6 +49,17 @@ type BankKeeper interface { } type PricefeedKeeper interface { + /* GetCurrentPrice fetches the current median price of all oracles for a specific market. + + args: + - ctx: cosmos-sdk context + - token0: the base asset + - token1: the quote asset + + ret: + - currPrice: the current price + - err: error if any + */ GetCurrentPrice(ctx sdk.Context, token0 string, token1 string, ) (pftypes.CurrentPrice, error) GetCurrentPrices(ctx sdk.Context) pftypes.CurrentPrices @@ -59,8 +70,19 @@ type PricefeedKeeper interface { IsWhitelistedOracle(ctx sdk.Context, pairID string, address sdk.AccAddress, ) bool GetOraclesForPair(ctx sdk.Context, pairID string) (oracles []sdk.AccAddress) - SetCurrentPrices(ctx sdk.Context, token0 string, token1 string) error - GetCurrentTWAPPrice(ctx sdk.Context, token0 string, token1 string) (pftypes.CurrentTWAP, error) + + /* GatherRawPrices updates the current price of an asset to the median of all valid posted oracle prices. + + args: + - ctx: cosmos-sdk context + - token0: the base asset + - token1: the quote asset + + ret: + - err: error if any + */ + GatherRawPrices(ctx sdk.Context, token0 string, token1 string) error + GetCurrentTWAP(ctx sdk.Context, token0 string, token1 string) (pftypes.CurrentTWAP, error) } type VpoolKeeper interface { @@ -238,8 +260,8 @@ type VpoolKeeper interface { ExistsPool(ctx sdk.Context, pair common.AssetPair) bool GetSettlementPrice(ctx sdk.Context, pair common.AssetPair) (sdk.Dec, error) - // GetCurrentTWAPPrice fetches the TWAP for the specified token pair / pool - GetCurrentTWAPPrice(ctx sdk.Context, pair common.AssetPair) (vpooltypes.CurrentTWAP, error) + // GetCurrentTWAP fetches the TWAP for the specified token pair / pool + GetCurrentTWAP(ctx sdk.Context, pair common.AssetPair) (vpooltypes.CurrentTWAP, error) } type EpochKeeper interface { diff --git a/x/pricefeed/abci.go b/x/pricefeed/abci.go index e40268e64..5feaddfba 100644 --- a/x/pricefeed/abci.go +++ b/x/pricefeed/abci.go @@ -17,7 +17,7 @@ func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { continue } - err := k.SetCurrentPrices(ctx, pair.Token0, pair.Token1) + err := k.GatherRawPrices(ctx, pair.Token0, pair.Token1) if err != nil && !errors.Is(err, types.ErrNoValidPrice) { panic(err) } diff --git a/x/pricefeed/abci_test.go b/x/pricefeed/abci_test.go index c7bf7513f..59fff1920 100644 --- a/x/pricefeed/abci_test.go +++ b/x/pricefeed/abci_test.go @@ -32,7 +32,7 @@ func TestTWAPriceUpdates(t *testing.T) { pricefeed.BeginBlocker(ctx, nibiruApp.PricefeedKeeper) } setPrice := func(price string) { - _, err := nibiruApp.PricefeedKeeper.SetPrice( + _, err := nibiruApp.PricefeedKeeper.PostRawPrice( ctx, oracle, pair.String(), sdk.MustNewDecFromStr(price), ctx.BlockTime().Add(time.Hour*5000*4)) require.NoError(t, err) @@ -68,7 +68,7 @@ func TestTWAPriceUpdates(t *testing.T) { (0.9 * 1463385600 + (0.9 + 0.8) / 2 * 1481385600) / (1463385600 + 1481385600) = 0.8749844622444971 */ - price, err := nibiruApp.PricefeedKeeper.GetCurrentTWAPPrice( + price, err := nibiruApp.PricefeedKeeper.GetCurrentTWAP( ctx, pair.Token0, pair.Token1) require.NoError(t, err) priceFloat, err := price.Price.Float64() @@ -88,7 +88,7 @@ func TestTWAPriceUpdates(t *testing.T) { (0.9 * 1463385600 + (0.9 + 0.8) / 2 * 1481385600 + 0.82 * 1499385600) / (1463385600 + 1481385600 + 1499385600) = 0.8563426456960295 */ - price, err = nibiruApp.PricefeedKeeper.GetCurrentTWAPPrice( + price, err = nibiruApp.PricefeedKeeper.GetCurrentTWAP( ctx, pair.Token0, pair.Token1) require.NoError(t, err) priceFloat, err = price.Price.Float64() @@ -108,7 +108,7 @@ func TestTWAPriceUpdates(t *testing.T) { */ setPrice("0.83") runBlock(time.Hour * 5000) - price, err = nibiruApp.PricefeedKeeper.GetCurrentTWAPPrice( + price, err = nibiruApp.PricefeedKeeper.GetCurrentTWAP( ctx, pair.Token0, pair.Token1) require.NoError(t, err) diff --git a/x/pricefeed/client/cli/cli_test.go b/x/pricefeed/client/cli/cli_test.go index 6507a2ed6..e4d9b0d99 100644 --- a/x/pricefeed/client/cli/cli_test.go +++ b/x/pricefeed/client/cli/cli_test.go @@ -8,21 +8,19 @@ import ( "testing" "time" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" + simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdktestutil "github.com/cosmos/cosmos-sdk/testutil" sdktestutilcli "github.com/cosmos/cosmos-sdk/testutil/cli" sdk "github.com/cosmos/cosmos-sdk/types" + govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/gogo/protobuf/proto" "github.com/stretchr/testify/suite" tmcli "github.com/tendermint/tendermint/libs/cli" - govcli "github.com/cosmos/cosmos-sdk/x/gov/client/cli" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/NibiruChain/nibiru/app" "github.com/NibiruChain/nibiru/x/common" "github.com/NibiruChain/nibiru/x/pricefeed/client/cli" diff --git a/x/pricefeed/genesis.go b/x/pricefeed/genesis.go index 00358f759..5712b5c5f 100644 --- a/x/pricefeed/genesis.go +++ b/x/pricefeed/genesis.go @@ -22,7 +22,7 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) for _, pp := range genState.PostedPrices { if pp.Expiry.After(ctx.BlockTime()) { oracle := sdk.MustAccAddressFromBech32(pp.Oracle) - _, err := k.SetPrice(ctx, oracle, pp.PairID, pp.Price, pp.Expiry) + _, err := k.PostRawPrice(ctx, oracle, pp.PairID, pp.Price, pp.Expiry) if err != nil { panic(err) } @@ -42,7 +42,7 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) if len(postedPrices) == 0 { continue } - err := k.SetCurrentPrices(ctx, pair.Token0, pair.Token1) + err := k.GatherRawPrices(ctx, pair.Token0, pair.Token1) if err != nil { panic(err) } diff --git a/x/pricefeed/keeper/keeper.go b/x/pricefeed/keeper/keeper.go index 012e74edc..322a37e5c 100644 --- a/x/pricefeed/keeper/keeper.go +++ b/x/pricefeed/keeper/keeper.go @@ -51,8 +51,8 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) } -// SetPrice updates the posted price for a specific oracle -func (k Keeper) SetPrice( +// PostRawPrice updates the posted price for a specific oracle +func (k Keeper) PostRawPrice( ctx sdk.Context, oracle sdk.AccAddress, pairStr string, @@ -104,8 +104,18 @@ func (k Keeper) SetPrice( return newPostedPrice, nil } -// SetCurrentPrices updates the price of an asset to the median of all valid oracle inputs -func (k Keeper) SetCurrentPrices(ctx sdk.Context, token0 string, token1 string) error { +/* +GatherRawPrices updates the current price of an asset to the median of all valid posted oracle prices. + +args: + - ctx: cosmos-sdk context + - token0: the base asset + - token1: the quote asset + +ret: + - err: error if any +*/ +func (k Keeper) GatherRawPrices(ctx sdk.Context, token0 string, token1 string) error { assetPair := common.AssetPair{Token0: token0, Token1: token1} pairID := assetPair.String() @@ -158,7 +168,7 @@ func (k Keeper) SetCurrentPrices(ctx sdk.Context, token0 string, token1 string) k.setCurrentPrice(ctx, pairID, currentPrice) // Update the TWA prices - err = k.updateTWAPPrice(ctx, pairID) + err = k.updateTWAP(ctx, pairID) if err != nil { return err } @@ -171,7 +181,7 @@ func (k Keeper) setCurrentPrice(ctx sdk.Context, pairID string, currentPrice typ store.Set(types.CurrentPriceKey(pairID), k.cdc.MustMarshal(¤tPrice)) } -/* updateTWAPPrice updates the twap price for a token0, token1 pair +/* updateTWAP updates the twap price for a token0, token1 pair We use the blocktime to update the twap price. Calculation is done as follow: @@ -182,7 +192,7 @@ With */ -func (k Keeper) updateTWAPPrice(ctx sdk.Context, pairID string) error { +func (k Keeper) updateTWAP(ctx sdk.Context, pairID string) error { tokens := common.DenomsFromPoolName(pairID) token0, token1 := tokens[0], tokens[1] @@ -191,7 +201,7 @@ func (k Keeper) updateTWAPPrice(ctx sdk.Context, pairID string) error { return err } - currentTWAP, err := k.GetCurrentTWAPPrice(ctx, token0, token1) + currentTWAP, err := k.GetCurrentTWAP(ctx, token0, token1) // Err there means no twap price have been set yet for this pair if err != nil { currentTWAP = types.CurrentTWAP{ @@ -214,7 +224,7 @@ func (k Keeper) updateTWAPPrice(ctx sdk.Context, pairID string) error { Price: newNumerator.Quo(newDenominator), } store := ctx.KVStore(k.storeKey) - store.Set(types.CurrentTWAPPriceKey("twap-"+pairID), k.cdc.MustMarshal(&newTWAP)) + store.Set(types.CurrentTWAPKey("twap-"+pairID), k.cdc.MustMarshal(&newTWAP)) return nil } @@ -246,7 +256,18 @@ func (k Keeper) calculateMeanPrice(priceA, priceB types.CurrentPrice) sdk.Dec { return mean } -// GetCurrentPrice fetches the current median price of all oracles for a specific market +/* +GetCurrentPrice fetches the current median price of all oracles for a specific market. + +args: + - ctx: cosmos-sdk context + - token0: the base asset + - token1: the quote asset + +ret: + - currPrice: the current price + - err: error if any +*/ func (k Keeper) GetCurrentPrice(ctx sdk.Context, token0 string, token1 string, ) (currPrice types.CurrentPrice, err error) { pair := common.AssetPair{Token0: token0, Token1: token1} @@ -280,8 +301,8 @@ func (k Keeper) GetCurrentPrice(ctx sdk.Context, token0 string, token1 string, return price, nil } -// GetCurrentTWAPPrice fetches the current median price of all oracles for a specific market -func (k Keeper) GetCurrentTWAPPrice(ctx sdk.Context, token0 string, token1 string) (currPrice types.CurrentTWAP, err error) { +// GetCurrentTWAP fetches the current median price of all oracles for a specific market +func (k Keeper) GetCurrentTWAP(ctx sdk.Context, token0 string, token1 string) (currPrice types.CurrentTWAP, err error) { pair := common.AssetPair{Token0: token0, Token1: token1} givenIsActive := k.IsActivePair(ctx, pair.String()) inverseIsActive := k.IsActivePair(ctx, pair.Inverse().String()) @@ -296,7 +317,7 @@ func (k Keeper) GetCurrentTWAPPrice(ctx sdk.Context, token0 string, token1 strin } store := ctx.KVStore(k.storeKey) - bz := store.Get(types.CurrentTWAPPriceKey("twap-" + pair.String())) + bz := store.Get(types.CurrentTWAPKey("twap-" + pair.String())) if bz == nil { return types.CurrentTWAP{}, types.ErrNoValidTWAP diff --git a/x/pricefeed/keeper/keeper_test.go b/x/pricefeed/keeper/keeper_test.go index 0657eace2..5353658c7 100644 --- a/x/pricefeed/keeper/keeper_test.go +++ b/x/pricefeed/keeper/keeper_test.go @@ -42,7 +42,7 @@ func TestKeeper_SetGetPair(t *testing.T) { require.False(t, keeper.IsActivePair(ctx, "nan:nan")) } -func TestKeeper_GetSetPrice(t *testing.T) { +func TestKeeper_GetPostRawPrice(t *testing.T) { app, ctx := testapp.NewNibiruAppAndContext(true) keeper := app.PricefeedKeeper @@ -65,7 +65,7 @@ func TestKeeper_GetSetPrice(t *testing.T) { for _, priceInfo := range priceInfos { // Set price by oracle 1 - pp, err := keeper.SetPrice( + pp, err := keeper.PostRawPrice( ctx, priceInfo.oracle, priceInfo.pairStr, @@ -96,7 +96,7 @@ func TestKeeper_GetSetPrice(t *testing.T) { Test case where two oracles try to set prices for a market and only one of the oracles is valid (i.e. registered with keeper.SetParams). */ -func TestKeeper_SetPriceWrongOracle(t *testing.T) { +func TestKeeper_PostRawPriceWrongOracle(t *testing.T) { app, ctx := testapp.NewNibiruAppAndContext(true) keeper := app.PricefeedKeeper pair := common.MustNewAssetPair("tst:usd") @@ -112,13 +112,13 @@ func TestKeeper_SetPriceWrongOracle(t *testing.T) { // Set price with valid oracle given (addrs[0]) keeper.WhitelistOracles(ctx, []sdk.AccAddress{addrs[0]}) expiry := ctx.BlockTime().UTC().Add(1 * time.Hour) - _, err := keeper.SetPrice( + _, err := keeper.PostRawPrice( ctx, addrs[0], pair.String(), price, expiry, ) require.NoError(t, err) // Set price with invalid oracle given (addrs[1]) - _, err = keeper.SetPrice( + _, err = keeper.PostRawPrice( ctx, addrs[1], pair.String(), price, expiry, ) require.Error(t, err) @@ -128,7 +128,7 @@ func TestKeeper_SetPriceWrongOracle(t *testing.T) { Test case where several oracles try to set prices for a market and "k" (int) of the oracles are valid (i.e. registered with keeper.SetParams). */ -func TestKeeper_SetPriceWrongOracles(t *testing.T) { +func TestKeeper_PostRawPriceWrongOracles(t *testing.T) { app, ctx := testapp.NewNibiruAppAndContext(true) keeper := app.PricefeedKeeper @@ -145,13 +145,13 @@ func TestKeeper_SetPriceWrongOracles(t *testing.T) { for i, addr := range addrs { if i < 5 { // Valid oracle addresses. This shouldn't raise an error. - _, err := keeper.SetPrice( + _, err := keeper.PostRawPrice( ctx, addr, pair.String(), price, time.Now().UTC().Add(1*time.Hour), ) require.NoError(t, err) } else { // Invalid oracle addresses. This should raise errors. - _, err := keeper.SetPrice( + _, err := keeper.PostRawPrice( ctx, addr, pair.String(), price, time.Now().UTC().Add(1*time.Hour), ) require.Error(t, err) @@ -173,33 +173,33 @@ func TestKeeper_GetSetCurrentPrice(t *testing.T) { keeper.OraclesStore().AddOracles(ctx, pair, addrs) keeper.SetParams(ctx, params) - _, err := keeper.SetPrice( + _, err := keeper.PostRawPrice( ctx, addrs[0], pair.String(), sdk.MustNewDecFromStr("0.33"), time.Now().Add(time.Hour*1)) require.NoError(t, err) - _, err = keeper.SetPrice( + _, err = keeper.PostRawPrice( ctx, addrs[1], pair.String(), sdk.MustNewDecFromStr("0.35"), time.Now().Add(time.Hour*1)) require.NoError(t, err) - _, err = keeper.SetPrice( + _, err = keeper.PostRawPrice( ctx, addrs[2], pair.String(), sdk.MustNewDecFromStr("0.34"), time.Now().Add(time.Hour*1)) require.NoError(t, err) t.Log("Add an expired one which should fail") - _, err = keeper.SetPrice( + _, err = keeper.PostRawPrice( ctx, addrs[3], pair.String(), sdk.MustNewDecFromStr("0.9"), ctx.BlockTime().Add(-time.Hour*1)) require.Error(t, err) t.Log("Add a non-expired price, but will not be counted when BlockTime is changed") - _, err = keeper.SetPrice( + _, err = keeper.PostRawPrice( ctx, addrs[3], pair.String(), sdk.MustNewDecFromStr("0.9"), time.Now().Add(time.Minute*30)) @@ -209,7 +209,7 @@ func TestKeeper_GetSetCurrentPrice(t *testing.T) { ctx = ctx.WithBlockTime(time.Now().Add(time.Minute * 45)) // Set current price - err = keeper.SetCurrentPrices(ctx, token0, token1) + err = keeper.GatherRawPrices(ctx, token0, token1) require.NoError(t, err) // Get current price @@ -225,13 +225,13 @@ func TestKeeper_GetSetCurrentPrice(t *testing.T) { ) // Even number of oracles - _, err = keeper.SetPrice( + _, err = keeper.PostRawPrice( ctx, addrs[4], pair.String(), sdk.MustNewDecFromStr("0.36"), time.Now().Add(time.Hour*1)) require.NoError(t, err) - err = keeper.SetCurrentPrices(ctx, token0, token1) + err = keeper.GatherRawPrices(ctx, token0, token1) require.NoError(t, err) price, err = keeper.GetCurrentPrice(ctx, "tst", "usd") @@ -249,7 +249,7 @@ func TestKeeper_GetSetCurrentPrice(t *testing.T) { require.Equal(t, price, prices[0]) } -func TestKeeper_ExpiredSetCurrentPrices(t *testing.T) { +func TestKeeper_ExpiredGatherRawPrices(t *testing.T) { _, oracles := sample.PrivKeyAddressPairs(5) app, ctx := testapp.NewNibiruAppAndContext(true) keeper := app.PricefeedKeeper @@ -262,19 +262,19 @@ func TestKeeper_ExpiredSetCurrentPrices(t *testing.T) { keeper.SetParams(ctx, params) keeper.OraclesStore().AddOracles(ctx, pair, oracles) - _, err := keeper.SetPrice( + _, err := keeper.PostRawPrice( ctx, oracles[0], pair.String(), sdk.MustNewDecFromStr("0.33"), time.Now().Add(time.Hour*1)) require.NoError(t, err) - _, err = keeper.SetPrice( + _, err = keeper.PostRawPrice( ctx, oracles[1], pair.String(), sdk.MustNewDecFromStr("0.35"), time.Now().Add(time.Hour*1)) require.NoError(t, err) - _, err = keeper.SetPrice( + _, err = keeper.PostRawPrice( ctx, oracles[2], pair.String(), sdk.MustNewDecFromStr("0.34"), time.Now().Add(time.Hour*1)) @@ -283,7 +283,7 @@ func TestKeeper_ExpiredSetCurrentPrices(t *testing.T) { // Update block time such that all prices expire ctx = ctx.WithBlockTime(time.Now().UTC().Add(time.Hour * 2)) - err = keeper.SetCurrentPrices(ctx, token0, token1) + err = keeper.GatherRawPrices(ctx, token0, token1) require.ErrorContains(t, err, "input prices are expired") _, err = keeper.GetCurrentPrice(ctx, token0, token1) diff --git a/x/pricefeed/keeper/msg_server.go b/x/pricefeed/keeper/msg_server.go index bb35dddc2..bb3070220 100644 --- a/x/pricefeed/keeper/msg_server.go +++ b/x/pricefeed/keeper/msg_server.go @@ -55,7 +55,7 @@ func (k msgServer) PostPrice(goCtx context.Context, msg *types.MsgPostPrice, postedPrice = msg.Price } - _, err = k.SetPrice(ctx, from, pair.String(), postedPrice, msg.Expiry) + _, err = k.PostRawPrice(ctx, from, pair.String(), postedPrice, msg.Expiry) if err != nil { return nil, err } diff --git a/x/pricefeed/types/keys.go b/x/pricefeed/types/keys.go index 5153bfbc9..ec897d36c 100644 --- a/x/pricefeed/types/keys.go +++ b/x/pricefeed/types/keys.go @@ -30,8 +30,8 @@ var ( // RawPriceFeedPrefix prefix for the raw pricefeed of an asset RawPriceFeedPrefix = []byte{0x01} - // TWAPPricePrefix prefix for the current price of an asset - TWAPPricePrefix = []byte{0x02} + // TWAPPrefix prefix for the current price of an asset + TWAPPrefix = []byte{0x02} ) // CurrentPriceKey returns the prefix for the current price @@ -39,9 +39,9 @@ func CurrentPriceKey(pairID string) []byte { return append(CurrentPricePrefix, []byte(pairID)...) } -// CurrentTWAPPriceKey returns the prefix for the current TWAP price -func CurrentTWAPPriceKey(twapPairID string) []byte { - return append(TWAPPricePrefix, []byte(twapPairID)...) +// CurrentTWAPKey returns the prefix for the current TWAP price +func CurrentTWAPKey(twapPairID string) []byte { + return append(TWAPPrefix, []byte(twapPairID)...) } // RawPriceIteratorKey returns the prefix for the raw price for a single market diff --git a/x/stablecoin/abci.go b/x/stablecoin/abci.go index 0e29ea7d4..82e0122e8 100644 --- a/x/stablecoin/abci.go +++ b/x/stablecoin/abci.go @@ -19,7 +19,7 @@ func EndBlocker(ctx sdk.Context, k keeper.Keeper) { k.SetParams(ctx, params) } - _, err := k.PricefeedKeeper.GetCurrentTWAPPrice(ctx, common.DenomStable, common.DenomColl) + _, err := k.PricefeedKeeper.GetCurrentTWAP(ctx, common.DenomStable, common.DenomColl) if err != nil { params := k.GetParams(ctx) params.IsCollateralRatioValid = false diff --git a/x/stablecoin/abci_test.go b/x/stablecoin/abci_test.go index 98f2d0816..dcf7b744e 100644 --- a/x/stablecoin/abci_test.go +++ b/x/stablecoin/abci_test.go @@ -120,7 +120,7 @@ func TestEpochInfoChangesBeginBlockerAndInitGenesis(t *testing.T) { app.PricefeedKeeper.SetParams(ctx, markets) app.PricefeedKeeper.WhitelistOracles(ctx, []sdk.AccAddress{oracle}) - _, err := app.PricefeedKeeper.SetPrice( + _, err := app.PricefeedKeeper.PostRawPrice( ctx, oracle, pairs[0].String(), @@ -128,7 +128,7 @@ func TestEpochInfoChangesBeginBlockerAndInitGenesis(t *testing.T) { /* expiry */ ctx.BlockTime().UTC().Add(time.Hour*1)) require.NoError(t, err) - err = app.PricefeedKeeper.SetCurrentPrices(ctx, pairs[0].Token0, pairs[0].Token1) + err = app.PricefeedKeeper.GatherRawPrices(ctx, pairs[0].Token0, pairs[0].Token1) require.NoError(t, err) err = app.StablecoinKeeper.SetCollRatio(ctx, tc.InCollRatio) @@ -166,10 +166,10 @@ func TestEpochInfoChangesCollateralValidity(t *testing.T) { app.PricefeedKeeper.SetParams(ctx, markets) // Sim set price set the price for one hour - _, err := app.PricefeedKeeper.SetPrice( + _, err := app.PricefeedKeeper.PostRawPrice( ctx, oracle, pairs[0].String(), sdk.MustNewDecFromStr("0.9"), ctx.BlockTime().Add(time.Hour)) require.NoError(t, err) - require.NoError(t, app.PricefeedKeeper.SetCurrentPrices(ctx, pairs[0].Token0, pairs[0].Token1)) + require.NoError(t, app.PricefeedKeeper.GatherRawPrices(ctx, pairs[0].Token0, pairs[0].Token1)) require.NoError(t, app.StablecoinKeeper.SetCollRatio(ctx, sdk.MustNewDecFromStr("0.8"))) // Mint block #2 @@ -181,7 +181,7 @@ func TestEpochInfoChangesCollateralValidity(t *testing.T) { require.False(t, app.StablecoinKeeper.GetParams(ctx).IsCollateralRatioValid) // Post price, collateral should be valid again - _, err = app.PricefeedKeeper.SetPrice( + _, err = app.PricefeedKeeper.PostRawPrice( ctx, oracle, pairs[0].String(), sdk.MustNewDecFromStr("0.9"), ctx.BlockTime().UTC().Add(time.Hour)) require.NoError(t, err) diff --git a/x/stablecoin/keeper/collateral_ratio.go b/x/stablecoin/keeper/collateral_ratio.go index 908309ce1..58945d87e 100644 --- a/x/stablecoin/keeper/collateral_ratio.go +++ b/x/stablecoin/keeper/collateral_ratio.go @@ -86,7 +86,7 @@ func (k *Keeper) EvaluateCollRatio(ctx sdk.Context) (err error) { upperBound := params.GetPriceUpperBoundAsDec() // Should take TWAP price - stablePrice, err := k.PricefeedKeeper.GetCurrentTWAPPrice( + stablePrice, err := k.PricefeedKeeper.GetCurrentTWAP( ctx, common.DenomStable, common.DenomColl) if err != nil { return err diff --git a/x/stablecoin/keeper/collateral_ratio_test.go b/x/stablecoin/keeper/collateral_ratio_test.go index 311cdd6b1..8254932a0 100644 --- a/x/stablecoin/keeper/collateral_ratio_test.go +++ b/x/stablecoin/keeper/collateral_ratio_test.go @@ -96,7 +96,7 @@ func TestSetCollRatioUpdate(t *testing.T) { err := stablecoinKeeper.SetCollRatio(ctx, tc.inCollRatio) require.NoError(t, err) - _, err = priceKeeper.SetPrice( + _, err = priceKeeper.PostRawPrice( ctx, oracle, /* pairStr */ pair.String(), @@ -104,7 +104,7 @@ func TestSetCollRatioUpdate(t *testing.T) { /* expiry */ ctx.BlockTime().UTC().Add(time.Hour*1)) require.NoError(t, err) - err = priceKeeper.SetCurrentPrices(ctx, common.DenomColl, common.DenomStable) + err = priceKeeper.GatherRawPrices(ctx, common.DenomColl, common.DenomStable) require.NoError(t, err) err = stablecoinKeeper.EvaluateCollRatio(ctx) @@ -260,12 +260,12 @@ func TestStableRequiredForTargetCollRatio(t *testing.T) { common.PairCollStable: tc.priceCollStable, } for _, pair := range tc.postedAssetPairs { - _, err := nibiruApp.PricefeedKeeper.SetPrice( + _, err := nibiruApp.PricefeedKeeper.PostRawPrice( ctx, oracle, pair.String(), prices[pair], priceExpiry) require.NoError(t, err) // Update the 'CurrentPrice' posted by the oracles. - err = nibiruApp.PricefeedKeeper.SetCurrentPrices(ctx, pair.Token0, pair.Token1) + err = nibiruApp.PricefeedKeeper.GatherRawPrices(ctx, pair.Token0, pair.Token1) require.NoError(t, err, "Error posting price for pair: %d", pair.String()) } @@ -347,13 +347,13 @@ func TestRecollateralizeCollAmtForTargetCollRatio(t *testing.T) { ctx, pair, []sdk.AccAddress{oracle}) // Post prices to each market with the oracle. - _, err := nibiruApp.PricefeedKeeper.SetPrice( + _, err := nibiruApp.PricefeedKeeper.PostRawPrice( ctx, oracle, pair.String(), tc.priceCollStable, priceExpiry) require.NoError(t, err) // Update the 'CurrentPrice' posted by the oracles. for _, pfPair := range pricefeedParams.Pairs { - err = nibiruApp.PricefeedKeeper.SetCurrentPrices(ctx, pfPair.Token0, pfPair.Token1) + err = nibiruApp.PricefeedKeeper.GatherRawPrices(ctx, pfPair.Token0, pfPair.Token1) require.NoError(t, err, "Error posting price for market: %d", pfPair.String()) } @@ -537,12 +537,12 @@ func TestGovAmtFromFullRecollateralize(t *testing.T) { common.PairCollStable: tc.priceCollStable, } for _, pair := range tc.postedAssetPairs { - _, err := nibiruApp.PricefeedKeeper.SetPrice( + _, err := nibiruApp.PricefeedKeeper.PostRawPrice( ctx, oracle, pair.String(), prices[pair], priceExpiry) require.NoError(t, err) // Update the 'CurrentPrice' posted by the oracles. - err = nibiruApp.PricefeedKeeper.SetCurrentPrices(ctx, pair.Token0, pair.Token1) + err = nibiruApp.PricefeedKeeper.GatherRawPrices(ctx, pair.Token0, pair.Token1) require.NoError(t, err, "Error posting price for pair: %d", pair.String()) } @@ -552,13 +552,13 @@ func TestGovAmtFromFullRecollateralize(t *testing.T) { common.PairGovStable: tc.priceGovStable, } for _, assetPair := range tc.postedAssetPairs { - _, err := nibiruApp.PricefeedKeeper.SetPrice( + _, err := nibiruApp.PricefeedKeeper.PostRawPrice( ctx, oracle, assetPair.String(), prices[assetPair], priceExpiry) require.NoError(t, err) // Update the 'CurrentPrice' posted by the oracles. - err = nibiruApp.PricefeedKeeper.SetCurrentPrices( + err = nibiruApp.PricefeedKeeper.GatherRawPrices( ctx, assetPair.Token0, assetPair.Token1) require.NoError( t, err, "Error posting price for pair: %d", assetPair.String()) @@ -824,12 +824,12 @@ func TestRecollateralize(t *testing.T) { common.PairCollStable: tc.scenario.priceCollStable, } for _, pair := range tc.postedAssetPairs { - _, err := nibiruApp.PricefeedKeeper.SetPrice( + _, err := nibiruApp.PricefeedKeeper.PostRawPrice( ctx, oracle, pair.String(), prices[pair], priceExpiry) require.NoError(t, err) // Update the 'CurrentPrice' posted by the oracles. - err = nibiruApp.PricefeedKeeper.SetCurrentPrices(ctx, pair.Token0, pair.Token1) + err = nibiruApp.PricefeedKeeper.GatherRawPrices(ctx, pair.Token0, pair.Token1) require.NoError(t, err, "Error posting price for pair: %d", pair.String()) } @@ -839,13 +839,13 @@ func TestRecollateralize(t *testing.T) { common.PairGovStable: tc.priceGovStable, } for _, assetPair := range tc.postedAssetPairs { - _, err := nibiruApp.PricefeedKeeper.SetPrice( + _, err := nibiruApp.PricefeedKeeper.PostRawPrice( ctx, oracle, assetPair.String(), prices[assetPair], priceExpiry) require.NoError(t, err) // Update the 'CurrentPrice' posted by the oracles. - err = nibiruApp.PricefeedKeeper.SetCurrentPrices( + err = nibiruApp.PricefeedKeeper.GatherRawPrices( ctx, assetPair.Token0, assetPair.Token1) require.NoError( t, err, "Error posting price for pair: %d", assetPair.String()) @@ -1222,24 +1222,24 @@ func TestBuyback(t *testing.T) { common.PairCollStable: tc.scenario.priceCollStable, } for _, pair := range tc.postedAssetPairs { - _, err := nibiruApp.PricefeedKeeper.SetPrice( + _, err := nibiruApp.PricefeedKeeper.PostRawPrice( ctx, oracle, pair.String(), prices[pair], priceExpiry) require.NoError(t, err) // Update the 'CurrentPrice' posted by the oracles. - err = nibiruApp.PricefeedKeeper.SetCurrentPrices(ctx, pair.Token0, pair.Token1) + err = nibiruApp.PricefeedKeeper.GatherRawPrices(ctx, pair.Token0, pair.Token1) require.NoError(t, err, "Error posting price for pair: %d", pair.String()) } // Post prices to each specified market with the oracle. for _, assetPair := range tc.postedAssetPairs { - _, err := nibiruApp.PricefeedKeeper.SetPrice( + _, err := nibiruApp.PricefeedKeeper.PostRawPrice( ctx, oracle, assetPair.String(), prices[assetPair], priceExpiry) require.NoError(t, err) // Update the 'CurrentPrice' posted by the oracles. - err = nibiruApp.PricefeedKeeper.SetCurrentPrices( + err = nibiruApp.PricefeedKeeper.GatherRawPrices( ctx, assetPair.Token0, assetPair.Token1) require.NoError( t, err, "Error posting price for pair: %d", assetPair.String()) @@ -1350,24 +1350,24 @@ func TestBuybackGovAmtForTargetCollRatio(t *testing.T) { common.PairCollStable: tc.scenario.priceCollStable, } for _, pair := range tc.postedAssetPairs { - _, err := nibiruApp.PricefeedKeeper.SetPrice( + _, err := nibiruApp.PricefeedKeeper.PostRawPrice( ctx, oracle, pair.String(), prices[pair], priceExpiry) require.NoError(t, err) // Update the 'CurrentPrice' posted by the oracles. - err = nibiruApp.PricefeedKeeper.SetCurrentPrices(ctx, pair.Token0, pair.Token1) + err = nibiruApp.PricefeedKeeper.GatherRawPrices(ctx, pair.Token0, pair.Token1) require.NoError(t, err, "Error posting price for pair: %d", pair.String()) } // Post prices to each specified market with the oracle. for _, assetPair := range tc.postedAssetPairs { - _, err := nibiruApp.PricefeedKeeper.SetPrice( + _, err := nibiruApp.PricefeedKeeper.PostRawPrice( ctx, oracle, assetPair.String(), prices[assetPair], priceExpiry) require.NoError(t, err) // Update the 'CurrentPrice' posted by the oracles. - err = nibiruApp.PricefeedKeeper.SetCurrentPrices( + err = nibiruApp.PricefeedKeeper.GatherRawPrices( ctx, assetPair.Token0, assetPair.Token1) require.NoError( t, err, "Error posting price for pair: %d", assetPair.String()) diff --git a/x/stablecoin/keeper/mint_burn_stable_test.go b/x/stablecoin/keeper/mint_burn_stable_test.go index bfb23a0bd..27c5467d4 100644 --- a/x/stablecoin/keeper/mint_burn_stable_test.go +++ b/x/stablecoin/keeper/mint_burn_stable_test.go @@ -155,18 +155,18 @@ func TestMsgMintStableResponse_HappyPath(t *testing.T) { // Post prices to each pair with the oracle. priceExpiry := ctx.BlockTime().Add(time.Hour) - _, err := priceKeeper.SetPrice( + _, err := priceKeeper.PostRawPrice( ctx, oracle, common.PairGovStable.String(), tc.govPrice, priceExpiry, ) require.NoError(t, err) - _, err = priceKeeper.SetPrice( + _, err = priceKeeper.PostRawPrice( ctx, oracle, common.PairCollStable.String(), tc.collPrice, priceExpiry, ) require.NoError(t, err) // Update the 'CurrentPrice' posted by the oracles. for _, pair := range pfParams.Pairs { - err = priceKeeper.SetCurrentPrices(ctx, pair.Token0, pair.Token1) + err = priceKeeper.GatherRawPrices(ctx, pair.Token0, pair.Token1) require.NoError(t, err, "Error posting price for pair: %d", pair.String()) } @@ -337,18 +337,18 @@ func TestMsgMintStableResponse_NotEnoughFunds(t *testing.T) { t.Log("Post prices to each pair with the oracle.") priceExpiry := ctx.BlockTime().Add(time.Hour) - _, err := priceKeeper.SetPrice( + _, err := priceKeeper.PostRawPrice( ctx, oracle, common.PairGovStable.String(), tc.govPrice, priceExpiry, ) require.NoError(t, err) - _, err = priceKeeper.SetPrice( + _, err = priceKeeper.PostRawPrice( ctx, oracle, common.PairCollStable.String(), tc.collPrice, priceExpiry, ) require.NoError(t, err) // Update the 'CurrentPrice' posted by the oracles. for _, pair := range pfParams.Pairs { - err = priceKeeper.SetCurrentPrices(ctx, pair.Token0, pair.Token1) + err = priceKeeper.GatherRawPrices(ctx, pair.Token0, pair.Token1) require.NoError(t, err, "Error posting price for pair: %d", pair.String()) } @@ -509,18 +509,18 @@ func TestMsgBurnResponse_NotEnoughFunds(t *testing.T) { t.Log("Post prices to each pair with the oracle.") priceExpiry := ctx.BlockTime().Add(time.Hour) - _, err := priceKeeper.SetPrice( + _, err := priceKeeper.PostRawPrice( ctx, oracle, common.PairGovStable.String(), tc.govPrice, priceExpiry, ) require.NoError(t, err) - _, err = priceKeeper.SetPrice( + _, err = priceKeeper.PostRawPrice( ctx, oracle, common.PairCollStable.String(), tc.collPrice, priceExpiry, ) require.NoError(t, err) // Update the 'CurrentPrice' posted by the oracles. for _, pair := range pfParams.Pairs { - err = priceKeeper.SetCurrentPrices(ctx, pair.Token0, pair.Token1) + err = priceKeeper.GatherRawPrices(ctx, pair.Token0, pair.Token1) require.NoError(t, err, "Error posting price for pair: %d", pair.String()) } @@ -660,18 +660,18 @@ func TestMsgBurnResponse_HappyPath(t *testing.T) { t.Log("Post prices to each pair with the oracle.") priceExpiry := ctx.BlockTime().Add(time.Hour) - _, err := priceKeeper.SetPrice( + _, err := priceKeeper.PostRawPrice( ctx, oracle, common.PairGovStable.String(), tc.govPrice, priceExpiry, ) require.NoError(t, err) - _, err = priceKeeper.SetPrice( + _, err = priceKeeper.PostRawPrice( ctx, oracle, common.PairCollStable.String(), tc.collPrice, priceExpiry, ) require.NoError(t, err) // Update the 'CurrentPrice' posted by the oracles. for _, pair := range pfParams.Pairs { - err = priceKeeper.SetCurrentPrices(ctx, pair.Token0, pair.Token1) + err = priceKeeper.GatherRawPrices(ctx, pair.Token0, pair.Token1) require.NoError(t, err, "Error posting price for pair: %d", pair.String()) } diff --git a/x/stablecoin/types/expected_keepers.go b/x/stablecoin/types/expected_keepers.go index c90ebc089..a8cca38d2 100644 --- a/x/stablecoin/types/expected_keepers.go +++ b/x/stablecoin/types/expected_keepers.go @@ -35,7 +35,7 @@ type BankKeeper interface { } type PricefeedKeeper interface { - GetCurrentTWAPPrice(ctx sdk.Context, token0 string, token1 string, + GetCurrentTWAP(ctx sdk.Context, token0 string, token1 string, ) (pftypes.CurrentTWAP, error) GetCurrentPrice(ctx sdk.Context, token0 string, token1 string, ) (pftypes.CurrentPrice, error) @@ -44,7 +44,7 @@ type PricefeedKeeper interface { IsWhitelistedOracle(ctx sdk.Context, pairID string, address sdk.AccAddress, ) bool GetOraclesForPair(ctx sdk.Context, pairID string) (oracles []sdk.AccAddress) - SetCurrentPrices(ctx sdk.Context, token0 string, token1 string) error + GatherRawPrices(ctx sdk.Context, token0 string, token1 string) error } type DexKeeper interface { diff --git a/x/testutil/mock/perp_interfaces.go b/x/testutil/mock/perp_interfaces.go index b86a40c2d..c01aedd17 100644 --- a/x/testutil/mock/perp_interfaces.go +++ b/x/testutil/mock/perp_interfaces.go @@ -240,6 +240,20 @@ func (m *MockPricefeedKeeper) EXPECT() *MockPricefeedKeeperMockRecorder { return m.recorder } +// GatherRawPrices mocks base method. +func (m *MockPricefeedKeeper) GatherRawPrices(arg0 types2.Context, arg1, arg2 string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GatherRawPrices", arg0, arg1, arg2) + ret0, _ := ret[0].(error) + return ret0 +} + +// GatherRawPrices indicates an expected call of GatherRawPrices. +func (mr *MockPricefeedKeeperMockRecorder) GatherRawPrices(arg0, arg1, arg2 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GatherRawPrices", reflect.TypeOf((*MockPricefeedKeeper)(nil).GatherRawPrices), arg0, arg1, arg2) +} + // GetCurrentPrice mocks base method. func (m *MockPricefeedKeeper) GetCurrentPrice(arg0 types2.Context, arg1, arg2 string) (types0.CurrentPrice, error) { m.ctrl.T.Helper() @@ -269,19 +283,19 @@ func (mr *MockPricefeedKeeperMockRecorder) GetCurrentPrices(arg0 interface{}) *g return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentPrices", reflect.TypeOf((*MockPricefeedKeeper)(nil).GetCurrentPrices), arg0) } -// GetCurrentTWAPPrice mocks base method. -func (m *MockPricefeedKeeper) GetCurrentTWAPPrice(arg0 types2.Context, arg1, arg2 string) (types0.CurrentTWAP, error) { +// GetCurrentTWAP mocks base method. +func (m *MockPricefeedKeeper) GetCurrentTWAP(arg0 types2.Context, arg1, arg2 string) (types0.CurrentTWAP, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentTWAPPrice", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "GetCurrentTWAP", arg0, arg1, arg2) ret0, _ := ret[0].(types0.CurrentTWAP) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetCurrentTWAPPrice indicates an expected call of GetCurrentTWAPPrice. -func (mr *MockPricefeedKeeperMockRecorder) GetCurrentTWAPPrice(arg0, arg1, arg2 interface{}) *gomock.Call { +// GetCurrentTWAP indicates an expected call of GetCurrentTWAP. +func (mr *MockPricefeedKeeperMockRecorder) GetCurrentTWAP(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentTWAPPrice", reflect.TypeOf((*MockPricefeedKeeper)(nil).GetCurrentTWAPPrice), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentTWAP", reflect.TypeOf((*MockPricefeedKeeper)(nil).GetCurrentTWAP), arg0, arg1, arg2) } // GetOraclesForPair mocks base method. @@ -354,20 +368,6 @@ func (mr *MockPricefeedKeeperMockRecorder) IsWhitelistedOracle(arg0, arg1, arg2 return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsWhitelistedOracle", reflect.TypeOf((*MockPricefeedKeeper)(nil).IsWhitelistedOracle), arg0, arg1, arg2) } -// SetCurrentPrices mocks base method. -func (m *MockPricefeedKeeper) SetCurrentPrices(arg0 types2.Context, arg1, arg2 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetCurrentPrices", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// SetCurrentPrices indicates an expected call of SetCurrentPrices. -func (mr *MockPricefeedKeeperMockRecorder) SetCurrentPrices(arg0, arg1, arg2 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCurrentPrices", reflect.TypeOf((*MockPricefeedKeeper)(nil).SetCurrentPrices), arg0, arg1, arg2) -} - // MockVpoolKeeper is a mock of VpoolKeeper interface. type MockVpoolKeeper struct { ctrl *gomock.Controller @@ -435,19 +435,19 @@ func (mr *MockVpoolKeeperMockRecorder) GetBaseAssetTWAP(arg0, arg1, arg2, arg3, return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBaseAssetTWAP", reflect.TypeOf((*MockVpoolKeeper)(nil).GetBaseAssetTWAP), arg0, arg1, arg2, arg3, arg4) } -// GetCurrentTWAPPrice mocks base method. -func (m *MockVpoolKeeper) GetCurrentTWAPPrice(arg0 types2.Context, arg1 common.AssetPair) (types1.CurrentTWAP, error) { +// GetCurrentTWAP mocks base method. +func (m *MockVpoolKeeper) GetCurrentTWAP(arg0 types2.Context, arg1 common.AssetPair) (types1.CurrentTWAP, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentTWAPPrice", arg0, arg1) + ret := m.ctrl.Call(m, "GetCurrentTWAP", arg0, arg1) ret0, _ := ret[0].(types1.CurrentTWAP) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetCurrentTWAPPrice indicates an expected call of GetCurrentTWAPPrice. -func (mr *MockVpoolKeeperMockRecorder) GetCurrentTWAPPrice(arg0, arg1 interface{}) *gomock.Call { +// GetCurrentTWAP indicates an expected call of GetCurrentTWAP. +func (mr *MockVpoolKeeperMockRecorder) GetCurrentTWAP(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentTWAPPrice", reflect.TypeOf((*MockVpoolKeeper)(nil).GetCurrentTWAPPrice), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentTWAP", reflect.TypeOf((*MockVpoolKeeper)(nil).GetCurrentTWAP), arg0, arg1) } // GetQuoteAssetPrice mocks base method. diff --git a/x/vpool/keeper/prices.go b/x/vpool/keeper/prices.go index 9ddedc124..067fb0bf4 100644 --- a/x/vpool/keeper/prices.go +++ b/x/vpool/keeper/prices.go @@ -272,8 +272,8 @@ func (k Keeper) calcTwap( return cumulativePrice.QuoInt64(cumulativePeriodMs), nil } -// GetCurrentTWAPPrice fetches the current median price of all oracles for a specific market -func (k Keeper) GetCurrentTWAPPrice(ctx sdk.Context, pair common.AssetPair) (types.CurrentTWAP, error) { +// GetCurrentTWAP fetches the current median price of all oracles for a specific market +func (k Keeper) GetCurrentTWAP(ctx sdk.Context, pair common.AssetPair) (types.CurrentTWAP, error) { // Ensure we still have valid prices _, err := k.GetSpotPrice(ctx, pair) if err != nil { @@ -281,7 +281,7 @@ func (k Keeper) GetCurrentTWAPPrice(ctx sdk.Context, pair common.AssetPair) (typ } store := ctx.KVStore(k.storeKey) - bz := store.Get(types.CurrentTWAPPriceKey("twap-" + pair.String())) + bz := store.Get(types.CurrentTWAPKey("twap-" + pair.String())) if bz == nil { return types.CurrentTWAP{}, types.ErrNoValidTWAP @@ -297,7 +297,7 @@ func (k Keeper) GetCurrentTWAPPrice(ctx sdk.Context, pair common.AssetPair) (typ } /* -updateTWAPPrice updates the twap price for a token0, token1 pair +updateTWAP updates the twap price for a token0, token1 pair We use the blocktime to update the twap price. Calculation is done as follow: @@ -308,7 +308,7 @@ With */ -func (k Keeper) UpdateTWAPPrice(ctx sdk.Context, pairID string) error { +func (k Keeper) UpdateTWAP(ctx sdk.Context, pairID string) error { pair, err := common.NewAssetPair(pairID) if err != nil { return err @@ -319,7 +319,7 @@ func (k Keeper) UpdateTWAPPrice(ctx sdk.Context, pairID string) error { return err } - currentTWAP, err := k.GetCurrentTWAPPrice(ctx, pair) + currentTWAP, err := k.GetCurrentTWAP(ctx, pair) // Err there means no twap price have been set yet for this pair if errors.Is(err, types.ErrNoValidTWAP) { currentTWAP = types.CurrentTWAP{ @@ -347,6 +347,6 @@ func (k Keeper) UpdateTWAPPrice(ctx sdk.Context, pairID string) error { Price: price, } store := ctx.KVStore(k.storeKey) - store.Set(types.CurrentTWAPPriceKey("twap-"+pairID), k.codec.MustMarshal(&newTWAP)) + store.Set(types.CurrentTWAPKey("twap-"+pairID), k.codec.MustMarshal(&newTWAP)) return nil } diff --git a/x/vpool/keeper/prices_test.go b/x/vpool/keeper/prices_test.go index f33562101..3c6fa64b6 100644 --- a/x/vpool/keeper/prices_test.go +++ b/x/vpool/keeper/prices_test.go @@ -484,7 +484,7 @@ func TestCalcTwap(t *testing.T) { } } -func TestGetTWAPPrice(t *testing.T) { +func TestGetTWAP(t *testing.T) { type positionUpdate struct { quoteAsset sdk.Dec baseAsset sdk.Dec @@ -496,20 +496,20 @@ func TestGetTWAPPrice(t *testing.T) { pair common.AssetPair positionUpdates []positionUpdate - expectedTwapPrices []sdk.Dec + expectedTWAPs []sdk.Dec expectedMarkPrices []sdk.Dec }{ { name: "Add quote to position", pair: BTCNusdPair, positionUpdates: []positionUpdate{{quoteAsset: sdk.NewDec(5_000), direction: types.Direction_ADD_TO_POOL, blockTs: time.Unix(2, 0)}}, - expectedTwapPrices: []sdk.Dec{sdk.MustNewDecFromStr("40006.667083333333333336")}, + expectedTWAPs: []sdk.Dec{sdk.MustNewDecFromStr("40006.667083333333333336")}, expectedMarkPrices: []sdk.Dec{sdk.MustNewDecFromStr("40010.000625000000000004")}, }, { name: "Remove quote from position", pair: BTCNusdPair, positionUpdates: []positionUpdate{{quoteAsset: sdk.NewDec(4_000), direction: types.Direction_REMOVE_FROM_POOL, blockTs: time.Unix(2, 0)}}, - expectedTwapPrices: []sdk.Dec{sdk.MustNewDecFromStr("39994.666933333333333333")}, + expectedTWAPs: []sdk.Dec{sdk.MustNewDecFromStr("39994.666933333333333333")}, expectedMarkPrices: []sdk.Dec{sdk.MustNewDecFromStr("39992.000400000000000000")}, }, { name: "Add and remove to/from quote position to return to initial TWAP", @@ -518,7 +518,7 @@ func TestGetTWAPPrice(t *testing.T) { {quoteAsset: sdk.NewDec(700), direction: types.Direction_ADD_TO_POOL, blockTs: time.Unix(4, 0)}, {quoteAsset: sdk.NewDec(1_234), direction: types.Direction_REMOVE_FROM_POOL, blockTs: time.Unix(7, 0)}, }, - expectedTwapPrices: []sdk.Dec{ + expectedTWAPs: []sdk.Dec{ sdk.MustNewDecFromStr("40001.120009799999999993"), sdk.MustNewDecFromStr("39999.843674908525000000"), }, @@ -530,13 +530,13 @@ func TestGetTWAPPrice(t *testing.T) { name: "Add base to position", pair: BTCNusdPair, positionUpdates: []positionUpdate{{baseAsset: sdk.NewDec(50), direction: types.Direction_ADD_TO_POOL, blockTs: time.Unix(2, 0)}}, - expectedTwapPrices: []sdk.Dec{sdk.MustNewDecFromStr("37520.786092214663643235")}, + expectedTWAPs: []sdk.Dec{sdk.MustNewDecFromStr("37520.786092214663643235")}, expectedMarkPrices: []sdk.Dec{sdk.MustNewDecFromStr("36281.179138321995464853")}}, { name: "Remove base from position", pair: BTCNusdPair, positionUpdates: []positionUpdate{{baseAsset: sdk.NewDec(40), direction: types.Direction_REMOVE_FROM_POOL, blockTs: time.Unix(2, 0)}}, - expectedTwapPrices: []sdk.Dec{sdk.MustNewDecFromStr("42268.518518518518518519")}, + expectedTWAPs: []sdk.Dec{sdk.MustNewDecFromStr("42268.518518518518518519")}, expectedMarkPrices: []sdk.Dec{sdk.MustNewDecFromStr("43402.777777777777777778")}, }, { @@ -546,7 +546,7 @@ func TestGetTWAPPrice(t *testing.T) { {baseAsset: sdk.NewDec(7), direction: types.Direction_ADD_TO_POOL, blockTs: time.Unix(4, 0)}, {baseAsset: sdk.MustNewDecFromStr("1.234"), direction: types.Direction_REMOVE_FROM_POOL, blockTs: time.Unix(7, 0)}, }, - expectedTwapPrices: []sdk.Dec{ + expectedTWAPs: []sdk.Dec{ sdk.MustNewDecFromStr("39556.660476959200196440"), sdk.MustNewDecFromStr("39548.504707649598914130"), }, @@ -575,11 +575,11 @@ func TestGetTWAPPrice(t *testing.T) { /*fluctuationLimitratio=*/ sdk.OneDec(), /*maxSpread=*/ sdk.OneDec(), ) - err := keeper.UpdateTWAPPrice(cctx, BTCNusdPair.String()) + err := keeper.UpdateTWAP(cctx, BTCNusdPair.String()) require.NoError(t, err) // Make sure price gets initialized correctly when the pool gets created pair := BTCNusdPair - twap, err := keeper.GetCurrentTWAPPrice(ctx, pair) + twap, err := keeper.GetCurrentTWAP(ctx, pair) require.NoError(t, err) require.EqualValues(t, initialTWAP, twap.Price) for i, p := range tc.positionUpdates { @@ -593,11 +593,11 @@ func TestGetTWAPPrice(t *testing.T) { require.NoError(t, err) markPriceEvt := getMarkPriceEvent(tc.expectedMarkPrices[i], cctx.BlockHeader().Time) testutilevents.RequireContainsTypedEvent(t, cctx, markPriceEvt) - err = keeper.UpdateTWAPPrice(cctx, BTCNusdPair.String()) + err = keeper.UpdateTWAP(cctx, BTCNusdPair.String()) require.NoError(t, err) - twapPrice, err := keeper.GetCurrentTWAPPrice(ctx, pair) + twap, err := keeper.GetCurrentTWAP(ctx, pair) require.NoError(t, err) - assert.Equal(t, tc.expectedTwapPrices[i], twapPrice.Price) + assert.Equal(t, tc.expectedTWAPs[i], twap.Price) } }) } diff --git a/x/vpool/module.go b/x/vpool/module.go index 0e53334de..7ee60cd05 100644 --- a/x/vpool/module.go +++ b/x/vpool/module.go @@ -173,7 +173,7 @@ func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { for _, pool := range am.keeper.GetAllPools(ctx) { assetPair := pool.Pair.String() - if err := am.keeper.UpdateTWAPPrice(ctx, assetPair); err != nil { + if err := am.keeper.UpdateTWAP(ctx, assetPair); err != nil { ctx.Logger().Error("failed to update TWAP", "assetPair", assetPair, "error", err) } } diff --git a/x/vpool/types/keys.go b/x/vpool/types/keys.go index 3b4fafa95..ae157aca4 100644 --- a/x/vpool/types/keys.go +++ b/x/vpool/types/keys.go @@ -22,7 +22,7 @@ var ( PoolKey = []byte{0x00} PoolReserveSnapshotCounter = []byte{0x01} PoolReserveSnapshots = []byte{0x02} - TWAPPricePrefix = []byte{0x03} + TWAPPrefix = []byte{0x03} ) // GetPoolKey returns pool key for KVStore @@ -46,7 +46,7 @@ func GetSnapshotKey(pair common.AssetPair, counter uint64) []byte { ) } -// CurrentTWAPPriceKey returns the prefix for the current TWAP price -func CurrentTWAPPriceKey(twapPairID string) []byte { - return append(TWAPPricePrefix, []byte(twapPairID)...) +// CurrentTWAPKey returns the prefix for the current TWAP price +func CurrentTWAPKey(twapPairID string) []byte { + return append(TWAPPrefix, []byte(twapPairID)...) }