Skip to content

Commit

Permalink
refactor(perp)!: PositionChangedEvent MarginToUser (#1427)
Browse files Browse the repository at this point in the history
* refactor(perp): PositionChangedEvent

* Update CHANGELOG.md
  • Loading branch information
k-yang authored Jun 16, 2023
1 parent c171ca3 commit 04b32c2
Show file tree
Hide file tree
Showing 9 changed files with 218 additions and 155 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* [#1388](https://github.com/NibiruChain/nibiru/pull/1388) - refactor(perp)!: idempotent position changed event
* [#1387](https://github.com/NibiruChain/nibiru/pull/1387) - feat: upgrade to Cosmos SDK v0.46.10
* [#1413](https://github.com/NibiruChain/nibiru/pull/1413) - fix(perp): provide descriptive errors when all liquidations fail in MultiLiquidate
* [#1427](https://github.com/NibiruChain/nibiru/pull/1427) - refactor(perp)!: PositionChangedEvent `MarginToUser`

### Improvements

Expand Down
17 changes: 11 additions & 6 deletions proto/perp/v2/event.proto
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,24 @@ message PositionChangedEvent {
// The block number at which this position was changed.
int64 block_height = 7;

// Exchanged margin is the amount of collateral received by the trader during
// margin_to_user is the amount of collateral received by the trader during
// the position change. A positve value indicates that the trader received
// funds, while a negative value indicates that the trader spent funds.
string exchanged_margin = 8 [
string margin_to_user = 8 [
(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int",
(gogoproto.nullable) = false
];

// Change type describes the type of state transition that resulted in the
// position change. Change type can take the following values:
// change_reason describes the reason for why the position resulted in a
// change. Change type can take the following values:
//
// ["open_position", "close_position", "liquidate", "add_margin", "remove_margin"]
string change_type = 9;
// - CHANGE_REASON_UNSPECIFIED: Unspecified change reason.
// - CHANGE_REASON_ADD_MARGIN: Margin was added to the position.
// - CHANGE_REASON_REMOVE_MARGIN: Margin was removed from the position.
// - CHANGE_REASON_OPEN_POSITION: A new position was opened.
// - CHANGE_REASON_CLOSE_POSITION: An existing position was closed.
string change_reason = 9
[ (gogoproto.customtype) = "ChangeReason", (gogoproto.nullable) = false ];
}

// Emitted when a position is liquidated.
Expand Down
8 changes: 4 additions & 4 deletions x/perp/v2/integration/assertion/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,15 @@ func (p positionChangedEventShouldBeEqual) Do(_ *app.NibiruApp, ctx sdk.Context)
fieldErrs = append(fieldErrs, err.Error())
}

if !theEvent.ExchangedMargin.Equal(p.ExpectedEvent.ExchangedMargin) {
if !theEvent.MarginToUser.Equal(p.ExpectedEvent.MarginToUser) {
err := fmt.Errorf("expected exchanged margin %s, got %s",
p.ExpectedEvent.ExchangedMargin, theEvent.ExchangedMargin)
p.ExpectedEvent.MarginToUser, theEvent.MarginToUser)
fieldErrs = append(fieldErrs, err.Error())
}

if theEvent.ChangeType != p.ExpectedEvent.ChangeType {
if theEvent.ChangeReason != p.ExpectedEvent.ChangeReason {
err := fmt.Errorf("expected change type %s, got %s",
p.ExpectedEvent.ChangeType, theEvent.ChangeType)
p.ExpectedEvent.ChangeReason, theEvent.ChangeReason)
fieldErrs = append(fieldErrs, err.Error())
}

Expand Down
12 changes: 5 additions & 7 deletions x/perp/v2/keeper/clearing_house.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,8 @@ func (k Keeper) OpenPosition(
}
}

changeType := "open_position"
if err = k.afterPositionUpdate(
ctx, market, *updatedAMM, traderAddr, *positionResp, changeType,
ctx, market, *updatedAMM, traderAddr, *positionResp, types.ChangeReason_OpenPosition,
); err != nil {
return nil, err
}
Expand Down Expand Up @@ -526,7 +525,7 @@ func (k Keeper) afterPositionUpdate(
amm types.AMM,
traderAddr sdk.AccAddress,
positionResp types.PositionResp,
changeType string,
changeType types.ChangeReason,
) (err error) {
// check bad debt
if !positionResp.BadDebt.IsZero() {
Expand Down Expand Up @@ -583,8 +582,8 @@ func (k Keeper) afterPositionUpdate(
BadDebt: sdk.NewCoin(market.Pair.QuoteDenom(), positionResp.BadDebt.RoundInt()),
FundingPayment: positionResp.FundingPayment,
BlockHeight: ctx.BlockHeight(),
ExchangedMargin: marginToVault.Neg().Sub(transferredFee),
ChangeType: changeType,
MarginToUser: marginToVault.Neg().Sub(transferredFee),
ChangeReason: changeType,
},
)

Expand Down Expand Up @@ -724,14 +723,13 @@ func (k Keeper) ClosePosition(ctx sdk.Context, pair asset.Pair, traderAddr sdk.A
return positionResp, nil
}

changeType := "close_position"
if err = k.afterPositionUpdate(
ctx,
market,
*updatedAMM,
traderAddr,
*positionResp,
changeType,
types.ChangeReason_ClosePosition,
); err != nil {
return nil, err
}
Expand Down
36 changes: 18 additions & 18 deletions x/perp/v2/keeper/clearing_house_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ func TestOpenPosition(t *testing.T) {
TransactionFee: sdk.NewCoin(denoms.NUSD, sdk.NewInt(20)),
BlockHeight: 1,
// exchangedMargin = - marginToVault - transferredFee
ExchangedMargin: sdk.NewInt(1_000 + 20).Neg(),
ChangeType: "open_position",
MarginToUser: sdk.NewInt(1_000 + 20).Neg(),
ChangeReason: types.ChangeReason_OpenPosition,
}),
),

Expand Down Expand Up @@ -146,8 +146,8 @@ func TestOpenPosition(t *testing.T) {
TransactionFee: sdk.NewCoin(denoms.NUSD, sdk.NewInt(20)), // 20 bps
BlockHeight: 2,
// exchangedMargin = - marginToVault - transferredFee
ExchangedMargin: sdk.NewInt(1_000 + 20).Neg(),
ChangeType: "open_position",
MarginToUser: sdk.NewInt(1_000 + 20).Neg(),
ChangeReason: types.ChangeReason_OpenPosition,
}),
),

Expand Down Expand Up @@ -202,8 +202,8 @@ func TestOpenPosition(t *testing.T) {
TransactionFee: sdk.NewCoin(denoms.NUSD, sdk.NewInt(10)), // 20 bps
BlockHeight: 2,
// exchangedMargin = - marginToVault - transferredFee
ExchangedMargin: sdk.NewInt(0 + 10).Neg(),
ChangeType: "open_position",
MarginToUser: sdk.NewInt(0 + 10).Neg(),
ChangeReason: types.ChangeReason_OpenPosition,
}),
),

Expand Down Expand Up @@ -258,8 +258,8 @@ func TestOpenPosition(t *testing.T) {
TransactionFee: sdk.NewCoin(denoms.NUSD, sdk.NewInt(60)), // 20 bps
BlockHeight: 2,
// exchangedMargin = - marginToVault - transferredFee
ExchangedMargin: sdk.NewInt(1_000 + 60).Neg(),
ChangeType: "open_position",
MarginToUser: sdk.NewInt(1_000 + 60).Neg(),
ChangeReason: types.ChangeReason_OpenPosition,
}),
),

Expand Down Expand Up @@ -322,8 +322,8 @@ func TestOpenPosition(t *testing.T) {
TransactionFee: sdk.NewCoin(denoms.NUSD, sdk.NewInt(20)),
BlockHeight: 1,
// exchangedMargin = - marginToVault - transferredFee
ExchangedMargin: sdk.NewInt(1_000 + 20).Neg(),
ChangeType: "open_position",
MarginToUser: sdk.NewInt(1_000 + 20).Neg(),
ChangeReason: types.ChangeReason_OpenPosition,
}),
),

Expand Down Expand Up @@ -378,8 +378,8 @@ func TestOpenPosition(t *testing.T) {
TransactionFee: sdk.NewCoin(denoms.NUSD, sdk.NewInt(20)), // 20 bps
BlockHeight: 2,
// exchangedMargin = - marginToVault - transferredFee
ExchangedMargin: sdk.NewInt(1_000 + 20).Neg(),
ChangeType: "open_position",
MarginToUser: sdk.NewInt(1_000 + 20).Neg(),
ChangeReason: types.ChangeReason_OpenPosition,
}),
),

Expand Down Expand Up @@ -434,8 +434,8 @@ func TestOpenPosition(t *testing.T) {
TransactionFee: sdk.NewCoin(denoms.NUSD, sdk.NewInt(10)), // 20 bps
BlockHeight: 2,
// exchangedMargin = - marginToVault - transferredFee
ExchangedMargin: sdk.NewInt(0 + 10).Neg(),
ChangeType: "open_position",
MarginToUser: sdk.NewInt(0 + 10).Neg(),
ChangeReason: types.ChangeReason_OpenPosition,
}),
),

Expand Down Expand Up @@ -490,8 +490,8 @@ func TestOpenPosition(t *testing.T) {
TransactionFee: sdk.NewCoin(denoms.NUSD, sdk.NewInt(60)), // 20 bps
BlockHeight: 2,
// exchangedMargin = - marginToVault - transferredFee
ExchangedMargin: sdk.NewInt(1_000 + 60).Neg(),
ChangeType: "open_position",
MarginToUser: sdk.NewInt(1_000 + 60).Neg(),
ChangeReason: types.ChangeReason_OpenPosition,
}),
),

Expand Down Expand Up @@ -1033,8 +1033,8 @@ func TestClosePosition(t *testing.T) {
TransactionFee: sdk.NewInt64Coin(denoms.NUSD, 0),
BlockHeight: ctx.BlockHeight(),
// exchangedMargin = - marginToVault - transferredFee
ExchangedMargin: tc.expectedMarginToVault.RoundInt().Neg().SubRaw(0),
ChangeType: "close_position",
MarginToUser: tc.expectedMarginToVault.RoundInt().Neg().SubRaw(0),
ChangeReason: types.ChangeReason_ClosePosition,
})
})
}
Expand Down
8 changes: 4 additions & 4 deletions x/perp/v2/keeper/margin.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ func (k Keeper) AddMargin(
BadDebt: sdk.NewCoin(pair.QuoteDenom(), sdk.ZeroInt()), // always zero when adding margin
FundingPayment: fundingPayment,
BlockHeight: ctx.BlockHeight(),
ExchangedMargin: marginToAdd.Amount.Neg(),
ChangeType: "add_margin",
MarginToUser: marginToAdd.Amount.Neg(),
ChangeReason: types.ChangeReason_AddMargin,
},
); err != nil {
return nil, err
Expand Down Expand Up @@ -185,8 +185,8 @@ func (k Keeper) RemoveMargin(
BadDebt: sdk.NewCoin(pair.QuoteDenom(), sdk.ZeroInt()), // always zero when removing margin
FundingPayment: fundingPayment,
BlockHeight: ctx.BlockHeight(),
ExchangedMargin: marginToRemove.Amount,
ChangeType: "remove_margin",
MarginToUser: marginToRemove.Amount,
ChangeReason: types.ChangeReason_RemoveMargin,
},
); err != nil {
return nil, err
Expand Down
20 changes: 10 additions & 10 deletions x/perp/v2/keeper/margin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ func TestAddMargin(t *testing.T) {
FundingPayment: sdk.ZeroDec(),
TransactionFee: sdk.NewCoin(denoms.USDC, sdk.ZeroInt()),
BlockHeight: 2,
ExchangedMargin: sdk.NewInt(-1_000),
ChangeType: "add_margin",
MarginToUser: sdk.NewInt(-1_000),
ChangeReason: types.ChangeReason_AddMargin,
}),
BalanceEqual(alice, denoms.USDC, sdk.ZeroInt()),
ModuleBalanceEqual(types.PerpEFModuleAccount, denoms.USDC, sdk.NewInt(10)),
Expand Down Expand Up @@ -113,8 +113,8 @@ func TestAddMargin(t *testing.T) {
FundingPayment: sdk.ZeroDec(),
TransactionFee: sdk.NewCoin(denoms.USDC, sdk.ZeroInt()),
BlockHeight: 2,
ExchangedMargin: sdk.NewInt(-1000),
ChangeType: "add_margin",
MarginToUser: sdk.NewInt(-1000),
ChangeReason: types.ChangeReason_AddMargin,
}),
BalanceEqual(alice, denoms.USDC, sdk.ZeroInt()),
ModuleBalanceEqual(types.PerpEFModuleAccount, denoms.USDC, sdk.NewInt(10)),
Expand Down Expand Up @@ -170,8 +170,8 @@ func TestRemoveMargin(t *testing.T) {
FundingPayment: sdk.ZeroDec(),
TransactionFee: sdk.NewCoin(denoms.USDC, sdk.ZeroInt()),
BlockHeight: 2,
ExchangedMargin: sdk.NewInt(500),
ChangeType: "remove_margin",
MarginToUser: sdk.NewInt(500),
ChangeReason: types.ChangeReason_RemoveMargin,
}),
BalanceEqual(alice, denoms.USDC, sdk.NewInt(500)),
ModuleBalanceEqual(types.PerpEFModuleAccount, denoms.USDC, sdk.NewInt(1)),
Expand Down Expand Up @@ -217,8 +217,8 @@ func TestRemoveMargin(t *testing.T) {
FundingPayment: sdk.ZeroDec(),
TransactionFee: sdk.NewCoin(denoms.USDC, sdk.ZeroInt()),
BlockHeight: 2,
ExchangedMargin: sdk.NewInt(0),
ChangeType: "remove_margin",
MarginToUser: sdk.NewInt(0),
ChangeReason: types.ChangeReason_RemoveMargin,
}),
BalanceEqual(alice, denoms.USDC, sdk.NewInt(0)),
ModuleBalanceEqual(types.PerpEFModuleAccount, denoms.USDC, sdk.NewInt(1)),
Expand Down Expand Up @@ -264,8 +264,8 @@ func TestRemoveMargin(t *testing.T) {
FundingPayment: sdk.ZeroDec(),
TransactionFee: sdk.NewCoin(denoms.USDC, sdk.ZeroInt()),
BlockHeight: 2,
ExchangedMargin: sdk.NewInt(500),
ChangeType: "remove_margin",
MarginToUser: sdk.NewInt(500),
ChangeReason: types.ChangeReason_RemoveMargin,
}),
BalanceEqual(alice, denoms.USDC, sdk.NewInt(500)),
ModuleBalanceEqual(types.PerpEFModuleAccount, denoms.USDC, sdk.NewInt(1)),
Expand Down
58 changes: 58 additions & 0 deletions x/perp/v2/types/change_reason.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package types

import "encoding/json"

type customProtobufType interface {
Marshal() ([]byte, error)
MarshalTo(data []byte) (n int, err error)
Unmarshal(data []byte) error
Size() int

MarshalJSON() ([]byte, error)
UnmarshalJSON(data []byte) error
}

var _ customProtobufType = (*ChangeReason)(nil)

type ChangeReason string

const (
ChangeReason_OpenPosition ChangeReason = "open_position"
ChangeReason_ClosePosition ChangeReason = "close_position"
ChangeReason_AddMargin ChangeReason = "add_margin"
ChangeReason_RemoveMargin ChangeReason = "remove_margin"
ChangeReason_Liquidate ChangeReason = "liquidate"
)

func (c *ChangeReason) Size() int {
return len(*c)
}

func (c *ChangeReason) Marshal() ([]byte, error) {
return []byte(*c), nil
}

func (c *ChangeReason) MarshalTo(data []byte) (n int, err error) {
return copy(data, *c), nil
}

func (c *ChangeReason) Unmarshal(data []byte) error {
*c = ChangeReason(data)
return nil
}

func (c *ChangeReason) MarshalJSON() ([]byte, error) {
return json.Marshal(*c)
}

func (c *ChangeReason) UnmarshalJSON(data []byte) error {
var s string

err := json.Unmarshal(data, &s)
if err != nil {
return err
}

*c = ChangeReason(s)
return nil
}
Loading

0 comments on commit 04b32c2

Please sign in to comment.