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

feat(perp): whitelisted liquidations #977

Merged
merged 4 commits into from
Sep 26, 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### State Machine Breaking

* [#977](https://github.com/NibiruChain/nibiru/pull/977) - x/perp add whitelisted liquidators
* [#960](https://github.com/NibiruChain/nibiru/pull/960) - x/common validate asset pair denoms
* [#952](https://github.com/NibiruChain/nibiru/pull/952) - x/perp move state logic to collections
* [#872](https://github.com/NibiruChain/nibiru/pull/872) - x/perp remove module balances from genesis
Expand Down
4 changes: 4 additions & 0 deletions proto/perp/v1/state.proto
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ message Params {
(gogoproto.jsontag) = "twap_lookback_window,omitempty",
(gogoproto.moretags) = "yaml:\"twap_lookback_window\""
];

// whitelisted_liquidators defines the list of addresses
// which are allowed to liquidate a position.
repeated string whitelisted_liquidators = 9;
}

// Position identifies and records information on a user's position on one of
Expand Down
15 changes: 11 additions & 4 deletions x/perp/client/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,14 @@ func (s *IntegrationTestSuite) SetupSuite() {
},
},
}
perpGenesis.Params.WhitelistedLiquidators = []string{"nibi1w89pf5yq8ntjg89048qmtaz929fdxup0a57d8m"} // address associated with mnemonic below
genesisState[perptypes.ModuleName] = encodingConfig.Marshaler.MustMarshalJSON(perpGenesis)

// set up pricefeed
genesisState[pftypes.ModuleName] = encodingConfig.Marshaler.MustMarshalJSON(NewPricefeedGen())

s.cfg = testutilcli.BuildNetworkConfig(genesisState)

s.cfg.Mnemonics = []string{"satisfy december text daring wheat vanish save viable holiday rural vessel shuffle dice skate promote fade badge federal sail during lend fever balance give"}
s.network = testutilcli.NewNetwork(s.T(), s.cfg)
_, err := s.network.WaitForHeight(1)
s.NoError(err)
Expand Down Expand Up @@ -184,6 +185,12 @@ func (s *IntegrationTestSuite) SetupSuite() {
common.DenomNIBI,
)
s.Require().NoError(err)

_, err = testutilcli.FillWalletFromValidator(
sdk.MustAccAddressFromBech32("nibi1w89pf5yq8ntjg89048qmtaz929fdxup0a57d8m"),
sdk.NewCoins(sdk.NewInt64Coin(common.DenomNIBI, 1000)),
val, common.DenomNIBI)
s.Require().NoError(err)
}

func (s *IntegrationTestSuite) TearDownSuite() {
Expand Down Expand Up @@ -434,7 +441,7 @@ func (s *IntegrationTestSuite) TestLiquidate() {

args := []string{
"--from",
s.users[1].String(),
"nibi1w89pf5yq8ntjg89048qmtaz929fdxup0a57d8m",
common.Pair_ETH_NUSD.String(),
s.users[1].String(),
}
Expand Down Expand Up @@ -490,14 +497,14 @@ func (s *IntegrationTestSuite) TestLiquidate() {
// liquidate
args = []string{
"--from",
s.users[1].String(),
"nibi1w89pf5yq8ntjg89048qmtaz929fdxup0a57d8m",
common.Pair_ETH_NUSD.String(),
s.users[1].String(),
}

s.T().Log("liquidating user 2....")
out, err = sdktestutilcli.ExecTestCLICmd(val.ClientCtx, cli.LiquidateCmd(), append(args, commonArgs...))
s.NotContains(out.String(), "fail")
s.NotContains(out.String(), "fail", out.String())
s.NoError(err)
}

Expand Down
14 changes: 14 additions & 0 deletions x/perp/keeper/liquidate.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ func (k Keeper) Liquidate(
pair common.AssetPair,
traderAddr sdk.AccAddress,
) (feeToLiquidator sdk.Coin, feeToFund sdk.Coin, err error) {
if !k.canLiquidate(ctx, liquidatorAddr) {
return sdk.Coin{}, sdk.Coin{}, types.ErrUnauthorized.Wrapf("not allowed to liquidate: %s", traderAddr)
}
err = k.requireVpool(ctx, pair)
if err != nil {
return sdk.Coin{}, sdk.Coin{}, err
Expand Down Expand Up @@ -392,3 +395,14 @@ func (k Keeper) MultiLiquidate(ctx sdk.Context, liquidator sdk.AccAddress, posit

return resp
}

func (k Keeper) canLiquidate(ctx sdk.Context, addr sdk.AccAddress) bool {
addrStr := addr.String()
params := k.GetParams(ctx)
for _, whitelisted := range params.WhitelistedLiquidators {
if addrStr == whitelisted {
return true
}
}
return false
}
9 changes: 9 additions & 0 deletions x/perp/keeper/liquidate_unit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ func TestLiquidateIntoPartialLiquidation(t *testing.T) {
Return(nil)

t.Log("execute liquidation")
setLiquidator(ctx, perpKeeper, liquidatorAddr)
feeToLiquidator, feeToFund, err := perpKeeper.Liquidate(ctx, liquidatorAddr, common.Pair_BTC_NUSD, traderAddr)
require.NoError(t, err)
assert.EqualValues(t, tc.expectedLiquidatorFee, feeToLiquidator)
Expand Down Expand Up @@ -343,6 +344,7 @@ func TestLiquidateIntoFullLiquidation(t *testing.T) {
}

t.Log("execute liquidation")
setLiquidator(ctx, perpKeeper, liquidatorAddr)
feeToLiquidator, feeToFund, err := perpKeeper.Liquidate(ctx, liquidatorAddr, common.Pair_BTC_NUSD, traderAddr)
require.NoError(t, err)
assert.EqualValues(t, tc.expectedLiquidatorFee, feeToLiquidator)
Expand Down Expand Up @@ -515,6 +517,7 @@ func TestLiquidateIntoFullLiquidationWithBadDebt(t *testing.T) {
Return(nil)

t.Log("execute liquidation")
setLiquidator(ctx, perpKeeper, liquidatorAddr)
feeToLiquidator, feeToFund, err := perpKeeper.Liquidate(ctx, liquidatorAddr, common.Pair_BTC_NUSD, traderAddr)
require.NoError(t, err)
assert.EqualValues(t, tc.expectedLiquidatorFee, feeToLiquidator)
Expand Down Expand Up @@ -1336,3 +1339,9 @@ func TestKeeper_ExecutePartialLiquidation(t *testing.T) {
})
}
}

func setLiquidator(ctx sdk.Context, k Keeper, addr sdk.AccAddress) {
p := k.GetParams(ctx)
p.WhitelistedLiquidators = []string{addr.String()}
k.SetParams(ctx, p)
}
15 changes: 3 additions & 12 deletions x/perp/keeper/msg_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,20 +100,11 @@ func (m msgServer) Liquidate(goCtx context.Context, msg *types.MsgLiquidate,
) (*types.MsgLiquidateResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)

liquidatorAddr, err := sdk.AccAddressFromBech32(msg.Sender)
if err != nil {
return nil, err
}
liquidatorAddr := sdk.MustAccAddressFromBech32(msg.Sender)

traderAddr, err := sdk.AccAddressFromBech32(msg.Trader)
if err != nil {
return nil, err
}
traderAddr := sdk.MustAccAddressFromBech32(msg.Trader)

pair, err := common.NewAssetPair(msg.TokenPair)
if err != nil {
return nil, err
}
pair := common.MustNewAssetPair(msg.TokenPair)

feeToLiquidator, feeToFund, err := m.k.Liquidate(ctx, liquidatorAddr, pair, traderAddr)
if err != nil {
Expand Down
31 changes: 8 additions & 23 deletions x/perp/keeper/msg_server_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package keeper_test

import (
"fmt"
"testing"
"time"

Expand Down Expand Up @@ -427,28 +426,6 @@ func TestMsgServerLiquidate(t *testing.T) {

expectedErr error
}{
{
name: "invalid pair",
pair: "foo",
liquidator: sample.AccAddress().String(),
trader: sample.AccAddress().String(),

expectedErr: common.ErrInvalidTokenPair,
},
{
name: "invalid liquidator address",
pair: common.Pair_BTC_NUSD.String(),
liquidator: "foo",
trader: sample.AccAddress().String(),
expectedErr: fmt.Errorf("decoding bech32 failed"),
},
{
name: "invalid trader address",
pair: common.Pair_BTC_NUSD.String(),
liquidator: sample.AccAddress().String(),
trader: "foo",
expectedErr: fmt.Errorf("decoding bech32 failed"),
},
{
name: "success",
pair: common.Pair_BTC_NUSD.String(),
Expand All @@ -462,6 +439,7 @@ func TestMsgServerLiquidate(t *testing.T) {
tc := tc
t.Run(tc.name, func(t *testing.T) {
app, ctx := simapp2.NewTestNibiruAppAndContext(true)
setLiquidator(ctx, app.PerpKeeper, tc.liquidator)
msgServer := keeper.NewMsgServerImpl(app.PerpKeeper)

t.Log("create vpool")
Expand Down Expand Up @@ -521,6 +499,12 @@ func TestMsgServerLiquidate(t *testing.T) {
}
}

func setLiquidator(ctx sdk.Context, perpKeeper keeper.Keeper, liquidator string) {
p := perpKeeper.GetParams(ctx)
p.WhitelistedLiquidators = []string{liquidator}
perpKeeper.SetParams(ctx, p)
}

func TestMsgServerMultiLiquidate(t *testing.T) {
app, ctx := simapp2.NewTestNibiruAppAndContext(true)
msgServer := keeper.NewMsgServerImpl(app.PerpKeeper)
Expand Down Expand Up @@ -590,6 +574,7 @@ func TestMsgServerMultiLiquidate(t *testing.T) {

require.NoError(t, simapp.FundModuleAccount(app.BankKeeper, ctx, types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(pair.QuoteDenom(), 2))))

setLiquidator(ctx, app.PerpKeeper, liquidator.String())
resp, err := msgServer.MultiLiquidate(sdk.WrapSDKContext(ctx), &types.MsgMultiLiquidate{
Sender: liquidator.String(),
Liquidations: []*types.MsgMultiLiquidate_MultiLiquidation{
Expand Down
19 changes: 19 additions & 0 deletions x/perp/types/params.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs {
&p.TwapLookbackWindow,
validateTwapLookbackWindow,
),
paramtypes.NewParamSetPair(
[]byte("WhitelistedLiquidators"),
&p.WhitelistedLiquidators,
validateAddress,
),
}
}

Expand Down Expand Up @@ -168,3 +173,17 @@ func validateTwapLookbackWindow(i interface{}) error {
}
return nil
}

func validateAddress(i interface{}) error {
val, ok := i.([]string)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
for _, addr := range val {
_, err := sdk.AccAddressFromBech32(addr)
if err != nil {
return err
}
}
return nil
}
Loading