Skip to content

Commit

Permalink
docs(perp): Added events specification for the perp module. (#814)
Browse files Browse the repository at this point in the history
* docs(perp): events #wip

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

* Squashed commit of the following:

commit b496438338d5cd136661e6cf79a694e47a8198b9
Author: Unique-Divine <[email protected]>
Date:   Fri Aug 12 18:03:02 2022 -0500

    remove deperecated docs from x/perp/README

commit fc260a5
Author: Unique Divine <[email protected]>
Date:   Thu Aug 11 16:37:34 2022 -0500

    chore: release v0.12.1-alpha (#820)

    update changelog

commit 8ec477a
Author: AgentSmithMatrix <[email protected]>
Date:   Thu Aug 11 19:47:03 2022 +0200

    feat: add golangci-lint to makefile (#819)

    * add linter to makefile

    * update changelog

commit 208a102
Author: Unique Divine <[email protected]>
Date:   Wed Aug 10 13:17:05 2022 -0500

    fix: missing max leverage on the pools in app_state.vpool.vpools (#818)

commit 75e8f03
Author: Unique Divine <[email protected]>
Date:   Wed Aug 10 07:38:00 2022 -0500

    feat(vpool): expose markPrice, markTwap, indexPrice, (and blockHeight?) on the all-pools query #789 (#813)

    * (vpool): add logger to keeper.go

    * feat: GetPoolPrices, fn to return the mark price, mark twap, index price, and swap inv. for a pool

    * docs: fix the fn description for GetCurrentTWAP

    * feat(vpool): implemenet PoolPrices and add it to 'nibid q vpool all-pools' command

    * update changelog

    * (vpool): add block number to all-pools.prices. Fix changelog

    Co-authored-by: AgentSmithMatrix <[email protected]>
    Co-authored-by: Agent Smith <[email protected]>

commit 674da1b
Author: Unique Divine <[email protected]>
Date:   Wed Aug 10 07:01:20 2022 -0500

    feat(perp): expose 'marginRatioIndex' and block number on QueryTraderPosition (#810)

    * feat(x/perp): add marginRatioIndex to the position query

    * add blockNumber to QueryTraderPosition

    * update CHANGELOG.md #763

    * fix(CHANGELOG)

commit c6ad354
Author: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Date:   Wed Aug 10 01:52:40 2022 -0500

    chore(deps): bump github.com/cosmos/ibc-go/v3 from 3.1.0 to 3.1.1 (#804)

    * chore(deps): bump github.com/cosmos/ibc-go/v3 from 3.1.0 to 3.1.1

    Bumps [github.com/cosmos/ibc-go/v3](https://github.com/cosmos/ibc-go) from 3.1.0 to 3.1.1.
    - [Release notes](https://github.com/cosmos/ibc-go/releases)
    - [Changelog](https://github.com/cosmos/ibc-go/blob/main/CHANGELOG.md)
    - [Commits](cosmos/ibc-go@v3.1.0...v3.1.1)

    ---
    updated-dependencies:
    - dependency-name: github.com/cosmos/ibc-go/v3
      dependency-type: direct:production
      update-type: version-update:semver-patch
    ...

    Signed-off-by: dependabot[bot] <[email protected]>

    * Update CHANGELOG.md

    Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
    Co-authored-by: NibiruHeisenberg <[email protected]>
    Co-authored-by: AgentSmithMatrix <[email protected]>

Co-authored-by: NibiruHeisenberg <[email protected]>
  • Loading branch information
Unique-Divine and NibiruHeisenberg authored Aug 15, 2022
1 parent 701b27f commit 247b6cd
Show file tree
Hide file tree
Showing 5 changed files with 95 additions and 84 deletions.
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 |
-->

0 comments on commit 247b6cd

Please sign in to comment.