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

docs(perp): Added events specification for the perp module. #814

Merged
merged 8 commits into from
Aug 15, 2022
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* [#816](https://github.com/NibiruChain/nibiru/pull/816) - Remove tobin tax from x/oracle
* [#810](https://github.com/NibiruChain/nibiru/pull/810) - feat(x/perp): expose 'marginRatioIndex' and block number on QueryTraderPosition

### Documentation

* [#814](https://github.com/NibiruChain/nibiru/pull/814) - docs(perp): Added events specification for the perp module.

## [v0.12.1](https://github.com/NibiruChain/nibiru/releases/tag/v0.12.1) - 2022-08-04

* [#796](https://github.com/NibiruChain/nibiru/pull/796) - fix bug that caused that epochKeeper was nil when running epoch hook from Perp module
Expand Down
6 changes: 4 additions & 2 deletions proto/perp/v1/event.proto
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ message PositionChangedEvent {
(gogoproto.nullable) = false
];

// Amount of bad debt cleared by the PerpEF during the change. Bad debt is negative net margin past the liquidation point of a position.
// Amount of bad debt cleared by the PerpEF during the change.
// Bad debt is negative net margin past the liquidation point of a position.
cosmos.base.v1beta1.Coin bad_debt = 10 [(gogoproto.nullable) = false];

// amt of margin (y) lost due to liquidation
Expand All @@ -68,7 +69,8 @@ message PositionChangedEvent {
(gogoproto.nullable) = false
];

// vPrice defined as yRes / xRes for a vpool, where yRes is the quote reserves and xRes is the base reserves.
// Spot price, synonymous with mark price in this context, is the quotient of
// the quote reserves and base reserves
string spot_price = 12 [
(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec",
(gogoproto.nullable) = false
Expand Down
2 changes: 2 additions & 0 deletions x/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

- [pricefeed](pricefeed/spec/README.md): Handles the posting of prices for various asset pairs by whitelisted oracles and the logic for querying these prices.

- [perp](perp/README.md): The `x/perp` module powers the Nibi-Perps exchange. This module enables traders to open long and short leveraged positions and houses all of the PnL calculation and liquidation logic.

- [stablecoin](stablecoin/spec/README.md): `x/stablecoin` is resonsible for handling mint and redeem transactions with NUSD.

- [testutil](testutil/spec/README.md): Helper functions for unit and integration tests.
34 changes: 1 addition & 33 deletions x/perp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,39 +20,7 @@ nibid tx perp --help
nibid query perp --help
```

CLI code is contained in the `/perp/client/cli` directory.
The implementation for this module's portion of the `nibid` CLI is contained within the `/perp/client/cli` directory.

## Perp Ecosystem Fund (PerpEF)
<!-- TODO Complete section and move a "Module Accounts" section inside concepts. -->

The PerpEF is a module account on Nibiru Protocol. All of its interactions can be encapsulated in two keeper methods.
- `WithdrawFromPerpEF()`
- `DepositToPerpEF()`


## Queries
<!-- TODO document queries and add to client file. -->


#### QueryPositionInfo

Given the `vpool` and `trader`, one could query the
`QueryPositionInfo(vpool string, trader sdk.AccAddress) -> PositionInfo`

```go
// A single trader's position information on a given Vpool.
type PositionInfo struct {
MarginRatio sdk.Dec
Position perptypes.Position
}
```

#### QueryAllVpools

`QueryAllVpools() -> []string`: Returns a list of all of the pool names.

#### QueryVpoolPrices

`QueryVpoolPrices() -> map[string]sdk.Dec`: Returns ech virtual pool and its corresponding price.


133 changes: 84 additions & 49 deletions x/perp/spec/04_events.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Events <!-- omit in toc -->

Here, we list and describe the event types used in x/perp.
Here, we document the event types used in the `x/perp` module.

Events in the Cosmos-SDK are Tendermint application blockchain interface (ABCI) events.
These are returned by ABCI methods such as CheckTx, DeliverTx, and Query.
Expand All @@ -14,51 +14,86 @@ For more information, see the [Tendermint Core ABCI methods and types specificat

# Event Types <!-- omit in toc -->

- [`transfer`](#transfer): Emitted when assets are transferred between addresses as a result of a Nibiru protocol.
- [`position_change`](#position_change): Emitted when a position state changes.
- [`position_liquidate`](#position_liquidate):
- [`position_settle`](#position_settle):
- [`margin_ratio_change`](#margin_ratio_change):
- [`margin_change`](#margin_change): Emitted when the margin of a single
- [`internal_position_response`](#internal_position_response):

<!-- TODO Create tx fee event -->

## `transfer`

Attributes - "transfer:

- "from": Sender address
- "to": Receiver address
- "denom": Cosmos-SDK token Bech 32 address for the token
- "amount": Amount of tokens sent in the transfer


## `position_change`

Attributes - "position_change":

- "owner": Address
- "vpool":
- "margin":
- "notional":
- "vsizeChange": magnitude of the change to the position size. Recall that the position size is the number of base assets for the perp position. E.g. an ETH:USD perp with 3 ETH of exposure has a posiiton size of 3.
- "txFee":
- "vsizeAfter":
- "realizedPnlAfter":
- "bad_debt":
- "unrealized_pnl_after":
- "liquidation_penalty":
- "mark_price":
- "funding_payment": A funding payment made or received by the trader on the current position. A "funding_payment" is positive if 'owner' is the sender and negative if 'owner' is the receiver of the payment. Its magnitude is abs(size * fundingRate). Funding payments act to converge the mark price and index price (average price on major spot exchanges).

## `position_liquidate`


## `position_settle`

## `margin_ratio_change`

## `margin_change`

## `internal_position_response`
- [`nibiru.perp.v1.PositionChangedEvent`](#nibiruperpv1positionchangedevent): Event omitted when a position changes
- [`nibiru.perp.v1.PositionLiquidatedEvent`](#nibiruperpv1positionliquidatedevent): Event emitted when a position is liquidated.
- [`nibiru.perp.v1.PositionSettledEvent`](#nibiruperpv1positionsettledevent): Event emitted when a position is settled.
- [`nibiru.perp.v1.FundingRateChangedEvent`](#nibiruperpv1fundingratechangedevent):


```ts
interface Coin {
denom: string; // Cosmos token Bech 32 address
amount: number; // Amount of tokens
}
```

## `nibiru.perp.v1.PositionChangedEvent`

| Attribute (type) | Description |
| ---------------- | ---------- |
| bad_debt (`Coin`) | Amount of bad debt cleared by the PerpEF during the change. Bad debt is negative net margin past the liquidation point of a position. |
| block_height (`int64`) | Block number at which the position changed |
| block_time_ms (`int64`) | Block time in Unix milliseconds at which the position changed. |
| exchanged_position_size (`Dec`) | magnitude of the change to the position size. Recall that the position size is the number of base assets for the perp position. E.g. an ETH:USD perp with 3 ETH of exposure has a posiiton size of 3. |
| funding_payment (`Dec`) | A funding payment made or received by the trader on the current position. A "funding_payment" is positive if 'owner' is the sender and negative if 'owner' is the receiver of the payment. Its magnitude is abs(size * fundingRate). Funding payments act to converge the mark price and index price (average price on major spot exchanges). |
| liquidation_penalty (`Dec`) | Amount of margin lost due to liquidation, whether partial or full. |
| margin (`Coin`) | Amount of margin backing the position |
| pair (`string`) | Identifier for the virtual pool corresponding to the position. A pair is of the form `basedenom:quote`. E.g. `uatom:unusd`. |
| position_notional (`Dec`) | |
| position_size (`Dec`) | Position size (base asset value) after the change |
| realized_pnl (`Dec`) | Realized profits and losses after the change |
| spot_price (`Dec`) | Spot price, synonymous with mark price in this context, is the quotient of the quote reserves and base reserves. |
| trader_address (`string`) | Owner of the position |
| transaction_fee (`Coin`) | Transaction fee paid |
| unrealized_pnl_after (`Dec`) | Unrealized PnL after the change |

## `nibiru.perp.v1.PositionLiquidatedEvent`

Event emitted when a position is liquidated.
Corresponds to the proto message, `PositionLiquidatedEvent`.

| Attribute (type) | Description |
| ---------------- | ---------- |
| bad_debt (`Coin`) | Bad debt (margin units) cleared by the PerpEF during the tx. Bad debt is negative net margin past the liquidation point of a position. |
| block_height (`int64`) | Block number at which the position changed |
| block_time_ms (`int64`) | Block time in Unix milliseconds at which the position changed. |
| exchanged_position_size (`Dec`) | magnitude of the change to the position size (base) |
| exchanged_quote_amount (`Dec`) | magnitude of the change to the position notional (quote) |
| fee_to_liquidator (`Coin`) | Transaction fee paid to the liquidator |
| fee_to_ecosystem_fund (`Coin`) | Transaction fee paid to the Nibi-Perps Ecosystem Fund |
| liquidator_address (`string`) | Address of the account that executed the tx |
| mark_price (`Dec`) | Spot price of the virtual pool after liquidation |
| margin (`Coin`) | Amount of margin remaining in the position after the liquidation |
| pair (`string`) | Identifier for the virtual pool corresponding to the position. A pair is of the form `basedenom:quote`. E.g. `uatom:unusd`. |
| position_notional (`Dec`) | Reamining position notional (quote units) after liquiation |
| position_size (`Dec`) | Remaing position size (base units) after liquidation |
| trader_address (`string`) | Owner of the position |
| unrealized_pnl (`Dec`) | Unrealized PnL in the position after liquidation |

## `nibiru.perp.v1.PositionSettledEvent`

| Attribute (type) | Description |
| ---------------- | ---------- |
| pair (`string`) | Identifier for the virtual pool corresponding to the position. A pair is of the form `basedenom:quote`. E.g. `uatom:unusd`. |
| settled_coins (`[]Coin`) | Coins transferred during the settlement |
| trader_address (`string`) | Owner of the position |

## `nibiru.perp.v1.FundingRateChangedEvent`

| Attribute (type) | Description |
| ---------------- | ---------- |
| block_height (`int64`) | Block number at which the position changed |
| block_time_ms (`int64`) | Block time in Unix milliseconds at which the position changed. |
| cumulative_funding_rate (`Dec`) | Cumulative funding rate. The sum of the cumulative premium fractions (CFPs) for the pair. The funding payment paid by a user is the `(latestCPF - lastUpdateCPF) * positionSize`, where `lastUpdateCPF` is the last cumulative funding payment the position applied and `latestCPF` is the most recent CPF for the virtual pool. |
| index_price (`Dec`) | Price of the "underlying" for the perpetual swap. |
| latest_funding_rate (`Dec`) | Most recent value for the funding rate. |
| mark_price (`Dec`) | Instantaneous derivate price for the perp position. Equivalent to the quotient of the quote and base reserves. |
| pair (`string`) | Identifier for the virtual pool corresponding to the position. A pair is of the form `basedenom:quote`. E.g. `uatom:unusd`. |

<!-- Template for other event specs

| Attribute (type) | Description |
| ------------------ | --------------- |
| attribute (`type`) | TODOdescription |

-->