From 68f8f5b9b523821087f2df81f79bc75d63ac5fca Mon Sep 17 00:00:00 2001 From: Matthias <97468149+matthiasmatt@users.noreply.github.com> Date: Tue, 2 Apr 2024 10:17:02 +0200 Subject: [PATCH] fix: unwire perp module for main branch (#1830) * feat: rest in peace * fix: fix e2e wasm test * fix: fix justfile and deplyo-wasm --------- Co-authored-by: Unique Divine <51418232+Unique-Divine@users.noreply.github.com> --- INSTALL.md | 36 +- README.md | 55 +- app/keepers.go | 27 +- cmd/nibid/cmd/root.go | 2 - contrib/docker/chaosnet.Dockerfile | 1 - contrib/scripts/chaosnet.sh | 7 +- contrib/scripts/feat-perp.sh | 62 - contrib/scripts/localnet.sh | 47 +- justfile | 2 +- proto/nibiru/perp/v2/event.proto | 262 - proto/nibiru/perp/v2/genesis.proto | 101 - proto/nibiru/perp/v2/query.proto | 163 - proto/nibiru/perp/v2/state.proto | 248 - proto/nibiru/perp/v2/tx.proto | 473 - simapp/sim_test.go | 2 - x/common/testutil/cli/network.go | 3 - x/common/testutil/cli/query.go | 48 - x/common/testutil/genesis/perp_genesis.go | 237 - x/common/testutil/mock/perp_amm.go | 37 - x/common/testutil/mock/perp_market.go | 32 - x/common/testutil/testapp/testapp.go | 2 - .../cli/gen_pricefeeder_delegation_test.go | 1 - x/oracle/keeper/hooks.go | 44 - x/oracle/keeper/hooks_test.go | 81 - x/perp/README.md | 3 - x/perp/v2/client/cli/cli_test.go | 762 -- x/perp/v2/client/cli/gen_market.go | 223 - x/perp/v2/client/cli/gen_market_test.go | 151 - x/perp/v2/client/cli/query.go | 221 - x/perp/v2/client/cli/tx.go | 400 - x/perp/v2/integration/action/dnr.go | 317 - x/perp/v2/integration/action/liquidation.go | 73 - x/perp/v2/integration/action/margin.go | 157 - x/perp/v2/integration/action/market.go | 236 - x/perp/v2/integration/action/params.go | 24 - x/perp/v2/integration/action/position.go | 407 - x/perp/v2/integration/action/query.go | 352 - x/perp/v2/integration/action/settlement.go | 125 - x/perp/v2/integration/action/snapshot.go | 60 - x/perp/v2/integration/action/tx.go | 316 - x/perp/v2/integration/action/withdraw.go | 36 - x/perp/v2/integration/assertion/bank.go | 34 - x/perp/v2/integration/assertion/event.go | 148 - x/perp/v2/integration/assertion/market.go | 178 - x/perp/v2/integration/assertion/notional.go | 48 - x/perp/v2/integration/assertion/position.go | 111 - x/perp/v2/integration/assertion/twap.go | 49 - x/perp/v2/keeper/amm.go | 127 - x/perp/v2/keeper/amm_test.go | 483 - x/perp/v2/keeper/calc.go | 98 - x/perp/v2/keeper/calc_test.go | 395 - x/perp/v2/keeper/clearing_house.go | 941 -- x/perp/v2/keeper/clearing_house_test.go | 2051 ---- x/perp/v2/keeper/dnr.go | 202 - x/perp/v2/keeper/dnr_test.go | 303 - x/perp/v2/keeper/fixture_test.go | 1 - x/perp/v2/keeper/grpc_query.go | 202 - x/perp/v2/keeper/grpc_query_test.go | 488 - x/perp/v2/keeper/hooks.go | 90 - x/perp/v2/keeper/hooks_test.go | 161 - x/perp/v2/keeper/keeper.go | 154 - x/perp/v2/keeper/liquidate.go | 437 - x/perp/v2/keeper/liquidate_test.go | 404 - x/perp/v2/keeper/margin.go | 199 - x/perp/v2/keeper/margin_test.go | 312 - x/perp/v2/keeper/msg_server.go | 241 - x/perp/v2/keeper/msg_server_test.go | 509 - x/perp/v2/keeper/position.go | 33 - x/perp/v2/keeper/position_test.go | 1 - x/perp/v2/keeper/settlement.go | 118 - x/perp/v2/keeper/settlement_test.go | 242 - x/perp/v2/keeper/sudo.go | 274 - x/perp/v2/keeper/sudo_test.go | 532 -- x/perp/v2/keeper/swap.go | 113 - x/perp/v2/keeper/swap_test.go | 213 - x/perp/v2/keeper/twap.go | 184 - x/perp/v2/keeper/twap_test.go | 404 - x/perp/v2/keeper/withdraw.go | 140 - x/perp/v2/keeper/withdraw_test.go | 95 - x/perp/v2/module/abci.go | 69 - x/perp/v2/module/abci_test.go | 146 - x/perp/v2/module/genesis.go | 187 - x/perp/v2/module/genesis_test.go | 198 - x/perp/v2/module/module.go | 186 - x/perp/v2/simulation/genesis.go | 24 - x/perp/v2/types/amm.go | 452 - x/perp/v2/types/amm_test.go | 836 -- x/perp/v2/types/change_reason.go | 61 - x/perp/v2/types/change_reason_test.go | 59 - x/perp/v2/types/codec.go | 41 - x/perp/v2/types/codec_test.go | 44 - x/perp/v2/types/collateral.go | 11 - x/perp/v2/types/errors.go | 64 - x/perp/v2/types/event.pb.go | 3204 ------- x/perp/v2/types/expected_keepers.go | 57 - x/perp/v2/types/export.go | 12 - x/perp/v2/types/genesis.go | 80 - x/perp/v2/types/genesis.pb.go | 2422 ----- x/perp/v2/types/genesis_test.go | 192 - x/perp/v2/types/keys.go | 33 - x/perp/v2/types/market.go | 203 - x/perp/v2/types/market_test.go | 192 - x/perp/v2/types/msgs.go | 464 - x/perp/v2/types/msgs_test.go | 667 -- x/perp/v2/types/position.go | 156 - x/perp/v2/types/position_test.go | 143 - x/perp/v2/types/query.pb.go | 3245 ------- x/perp/v2/types/query.pb.gw.go | 550 -- x/perp/v2/types/snapshot.go | 43 - x/perp/v2/types/snapshot_test.go | 130 - x/perp/v2/types/state.pb.go | 2705 ------ x/perp/v2/types/tx.pb.go | 8448 ----------------- x/sudo/module.go | 1 - 113 files changed, 63 insertions(+), 41813 deletions(-) delete mode 100644 contrib/scripts/feat-perp.sh delete mode 100644 proto/nibiru/perp/v2/event.proto delete mode 100644 proto/nibiru/perp/v2/genesis.proto delete mode 100644 proto/nibiru/perp/v2/query.proto delete mode 100644 proto/nibiru/perp/v2/state.proto delete mode 100644 proto/nibiru/perp/v2/tx.proto delete mode 100644 x/common/testutil/genesis/perp_genesis.go delete mode 100644 x/common/testutil/mock/perp_amm.go delete mode 100644 x/common/testutil/mock/perp_market.go delete mode 100644 x/oracle/keeper/hooks_test.go delete mode 100644 x/perp/README.md delete mode 100644 x/perp/v2/client/cli/cli_test.go delete mode 100644 x/perp/v2/client/cli/gen_market.go delete mode 100644 x/perp/v2/client/cli/gen_market_test.go delete mode 100644 x/perp/v2/client/cli/query.go delete mode 100644 x/perp/v2/client/cli/tx.go delete mode 100644 x/perp/v2/integration/action/dnr.go delete mode 100644 x/perp/v2/integration/action/liquidation.go delete mode 100644 x/perp/v2/integration/action/margin.go delete mode 100644 x/perp/v2/integration/action/market.go delete mode 100644 x/perp/v2/integration/action/params.go delete mode 100644 x/perp/v2/integration/action/position.go delete mode 100644 x/perp/v2/integration/action/query.go delete mode 100644 x/perp/v2/integration/action/settlement.go delete mode 100644 x/perp/v2/integration/action/snapshot.go delete mode 100644 x/perp/v2/integration/action/tx.go delete mode 100644 x/perp/v2/integration/action/withdraw.go delete mode 100644 x/perp/v2/integration/assertion/bank.go delete mode 100644 x/perp/v2/integration/assertion/event.go delete mode 100644 x/perp/v2/integration/assertion/market.go delete mode 100644 x/perp/v2/integration/assertion/notional.go delete mode 100644 x/perp/v2/integration/assertion/position.go delete mode 100644 x/perp/v2/integration/assertion/twap.go delete mode 100644 x/perp/v2/keeper/amm.go delete mode 100644 x/perp/v2/keeper/amm_test.go delete mode 100644 x/perp/v2/keeper/calc.go delete mode 100644 x/perp/v2/keeper/calc_test.go delete mode 100644 x/perp/v2/keeper/clearing_house.go delete mode 100644 x/perp/v2/keeper/clearing_house_test.go delete mode 100644 x/perp/v2/keeper/dnr.go delete mode 100644 x/perp/v2/keeper/dnr_test.go delete mode 100644 x/perp/v2/keeper/fixture_test.go delete mode 100644 x/perp/v2/keeper/grpc_query.go delete mode 100644 x/perp/v2/keeper/grpc_query_test.go delete mode 100644 x/perp/v2/keeper/hooks.go delete mode 100644 x/perp/v2/keeper/hooks_test.go delete mode 100644 x/perp/v2/keeper/keeper.go delete mode 100644 x/perp/v2/keeper/liquidate.go delete mode 100644 x/perp/v2/keeper/liquidate_test.go delete mode 100644 x/perp/v2/keeper/margin.go delete mode 100644 x/perp/v2/keeper/margin_test.go delete mode 100644 x/perp/v2/keeper/msg_server.go delete mode 100644 x/perp/v2/keeper/msg_server_test.go delete mode 100644 x/perp/v2/keeper/position.go delete mode 100644 x/perp/v2/keeper/position_test.go delete mode 100644 x/perp/v2/keeper/settlement.go delete mode 100644 x/perp/v2/keeper/settlement_test.go delete mode 100644 x/perp/v2/keeper/sudo.go delete mode 100644 x/perp/v2/keeper/sudo_test.go delete mode 100644 x/perp/v2/keeper/swap.go delete mode 100644 x/perp/v2/keeper/swap_test.go delete mode 100644 x/perp/v2/keeper/twap.go delete mode 100644 x/perp/v2/keeper/twap_test.go delete mode 100644 x/perp/v2/keeper/withdraw.go delete mode 100644 x/perp/v2/keeper/withdraw_test.go delete mode 100644 x/perp/v2/module/abci.go delete mode 100644 x/perp/v2/module/abci_test.go delete mode 100644 x/perp/v2/module/genesis.go delete mode 100644 x/perp/v2/module/genesis_test.go delete mode 100644 x/perp/v2/module/module.go delete mode 100644 x/perp/v2/simulation/genesis.go delete mode 100644 x/perp/v2/types/amm.go delete mode 100644 x/perp/v2/types/amm_test.go delete mode 100644 x/perp/v2/types/change_reason.go delete mode 100644 x/perp/v2/types/change_reason_test.go delete mode 100644 x/perp/v2/types/codec.go delete mode 100644 x/perp/v2/types/codec_test.go delete mode 100644 x/perp/v2/types/collateral.go delete mode 100644 x/perp/v2/types/errors.go delete mode 100644 x/perp/v2/types/event.pb.go delete mode 100644 x/perp/v2/types/expected_keepers.go delete mode 100644 x/perp/v2/types/export.go delete mode 100644 x/perp/v2/types/genesis.go delete mode 100644 x/perp/v2/types/genesis.pb.go delete mode 100644 x/perp/v2/types/genesis_test.go delete mode 100644 x/perp/v2/types/keys.go delete mode 100644 x/perp/v2/types/market.go delete mode 100644 x/perp/v2/types/market_test.go delete mode 100644 x/perp/v2/types/msgs.go delete mode 100644 x/perp/v2/types/msgs_test.go delete mode 100644 x/perp/v2/types/position.go delete mode 100644 x/perp/v2/types/position_test.go delete mode 100644 x/perp/v2/types/query.pb.go delete mode 100644 x/perp/v2/types/query.pb.gw.go delete mode 100644 x/perp/v2/types/snapshot.go delete mode 100644 x/perp/v2/types/snapshot_test.go delete mode 100644 x/perp/v2/types/state.pb.go delete mode 100644 x/perp/v2/types/tx.pb.go diff --git a/INSTALL.md b/INSTALL.md index 26dfd15a1..39461d675 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -1,14 +1,18 @@ -# Install `nibid` binaries +# Install `nibid` binaries This guide will explain how to install the Nibiru Chain binary, `nibid`, onto your system. #### Table of Contents + - [1. Update the system](#1-update-the-system) - [2. Install Golang](#2-install-golang) - [3. Install build requirements](#3-install-build-requirements) - [4. Clone the Nibiru Repository](#4-clone-the-nibiru-repository) - [Upgrade](#upgrade) - +- [Troubleshooting](#troubleshooting) +- [Contributing](#contributing) +- [Troubleshooting](#troubleshooting-1) + - [Error when running `make install` on MacOS](#error-when-running-make-install-on-macos) ## 1. Update the system @@ -19,7 +23,7 @@ sudo apt update sudo apt upgrade --yes ``` -## 2. Install Golang +## 2. Install Golang Steps described here: https://go.dev/doc/install @@ -34,7 +38,6 @@ wget -q -O - https://git.io/vQhTU | bash -s -- --version 1.16 After installed, open new terminal to properly load go - ## 4. Clone the Nibiru Repository ```sh @@ -43,19 +46,21 @@ git clone https://github.com/NibiruChain/nibiru cd nibiru ``` -On this fresh clone of the repo, simply run +On this fresh clone of the repo, simply run + ```sh -make build +make build make install make localnet ``` -and open another terminal. + +and open another terminal. --- ## Upgrade -The scheduled mainnet upgrade to `nibiru-2` is planned for +The scheduled mainnet upgrade to `nibiru-2` is planned for ``` cd nibiru @@ -63,12 +68,11 @@ git fetch tags git checkout v0.0.1 ``` - - Testnet +Testnet One the Nibiru binary has been installed, for further information on joining the testnet, head over to the [testnet repo](https://github.com/NibiruChain/Networks/tree/main/Testnet). - Mainnet +Mainnet One the Nibiru binary has been installed, for further information on joining mainnet, head over to the [mainnet repo](https://github.com/NibiruChain/Networks/tree/main/Mainnet). @@ -84,9 +88,9 @@ B. New commands you've made on the `nibid` don't show up. Your `nibid` probably ## Contributing -The code for `nibid` is located in the `/cmd/nibid` folder. +The code for `nibid` is located in the `/cmd/nibid` folder. -In addition to the commands available within that folder, `nibid` pulls in cli subcommands from the modules e.g. `/x/perps/cli` +In addition to the commands available within that folder, `nibid` pulls in cli subcommands from the modules e.g. `/x/oracle/cli` After updating the code run @@ -98,14 +102,14 @@ make install To see all the commands available just add `--help` to the end. Example: + ```bash nibid --help nibid query --help nibid tx --help -nibid query perp --help +nibid query oracle --help ``` - ## Troubleshooting ### Error when running `make install` on MacOS @@ -120,4 +124,4 @@ You can fix it by installing `wget` with Homebrew: ``` brew install wget -``` \ No newline at end of file +``` diff --git a/README.md b/README.md index a85248c0c..b731c9a25 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ ## ⚙️ — Documentation -- [Docs | Nibiru Chain](https://nibiru.fi/docs/): Conceptual and technical documentation can be found here. +- [Docs | Nibiru Chain](https://nibiru.fi/docs/): Conceptual and technical documentation can be found here. - [Complete Golang reference docs](https://pkg.go.dev/github.com/NibiruChain/nibiru): (`pkg.go.dev`) For the blockchain implementation . - ["X Module"](https://nibiru.fi/docs/dev/x/)-specific documentation @@ -30,9 +30,9 @@ If you have questions or concerns, feel free to connect with a developer or community member in the [Nibiru Discord][social-discord]. We also have active communities on [Twitter][social-twitter] and [Telegram][social-telegram]. - @@ -44,33 +44,30 @@ If you have questions or concerns, feel free to connect with a developer or comm ## 🧱 — Components of Nibiru -- **CosmWasm Smart Contracts**: Rust-based, Wasm smart contracts built enhanced security, performance, and interoperability. See our [CosmWasm sandbox monorepo (cw-nibiru)](https://github.com/NibiruChain/cw-nibiru/tree/main) for the protocol's core smart contracts. -- **Nibi-Perps**: A perpetual futures exchange where users can take leveraged exposure and trade on a plethora of assets — completely on-chain, completely non-custodially, and with minimal gas fees. +- **CosmWasm Smart Contracts**: Rust-based, Wasm smart contracts built enhanced security, performance, and interoperability. See our [CosmWasm sandbox monorepo (cw-nibiru)](https://github.com/NibiruChain/cw-nibiru/tree/main) for the protocol's core smart contracts. - **Nibi-Oracle**: Nibiru accurately prices assets using a native, system of decentralized oracles, and communicates with other Cosmos layer-1 chains using the Inter-Blockchain Communication (IBC) (opens new window)protocol. - **Nibi-Swap**: An automated market maker protocol for multichain assets. This application gives users access to swaps, pools, and bonded liquidity gauges. -| Module | Description | -| --- | --- | -| [wasm][code-x-wasm] | Implements the execution environment for [WebAssembly (WASM) smart contracts](https://nibiru.fi/docs/wasm/). | -| [devgas][code-x-devgas] | The `devgas` module of Nibiru Chain shares contract execution fees with smart contract developers. This aims to increase the adoption of Nibiru by offering CosmWasm smart contract developers a direct source of income based on usage. | -| [epochs][code-x-epochs] | The `epochs` module allows other modules to set hooks to be called to execute code automatically on a period basis. For example, "once a week, starting at UTC-time = x". `epochs` creates a generalized epoch interface. | -| [inflation][code-x-inflation] | Implements the [tokenomics](https://nibiru.fi/docs/learn/tokenomics.html) for Nibiru. | -| [common][code-x-common] | Holds helper and utility functions to be utilized by other `x/` modules. | -| [oracle][code-x-oracle] | Handles the posting of an up-to-date and accurate feed of exchange rates from the validators. | -| [perp][code-x-perp] | 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. | -| [spot][code-x-spot] | Responsible for creating, joining, and exiting liquidity pools. It also allows users to swap between two assets in an existing pool. It's a fully functional AMM. | +| Module | Description | +| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [wasm][code-x-wasm] | Implements the execution environment for [WebAssembly (WASM) smart contracts](https://nibiru.fi/docs/wasm/). | +| [devgas][code-x-devgas] | The `devgas` module of Nibiru Chain shares contract execution fees with smart contract developers. This aims to increase the adoption of Nibiru by offering CosmWasm smart contract developers a direct source of income based on usage. | +| [epochs][code-x-epochs] | The `epochs` module allows other modules to set hooks to be called to execute code automatically on a period basis. For example, "once a week, starting at UTC-time = x". `epochs` creates a generalized epoch interface. | +| [inflation][code-x-inflation] | Implements the [tokenomics](https://nibiru.fi/docs/learn/tokenomics.html) for Nibiru. | +| [common][code-x-common] | Holds helper and utility functions to be utilized by other `x/` modules. | +| [oracle][code-x-oracle] | Handles the posting of an up-to-date and accurate feed of exchange rates from the validators. | +| [spot][code-x-spot] | Responsible for creating, joining, and exiting liquidity pools. It also allows users to swap between two assets in an existing pool. It's a fully functional AMM. | [code-x-common]: https://github.com/NibiruChain/nibiru/tree/main/x/common [code-x-devgas]: https://nibiru.fi/docs/dev/x/nibiru-chain/devgas.html [code-x-epochs]: https://github.com/NibiruChain/nibiru/tree/main/x/epochs [code-x-inflation]: https://github.com/NibiruChain/nibiru/tree/main/x/inflation [code-x-oracle]: https://github.com/NibiruChain/nibiru/tree/main/x/oracle -[code-x-perp]: https://github.com/NibiruChain/nibiru/tree/main/x/perp [code-x-spot]: https://github.com/NibiruChain/nibiru/tree/main/x/spot Nibiru is built with the [Cosmos-SDK][cosmos-sdk-repo] on [Tendermint Core](https://tendermint.com/core/) consensus and communicates with other blockchain chains using the [Inter-Blockchain Communication (IBC)](https://github.com/cosmos/ibc) protocol. ----- +--- ## ⛓️ — Building: `make` commands @@ -94,10 +91,12 @@ Usage instructions for the `nibid` CLI are available at [docs.nibiru.fi/dev/cli] ### Running a Local Node On a fresh clone of the repo, simply run: + ```bash make localnet -``` -and open another terminal. +``` + +and open another terminal. ### Generate the protobufs @@ -131,19 +130,13 @@ Licensed under the [MIT License](./LICENSE.md). [license-badge]: https://img.shields.io/badge/License-MIT-blue.svg [cosmos-sdk-repo]: https://github.com/cosmos/cosmos-sdk -[badge-go-linter]: -https://github.com/NibiruChain/nibiru/actions/workflows/golangci-lint.yml/badge.svg?query=branch%3Amain -[workflow-go-linter]: -https://github.com/NibiruChain/nibiru/actions/workflows/golangci-lint.yml?query=branch%3Amain -[badge-go-releaser]: -https://github.com/NibiruChain/nibiru/actions/workflows/goreleaser.yml/badge.svg?query=branch%3Amain -[workflow-go-releaser]: -https://github.com/NibiruChain/nibiru/actions/workflows/goreleaser.yml?query=branch%3Amain - +[badge-go-linter]: https://github.com/NibiruChain/nibiru/actions/workflows/golangci-lint.yml/badge.svg?query=branch%3Amain +[workflow-go-linter]: https://github.com/NibiruChain/nibiru/actions/workflows/golangci-lint.yml?query=branch%3Amain +[badge-go-releaser]: https://github.com/NibiruChain/nibiru/actions/workflows/goreleaser.yml/badge.svg?query=branch%3Amain +[workflow-go-releaser]: https://github.com/NibiruChain/nibiru/actions/workflows/goreleaser.yml?query=branch%3Amain [social-twitter]: https://twitter.com/NibiruChain [social-discord]: https://discord.gg/nibirufi [social-telegram]: https://t.me/nibiruchain - [discord-badge]: https://img.shields.io/badge/Discord-7289DA?&logo=discord&logoColor=white [twitter-badge]: https://img.shields.io/badge/Twitter-1DA1F2?&logo=twitter&logoColor=white [telegram-badge]: https://img.shields.io/badge/Telegram-2CA5E0?&logo=telegram&logoColor=white @@ -153,7 +146,7 @@ https://github.com/NibiruChain/nibiru/actions/workflows/goreleaser.yml?query=bra [![version](https://img.shields.io/github/tag/nibiru-labs/nibiru.svg)](https://github.com/NibiruChain/nibiru/releases/latest) -[![Go Report Card](https://goreportcard.com/badge/github.com/NibiruChain/nibiru)](https://goreportcard.com/report/github.com/NibiruChain/nibiru) +[![Go Report Card](https://goreportcard.com/badge/github.com/NibiruChain/nibiru)](https://goreportcard.com/report/github.com/NibiruChain/nibiru) [![API Reference](https://godoc.org/github.com/NibiruChain/nibiru?status.svg)](https://godoc.org/github.com/NibiruChain/nibiru) diff --git a/app/keepers.go b/app/keepers.go index b6b54243f..2bcad97a8 100644 --- a/app/keepers.go +++ b/app/keepers.go @@ -110,9 +110,6 @@ import ( oracle "github.com/NibiruChain/nibiru/x/oracle" oraclekeeper "github.com/NibiruChain/nibiru/x/oracle/keeper" oracletypes "github.com/NibiruChain/nibiru/x/oracle/types" - perpkeeper "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - perpmodule "github.com/NibiruChain/nibiru/x/perp/v2/module" - perptypes "github.com/NibiruChain/nibiru/x/perp/v2/types" "github.com/NibiruChain/nibiru/x/spot" spotkeeper "github.com/NibiruChain/nibiru/x/spot/keeper" @@ -172,7 +169,6 @@ type AppKeepers struct { // Nibiru keepers // --------------- EpochsKeeper epochskeeper.Keeper - PerpKeeperV2 perpkeeper.Keeper SpotKeeper spotkeeper.Keeper OracleKeeper oraclekeeper.Keeper InflationKeeper inflationkeeper.Keeper @@ -215,7 +211,6 @@ func initStoreKeys() ( spottypes.StoreKey, oracletypes.StoreKey, epochstypes.StoreKey, - perptypes.StoreKey, inflationtypes.StoreKey, sudotypes.StoreKey, wasmtypes.StoreKey, @@ -371,12 +366,6 @@ func (app *NibiruApp) InitKeepers( appCodec, keys[epochstypes.StoreKey], ) - app.PerpKeeperV2 = perpkeeper.NewKeeper( - appCodec, keys[perptypes.StoreKey], - app.AccountKeeper, app.BankKeeper, app.OracleKeeper, app.EpochsKeeper, - app.SudoKeeper, - ) - app.InflationKeeper = inflationkeeper.NewKeeper( appCodec, keys[inflationtypes.StoreKey], app.GetSubspace(inflationtypes.ModuleName), app.AccountKeeper, app.BankKeeper, app.DistrKeeper, app.stakingKeeper, app.SudoKeeper, authtypes.FeeCollectorName, @@ -384,7 +373,6 @@ func (app *NibiruApp) InitKeepers( app.EpochsKeeper.SetHooks( epochstypes.NewMultiEpochHooks( - app.PerpKeeperV2.Hooks(), app.InflationKeeper.Hooks(), app.OracleKeeper.Hooks(), ), @@ -437,8 +425,8 @@ func (app *NibiruApp) InitKeepers( // NOTE: This keeper depends on all of pointers to the the Keepers to which // it binds. Thus, it must be instantiated after those keepers have been // assigned. - // For example, if there are bindings for the x/perp module, then the app - // passed to GetWasmOpts must already have a non-nil PerpKeeper. + // For example, if there are bindings for the x/inflation module, then the app + // passed to GetWasmOpts must already have a non-nil InflationKeeper. supportedFeatures := strings.Join(wasmdapp.AllCapabilities(), ",") app.WasmKeeper = wasmkeeper.NewKeeper( appCodec, @@ -593,7 +581,6 @@ func (app *NibiruApp) initAppModules( spot.NewAppModule(appCodec, app.SpotKeeper, app.AccountKeeper, app.BankKeeper), oracle.NewAppModule(appCodec, app.OracleKeeper, app.AccountKeeper, app.BankKeeper), epochs.NewAppModule(appCodec, app.EpochsKeeper), - perpmodule.NewAppModule(appCodec, app.PerpKeeperV2, app.AccountKeeper, app.BankKeeper, app.OracleKeeper), inflation.NewAppModule(app.InflationKeeper, app.AccountKeeper, *app.stakingKeeper), sudo.NewAppModule(appCodec, app.SudoKeeper), genmsg.NewAppModule(app.MsgServiceRouter()), @@ -664,7 +651,6 @@ func orderedModuleNames() []string { epochstypes.ModuleName, spottypes.ModuleName, oracletypes.ModuleName, - perptypes.ModuleName, inflationtypes.ModuleName, sudotypes.ModuleName, @@ -779,7 +765,6 @@ func ModuleBasicManager() module.BasicManager { spot.AppModuleBasic{}, oracle.AppModuleBasic{}, epochs.AppModuleBasic{}, - perpmodule.AppModuleBasic{}, inflation.AppModuleBasic{}, sudo.AppModuleBasic{}, wasm.AppModuleBasic{}, @@ -803,13 +788,6 @@ func ModuleAccPerms() map[string][]string { ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, ibcfeetypes.ModuleName: {}, - perptypes.ModuleName: {}, - perptypes.VaultModuleAccount: {}, - perptypes.PerpFundModuleAccount: {}, - perptypes.FeePoolModuleAccount: {}, - perptypes.DNRAllocationModuleAccount: {}, - perptypes.DNREscrowModuleAccount: {}, - epochstypes.ModuleName: {}, sudotypes.ModuleName: {}, common.TreasuryPoolModuleAccount: {}, @@ -818,7 +796,6 @@ func ModuleAccPerms() map[string][]string { } } -// initParamsKeeper init params perpammkeeper and its subspaces func initParamsKeeper( appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey storetypes.StoreKey, diff --git a/cmd/nibid/cmd/root.go b/cmd/nibid/cmd/root.go index 72587fac6..7e67c2610 100644 --- a/cmd/nibid/cmd/root.go +++ b/cmd/nibid/cmd/root.go @@ -29,7 +29,6 @@ import ( "github.com/NibiruChain/nibiru/app" oraclecli "github.com/NibiruChain/nibiru/x/oracle/client/cli" - perpv2cli "github.com/NibiruChain/nibiru/x/perp/v2/client/cli" ) // NewRootCmd creates a new root command for nibid. It is called once in the @@ -156,7 +155,6 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig app.EncodingConfig) { genesisCommand( encodingConfig, oraclecli.AddGenesisPricefeederDelegationCmd(app.DefaultNodeHome), - perpv2cli.AddMarketGenesisCmd(app.DefaultNodeHome), cli.AddSudoRootAccountCmd(app.DefaultNodeHome), ), queryCommand(), diff --git a/contrib/docker/chaosnet.Dockerfile b/contrib/docker/chaosnet.Dockerfile index 036b97f00..349823ec7 100644 --- a/contrib/docker/chaosnet.Dockerfile +++ b/contrib/docker/chaosnet.Dockerfile @@ -23,7 +23,6 @@ RUN apk --no-cache add \ COPY --from=builder /nibiru/build/nibid /usr/local/bin/nibid COPY ./contrib/scripts/chaosnet.sh ./ -COPY ./contrib/scripts/feat-perp.sh ./ RUN chmod +x ./chaosnet.sh ARG MNEMONIC ARG CHAIN_ID diff --git a/contrib/scripts/chaosnet.sh b/contrib/scripts/chaosnet.sh index 32ba318ff..40faf61e6 100755 --- a/contrib/scripts/chaosnet.sh +++ b/contrib/scripts/chaosnet.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # # This script is used in tandem with `contrib/docker/chaosnet.Dockerfile` to -# run nodes for Nibiru Chain networks inside docker containers. +# run nodes for Nibiru Chain networks inside docker containers. # - See CHAOSNET.md for usage instructions. set -e @@ -27,7 +27,6 @@ sed -i 's/enabled-unsafe-cors = false/enabled-unsafe-cors = true/' $HOME/.nibid/ sed -i "s/localhost:1317/0.0.0.0:$LCD_PORT/" $HOME/.nibid/config/app.toml sed -i "s/localhost:9090/0.0.0.0:$GRPC_PORT/" $HOME/.nibid/config/app.toml - # ------------------------------------------------------------------------ # Configure genesis params # ------------------------------------------------------------------------ @@ -44,9 +43,7 @@ add_genesis_param() { mv $HOME/.nibid/config/tmp_genesis.json $HOME/.nibid/config/genesis.json } -curr_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" -source "$curr_dir/feat-perp.sh" -add_genesis_perp_markets_offline +curr_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)" # recover mnemonic echo "$MNEMONIC" | nibid keys add validator --recover diff --git a/contrib/scripts/feat-perp.sh b/contrib/scripts/feat-perp.sh deleted file mode 100644 index 01a237186..000000000 --- a/contrib/scripts/feat-perp.sh +++ /dev/null @@ -1,62 +0,0 @@ -#!/bin/bash -set -e - -# add_genesis_reserve_amt: Used to configure initial reserve values of genesis -# perp markets. -add_genesis_reserve_amt() { - local M=1000000 - local num_users=300000 - local faucet_nusd_amt=100 - local reserve_amt=$(($num_users * $faucet_nusd_amt * $M)) - echo "$reserve_amt" -} - -# add_genesis_perp_markets_with_coingecko_prices: Queries Coingecko to set the -# initial values to for x/perp markets in the genesis. -add_genesis_perp_markets_with_coingecko_prices() { - local temp_json_fname="tmp_market_prices.json" - curl -X 'GET' \ - 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Cethereum&vs_currencies=usd' \ - -H 'accept: application/json' \ - >$temp_json_fname - - local reserve_amt=$(add_genesis_reserve_amt) - - price_btc=$(cat tmp_market_prices.json | jq -r '.bitcoin.usd') - price_btc=${price_btc%.*} - if [ -z "$price_btc" ]; then - return 1 - fi - - check_fail() { - if [ $? -eq 0 ]; then - echo "Command \"$*\" executed successfully." - else - echo "Command \"$*\" failed." - exit 1 - fi - } - - check_fail nibid genesis add-genesis-perp-market --pair="ubtc:unusd" --sqrt-depth="$reserve_amt" --price-multiplier="$price_btc" --oracle-pair="ubtc:uusd" - - price_eth=$(cat tmp_market_prices.json | jq -r '.ethereum.usd') - price_eth=${price_eth%.*} - if [ -z "$price_eth" ]; then - return 1 - fi - - check_fail nibid genesis add-genesis-perp-market --pair="ueth:unusd" --sqrt-depth=$reserve_amt --price-multiplier="$price_eth" --oracle-pair="ueth:uusd" - - echo 'tmp_market_prices: ' - cat $temp_json_fname | jq . - rm -f $temp_json_fname -} - -add_genesis_perp_markets_offline() { - local reserve_amt - reserve_amt=$(add_genesis_reserve_amt) - price_btc="20000" - price_eth="2000" - nibid genesis add-genesis-perp-market --pair="ubtc:unusd" --sqrt-depth="$reserve_amt" --price-multiplier="$price_btc" --oracle-pair="ubtc:uusd" - nibid genesis add-genesis-perp-market --pair="ueth:unusd" --sqrt-depth="$reserve_amt" --price-multiplier="$price_eth" --oracle-pair="ueth:uusd" -} diff --git a/contrib/scripts/localnet.sh b/contrib/scripts/localnet.sh index 21ff0443f..59331148f 100755 --- a/contrib/scripts/localnet.sh +++ b/contrib/scripts/localnet.sh @@ -58,9 +58,6 @@ echo_info "Parsing flags for the script..." # behavior of the script is to run make install if the flag --no-build is not present. FLAG_NO_BUILD=false -# $FLAG_PERP: Feature flag for x/perp. Enabled with `--features perp`. -FLAG_PERP=false - # $FLAG_SPOT: Feature flag for x/spot. Enabled with `--features spot`. FLAG_SPOT=false @@ -77,27 +74,26 @@ build_from_source() { # enable_feature_flag: Enables feature flags variables if present enable_feature_flag() { case $1 in - perp) FLAG_PERP=true ;; - spot) FLAG_SPOT=true ;; - *) echo_error "Unknown feature: $1" ;; + spot) FLAG_SPOT=true ;; + *) echo_error "Unknown feature: $1" ;; esac } # Iterate over flags, handling the cases: "--no-build" and "--features" while [[ $# -gt 0 ]]; do case $1 in - --no-build) - FLAG_NO_BUILD=true - shift - ;; - --features) - shift # Remove '--features' from arguments - while [[ $# -gt 0 && $1 != --* ]]; do - enable_feature_flag "$1" - shift # Remove the feature name from arguments - done - ;; - *) shift ;; # Unknown arg + --no-build) + FLAG_NO_BUILD=true + shift + ;; + --features) + shift # Remove '--features' from arguments + while [[ $# -gt 0 && $1 != --* ]]; do + enable_feature_flag "$1" + shift # Remove the feature name from arguments + done + ;; + *) shift ;; # Unknown arg esac done @@ -108,7 +104,6 @@ fi echo_info "Features flags:" echo "FLAG_NO_BUILD: $FLAG_NO_BUILD" -echo "FLAG_PERP: $FLAG_PERP" echo "FLAG_SPOT: $FLAG_SPOT" SEDOPTION="" @@ -193,20 +188,6 @@ add_genesis_param() { echo_info "Configuring genesis params" -if $FLAG_PERP; then - curr_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" - source "$curr_dir/feat-perp.sh" - - if add_genesis_perp_markets_with_coingecko_prices; then - echo_success "set perp markets with coingecko prices" - elif add_genesis_perp_markets_offline; then - echo_success "set perp markets with offline defaults" - else - echo_error "failed to set genesis perp markets" - exit 1 - fi -fi - # if $FLAG_SPOT; then # # Perform any actions specific to the x/spot feature # fi diff --git a/justfile b/justfile index 9c4a02662..037b68db2 100644 --- a/justfile +++ b/justfile @@ -39,7 +39,7 @@ lint: golangci-lint run --allow-parallel-runners --fix -# Runs a Nibiru local network. Ex: "just localnet --features perp spot" +# Runs a Nibiru local network. Ex: "just localnet --features spot" localnet *PASS_FLAGS: make localnet FLAGS="{{PASS_FLAGS}}" diff --git a/proto/nibiru/perp/v2/event.proto b/proto/nibiru/perp/v2/event.proto deleted file mode 100644 index c3854dd85..000000000 --- a/proto/nibiru/perp/v2/event.proto +++ /dev/null @@ -1,262 +0,0 @@ -syntax = "proto3"; - -package nibiru.perp.v2; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "nibiru/perp/v2/state.proto"; -import "google/protobuf/timestamp.proto"; - -option go_package = "github.com/NibiruChain/nibiru/x/perp/v2/types"; - -// Emitted when a position changes. -message PositionChangedEvent { - nibiru.perp.v2.Position final_position = 1 [ (gogoproto.nullable) = false ]; - - // Position notional (in quote units) after the change. In general, - // 'notional = baseAmount * priceQuotePerBase', where size is the baseAmount. - string position_notional = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // Transaction fee paid. A "taker" fee. - cosmos.base.v1beta1.Coin transaction_fee = 3 [ - (gogoproto.moretags) = "yaml:\"transaction_fee\"", - (gogoproto.nullable) = false - ]; - - // realize profits and losses after the change - string realized_pnl = 4 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (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. - cosmos.base.v1beta1.Coin bad_debt = 5 [ (gogoproto.nullable) = false ]; - - /* A funding payment made or received by the trader on the current position. - 'fundingPayment' 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 exchanges). - */ - string funding_payment = 6 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The block number at which this position was changed. - int64 block_height = 7; - - // 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 margin_to_user = 8 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - - // change_reason describes the reason for why the position resulted in a - // change. Change type can take the following values: - // - // - 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 ]; - - // exchanged_size represent the change in size for an existing position - // after the change. A positive value indicates that the position size - // increased, while a negative value indicates that the position size - // decreased. - string exchanged_size = 10 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // exchanged_notional represent the change in notional for an existing - // position after the change. A positive value indicates that the position - // notional increased, while a negative value indicates that the position - // notional decreased. - string exchanged_notional = 11 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// Emitted when a position is liquidated. Wraps a PositionChanged event since a -// liquidation causes position changes. -message PositionLiquidatedEvent { - nibiru.perp.v2.PositionChangedEvent position_changed_event = 1 - [ (gogoproto.nullable) = false ]; - - // Address of the account that executed the tx. - string liquidator_address = 2; - - // Commission (in margin units) received by 'liquidator'. - cosmos.base.v1beta1.Coin fee_to_liquidator = 3 [ - (gogoproto.moretags) = "yaml:\"fee_to_liquidator\"", - (gogoproto.nullable) = false - ]; - - // Commission (in margin units) given to the ecosystem fund. - cosmos.base.v1beta1.Coin fee_to_ecosystem_fund = 4 [ - (gogoproto.moretags) = "yaml:\"fee_to_ecosystem_fund\"", - (gogoproto.nullable) = false - ]; -} - -// Emitted when a position is settled. -message PositionSettledEvent { - // Identifier for the virtual pool of the position. - string pair = 1 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - - // Owner of the position. - string trader_address = 2; - - // Settled coin as dictated by the settlement price of the perp.amm. - repeated cosmos.base.v1beta1.Coin settled_coins = 3 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.moretags) = "yaml:\"settled_coins\"", - (gogoproto.nullable) = false - ]; -} - -// Emitted when the funding rate changes for a market. -message FundingRateChangedEvent { - // The pair for which the funding rate was calculated. - string pair = 1 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - - // The mark price of the pair. - string mark_price_twap = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The oracle index price of the pair. - string index_price_twap = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The latest premium fraction just calculated. - string premium_fraction = 5 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The market's latest cumulative premium fraction. - // The funding payment a position will pay is the difference between this - // value and the latest cumulative premium fraction on the position, - // multiplied by the position size. - string cumulative_premium_fraction = 6 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// Emitted when liquidation fails. -message LiquidationFailedEvent { - // The pair for which we are trying to liquidate. - string pair = 1 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - - // owner of the position. - string trader = 2; - - // Address of the account that executed the tx. - string liquidator = 3; - - enum LiquidationFailedReason { - UNSPECIFIED = 0; - - // the position is healthy and does not need to be liquidated. - POSITION_HEALTHY = 1; - - // the pair does not exist. - NONEXISTENT_PAIR = 2; - - // the position does not exist. - NONEXISTENT_POSITION = 3; - } - // Reason for the liquidation failure. - LiquidationFailedReason reason = 4; -} - -// This event is emitted when the amm is updated, which can be triggered by -// the following events: -// -// - swap -// - edit price multiplier -// - edit depth -message AmmUpdatedEvent { - // the final state of the AMM - nibiru.perp.v2.AMM final_amm = 1 [ (gogoproto.nullable) = false ]; - - // The mark price of the pair. - string mark_price_twap = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The oracle index price of the pair. - string index_price_twap = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// This event is emitted at the end of every block for persisting market changes -// off-chain -// -// Market changes are triggered by the following actions: -// -// - disabling market -// - changing market fees -// - bad debt is prepaid by the ecosystem fund -message MarketUpdatedEvent { - // the final state of the market - nibiru.perp.v2.Market final_market = 1 [ (gogoproto.nullable) = false ]; -} - -// EventShiftPegMultiplier: ABCI event emitted from MsgShiftPegMultiplier -message EventShiftPegMultiplier { - string old_peg_multiplier = 1 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string new_peg_multiplier = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - cosmos.base.v1beta1.Coin cost_paid = 3 [ (gogoproto.nullable) = false ]; -} - -// EventShiftSwapInvariant: ABCI event emitted from MsgShiftSwapInvariant -message EventShiftSwapInvariant { - string old_swap_invariant = 1 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - string new_swap_invariant = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - cosmos.base.v1beta1.Coin cost_paid = 3 [ (gogoproto.nullable) = false ]; -} diff --git a/proto/nibiru/perp/v2/genesis.proto b/proto/nibiru/perp/v2/genesis.proto deleted file mode 100644 index 6e66a77e8..000000000 --- a/proto/nibiru/perp/v2/genesis.proto +++ /dev/null @@ -1,101 +0,0 @@ -syntax = "proto3"; - -package nibiru.perp.v2; - -import "cosmos/base/v1beta1/coin.proto"; -import "google/api/annotations.proto"; -import "gogoproto/gogo.proto"; -import "nibiru/perp/v2/state.proto"; - -option go_package = "github.com/NibiruChain/nibiru/x/perp/v2/types"; - -// GenesisState defines the perp module's genesis state. -// Thge genesis state is used not only to start the network but also useful for -// exporting and importing state during network upgrades. -message GenesisState { - repeated nibiru.perp.v2.Market markets = 2 [ (gogoproto.nullable) = false ]; - - repeated nibiru.perp.v2.AMM amms = 3 [ (gogoproto.nullable) = false ]; - - repeated GenesisPosition positions = 4 [ (gogoproto.nullable) = false ]; - - repeated nibiru.perp.v2.ReserveSnapshot reserve_snapshots = 5 - [ (gogoproto.nullable) = false ]; - - uint64 dnr_epoch = 6; - - message TraderVolume { - string trader = 1; - uint64 epoch = 2; - string volume = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - } - - // For testing purposes, we allow the collateral to be set at genesis - string collateral_denom = 11; - - repeated TraderVolume trader_volumes = 7 [ (gogoproto.nullable) = false ]; - - message Discount { - string fee = 1 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - string volume = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - } - - repeated Discount global_discount = 8 [ (gogoproto.nullable) = false ]; - - repeated CustomDiscount custom_discounts = 9 [ (gogoproto.nullable) = false ]; - - message CustomDiscount { - string trader = 1; - Discount discount = 2; - } - - repeated nibiru.perp.v2.GenesisMarketLastVersion market_last_versions = 10 - [ (gogoproto.nullable) = false ]; - - repeated GlobalVolume global_volumes = 13 [ (gogoproto.nullable) = false ]; - - repeated DNRAllocation rebates_allocations = 12 [ (gogoproto.nullable) = false ]; - - string dnr_epoch_name = 14; - - message GlobalVolume { - uint64 epoch = 1; - string volume = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - } -} - -// GenesisMarketLastVersion is the last version including pair only used for -// genesis -message GenesisMarketLastVersion { - string pair = 1 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - - uint64 version = 2; -} - -message GenesisPosition { - string pair = 1 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - - uint64 version = 2; - - Position position = 3 [ (gogoproto.nullable) = false ]; -} diff --git a/proto/nibiru/perp/v2/query.proto b/proto/nibiru/perp/v2/query.proto deleted file mode 100644 index 7d16b8f0f..000000000 --- a/proto/nibiru/perp/v2/query.proto +++ /dev/null @@ -1,163 +0,0 @@ -syntax = "proto3"; - -package nibiru.perp.v2; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "nibiru/perp/v2/state.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos/base/query/v1beta1/pagination.proto"; - -option go_package = "github.com/NibiruChain/nibiru/x/perp/v2/types"; - -// Query defines the gRPC querier service. -service Query { - // QueryPosition: Query one position on the given market for a user - rpc QueryPosition(QueryPositionRequest) returns (QueryPositionResponse) { - option (google.api.http).get = "/nibiru/perp/v2/position"; - } - - // QueryPositions: Query all positions for a user - rpc QueryPositions(QueryPositionsRequest) returns (QueryPositionsResponse) { - option (google.api.http).get = "/nibiru/perp/v2/positions"; - } - - // QueryPositionStore queries all of the positions in the KV store. - rpc QueryPositionStore(QueryPositionStoreRequest) - returns (QueryPositionStoreResponse) { - option (google.api.http).get = "/nibiru/perp/v2/position_store"; - } - - // Queries the module accounts for x/perp - rpc ModuleAccounts(QueryModuleAccountsRequest) - returns (QueryModuleAccountsResponse) { - option (google.api.http).get = "/nibiru/perp/v2/module_accounts"; - } - - // QueryMarkets: Query all markets - rpc QueryMarkets(QueryMarketsRequest) returns (QueryMarketsResponse) { - option (google.api.http).get = "/nibiru/perp/v2/markets"; - } - - // QueryCollateral: Queries info about the collateral - rpc QueryCollateral(QueryCollateralRequest) - returns (QueryCollateralResponse) { - option (google.api.http).get = "/nibiru/perp/v2/collateral"; - } -} - -// ---------------------------------------- Positions - -// QueryPositionsRequest: Request type for the -// "nibiru.perp.v2.Query/Positions" gRPC service method -message QueryPositionsRequest { string trader = 1; } - -// QueryPositionsResponse: Response type for the -// "nibiru.perp.v2.Query/Positions" gRPC service method -message QueryPositionsResponse { - repeated nibiru.perp.v2.QueryPositionResponse positions = 1 - [ (gogoproto.nullable) = false ]; -} - -// QueryPositionStoreRequest: Request type for the -// "nibiru.perp.v2.Query/PositionStore" gRPC service method -message QueryPositionStoreRequest { - // pagination defines a paginated request - cosmos.base.query.v1beta1.PageRequest pagination = 1; -} - -// QueryPositionStoreResponse: Response type for the -// "nibiru.perp.v2.Query/PositionStore" gRPC service method -message QueryPositionStoreResponse { - // Position responses: collection of all stored positions (with pagination) - repeated nibiru.perp.v2.Position positions = 1 - [ (gogoproto.nullable) = false ]; - - // pagination defines a paginated response - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// ---------------------------------------- Position - -// QueryPositionRequest: Request type for the -// "nibiru.perp.v2.Query/Position" gRPC service method -message QueryPositionRequest { - string pair = 1 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - - string trader = 2; -} - -// QueryPositionResponse: Response type for the -// "nibiru.perp.v2.Query/Position" gRPC service method -message QueryPositionResponse { - // The position as it exists in the blockchain state - nibiru.perp.v2.Position position = 1 [ (gogoproto.nullable) = false ]; - - // The position's current notional value, if it were to be entirely closed (in - // margin units). - string position_notional = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The position's unrealized PnL. - string unrealized_pnl = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // margin ratio of the position based on the spot price - string margin_ratio = 4 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// ---------------------------------------- QueryModuleAccounts - -// QueryModuleAccountsRequest: Request type for the -// "nibiru.perp.v2.Query/ModuleAccounts" gRPC service method -message QueryModuleAccountsRequest {} - -// QueryModuleAccountsResponse: Response type for the -// "nibiru.perp.v2.Query/ModuleAccounts" gRPC service method -message QueryModuleAccountsResponse { - repeated nibiru.perp.v2.AccountWithBalance accounts = 1 - [ (gogoproto.nullable) = false ]; -} - -message AccountWithBalance { - string name = 1; - string address = 2; - - repeated cosmos.base.v1beta1.Coin balance = 3 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -message AmmMarket { - nibiru.perp.v2.Market market = 1 [ (gogoproto.nullable) = false ]; - nibiru.perp.v2.AMM amm = 2 [ (gogoproto.nullable) = false ]; -} - -message QueryMarketsRequest { bool versioned = 1; } - -message QueryMarketsResponse { - repeated nibiru.perp.v2.AmmMarket amm_markets = 1 - [ (gogoproto.nullable) = false ]; -} - -// ---------------------------------------- QueryCollateral - -// QueryCollateralRequest: Request type for the -// "nibiru.perp.v2.Query/Collateral" gRPC service method -message QueryCollateralRequest {} - -// QueryCollateralRequest: Response type for the -// "nibiru.perp.v2.Query/Collateral" gRPC service method -message QueryCollateralResponse { string collateral_denom = 1; } diff --git a/proto/nibiru/perp/v2/state.proto b/proto/nibiru/perp/v2/state.proto deleted file mode 100644 index 50a2d4f4b..000000000 --- a/proto/nibiru/perp/v2/state.proto +++ /dev/null @@ -1,248 +0,0 @@ -syntax = "proto3"; - -package nibiru.perp.v2; - -import "gogoproto/gogo.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; -import "google/protobuf/duration.proto"; - -option go_package = "github.com/NibiruChain/nibiru/x/perp/v2/types"; - -// The direction that the user is trading in -// LONG means the user is going long the base asset (e.g. buy BTC) -// SHORT means the user is shorting the base asset (e.g. sell BTC) -enum Direction { - DIRECTION_UNSPECIFIED = 0; - LONG = 1; - SHORT = 2; -} - -// Enumerates different options of calculating twap. -enum TwapCalcOption { - TWAP_CALC_OPTION_UNSPECIFIED = 0; - - // Spot price from quote asset reserve / base asset reserve - SPOT = 1; - - // Swapping with quote assets, output denominated in base assets - QUOTE_ASSET_SWAP = 2; - - // Swapping with base assets, output denominated in quote assets - BASE_ASSET_SWAP = 3; -} - -message Market { - // the trading pair represented by this market - // always BASE:QUOTE, e.g. BTC:NUSD or ETH:NUSD - string pair = 1 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - - // whether or not the market is enabled - bool enabled = 2; - - // the version of the Market, only one market can exist per pair, when one is closed it cannot be reactivated, - // so a new market must be created, this is the version of the market - uint64 version = 14; - - // the minimum margin ratio which a user must maintain on this market - string maintenance_margin_ratio = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // the maximum leverage a user is able to be taken on this market - string max_leverage = 4 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // Latest cumulative premium fraction for a given pair. - // Calculated once per funding rate interval. - // A premium fraction is the difference between mark and index, divided by the - // number of payments per day. (mark - index) / # payments in a day - string latest_cumulative_premium_fraction = 5 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // the percentage of the notional given to the exchange when trading - string exchange_fee_ratio = 6 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // the percentage of the notional transferred to the ecosystem fund when - // trading - string ecosystem_fund_fee_ratio = 7 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // the percentage of liquidated position that will be - // given to out as a reward. Half of the liquidation fee is given to the - // liquidator, and the other half is given to the ecosystem fund. - string liquidation_fee_ratio = 8 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // the portion of the position size we try to liquidate if the available - // margin is higher than liquidation fee - string partial_liquidation_ratio = 9 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // specifies the interval on which the funding rate is updated - string funding_rate_epoch_id = 10; - - // amount of time to look back for TWAP calculations - google.protobuf.Duration twap_lookback_window = 11 - [ (gogoproto.nullable) = false, (gogoproto.stdduration) = true ]; - - // the amount of collateral already credited from the ecosystem fund - cosmos.base.v1beta1.Coin prepaid_bad_debt = 12 - [ (gogoproto.nullable) = false ]; - - // the maximum funding rate payment per epoch, this represents the maximum - // amount of funding that can be paid out per epoch as a percentage of the - // position size - string max_funding_rate = 13 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.stdduration) = true, - (gogoproto.nullable) = false - ]; - - // the pair of the oracle that is used to determine the index price - // for the market - string oracle_pair = 15 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; -} - -// MarketLastVersion is used to store the last version of the market -message MarketLastVersion { - // version of the market - uint64 version = 1; -} - -message AMM { - // identifies the market this AMM belongs to - string pair = 1 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - - // the version of the AMM, only one AMM can exist per pair, when one is closed it cannot be reactivated, - // so a new AMM must be created, this is the version of the AMM - uint64 version = 8; - - // the amount of base reserves this AMM has - string base_reserve = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // the amount of quote reserves this AMM has - string quote_reserve = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // sqrt(k) - string sqrt_depth = 4 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // the price multiplier of the dynamic AMM - string price_multiplier = 5 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // Total long refers to the sum of long open notional in base. - string total_long = 6 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // Total short refers to the sum of short open notional in base. - string total_short = 7 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The settlement price if the AMM is settled. - string settlement_price = 9 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.stdduration) = true, - (gogoproto.nullable) = false - ]; -} - -message Position { - // address identifies the address owner of this position - string trader_address = 1; - - // pair identifies the pair associated with this position - string pair = 2 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - - // the position size - string size = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // amount of margin remaining in the position - string margin = 4 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // value of position in quote assets when opened - string open_notional = 5 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The most recent cumulative premium fraction this position has. - // Used to calculate the next funding payment. - string latest_cumulative_premium_fraction = 6 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // last block number this position was updated - int64 last_updated_block_number = 7; -} - -// a snapshot of the perp.amm's reserves at a given point in time -message ReserveSnapshot { - AMM amm = 1 [ (gogoproto.nullable) = false ]; - - // milliseconds since unix epoch - int64 timestamp_ms = 2; -} - -// DNRAllocation represents a rebates allocation for a given epoch. -message DNRAllocation { - // epoch defines the reference epoch for the allocation. - uint64 epoch = 1; - // amount of DNR allocated for the epoch. - repeated cosmos.base.v1beta1.Coin amount = 2 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} diff --git a/proto/nibiru/perp/v2/tx.proto b/proto/nibiru/perp/v2/tx.proto deleted file mode 100644 index 4a8e22893..000000000 --- a/proto/nibiru/perp/v2/tx.proto +++ /dev/null @@ -1,473 +0,0 @@ -syntax = "proto3"; - -package nibiru.perp.v2; - -import "google/api/annotations.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "gogoproto/gogo.proto"; -import "nibiru/perp/v2/state.proto"; - -option go_package = "github.com/NibiruChain/nibiru/x/perp/v2/types"; - -// Msg defines the x/perp Msg service. -service Msg { - - rpc RemoveMargin(MsgRemoveMargin) returns (MsgRemoveMarginResponse) {} - - rpc AddMargin(MsgAddMargin) returns (MsgAddMarginResponse) {} - - rpc MultiLiquidate(MsgMultiLiquidate) returns (MsgMultiLiquidateResponse) {} - - rpc MarketOrder(MsgMarketOrder) returns (MsgMarketOrderResponse) {} - - rpc ClosePosition(MsgClosePosition) returns (MsgClosePositionResponse) {} - - rpc PartialClose(MsgPartialClose) returns (MsgPartialCloseResponse) {} - - rpc SettlePosition(MsgSettlePosition) returns (MsgClosePositionResponse) {} - - rpc DonateToEcosystemFund(MsgDonateToEcosystemFund) - returns (MsgDonateToEcosystemFundResponse) {} - - // ChangeCollateralDenom: Updates the collateral denom. A denom is valid if it - // is possible to make an sdk.Coin using it. [SUDO] Only callable by sudoers. - rpc ChangeCollateralDenom(MsgChangeCollateralDenom) - returns (MsgChangeCollateralDenomResponse) {} - - rpc AllocateEpochRebates(MsgAllocateEpochRebates) - returns (MsgAllocateEpochRebatesResponse) {} - - rpc WithdrawEpochRebates(MsgWithdrawEpochRebates) - returns (MsgWithdrawEpochRebatesResponse) {} - - // ShiftPegMultiplier: gRPC tx msg for changing a market's peg multiplier. - // [SUDO] Only callable by sudoers. - rpc ShiftPegMultiplier(MsgShiftPegMultiplier) - returns (MsgShiftPegMultiplierResponse) {} - - // ShiftSwapInvariant: gRPC tx msg for changing a market's swap invariant. - // [SUDO] Only callable by sudoers. - rpc ShiftSwapInvariant(MsgShiftSwapInvariant) - returns (MsgShiftSwapInvariantResponse) {} - - // WithdrawFromPerpFund: gRPC tx msg to withdraw from the perp fund module - // account. [SUDO] Only callable by sudoers. - rpc WithdrawFromPerpFund(MsgWithdrawFromPerpFund) - returns (MsgWithdrawFromPerpFundResponse) {} - - // CloseMarket: gRPC tx msg for closing a market. - // [Admin] Only callable by sudoers. - rpc CloseMarket(MsgCloseMarket) returns (MsgCloseMarketResponse) {} -} - - -// -------------------------- Settle Position -------------------------- - -/* MsgSettlePosition: Msg to remove margin. */ -message MsgSettlePosition { - string sender = 1; - - string pair = 2 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - - uint64 version = 3; -} - -// -------------------------- RemoveMargin -------------------------- - -/* MsgRemoveMargin: Msg to remove margin. */ -message MsgRemoveMargin { - string sender = 1; - - string pair = 2 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - - cosmos.base.v1beta1.Coin margin = 3 [ (gogoproto.nullable) = false ]; -} - -message MsgRemoveMarginResponse { - // tokens transferred back to the trader - cosmos.base.v1beta1.Coin margin_out = 1 [ (gogoproto.nullable) = false ]; - - // the funding payment applied on this position interaction - string funding_payment = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The resulting position - nibiru.perp.v2.Position position = 3; -} - -// -------------------------- AddMargin -------------------------- - -/* MsgAddMargin: Msg to remove margin. */ -message MsgAddMargin { - string sender = 1; - - string pair = 2 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - - cosmos.base.v1beta1.Coin margin = 3 [ (gogoproto.nullable) = false ]; -} - -message MsgAddMarginResponse { - string funding_payment = 1 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - nibiru.perp.v2.Position position = 2; -} - -// -------------------------- Liquidation -------------------------- - -message MsgMultiLiquidate { - string sender = 1; - - message Liquidation { - string pair = 1 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - string trader = 2; - } - - repeated Liquidation liquidations = 2; -} - -message MsgMultiLiquidateResponse { - message LiquidationResponse { - bool success = 1; - string error = 2; - - cosmos.base.v1beta1.Coin liquidator_fee = 3 [ (gogoproto.nullable) = true ]; - // nullable since no fee is taken on failed liquidation - - cosmos.base.v1beta1.Coin perp_ef_fee = 4 - [ (gogoproto.nullable) = true ]; // perp ecosystem fund - // nullable since no fee is taken on failed liquidation - - string trader = 5; - string pair = 6 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - } - - repeated LiquidationResponse liquidations = 1; -} - -// -------------------------- MarketOrder -------------------------- - -message MsgMarketOrder { - string sender = 1; - - string pair = 2 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - - nibiru.perp.v2.Direction side = 3; - - string quote_asset_amount = 4 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - - string leverage = 5 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - string base_asset_amount_limit = 6 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} - -message MsgMarketOrderResponse { - nibiru.perp.v2.Position position = 1; - - // The amount of quote assets exchanged. - string exchanged_notional_value = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The amount of base assets exchanged. - string exchanged_position_size = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The funding payment applied on this position change, measured in quote - // units. - string funding_payment = 4 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The amount of PnL realized on this position changed, measured in quote - // units. - string realized_pnl = 5 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The unrealized PnL in the position after the position change, measured in - // quote units. - string unrealized_pnl_after = 6 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The amount of margin the trader has to give to the vault. - // A negative value means the vault pays the trader. - string margin_to_vault = 7 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The position's notional value after the position change, measured in quote - // units. - string position_notional = 8 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// -------------------------- ClosePosition -------------------------- - -message MsgClosePosition { - string sender = 1; - - string pair = 2 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; -} - -message MsgClosePositionResponse { - // The amount of quote assets exchanged. - string exchanged_notional_value = 1 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The amount of base assets exchanged. - string exchanged_position_size = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The funding payment applied on this position change, measured in quote - // units. - string funding_payment = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The amount of PnL realized on this position changed, measured in quote - // units. - string realized_pnl = 4 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The amount of margin the trader receives after closing the position, from - // the vault. Should never be negative. - string margin_to_trader = 5 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -message MsgPartialClose { - string sender = 1; - - string pair = 2 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - - string size = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -message MsgPartialCloseResponse { - // The amount of quote assets exchanged. - string exchanged_notional_value = 1 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The amount of base assets exchanged. - string exchanged_position_size = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The funding payment applied on this position change, measured in quote - // units. - string funding_payment = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The amount of PnL realized on this position changed, measured in quote - // units. - string realized_pnl = 4 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; - - // The amount of margin the trader receives after closing the position, from - // the vault. Should never be negative. - string margin_to_trader = 5 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -// -------------------------- DonateToEcosystemFund -------------------------- - -message MsgDonateToEcosystemFund { - string sender = 1; - - // donation to the EF - cosmos.base.v1beta1.Coin donation = 2 [ - (gogoproto.moretags) = "yaml:\"donation\"", - (gogoproto.nullable) = false - ]; -} - -message MsgDonateToEcosystemFundResponse {} - -// ----------------------- MsgChangeCollateralDenom ----------------------- - -// MsgChangeCollateralDenom: Changes the collateral denom for the module. -// [SUDO] Only callable by sudoers. -message MsgChangeCollateralDenom { - string sender = 1; - string new_denom = 2; -} - -message MsgChangeCollateralDenomResponse {} - -// -------------------------- AllocateEpochRebates -------------------------- -message MsgAllocateEpochRebates { - string sender = 1; - - // rebates to allocate - repeated cosmos.base.v1beta1.Coin rebates = 2 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -message MsgAllocateEpochRebatesResponse { - repeated cosmos.base.v1beta1.Coin total_epoch_rebates = 1 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// -------------------------- WithdrawEpochRebates -------------------------- -message MsgWithdrawEpochRebates { - string sender = 1; - repeated uint64 epochs = 2; -} - -message MsgWithdrawEpochRebatesResponse { - repeated cosmos.base.v1beta1.Coin withdrawn_rebates = 1 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// -------------------------- ShiftPegMultiplier -------------------------- - -// MsgShiftPegMultiplier: gRPC tx msg for changing the peg multiplier. -// [SUDO] Only callable sudoers. -message MsgShiftPegMultiplier { - string sender = 1; - string pair = 2 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - string new_peg_mult = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; -} - -message MsgShiftPegMultiplierResponse {} - -// -------------------------- ShiftSwapInvariant -------------------------- - -// MsgShiftSwapInvariant: gRPC tx msg for changing the swap invariant. -// [SUDO] Only callable sudoers. -message MsgShiftSwapInvariant { - string sender = 1; - string pair = 2 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; - string new_swap_invariant = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; -} - -message MsgShiftSwapInvariantResponse {} - -// -------------------------- WithdrawFromPerpFund -------------------------- - -// MsgWithdrawFromPerpFund: gRPC tx msg for changing the swap invariant. -// [SUDO] Only callable sudoers. -message MsgWithdrawFromPerpFund { - string sender = 1; - string amount = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.nullable) = false - ]; - // Optional denom in case withdrawing assets aside from NUSD. - string denom = 3; - string to_addr = 4; -} - -message MsgWithdrawFromPerpFundResponse {} - -// -------------------------- CloseMarket -------------------------- - -// CloseMarket: gRPC tx msg for closing a market. -// Admin-only. -message MsgCloseMarket { - string sender = 1; - string pair = 2 [ - (gogoproto.customtype) = - "github.com/NibiruChain/nibiru/x/common/asset.Pair", - (gogoproto.nullable) = false - ]; -} - -message MsgCloseMarketResponse {} diff --git a/simapp/sim_test.go b/simapp/sim_test.go index a1e1bc4ce..5f3e5a2fd 100644 --- a/simapp/sim_test.go +++ b/simapp/sim_test.go @@ -40,7 +40,6 @@ import ( epochstypes "github.com/NibiruChain/nibiru/x/epochs/types" inflationtypes "github.com/NibiruChain/nibiru/x/inflation/types" oracletypes "github.com/NibiruChain/nibiru/x/oracle/types" - perptypes "github.com/NibiruChain/nibiru/x/perp/v2/types" spottypes "github.com/NibiruChain/nibiru/x/spot/types" sudotypes "github.com/NibiruChain/nibiru/x/sudo/types" tokenfactorytypes "github.com/NibiruChain/nibiru/x/tokenfactory/types" @@ -282,7 +281,6 @@ func TestAppImportExport(t *testing.T) { {oldApp.GetKey(epochstypes.StoreKey), newApp.GetKey(epochstypes.StoreKey), [][]byte{}}, {oldApp.GetKey(inflationtypes.StoreKey), newApp.GetKey(inflationtypes.StoreKey), [][]byte{}}, {oldApp.GetKey(oracletypes.StoreKey), newApp.GetKey(oracletypes.StoreKey), [][]byte{}}, - {oldApp.GetKey(perptypes.StoreKey), newApp.GetKey(perptypes.StoreKey), [][]byte{}}, {oldApp.GetKey(spottypes.StoreKey), newApp.GetKey(spottypes.StoreKey), [][]byte{}}, {oldApp.GetKey(sudotypes.StoreKey), newApp.GetKey(sudotypes.StoreKey), [][]byte{}}, {oldApp.GetKey(tokenfactorytypes.StoreKey), newApp.GetKey(tokenfactorytypes.StoreKey), [][]byte{}}, diff --git a/x/common/testutil/cli/network.go b/x/common/testutil/cli/network.go index b80d227eb..897f286a5 100644 --- a/x/common/testutil/cli/network.go +++ b/x/common/testutil/cli/network.go @@ -42,8 +42,6 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "google.golang.org/grpc" - perpV2types "github.com/NibiruChain/nibiru/x/perp/v2/types" - "github.com/NibiruChain/nibiru/x/common/denoms" "github.com/NibiruChain/nibiru/app" @@ -176,7 +174,6 @@ func BuildNetworkConfig(appGenesis app.GenesisState) Config { BondedTokens: sdk.TokensFromConsensusPower(100, sdk.DefaultPowerReduction), StartingTokens: sdk.NewCoins( sdk.NewCoin(denoms.NUSD, sdk.TokensFromConsensusPower(1e12, sdk.DefaultPowerReduction)), - sdk.NewCoin(perpV2types.TestingCollateralDenomNUSD, sdk.TokensFromConsensusPower(1e12, sdk.DefaultPowerReduction)), sdk.NewCoin(denoms.NIBI, sdk.TokensFromConsensusPower(1e12, sdk.DefaultPowerReduction)), sdk.NewCoin(denoms.USDC, sdk.TokensFromConsensusPower(1e12, sdk.DefaultPowerReduction)), ), diff --git a/x/common/testutil/cli/query.go b/x/common/testutil/cli/query.go index ef96a2ef2..871cc525a 100644 --- a/x/common/testutil/cli/query.go +++ b/x/common/testutil/cli/query.go @@ -16,8 +16,6 @@ import ( "github.com/NibiruChain/nibiru/x/common/asset" oraclecli "github.com/NibiruChain/nibiru/x/oracle/client/cli" oracletypes "github.com/NibiruChain/nibiru/x/oracle/types" - perpv2cli "github.com/NibiruChain/nibiru/x/perp/v2/client/cli" - perpv2types "github.com/NibiruChain/nibiru/x/perp/v2/types" sudocli "github.com/NibiruChain/nibiru/x/sudo/cli" sudotypes "github.com/NibiruChain/nibiru/x/sudo/types" ) @@ -92,44 +90,6 @@ func ExecQuery( } } -func QueryMarketsV2( - clientCtx client.Context, -) (*perpv2types.QueryMarketsResponse, error) { - queryResp := new(perpv2types.QueryMarketsResponse) - if err := ExecQuery(clientCtx, perpv2cli.CmdQueryMarkets(), []string{}, queryResp); err != nil { - return nil, err - } - return queryResp, nil -} - -func QueryMarketV2( - clientCtx client.Context, pair asset.Pair, -) (*perpv2types.AmmMarket, error) { - queryResp, err := QueryMarketsV2(clientCtx) - if err != nil { - return nil, err - } - - ammMarket := new(perpv2types.AmmMarket) - found := false - for _, duo := range queryResp.AmmMarkets { - if duo.Amm.Pair == pair { - *ammMarket = duo - found = true - break - } - } - - if !found { - jsonBz := clientCtx.Codec.MustMarshalJSON(queryResp) - - return nil, fmt.Errorf( - `expected market "%s" in response\nqueryResp: %s`, - pair, jsonBz) - } - return ammMarket, nil -} - func QueryOracleExchangeRate(clientCtx client.Context, pair asset.Pair) (*oracletypes.QueryExchangeRateResponse, error) { var queryResp oracletypes.QueryExchangeRateResponse if err := ExecQuery(clientCtx, oraclecli.GetCmdQueryExchangeRates(), []string{pair.String()}, &queryResp); err != nil { @@ -138,14 +98,6 @@ func QueryOracleExchangeRate(clientCtx client.Context, pair asset.Pair) (*oracle return &queryResp, nil } -func QueryPositionV2(ctx client.Context, pair asset.Pair, trader sdk.AccAddress) (*perpv2types.QueryPositionResponse, error) { - var queryResp perpv2types.QueryPositionResponse - if err := ExecQuery(ctx, perpv2cli.CmdQueryPosition(), []string{trader.String(), pair.String()}, &queryResp); err != nil { - return nil, err - } - return &queryResp, nil -} - func QueryTx(ctx client.Context, txHash string) (*sdk.TxResponse, error) { var queryResp sdk.TxResponse if err := ExecQuery( diff --git a/x/common/testutil/genesis/perp_genesis.go b/x/common/testutil/genesis/perp_genesis.go deleted file mode 100644 index 3d9287014..000000000 --- a/x/common/testutil/genesis/perp_genesis.go +++ /dev/null @@ -1,237 +0,0 @@ -package genesis - -import ( - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - epochstypes "github.com/NibiruChain/nibiru/x/epochs/types" - perpv2types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func AddPerpV2Genesis(gen app.GenesisState) app.GenesisState { - extraMarketAmms := map[asset.Pair]perpv2types.AmmMarket{ - asset.Registry.Pair(denoms.BTC, denoms.NUSD): { - Market: perpv2types.Market{ - Pair: asset.NewPair(denoms.BTC, denoms.NUSD), - OraclePair: asset.NewPair(denoms.BTC, denoms.USD), - Version: 1, - Enabled: true, - MaintenanceMarginRatio: sdk.MustNewDecFromStr("0.04"), - MaxLeverage: sdk.MustNewDecFromStr("20"), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - ExchangeFeeRatio: sdk.MustNewDecFromStr("0.0010"), - EcosystemFundFeeRatio: sdk.MustNewDecFromStr("0.0010"), - LiquidationFeeRatio: sdk.MustNewDecFromStr("0.0500"), - PartialLiquidationRatio: sdk.MustNewDecFromStr("0.5"), - FundingRateEpochId: "30 min", - MaxFundingRate: sdk.NewDec(1), - TwapLookbackWindow: time.Minute * 30, - PrepaidBadDebt: sdk.NewInt64Coin(denoms.NUSD, 0), - }, - Amm: perpv2types.AMM{ - Pair: asset.Registry.Pair(denoms.BTC, denoms.NUSD), - Version: 1, - BaseReserve: sdk.NewDec(10e6), - QuoteReserve: sdk.NewDec(10e6), - SqrtDepth: sdk.NewDec(10e6), - PriceMultiplier: sdk.NewDec(6_000), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - }, - asset.Registry.Pair(denoms.ATOM, denoms.NUSD): { - Market: perpv2types.Market{ - Pair: asset.NewPair(denoms.ATOM, denoms.NUSD), - OraclePair: asset.NewPair(denoms.ATOM, denoms.USD), - Enabled: true, - Version: 1, - MaintenanceMarginRatio: sdk.MustNewDecFromStr("0.0625"), - MaxLeverage: sdk.MustNewDecFromStr("15"), - ExchangeFeeRatio: sdk.MustNewDecFromStr("0.0010"), - EcosystemFundFeeRatio: sdk.MustNewDecFromStr("0.0010"), - LiquidationFeeRatio: sdk.MustNewDecFromStr("0.0500"), - PartialLiquidationRatio: sdk.MustNewDecFromStr("0.5"), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - FundingRateEpochId: epochstypes.ThirtyMinuteEpochID, - MaxFundingRate: sdk.NewDec(1), - TwapLookbackWindow: time.Minute * 30, - PrepaidBadDebt: sdk.NewInt64Coin(denoms.NUSD, 0), - }, - Amm: perpv2types.AMM{ - Pair: asset.Registry.Pair(denoms.ATOM, denoms.NUSD), - Version: 1, - BaseReserve: sdk.NewDec(10e6), - QuoteReserve: sdk.NewDec(10e6), - SqrtDepth: sdk.NewDec(10e6), - PriceMultiplier: sdk.NewDec(6_000), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - }, - asset.Registry.Pair(denoms.OSMO, denoms.NUSD): { - Market: perpv2types.Market{ - Pair: asset.NewPair(denoms.OSMO, denoms.NUSD), - OraclePair: asset.NewPair(denoms.OSMO, denoms.USD), - Enabled: true, - Version: 1, - MaintenanceMarginRatio: sdk.MustNewDecFromStr("0.0625"), - MaxLeverage: sdk.MustNewDecFromStr("15"), - ExchangeFeeRatio: sdk.MustNewDecFromStr("0.0010"), - EcosystemFundFeeRatio: sdk.MustNewDecFromStr("0.0010"), - LiquidationFeeRatio: sdk.MustNewDecFromStr("0.0500"), - PartialLiquidationRatio: sdk.MustNewDecFromStr("0.5"), - FundingRateEpochId: epochstypes.ThirtyMinuteEpochID, - MaxFundingRate: sdk.NewDec(1), - TwapLookbackWindow: time.Minute * 30, - PrepaidBadDebt: sdk.NewInt64Coin(denoms.NUSD, 0), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }, - Amm: perpv2types.AMM{ - Pair: asset.Registry.Pair(denoms.OSMO, denoms.NUSD), - Version: 1, - BaseReserve: sdk.NewDec(10e6), - QuoteReserve: sdk.NewDec(10e6), - SqrtDepth: sdk.NewDec(10e6), - PriceMultiplier: sdk.NewDec(6_000), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - }, - } - for pair, market := range START_MARKETS { - extraMarketAmms[pair] = market - } - - var marketsv2 []perpv2types.Market - var ammsv2 []perpv2types.AMM - var marketLastVersions []perpv2types.GenesisMarketLastVersion - for _, marketAmm := range extraMarketAmms { - marketsv2 = append(marketsv2, marketAmm.Market) - ammsv2 = append(ammsv2, marketAmm.Amm) - marketLastVersions = append(marketLastVersions, perpv2types.GenesisMarketLastVersion{ - Pair: marketAmm.Market.Pair, - Version: marketAmm.Market.Version, - }) - } - - perpV2Gen := &perpv2types.GenesisState{ - Markets: marketsv2, - MarketLastVersions: marketLastVersions, - Amms: ammsv2, - Positions: []perpv2types.GenesisPosition{}, - ReserveSnapshots: []perpv2types.ReserveSnapshot{}, - CollateralDenom: perpv2types.TestingCollateralDenomNUSD, - } - - gen[perpv2types.ModuleName] = app.MakeEncodingConfig().Marshaler. - MustMarshalJSON(perpV2Gen) - return gen -} - -var START_MARKETS = map[asset.Pair]perpv2types.AmmMarket{ - asset.Registry.Pair(denoms.ETH, denoms.NUSD): { - Market: perpv2types.Market{ - Pair: asset.Registry.Pair(denoms.ETH, denoms.NUSD), - OraclePair: asset.Registry.Pair(denoms.ETH, denoms.USD), - Enabled: true, - Version: 1, - MaintenanceMarginRatio: sdk.MustNewDecFromStr("0.0625"), - MaxLeverage: sdk.MustNewDecFromStr("15"), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - ExchangeFeeRatio: sdk.MustNewDecFromStr("0.0010"), - EcosystemFundFeeRatio: sdk.MustNewDecFromStr("0.0010"), - LiquidationFeeRatio: sdk.MustNewDecFromStr("0.0500"), - PartialLiquidationRatio: sdk.MustNewDecFromStr("0.5"), - FundingRateEpochId: epochstypes.ThirtyMinuteEpochID, - MaxFundingRate: sdk.NewDec(1), - TwapLookbackWindow: time.Minute * 30, - PrepaidBadDebt: sdk.NewCoin(denoms.NUSD, sdk.ZeroInt()), - }, - Amm: perpv2types.AMM{ - Pair: asset.Registry.Pair(denoms.ETH, denoms.NUSD), - Version: 1, - BaseReserve: sdk.NewDec(10e6), - QuoteReserve: sdk.NewDec(10e6), - SqrtDepth: sdk.NewDec(10e6), - PriceMultiplier: sdk.NewDec(6_000), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - }, - asset.Registry.Pair(denoms.NIBI, denoms.NUSD): { - Market: perpv2types.Market{ - Pair: asset.Registry.Pair(denoms.NIBI, denoms.NUSD), - OraclePair: asset.Registry.Pair(denoms.NIBI, denoms.USD), - Enabled: true, - Version: 1, - MaintenanceMarginRatio: sdk.MustNewDecFromStr("0.04"), - MaxLeverage: sdk.MustNewDecFromStr("20"), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - ExchangeFeeRatio: sdk.MustNewDecFromStr("0.0010"), - EcosystemFundFeeRatio: sdk.MustNewDecFromStr("0.0010"), - LiquidationFeeRatio: sdk.MustNewDecFromStr("0.0500"), - PartialLiquidationRatio: sdk.MustNewDecFromStr("0.5"), - FundingRateEpochId: epochstypes.ThirtyMinuteEpochID, - MaxFundingRate: sdk.NewDec(1), - TwapLookbackWindow: time.Minute * 30, - PrepaidBadDebt: sdk.NewCoin(denoms.NUSD, sdk.ZeroInt()), - }, - Amm: perpv2types.AMM{ - Pair: asset.Registry.Pair(denoms.NIBI, denoms.NUSD), - Version: 1, - BaseReserve: sdk.NewDec(10 * common.TO_MICRO), - QuoteReserve: sdk.NewDec(10 * common.TO_MICRO), - SqrtDepth: common.MustSqrtDec(sdk.NewDec(10 * common.TO_MICRO * 10 * common.TO_MICRO)), - PriceMultiplier: sdk.NewDec(10), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - }, -} - -func PerpV2Genesis() *perpv2types.GenesisState { - return &perpv2types.GenesisState{ - Markets: []perpv2types.Market{ - { - Pair: asset.Registry.Pair(denoms.BTC, denoms.NUSD), - OraclePair: asset.Registry.Pair(denoms.BTC, denoms.USD), - Enabled: true, - MaintenanceMarginRatio: sdk.MustNewDecFromStr("0.04"), - MaxLeverage: sdk.MustNewDecFromStr("20"), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - ExchangeFeeRatio: sdk.MustNewDecFromStr("0.0010"), - EcosystemFundFeeRatio: sdk.MustNewDecFromStr("0.0010"), - LiquidationFeeRatio: sdk.MustNewDecFromStr("0.0500"), - PartialLiquidationRatio: sdk.MustNewDecFromStr("0.5"), - FundingRateEpochId: epochstypes.ThirtyMinuteEpochID, - MaxFundingRate: sdk.NewDec(1), - TwapLookbackWindow: time.Minute * 30, - PrepaidBadDebt: sdk.NewCoin(denoms.NUSD, sdk.ZeroInt()), - }, - }, - MarketLastVersions: []perpv2types.GenesisMarketLastVersion{ - { - Pair: asset.Registry.Pair(denoms.BTC, denoms.NUSD), - Version: 1, - }, - }, - Amms: []perpv2types.AMM{ - { - Pair: asset.Registry.Pair(denoms.BTC, denoms.NUSD), - BaseReserve: sdk.NewDec(10 * common.TO_MICRO), - QuoteReserve: sdk.NewDec(10 * common.TO_MICRO), - SqrtDepth: common.MustSqrtDec(sdk.NewDec(10 * common.TO_MICRO * 10 * common.TO_MICRO)), - PriceMultiplier: sdk.NewDec(10), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - }, - Positions: []perpv2types.GenesisPosition{}, - ReserveSnapshots: []perpv2types.ReserveSnapshot{}, - } -} diff --git a/x/common/testutil/mock/perp_amm.go b/x/common/testutil/mock/perp_amm.go deleted file mode 100644 index 2996e6503..000000000 --- a/x/common/testutil/mock/perp_amm.go +++ /dev/null @@ -1,37 +0,0 @@ -package mock - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - asset "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// default market with sensible values for tests -func TestAMMDefault() *types.AMM { - return &types.AMM{ - Pair: asset.NewPair(denoms.BTC, denoms.NUSD), - Version: 1, - BaseReserve: sdk.NewDec(1e12), - QuoteReserve: sdk.NewDec(1e12), - SqrtDepth: sdk.NewDec(1e12), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - SettlementPrice: sdk.ZeroDec(), - } -} - -// default market with sensible values for tests -func TestAMM(sqrtK sdk.Dec, priceMultiplier sdk.Dec) *types.AMM { - return &types.AMM{ - Pair: asset.NewPair(denoms.BTC, denoms.NUSD), - BaseReserve: sqrtK, - QuoteReserve: sqrtK, - SqrtDepth: sqrtK, - PriceMultiplier: priceMultiplier, - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - } -} diff --git a/x/common/testutil/mock/perp_market.go b/x/common/testutil/mock/perp_market.go deleted file mode 100644 index 96a1c4167..000000000 --- a/x/common/testutil/mock/perp_market.go +++ /dev/null @@ -1,32 +0,0 @@ -package mock - -import ( - time "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - asset "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// default market with sensible values for tests -func TestMarket() *types.Market { - return &types.Market{ - Pair: asset.NewPair(denoms.BTC, denoms.NUSD), - Enabled: true, - Version: 1, - MaintenanceMarginRatio: sdk.MustNewDecFromStr("0.0625"), - MaxLeverage: sdk.MustNewDecFromStr("10"), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - ExchangeFeeRatio: sdk.MustNewDecFromStr("0.0010"), - EcosystemFundFeeRatio: sdk.MustNewDecFromStr("0.0010"), - LiquidationFeeRatio: sdk.MustNewDecFromStr("0.0005"), - PartialLiquidationRatio: sdk.MustNewDecFromStr("0.5"), - FundingRateEpochId: "30 min", - MaxFundingRate: sdk.NewDec(1), - TwapLookbackWindow: time.Minute * 30, - PrepaidBadDebt: sdk.NewInt64Coin(denoms.NUSD, 0), - OraclePair: asset.NewPair(denoms.BTC, denoms.USD), - } -} diff --git a/x/common/testutil/testapp/testapp.go b/x/common/testutil/testapp/testapp.go index 3d5f1f989..7f3b75dad 100644 --- a/x/common/testutil/testapp/testapp.go +++ b/x/common/testutil/testapp/testapp.go @@ -19,7 +19,6 @@ import ( "github.com/NibiruChain/nibiru/x/common/testutil" epochstypes "github.com/NibiruChain/nibiru/x/epochs/types" inflationtypes "github.com/NibiruChain/nibiru/x/inflation/types" - "github.com/NibiruChain/nibiru/x/perp/v2/types" sudotypes "github.com/NibiruChain/nibiru/x/sudo/types" ) @@ -54,7 +53,6 @@ func NewNibiruTestAppAndContext() (*app.NibiruApp, sdk.Context) { // Set defaults for certain modules. app.OracleKeeper.SetPrice(ctx, asset.Registry.Pair(denoms.BTC, denoms.NUSD), sdk.NewDec(20000)) app.OracleKeeper.SetPrice(ctx, "xxx:yyy", sdk.NewDec(20000)) - app.PerpKeeperV2.Collateral.Set(ctx, types.TestingCollateralDenomNUSD) app.SudoKeeper.Sudoers.Set(ctx, DefaultSudoers()) return app, ctx diff --git a/x/oracle/client/cli/gen_pricefeeder_delegation_test.go b/x/oracle/client/cli/gen_pricefeeder_delegation_test.go index b0870e92a..be4a98254 100644 --- a/x/oracle/client/cli/gen_pricefeeder_delegation_test.go +++ b/x/oracle/client/cli/gen_pricefeeder_delegation_test.go @@ -12,7 +12,6 @@ import ( "github.com/stretchr/testify/require" ) -// Tests "add-genesis-perp-market", a command that adds a market to genesis.json func TestAddGenesisPricefeederDelegation(t *testing.T) { app.SetPrefixes(app.AccountAddressPrefix) diff --git a/x/oracle/keeper/hooks.go b/x/oracle/keeper/hooks.go index 69e26117d..077361353 100644 --- a/x/oracle/keeper/hooks.go +++ b/x/oracle/keeper/hooks.go @@ -7,7 +7,6 @@ import ( "github.com/NibiruChain/nibiru/x/epochs/types" oracletypes "github.com/NibiruChain/nibiru/x/oracle/types" - perptypes "github.com/NibiruChain/nibiru/x/perp/v2/types" ) var _ types.EpochHooks = Hooks{} @@ -32,49 +31,6 @@ func NewHooks(k Keeper, accountKeeper keeper.AccountKeeper, bankKeeper bankkeepe } func (h Hooks) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, _ uint64) { - if epochIdentifier == types.WeekEpochID { - params, err := h.k.Params.Get(ctx) - if err != nil { - h.k.Logger(ctx).Error("failed to get params", "error", err) - return - } - - account := h.accountKeeper.GetModuleAccount(ctx, perptypes.FeePoolModuleAccount) - totalOracleRewards, totalRemainder := sdk.Coins{}, sdk.Coins{} - - balances := h.bankKeeper.GetAllBalances(ctx, account.GetAddress()) - for _, balance := range balances { - oracleRewards := sdk.NewDecFromInt(balance.Amount).Mul(params.ValidatorFeeRatio).TruncateInt() - remainder := balance.Amount.Sub(oracleRewards) - - if !oracleRewards.IsZero() { - totalOracleRewards = append(totalOracleRewards, sdk.NewCoin(balance.Denom, oracleRewards)) - } - - if !remainder.IsZero() { - totalRemainder = append(totalRemainder, sdk.NewCoin(balance.Denom, remainder)) - } - } - - if !totalRemainder.IsZero() { - err = h.bankKeeper.SendCoinsFromModuleToModule(ctx, perptypes.FeePoolModuleAccount, perptypes.PerpFundModuleAccount, totalRemainder) - if err != nil { - h.k.Logger(ctx).Error("Failed to send coins to perp ef module", "err", err) - } - } - - if !totalOracleRewards.IsZero() { - err = h.k.AllocateRewards( - ctx, - perptypes.FeePoolModuleAccount, - totalOracleRewards, - 1, - ) - if err != nil { - h.k.Logger(ctx).Error("Failed to allocate oracle rewards from perp fee pool", "err", err) - } - } - } } func (h Hooks) BeforeEpochStart(_ sdk.Context, _ string, _ uint64) {} diff --git a/x/oracle/keeper/hooks_test.go b/x/oracle/keeper/hooks_test.go deleted file mode 100644 index 5f655dfc9..000000000 --- a/x/oracle/keeper/hooks_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - "github.com/NibiruChain/nibiru/x/epochs/types" - "github.com/NibiruChain/nibiru/x/oracle/keeper" - oracletypes "github.com/NibiruChain/nibiru/x/oracle/types" - perptypes "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func init() { - testapp.EnsureNibiruPrefix() -} - -func TestHooks_AfterEpochEnd(t *testing.T) { - tests := []struct { - name string - initialFunds sdk.Coins - epochIdentifier string - expectedOracleBalances sdk.Coins - expectedEFBalances sdk.Coins - }{ - { - name: "happy path", - initialFunds: sdk.NewCoins( - sdk.NewCoin("coin1", sdk.NewInt(1000000000000000000)), - sdk.NewCoin("coin2", sdk.NewInt(1000000000000000000)), - ), - epochIdentifier: types.WeekEpochID, - expectedOracleBalances: sdk.NewCoins( - sdk.NewCoin("coin1", sdk.NewInt(50000000000000000)), - sdk.NewCoin("coin2", sdk.NewInt(50000000000000000)), - ), - expectedEFBalances: sdk.NewCoins( - sdk.NewCoin("coin1", sdk.NewInt(950000000000000000)), - sdk.NewCoin("coin2", sdk.NewInt(950000000000000000)), - ), - }, - { - name: "zero oracle fees", - initialFunds: sdk.Coins{ - sdk.NewCoin("coin1", sdk.OneInt()), - sdk.NewCoin("coin2", sdk.OneInt()), - }, - epochIdentifier: types.WeekEpochID, - expectedOracleBalances: sdk.Coins{}, - expectedEFBalances: sdk.Coins{ - sdk.NewCoin("coin1", sdk.OneInt()), - sdk.NewCoin("coin2", sdk.OneInt()), - }, - }, - } - - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - h := keeper.NewHooks(app.OracleKeeper, app.AccountKeeper, app.BankKeeper) - - err := testapp.FundModuleAccount(app.BankKeeper, ctx, perptypes.FeePoolModuleAccount, tt.initialFunds) - require.NoError(t, err) - - h.AfterEpochEnd(ctx, tt.epochIdentifier, 0) - - account := app.AccountKeeper.GetModuleAccount(ctx, oracletypes.ModuleName) - balances := app.BankKeeper.GetAllBalances(ctx, account.GetAddress()) - assert.Equal(t, tt.expectedOracleBalances, balances) - - account = app.AccountKeeper.GetModuleAccount(ctx, perptypes.PerpFundModuleAccount) - balances = app.BankKeeper.GetAllBalances(ctx, account.GetAddress()) - assert.Equal(t, tt.expectedEFBalances, balances) - }) - } -} diff --git a/x/perp/README.md b/x/perp/README.md deleted file mode 100644 index 467e27c9f..000000000 --- a/x/perp/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `x/perp` - -Please refer to our [GitBook](https://docs.nibiru.fi/module-reference/perp). diff --git a/x/perp/v2/client/cli/cli_test.go b/x/perp/v2/client/cli/cli_test.go deleted file mode 100644 index 47a6a8b4f..000000000 --- a/x/perp/v2/client/cli/cli_test.go +++ /dev/null @@ -1,762 +0,0 @@ -package cli_test - -import ( - "fmt" - "testing" - - "cosmossdk.io/errors" - - abcitypes "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - bankcli "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - "github.com/stretchr/testify/suite" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - testutilcli "github.com/NibiruChain/nibiru/x/common/testutil/cli" - "github.com/NibiruChain/nibiru/x/common/testutil/genesis" - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - oracletypes "github.com/NibiruChain/nibiru/x/oracle/types" - "github.com/NibiruChain/nibiru/x/perp/v2/client/cli" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -type IntegrationTestSuite struct { - suite.Suite - - cfg testutilcli.Config - network *testutilcli.Network - users []sdk.AccAddress - liquidator sdk.AccAddress -} - -func (s *IntegrationTestSuite) SetupSuite() { - testutil.BeforeIntegrationSuite(s.T()) - testapp.EnsureNibiruPrefix() - - // setup market - encodingConfig := app.MakeEncodingConfig() - genState := genesis.NewTestGenesisState(encodingConfig) - genState = genesis.AddPerpV2Genesis(genState) - genState = genesis.AddOracleGenesis(genState) - - oracleGenesis := oracletypes.DefaultGenesisState() - oracleGenesis.Params.Whitelist = []asset.Pair{ - asset.Registry.Pair(denoms.BTC, denoms.NUSD), - asset.Registry.Pair(denoms.ETH, denoms.NUSD), - asset.Registry.Pair(denoms.ATOM, denoms.NUSD), - asset.Registry.Pair(denoms.OSMO, denoms.NUSD), - } - oracleGenesis.Params.VotePeriod = 1_000 - oracleGenesis.ExchangeRates = []oracletypes.ExchangeRateTuple{ - {Pair: asset.Registry.Pair(denoms.BTC, denoms.NUSD), ExchangeRate: sdk.NewDec(20_000)}, - {Pair: asset.Registry.Pair(denoms.ETH, denoms.NUSD), ExchangeRate: sdk.NewDec(2_000)}, - {Pair: asset.Registry.Pair(denoms.ATOM, denoms.NUSD), ExchangeRate: sdk.NewDec(6_000)}, - {Pair: asset.Registry.Pair(denoms.OSMO, denoms.NUSD), ExchangeRate: sdk.NewDec(6_000)}, - } - genState[oracletypes.ModuleName] = encodingConfig.Marshaler.MustMarshalJSON(oracleGenesis) - - s.cfg = testutilcli.BuildNetworkConfig(genState) - s.cfg.NumValidators = 1 - 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"} - network, err := testutilcli.New( - s.T(), - s.T().TempDir(), - s.cfg, - ) - s.Require().NoError(err) - s.network = network - - s.NoError(s.network.WaitForNextBlock()) - - val := s.network.Validators[0] - - for i := 0; i < 8; i++ { - newUser := testutilcli.NewAccount(s.network, fmt.Sprintf("user%d", i)) - s.users = append(s.users, newUser) - s.Require().NoError( - testutilcli.FillWalletFromValidator(newUser, - sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 10e6), - sdk.NewInt64Coin(denoms.USDC, 1e3*common.TO_MICRO), - sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 5e3*common.TO_MICRO), - ), - val, - denoms.NIBI, - ), - ) - s.NoError(s.network.WaitForNextBlock()) - } - - s.liquidator = sdk.MustAccAddressFromBech32("nibi1w89pf5yq8ntjg89048qmtaz929fdxup0a57d8m") - s.NoError( - testutilcli.FillWalletFromValidator(s.liquidator, - sdk.NewCoins(sdk.NewInt64Coin(denoms.NIBI, 1000)), - val, - denoms.NIBI, - ), - ) - s.NoError(s.network.WaitForNextBlock()) -} - -func (s *IntegrationTestSuite) TearDownSuite() { - s.T().Log("tearing down integration test suite") - s.network.Cleanup() -} - -func (s *IntegrationTestSuite) TestMultiLiquidate() { - s.T().Log("opening positions") - _, err := s.network.ExecTxCmd(cli.MarketOrderCmd(), s.users[2], []string{ - "buy", - asset.Registry.Pair(denoms.ATOM, denoms.NUSD).String(), - "15", // Leverage - "9000000", // Quote asset amount - "0", // Base asset limit - }) - s.Require().NoError(err) - - _, err = s.network.ExecTxCmd(cli.MarketOrderCmd(), s.users[3], []string{ - "buy", - asset.Registry.Pair(denoms.OSMO, denoms.NUSD).String(), - "15", // Leverage - "9000000", // Quote asset amount - "0", // Base asset limit - }) - s.Require().NoError(err) - - s.T().Log("opening counter positions") - _, err = s.network.ExecTxCmd(cli.MarketOrderCmd(), s.users[4], []string{ - "sell", - asset.Registry.Pair(denoms.ATOM, denoms.NUSD).String(), - "15", // Leverage - "90000000", // Quote asset amount - "0", - }) - s.Require().NoError(err) - - s.T().Logf("review positions") - resp := new(types.QueryPositionsResponse) - s.NoError( - testutilcli.ExecQuery( - s.network.Validators[0].ClientCtx, - cli.CmdQueryPositions(), - []string{s.users[2].String()}, - resp, - ), - ) - - _, err = s.network.ExecTxCmd(cli.MarketOrderCmd(), s.users[5], []string{ - "sell", - asset.Registry.Pair(denoms.OSMO, denoms.NUSD).String(), - "15", // Leverage - "90000000", // Quote asset amount - "0", - }) - s.Require().NoError(err) - - s.T().Log("wait 10 blocks") - height, err := s.network.LatestHeight() - s.Require().NoError(err) - _, err = s.network.WaitForHeight(height + 10) - s.Require().NoError(err) - - s.T().Log("liquidating all users...") - _, err = s.network.ExecTxCmd(cli.MultiLiquidateCmd(), s.liquidator, []string{ - fmt.Sprintf("%s:%s:%s", denoms.ATOM, denoms.NUSD, s.users[2].String()), - fmt.Sprintf("%s:%s:%s", denoms.OSMO, denoms.NUSD, s.users[3].String()), - }) - s.Require().NoError(err) - err = s.network.WaitForNextBlock() - s.Require().NoError(err) - - s.T().Log("check trader position") - _, err = testutilcli.QueryPositionV2(s.network.Validators[0].ClientCtx, asset.Registry.Pair(denoms.ATOM, denoms.NUSD), s.users[2]) - s.Require().Error(err) - - _, err = testutilcli.QueryPositionV2(s.network.Validators[0].ClientCtx, asset.Registry.Pair(denoms.OSMO, denoms.NUSD), s.users[3]) - s.Require().Error(err) - - s.T().Log("closing positions - fail") - _, err = s.network.ExecTxCmd(cli.ClosePositionCmd(), s.users[4], []string{ - "asset.Registry.Pair(denoms.ATOM, denoms.NUSD).String()", - }) - s.Require().Error(err) // invalid pair - - _, err = s.network.ExecTxCmd(cli.ClosePositionCmd(), s.users[4], []string{ - "uluna:usdt", - }) - s.Require().Error(err) // non whitelisted pair - - s.T().Log("closing positions") - - _, err = s.network.ExecTxCmd(cli.ClosePositionCmd(), s.users[4], []string{ - asset.Registry.Pair(denoms.ATOM, denoms.NUSD).String(), - }) - s.Require().NoError(err) - - _, err = s.network.ExecTxCmd(cli.ClosePositionCmd(), s.users[5], []string{ - asset.Registry.Pair(denoms.OSMO, denoms.NUSD).String(), - }) - s.Require().NoError(err) -} - -// user[0] opens a long position -func (s *IntegrationTestSuite) TestMarketOrdersAndCloseCmd() { - val := s.network.Validators[0] - user := s.users[0] - - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - exchangeRate, err := testutilcli.QueryOracleExchangeRate( - val.ClientCtx, pair, - ) - s.T().Logf("0. current exchange rate is: %+v", exchangeRate) - s.NoError(err) - - s.T().Log("A. check market balances") - ammMarketDuo, err := testutilcli.QueryMarketV2(val.ClientCtx, pair) - s.Require().NoError(err) - s.EqualValues(sdk.NewDec(10e6), ammMarketDuo.Amm.BaseReserve) - s.EqualValues(sdk.NewDec(10e6), ammMarketDuo.Amm.QuoteReserve) - - s.T().Log("A. check trader has no existing positions") - _, err = testutilcli.QueryPositionV2( - val.ClientCtx, asset.Registry.Pair(denoms.BTC, denoms.NUSD), user, - ) - s.Error(err) - - s.T().Log("B. open position") - txResp, err := s.network.ExecTxCmd(cli.MarketOrderCmd(), user, []string{ - "buy", - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - /* leverage */ "1", - /* quoteAmt */ "2000000", // 2*10^6 uNUSD - /* baseAssetLimit */ "1", - }, - ) - s.NoError(err) - s.EqualValues(abcitypes.CodeTypeOK, txResp.Code) - s.NoError(s.network.WaitForNextBlock()) - - s.T().Log("B. check market balance after open position") - ammMarketDuo, err = testutilcli.QueryMarketV2(val.ClientCtx, pair) - s.Require().NoError(err) - s.T().Logf("ammMarketDuo: %s", ammMarketDuo.String()) - s.EqualValues(sdk.MustNewDecFromStr("9999667.344399676304101617"), ammMarketDuo.Amm.BaseReserve) - s.EqualValues(sdk.MustNewDecFromStr("10000332.666666666666666667"), ammMarketDuo.Amm.QuoteReserve) - - s.T().Log("B. check trader position") - queryResp, err := testutilcli.QueryPositionV2(val.ClientCtx, asset.Registry.Pair(denoms.BTC, denoms.NUSD), user) - s.NoError(err) - s.T().Logf("query response: %+v", queryResp) - s.EqualValues(user.String(), queryResp.Position.TraderAddress) - s.EqualValues(asset.Registry.Pair(denoms.BTC, denoms.NUSD), queryResp.Position.Pair) - s.EqualValues(sdk.MustNewDecFromStr("332.655600323695898383"), queryResp.Position.Size_) - s.EqualValues(sdk.MustNewDecFromStr("1996000.000000000000000000"), queryResp.Position.Margin) - s.EqualValues(sdk.MustNewDecFromStr("1996000.000000000000000000"), queryResp.Position.OpenNotional) - s.EqualValues(sdk.MustNewDecFromStr("1996000.000000000000002000"), queryResp.PositionNotional) - s.EqualValues(sdk.MustNewDecFromStr("0.000000000000002000"), queryResp.UnrealizedPnl) - s.EqualValues(sdk.OneDec(), queryResp.MarginRatio) - - s.T().Log("C. open position with 2x leverage and zero baseAmtLimit") - txResp, err = s.network.ExecTxCmd(cli.MarketOrderCmd(), user, []string{ - "buy", - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - /* leverage */ "2", - /* quoteAmt */ "2000000", // 2*10^6 uNUSD - /* baseAmtLimit */ "0", - }) - s.NoError(err) - s.EqualValues(abcitypes.CodeTypeOK, txResp.Code) - s.NoError(s.network.WaitForNextBlock()) - - s.T().Log("C. check trader position") - queryResp, err = testutilcli.QueryPositionV2(val.ClientCtx, asset.Registry.Pair(denoms.BTC, denoms.NUSD), user) - s.NoError(err) - s.T().Logf("query response: %+v", queryResp) - s.EqualValues(user.String(), queryResp.Position.TraderAddress) - s.EqualValues(asset.Registry.Pair(denoms.BTC, denoms.NUSD), queryResp.Position.Pair) - s.EqualValues(sdk.MustNewDecFromStr("996.567342121568550334"), queryResp.Position.Size_) - s.EqualValues(sdk.MustNewDecFromStr("3988000.000000000000000000"), queryResp.Position.Margin) - s.EqualValues(sdk.MustNewDecFromStr("5980000.0"), queryResp.Position.OpenNotional) - s.EqualValues(sdk.MustNewDecFromStr("5979999.999999999999996000"), queryResp.PositionNotional) - s.EqualValues(sdk.MustNewDecFromStr("-0.000000000000004000"), queryResp.UnrealizedPnl) - s.EqualValues(sdk.MustNewDecFromStr("0.666889632107023411"), queryResp.MarginRatio) - - s.T().Log("D. Open a reverse position smaller than the existing position") - txResp, err = s.network.ExecTxCmd(cli.MarketOrderCmd(), user, []string{ - "sell", - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - /* leverage */ "1", - /* quoteAmt */ "1000000", // 100 uNUSD - /* baseAssetLimit */ "0", - }) - s.NoError(err) - s.EqualValues(abcitypes.CodeTypeOK, txResp.Code) - s.NoError(s.network.WaitForNextBlock()) - - s.T().Log("D. Check market after opening reverse position") - - ammMarketDuo, err = testutilcli.QueryMarketV2(val.ClientCtx, pair) - s.Require().NoError(err) - s.T().Logf("ammMarketDuo: %s", ammMarketDuo.String()) - s.EqualValues(sdk.MustNewDecFromStr("9999169.735606286824650660"), ammMarketDuo.Amm.BaseReserve) - s.EqualValues(sdk.MustNewDecFromStr("10000830.333333333333333334"), ammMarketDuo.Amm.QuoteReserve) - - s.T().Log("D. Check trader position") - queryResp, err = testutilcli.QueryPositionV2(val.ClientCtx, asset.Registry.Pair(denoms.BTC, denoms.NUSD), user) - s.NoError(err) - s.T().Logf("query response: %+v", queryResp) - s.EqualValues(user.String(), queryResp.Position.TraderAddress) - s.EqualValues(asset.Registry.Pair(denoms.BTC, denoms.NUSD), queryResp.Position.Pair) - s.EqualValues(sdk.MustNewDecFromStr("830.264393713175349340"), queryResp.Position.Size_) - s.EqualValues(sdk.MustNewDecFromStr("3987999.999999999999999332"), queryResp.Position.Margin) - s.EqualValues(sdk.MustNewDecFromStr("3987999.999999999999999332"), queryResp.Position.Margin) - - s.EqualValues(sdk.MustNewDecFromStr("4981999.999999999999999332"), queryResp.Position.OpenNotional) - s.EqualValues(sdk.MustNewDecFromStr("4981999.999999999999998000"), queryResp.PositionNotional) - s.EqualValues(sdk.MustNewDecFromStr("-0.000000000000001332"), queryResp.UnrealizedPnl) - s.EqualValues(sdk.MustNewDecFromStr("0.800481734243275793"), queryResp.MarginRatio) - - s.T().Log("E. Open a reverse position larger than the existing position") - txResp, err = s.network.ExecTxCmd(cli.MarketOrderCmd(), user, []string{ - "sell", - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - /* leverage */ "1", - /* quoteAmt */ "8000000", // 8*10^6 uNUSD - /* baseAssetLimit */ "0", - }) - s.NoError(err) - s.EqualValues(abcitypes.CodeTypeOK, txResp.Code) - s.NoError(s.network.WaitForNextBlock()) - - s.T().Log("E. Check trader position") - queryResp, err = testutilcli.QueryPositionV2(val.ClientCtx, asset.Registry.Pair(denoms.BTC, denoms.NUSD), user) - s.NoError(err) - s.T().Logf("query response: %+v", queryResp) - s.EqualValues(user.String(), queryResp.Position.TraderAddress) - s.EqualValues(asset.Registry.Pair(denoms.BTC, denoms.NUSD), queryResp.Position.Pair) - s.EqualValues(sdk.MustNewDecFromStr("-500.358367930342114784"), queryResp.Position.Size_) - s.EqualValues(sdk.MustNewDecFromStr("3002000.000000000000002000"), queryResp.Position.OpenNotional) - s.EqualValues(sdk.MustNewDecFromStr("3002000.000000000000002000"), queryResp.Position.Margin) - s.EqualValues(sdk.MustNewDecFromStr("3002000.000000000000004000"), queryResp.PositionNotional) - s.EqualValues(sdk.MustNewDecFromStr("-0.000000000000002000"), queryResp.UnrealizedPnl) - // there is a random delta due to twap margin ratio calculation and random block times in the in-process network - s.InDelta(1, queryResp.MarginRatio.MustFloat64(), 0.008) - - s.T().Log("F. Close position") - txResp, err = s.network.ExecTxCmd(cli.ClosePositionCmd(), user, []string{ - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - }) - s.NoError(err) - s.EqualValues(abcitypes.CodeTypeOK, txResp.Code) - s.NoError(s.network.WaitForNextBlock()) - - s.T().Log("F. check trader position") - queryResp, err = testutilcli.QueryPositionV2(val.ClientCtx, asset.Registry.Pair(denoms.BTC, denoms.NUSD), user) - s.Error(err) - errors.IsOf(err, types.ErrPositionNotFound) - s.T().Logf("query response: %+v", queryResp) -} - -func (s *IntegrationTestSuite) TestPartialCloseCmd() { - val := s.network.Validators[0] - user := s.users[6] - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - var err error - - s.T().Log("Open position") - txResp, err := s.network.ExecTxCmd(cli.MarketOrderCmd(), user, []string{ - "buy", - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - /* leverage */ "1", - /* quoteAmt */ "12000000", // 12e6 uNUSD - /* baseAssetLimit */ "0", - }, - ) - s.NoError(err) - s.EqualValues(abcitypes.CodeTypeOK, txResp.Code) - s.NoError(s.network.WaitForNextBlock()) - - s.T().Log("Check market balance after open position") - ammMarketDuo, err := testutilcli.QueryMarketV2(val.ClientCtx, pair) - s.Require().NoError(err) - s.T().Logf("ammMarketDuo: %s", ammMarketDuo.String()) - s.EqualValues(sdk.MustNewDecFromStr("9998004.398322094909855993"), ammMarketDuo.Amm.BaseReserve) - s.EqualValues(sdk.MustNewDecFromStr("10001996.000000000000000001"), ammMarketDuo.Amm.QuoteReserve) - - s.T().Log("Check trader position") - queryResp, err := testutilcli.QueryPositionV2(val.ClientCtx, asset.Registry.Pair(denoms.BTC, denoms.NUSD), user) - s.NoError(err) - s.T().Logf("query response: %+v", queryResp) - s.EqualValues(user.String(), queryResp.Position.TraderAddress) - s.EqualValues(pair, queryResp.Position.Pair) - s.EqualValues(sdk.MustNewDecFromStr("1995.601677905090144007"), queryResp.Position.Size_) - s.EqualValues(sdk.MustNewDecFromStr("11976000.000000000000000000"), queryResp.Position.Margin) - s.EqualValues(sdk.MustNewDecFromStr("11976000.000000000000000000"), queryResp.Position.OpenNotional) - s.EqualValues(sdk.MustNewDecFromStr("11976000.000000000000000000"), queryResp.PositionNotional) - s.EqualValues(sdk.ZeroDec(), queryResp.UnrealizedPnl) - s.EqualValues(sdk.OneDec(), queryResp.MarginRatio) - - s.T().Log("Partially close the position - fails") - _, err = s.network.ExecTxCmd(cli.PartialCloseCmd(), user, []string{ - pair.String(), - "", - }) - s.Error(err) // invalid size amount - _, err = s.network.ExecTxCmd(cli.PartialCloseCmd(), user, []string{ - "pair.String()", - "500", - }) - s.Error(err) // invalid pair - _, err = s.network.ExecTxCmd(cli.PartialCloseCmd(), user, []string{ - "uluna:usdt", - "500", - }) - s.Error(err) // not whitelisted pair - - s.T().Log("Partially close the position") - txResp, err = s.network.ExecTxCmd(cli.PartialCloseCmd(), user, []string{ - pair.String(), - "500", // 500 uBTC - }) - s.NoError(err) - s.EqualValues(abcitypes.CodeTypeOK, txResp.Code) - s.NoError(s.network.WaitForNextBlock()) - - s.T().Log("Check market after partial close") - ammMarketDuo, err = testutilcli.QueryMarketV2(val.ClientCtx, pair) - s.Require().NoError(err) - s.T().Logf("ammMarketDuo: %s", ammMarketDuo.String()) - s.EqualValues(sdk.MustNewDecFromStr("9998503.398288059264958855"), ammMarketDuo.Amm.BaseReserve) - s.EqualValues(sdk.MustNewDecFromStr("10001496.825727135305804567"), ammMarketDuo.Amm.QuoteReserve) - - s.T().Log("Check trader position") - queryResp, err = testutilcli.QueryPositionV2(val.ClientCtx, asset.Registry.Pair(denoms.BTC, denoms.NUSD), user) - s.NoError(err) - s.T().Logf("query response: %+v", queryResp) - s.EqualValues(user.String(), queryResp.Position.TraderAddress) - s.EqualValues(asset.Registry.Pair(denoms.BTC, denoms.NUSD), queryResp.Position.Pair) - s.EqualValues(sdk.MustNewDecFromStr("1496.601711940735041145"), queryResp.Position.Size_) - s.EqualValues(sdk.MustNewDecFromStr("11976000.000000000000000000"), queryResp.Position.Margin) - s.EqualValues(sdk.MustNewDecFromStr("8980954.362811834827398000"), queryResp.Position.OpenNotional) - s.EqualValues(sdk.MustNewDecFromStr("8980954.362811834827396000"), queryResp.PositionNotional) - s.EqualValues(sdk.MustNewDecFromStr("-0.000000000000002000"), queryResp.UnrealizedPnl) - s.EqualValues(sdk.MustNewDecFromStr("1.333488571057658776"), queryResp.MarginRatio) -} - -func (s *IntegrationTestSuite) TestPositionEmptyAndClose() { - val := s.network.Validators[0] - user := s.users[0] - - // verify trader has no position (empty) - _, err := testutilcli.QueryPositionV2(val.ClientCtx, asset.Registry.Pair(denoms.ETH, denoms.NUSD), user) - s.Error(err, "no position found") - - // close position should produce error - _, err = s.network.ExecTxCmd(cli.ClosePositionCmd(), user, []string{ - asset.Registry.Pair(denoms.ETH, denoms.NUSD).String(), - }) - s.Contains(err.Error(), types.ErrPositionNotFound.Error()) -} - -// user[0] opens a position and removes margin to trigger bad debt -func (s *IntegrationTestSuite) TestRemoveMargin() { - // Open a position with first user - s.T().Log("opening a position with user 0") - _, err := s.network.ExecTxCmd(cli.MarketOrderCmd(), s.users[0], []string{ - "buy", - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - "10", // Leverage - "1000000", // Quote asset amount - "0", - }) - s.NoError(err) - s.NoError(s.network.WaitForNextBlock()) - - // Remove margin to trigger bad debt on user 0 - s.T().Log("removing margin on user 0....") - _, err = s.network.ExecTxCmd(cli.RemoveMarginCmd(), s.users[0], []string{ - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - fmt.Sprintf("%s%s", "10000000", types.TestingCollateralDenomNUSD), - }) - s.Contains(err.Error(), types.ErrBadDebt.Error()) - - s.T().Log("removing margin on user 0....") - _, err = s.network.ExecTxCmd(cli.RemoveMarginCmd(), s.users[0], []string{ - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - fmt.Sprintf("%s%s", "1", types.TestingCollateralDenomNUSD), - }) - s.NoError(err) - s.NoError(s.network.WaitForNextBlock()) -} - -// user[1] opens a position and adds margin -func (s *IntegrationTestSuite) TestX_AddMargin() { - // Open a new position - s.T().Log("opening a position with user 1....") - txResp, err := s.network.ExecTxCmd(cli.MarketOrderCmd(), s.users[1], []string{ - "buy", - asset.Registry.Pair(denoms.ETH, denoms.NUSD).String(), - "10", // Leverage - "1000000", // Quote asset amount - "0.0000001", - }) - s.Require().NoError(err, txResp) - s.NoError(s.network.WaitForNextBlock()) - - testCases := []struct { - name string - args []string - expectedCode uint32 - expectedMargin sdk.Dec - expectFail bool - }{ - { - name: "fail: not correct margin denom", - args: []string{ - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - fmt.Sprintf("10000%s", denoms.USDT), - }, - expectFail: false, - expectedMargin: sdk.NewDec(980000), - expectedCode: 1, - }, - { - name: "fail: position not found", - args: []string{ - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - fmt.Sprintf("10000%s", types.TestingCollateralDenomNUSD), - }, - expectedCode: types.ErrPositionNotFound.ABCICode(), - expectedMargin: sdk.NewDec(980000), - expectFail: false, - }, - { - name: "PASS: add margin to correct position", - args: []string{ - asset.Registry.Pair(denoms.ETH, denoms.NUSD).String(), - fmt.Sprintf("10000%s", types.TestingCollateralDenomNUSD), - }, - expectedCode: 0, - expectedMargin: sdk.NewDec(990_000), - expectFail: false, - }, - { - name: "fail: invalid coin", - args: []string{ - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - "100", - }, - expectFail: true, - }, - { - name: "fail: invalid pair", - args: []string{ - "alisdhjal;dhao;sdh", - fmt.Sprintf("10000%s", types.TestingCollateralDenomNUSD), - }, - expectFail: true, - }, - } - - for _, tc := range testCases { - tc := tc - s.T().Run(tc.name, func(t *testing.T) { - s.T().Log("adding margin on user 3....") - canFail := true - if tc.expectFail { - txResp, err = s.network.ExecTxCmd( - cli.AddMarginCmd(), s.users[1], tc.args, - testutilcli.WithTxOptions( - testutilcli.TxOptionChanges{CanFail: &canFail}), - ) - s.Require().Error(err, txResp) - } else { - txResp, err := s.network.ExecTxCmd( - cli.AddMarginCmd(), s.users[1], tc.args, - testutilcli.WithTxOptions( - testutilcli.TxOptionChanges{CanFail: &canFail}), - ) - s.Require().NoError(err) - s.Require().NoError(s.network.WaitForNextBlock()) - - resp, err := testutilcli.QueryTx(s.network.Validators[0].ClientCtx, txResp.TxHash) - s.Require().NoError(err) - s.Require().EqualValues(tc.expectedCode, resp.Code) - - // query trader position - queryResp, err := testutilcli.QueryPositionV2(s.network.Validators[0].ClientCtx, asset.Registry.Pair(denoms.ETH, denoms.NUSD), s.users[1]) - s.NoError(err) - s.EqualValues(tc.expectedMargin, queryResp.Position.Margin) - } - }) - } -} - -// user[1] opens a position and removes margin -func (s *IntegrationTestSuite) TestX_RemoveMargin() { - // Open a new position - s.T().Log("opening a position with user 1....") - _, err := s.network.ExecTxCmd(cli.MarketOrderCmd(), s.users[2], []string{ - "buy", - asset.Registry.Pair(denoms.ETH, denoms.NUSD).String(), - "10", // Leverage - "1000000", // Quote asset amount - "0.0000001", - }) - s.Require().NoError(err) - s.NoError(s.network.WaitForNextBlock()) - - testCases := []struct { - name string - args []string - expectedCode uint32 - expectedMargin sdk.Dec - expectFail bool - }{ - { - name: "fail: not correct margin denom", - args: []string{ - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - fmt.Sprintf("10000%s", denoms.USDT), - }, - expectFail: false, - expectedCode: 1, - expectedMargin: sdk.NewDec(980_000), - }, - { - name: "fail: position not found", - args: []string{ - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - fmt.Sprintf("10000%s", types.TestingCollateralDenomNUSD), - }, - expectedCode: types.ErrPositionNotFound.ABCICode(), - expectedMargin: sdk.NewDec(980_000), - expectFail: false, - }, - { - name: "PASS: remove margin to correct position", - args: []string{ - asset.Registry.Pair(denoms.ETH, denoms.NUSD).String(), - fmt.Sprintf("10000%s", types.TestingCollateralDenomNUSD), - }, - expectedCode: 0, - expectedMargin: sdk.NewDec(970_000), - expectFail: false, - }, - { - name: "fail: invalid coin", - args: []string{ - asset.Registry.Pair(denoms.BTC, denoms.NUSD).String(), - "100", - }, - expectFail: true, - }, - { - name: "fail: invalid pair", - args: []string{ - "alisdhjal;dhao;sdh", - fmt.Sprintf("10000%s", types.TestingCollateralDenomNUSD), - }, - expectFail: true, - }, - } - - for _, tc := range testCases { - tc := tc - s.T().Run(tc.name, func(t *testing.T) { - s.T().Log("removing margin on user 3....") - - canFail := true - txResp, err := s.network.ExecTxCmd( - cli.RemoveMarginCmd(), s.users[2], tc.args, - testutilcli.WithTxOptions( - testutilcli.TxOptionChanges{CanFail: &canFail}), - ) - if tc.expectFail { - s.Require().Errorf(err, "txResp: %v", txResp) - } else { - s.Require().NoErrorf(err, "txResp: %v", txResp) - s.Require().NoError(s.network.WaitForNextBlock()) - - resp, err := testutilcli.QueryTx(s.network.Validators[0].ClientCtx, txResp.TxHash) - s.Require().NoError(err) - s.Require().EqualValues(tc.expectedCode, resp.Code) - - queryResp, err := testutilcli.QueryPositionV2(s.network.Validators[0].ClientCtx, asset.Registry.Pair(denoms.ETH, denoms.NUSD), s.users[2]) - s.NoError(err) - s.EqualValues(tc.expectedMargin, queryResp.Position.Margin) - } - }) - } -} - -func (s *IntegrationTestSuite) TestDonateToEcosystemFund() { - s.T().Logf("donate to ecosystem fund") - out, err := s.network.ExecTxCmd( - cli.DonateToEcosystemFundCmd(), - sdk.MustAccAddressFromBech32("nibi1w89pf5yq8ntjg89048qmtaz929fdxup0a57d8m"), - []string{"100" + types.TestingCollateralDenomNUSD}, - ) - s.NoError(err) - s.Require().EqualValues(abcitypes.CodeTypeOK, out.Code) - - s.NoError(s.network.WaitForNextBlock()) - - _, err = s.network.ExecTxCmd( - cli.DonateToEcosystemFundCmd(), - sdk.MustAccAddressFromBech32("nibi1w89pf5yq8ntjg89048qmtaz929fdxup0a57d8m"), - []string{"10"}) - s.Error(err) - - s.NoError(s.network.WaitForNextBlock()) - resp := new(sdk.Coin) - - moduleAccPerpFund := authtypes.NewModuleAddress( - types.PerpFundModuleAccount).String() - s.NoError( - testutilcli.ExecQuery( - s.network.Validators[0].ClientCtx, - bankcli.GetBalancesCmd(), - []string{moduleAccPerpFund, "--denom", types.TestingCollateralDenomNUSD}, - resp, - ), - ) - s.Require().EqualValues( - sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 100).String(), - resp.String(), - ) -} - -func (s *IntegrationTestSuite) TestQueryModuleAccount() { - resp := new(types.QueryModuleAccountsResponse) - s.NoError( - s.network.ExecQuery( - cli.NewQueryCmd(), - []string{"module-accounts"}, - resp, - ), - ) - s.NotEmpty(resp.Accounts) -} - -func (s *IntegrationTestSuite) TestQueryCollateralDenom() { - resp := new(types.QueryCollateralResponse) - s.NoError( - s.network.ExecQuery( - cli.NewQueryCmd(), - []string{"collateral"}, - resp, - ), - ) - s.Equal(types.TestingCollateralDenomNUSD, resp.CollateralDenom, - "resp: %s", resp.String()) -} - -func TestIntegrationTestSuite(t *testing.T) { - suite.Run(t, new(IntegrationTestSuite)) -} diff --git a/x/perp/v2/client/cli/gen_market.go b/x/perp/v2/client/cli/gen_market.go deleted file mode 100644 index 5c8f18bee..000000000 --- a/x/perp/v2/client/cli/gen_market.go +++ /dev/null @@ -1,223 +0,0 @@ -package cli - -import ( - "encoding/json" - "fmt" - "time" - - flag "github.com/spf13/pflag" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/server" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/genutil" - genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" - "github.com/spf13/cobra" - - "github.com/NibiruChain/nibiru/x/common/asset" - epochstypes "github.com/NibiruChain/nibiru/x/epochs/types" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -const ( - FlagPair = "pair" - FlagSqrtDepth = "sqrt-depth" - FlagPriceMultiplier = "price-multiplier" - FlagMaintenenceMarginRatio = "mmr" - FlagMaxLeverage = "max-leverage" - FlagMaxFundingrate = "max-funding-rate" - FlagOraclePair = "oracle-pair" -) - -var addMarketGenesisFlags = map[string]struct { - defaultValue string - usageDocString string -}{ - FlagPair: {"", "trading pair identifier of the form 'base:quote'. E.g., ueth:unusd"}, - FlagSqrtDepth: {"", "sqrt k"}, - FlagPriceMultiplier: {"", "the peg multiplier for the pool"}, - FlagMaintenenceMarginRatio: {"0.0625", "maintenance margin ratio"}, - FlagMaxLeverage: {"10", "maximum leverage for opening a position"}, - FlagMaxFundingrate: {"0.01", "maximum funding rate for the market"}, - FlagOraclePair: {"", "oracle pair identifier of the form 'base:quote'. E.g., ueth:uusd"}, -} - -// getCmdFlagSet returns a flag set and list of required flags for the command. -func getCmdFlagSet() (fs *flag.FlagSet, reqFlags []string) { - fs = flag.NewFlagSet("flags-add-genesis-pool", flag.ContinueOnError) - - for flagName, flagArgs := range addMarketGenesisFlags { - fs.String(flagName, flagArgs.defaultValue, flagArgs.usageDocString) - } - return fs, []string{FlagPair, FlagSqrtDepth, FlagPriceMultiplier} -} - -// AddMarketGenesisCmd returns add-market-genesis -func AddMarketGenesisCmd(defaultNodeHome string) *cobra.Command { - cmd := &cobra.Command{ - Use: "add-genesis-perp-market", - Short: "Add perp markets to genesis.json", - Long: `Add perp markets to genesis.json.`, - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx := client.GetClientContextFromCmd(cmd) - serverCtx := server.GetServerContextFromCmd(cmd) - config := serverCtx.Config - - config.SetRoot(clientCtx.HomeDir) - - genFile := config.GenesisFile() - appState, genDoc, err := genutiltypes.GenesisStateFromGenFile(genFile) - if err != nil { - return err - } - - market, amm, err := newMarketFromFlags(cmd.Flags()) - if err != nil { - return err - } - - perpGenState := types.GetGenesisStateFromAppState(clientCtx.Codec, appState) - perpGenState.Markets = append(perpGenState.Markets, market) - perpGenState.Amms = append(perpGenState.Amms, amm) - - var marketsLastVersion []types.GenesisMarketLastVersion - for _, market := range perpGenState.Markets { - marketsLastVersion = append(marketsLastVersion, types.GenesisMarketLastVersion{ - Pair: market.Pair, - Version: market.Version, - }) - } - - perpGenState.MarketLastVersions = marketsLastVersion - - perpGenStateBz, err := clientCtx.Codec.MarshalJSON(perpGenState) - if err != nil { - return fmt.Errorf("failed to marshal market genesis state: %w", err) - } - - appState[types.ModuleName] = perpGenStateBz - - appStateJSON, err := json.Marshal(appState) - if err != nil { - return fmt.Errorf("failed to marshal application genesis state: %w", err) - } - - genDoc.AppState = appStateJSON - return genutil.ExportGenesisFile(genDoc, genFile) - }, - } - - cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") - - flagSet, requiredFlags := getCmdFlagSet() - cmd.Flags().AddFlagSet(flagSet) - for _, reqFlag := range requiredFlags { - _ = cmd.MarkFlagRequired(reqFlag) - } - - return cmd -} - -func newMarketFromFlags(flagSet *flag.FlagSet, -) (market types.Market, amm types.AMM, err error) { - flagErrors := []error{} - - pairStr, err := flagSet.GetString(FlagPair) - flagErrors = append(flagErrors, err) - - sqrtDepthStr, err := flagSet.GetString(FlagSqrtDepth) - flagErrors = append(flagErrors, err) - - priceMultiplierStr, err := flagSet.GetString(FlagPriceMultiplier) - flagErrors = append(flagErrors, err) - - mmrAsString, err := flagSet.GetString(FlagMaintenenceMarginRatio) - flagErrors = append(flagErrors, err) - - maxLeverageStr, err := flagSet.GetString(FlagMaxLeverage) - flagErrors = append(flagErrors, err) - - maxFundingRateStr, err := flagSet.GetString(FlagMaxFundingrate) - flagErrors = append(flagErrors, err) - - oraclePairStr, err := flagSet.GetString(FlagOraclePair) - flagErrors = append(flagErrors, err) - - for _, err := range flagErrors { // for brevity's sake - if err != nil { - return types.Market{}, types.AMM{}, err - } - } - - pair, err := asset.TryNewPair(pairStr) - if err != nil { - return - } - - sqrtDepth, err := sdk.NewDecFromStr(sqrtDepthStr) - if err != nil { - return - } - - maintenanceMarginRatio, err := sdk.NewDecFromStr(mmrAsString) - if err != nil { - return - } - - maxLeverage, err := sdk.NewDecFromStr(maxLeverageStr) - if err != nil { - return - } - - maxFundingRate, err := sdk.NewDecFromStr(maxFundingRateStr) - if err != nil { - return - } - - oraclePair, err := asset.TryNewPair(oraclePairStr) - if err != nil { - return - } - - priceMultiplier, err := sdk.NewDecFromStr(priceMultiplierStr) - if err != nil { - return - } - - market = types.Market{ - Pair: pair, - Enabled: true, - MaintenanceMarginRatio: maintenanceMarginRatio, - MaxLeverage: maxLeverage, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - ExchangeFeeRatio: sdk.MustNewDecFromStr("0.0010"), - EcosystemFundFeeRatio: sdk.MustNewDecFromStr("0.0010"), - LiquidationFeeRatio: sdk.MustNewDecFromStr("0.0500"), - PartialLiquidationRatio: sdk.MustNewDecFromStr("0.5"), - FundingRateEpochId: epochstypes.ThirtyMinuteEpochID, - MaxFundingRate: maxFundingRate, - TwapLookbackWindow: time.Minute * 30, - PrepaidBadDebt: sdk.NewInt64Coin(pair.QuoteDenom(), 0), - OraclePair: oraclePair, - } - if err := market.Validate(); err != nil { - return types.Market{}, types.AMM{}, err - } - - amm = types.AMM{ - Pair: pair, - BaseReserve: sqrtDepth, - QuoteReserve: sqrtDepth, - SqrtDepth: sqrtDepth, - PriceMultiplier: priceMultiplier, - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - } - if err := amm.Validate(); err != nil { - return types.Market{}, types.AMM{}, err - } - - return market, amm, nil -} diff --git a/x/perp/v2/client/cli/gen_market_test.go b/x/perp/v2/client/cli/gen_market_test.go deleted file mode 100644 index ad38f62e9..000000000 --- a/x/perp/v2/client/cli/gen_market_test.go +++ /dev/null @@ -1,151 +0,0 @@ -package cli_test - -import ( - "fmt" - "testing" - - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/testutil" - "github.com/NibiruChain/nibiru/x/perp/v2/client/cli" -) - -// Tests "add-genesis-perp-market", a command that adds a market to genesis.json -func TestAddMarketGenesisCmd(t *testing.T) { - tests := []struct { - name string - pairName string - sqrtDepth string - priceMultiplier string - maintainRatio string - maxLeverage string - maxFundingRate string - oraclePair string - expectError bool - }{ - { - name: "pair name empty", - pairName: "", - sqrtDepth: "1", - priceMultiplier: "1", - maintainRatio: "1", - maxLeverage: "1", - maxFundingRate: "1", - oraclePair: "token0:token1", - expectError: true, - }, - { - name: "invalid pair name", - pairName: "token0:token1:token2", - sqrtDepth: "1", - priceMultiplier: "1", - maintainRatio: "1", - maxLeverage: "1", - maxFundingRate: "1", - oraclePair: "token0:token1", - expectError: true, - }, - { - name: "empty sqrt depth input", - pairName: "token0:token1", - sqrtDepth: "", - priceMultiplier: "1", - maintainRatio: "1", - maxLeverage: "1", - maxFundingRate: "1", - oraclePair: "token0:token1", - expectError: true, - }, - { - name: "max leverage cannot be zero", - pairName: "token0:token1", - sqrtDepth: "100", - priceMultiplier: "1", - maintainRatio: "0.1", - maxLeverage: "0", - maxFundingRate: "0", - oraclePair: "token0:token1", - expectError: true, - }, - { - name: "price multiplier cannot be zero", - pairName: "token0:token1", - sqrtDepth: "100", - priceMultiplier: "0", - maintainRatio: "0.1", - maxLeverage: "1", - maxFundingRate: "1", - oraclePair: "token0:token1", - expectError: true, - }, - { - name: "price multiplier cannot be negative", - pairName: "token0:token1", - sqrtDepth: "100", - priceMultiplier: "-1", - maintainRatio: "0.1", - maxLeverage: "1", - maxFundingRate: "1", - oraclePair: "token0:token1", - expectError: true, - }, - { - name: "negative max funding rate", - pairName: "token0:token1", - sqrtDepth: "100", - priceMultiplier: "1", - maintainRatio: "0.1", - maxLeverage: "10", - maxFundingRate: "-1", - oraclePair: "token0:token1", - expectError: true, - }, - { - name: "invalid oracle pair", - pairName: "token0:token1", - sqrtDepth: "100", - priceMultiplier: "1", - maintainRatio: "0.1", - maxLeverage: "10", - maxFundingRate: "-1", - oraclePair: "invalidPair", - expectError: true, - }, - { - name: "valid market pair", - pairName: "token0:token1", - sqrtDepth: "100", - priceMultiplier: "1", - maintainRatio: "0.1", - maxLeverage: "10", - maxFundingRate: "10", - oraclePair: "token0:token1", - expectError: false, - }, - } - - ctx := testutil.SetupClientCtx(t) - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - cmd := cli.AddMarketGenesisCmd("home") - cmd.SetArgs([]string{ - fmt.Sprintf("--%s=%s", cli.FlagPair, tc.pairName), - fmt.Sprintf("--%s=%s", cli.FlagSqrtDepth, tc.sqrtDepth), - fmt.Sprintf("--%s=%s", cli.FlagPriceMultiplier, tc.priceMultiplier), - fmt.Sprintf("--%s=%s", cli.FlagMaintenenceMarginRatio, tc.maintainRatio), - fmt.Sprintf("--%s=%s", cli.FlagMaxLeverage, tc.maxLeverage), - fmt.Sprintf("--%s=%s", cli.FlagMaxFundingrate, tc.maxFundingRate), - fmt.Sprintf("--%s=%s", cli.FlagOraclePair, tc.oraclePair), - fmt.Sprintf("--%s=home", flags.FlagHome), - }) - - if tc.expectError { - require.Error(t, cmd.ExecuteContext(ctx)) - } else { - require.NoError(t, cmd.ExecuteContext(ctx)) - } - }) - } -} diff --git a/x/perp/v2/client/cli/query.go b/x/perp/v2/client/cli/query.go deleted file mode 100644 index 8a37b6528..000000000 --- a/x/perp/v2/client/cli/query.go +++ /dev/null @@ -1,221 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/MakeNowJust/heredoc/v2" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/spf13/cobra" - - "github.com/NibiruChain/nibiru/x/common/asset" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -const FlagVersioned = "versioned" - -// NewQueryCmd returns the cli query commands for this module -func NewQueryCmd() *cobra.Command { - // Group stablecoin queries under a subcommand - moduleQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf( - "Querying commands for the %s module", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmds := []*cobra.Command{ - CmdQueryPosition(), - CmdQueryPositions(), - CmdQueryModuleAccounts(), - CmdQueryMarkets(), - CmdQueryCollateral(), - } - for _, cmd := range cmds { - moduleQueryCmd.AddCommand(cmd) - } - - return moduleQueryCmd -} - -// sample token-pair: btc:nusd -func CmdQueryPosition() *cobra.Command { - cmd := &cobra.Command{ - Use: "position [trader] [token-pair]", - Short: "trader's position for a given token pair/perp/amm", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - trader, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return fmt.Errorf("invalid trader address: %w", err) - } - - pair, err := asset.TryNewPair(args[1]) - if err != nil { - return err - } - - res, err := queryClient.QueryPosition( - cmd.Context(), &types.QueryPositionRequest{ - Trader: trader.String(), - Pair: pair, - }, - ) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} - -func CmdQueryPositions() *cobra.Command { - cmd := &cobra.Command{ - Use: "positions [trader]", - Short: "return all of a trader's open positions", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - trader, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return fmt.Errorf("invalid trader address: %w", err) - } - - res, err := queryClient.QueryPositions( - cmd.Context(), &types.QueryPositionsRequest{ - Trader: trader.String(), - }, - ) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} - -func CmdQueryModuleAccounts() *cobra.Command { - cmd := &cobra.Command{ - Use: "module-accounts", - Short: "shows all the module accounts in the blockchain", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.ModuleAccounts(cmd.Context(), &types.QueryModuleAccountsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} - -func CmdQueryMarkets() *cobra.Command { - cmd := &cobra.Command{ - Use: "markets", - Short: "Query all market info", - Long: heredoc.Doc(` -Query all market info. By default, only active tradable markets are shown. -If --versioned is to to true, the query will return all markets including the -inactive ones.`), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - versioned, err := cmd.Flags().GetBool(FlagVersioned) - if err != nil { - return err - } - - res, err := queryClient.QueryMarkets(cmd.Context(), &types.QueryMarketsRequest{ - Versioned: versioned, - }) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - cmd.Flags().Bool(FlagVersioned, false, "toggles whether to include inactive markets") - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} - -// CmdQueryCollateral: Command for the "Query/Collateral" gRPC service method. -func CmdQueryCollateral() *cobra.Command { - cmd := &cobra.Command{ - Use: "collateral", - Aliases: []string{"coll"}, - Short: "Query the collateral denomination info.", - Long: heredoc.Doc(` - Query the metadata of the fungible collateral used by the perp module. - `, - ), - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.QueryCollateral( - cmd.Context(), &types.QueryCollateralRequest{}, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - return cmd -} diff --git a/x/perp/v2/client/cli/tx.go b/x/perp/v2/client/cli/tx.go deleted file mode 100644 index b45a8b966..000000000 --- a/x/perp/v2/client/cli/tx.go +++ /dev/null @@ -1,400 +0,0 @@ -package cli - -import ( - "fmt" - "strconv" - "strings" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - "github.com/spf13/cobra" - - "github.com/NibiruChain/nibiru/x/common/asset" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func NewTxCmd() *cobra.Command { - txCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Generalized automated market maker transaction subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - txCmd.AddCommand( - RemoveMarginCmd(), - AddMarginCmd(), - MarketOrderCmd(), - ClosePositionCmd(), - SettlePositionCmd(), - PartialCloseCmd(), - MultiLiquidateCmd(), - DonateToEcosystemFundCmd(), - ) - - return txCmd -} - -func MultiLiquidateCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "multi-liquidate [Pair1:Trader1] [Pair2:Trader2] ...", - Short: "liquidates multiple positions at once", - Long: strings.TrimSpace( - fmt.Sprintf(` - $ %s tx perp multi-liquidate ubtc:unusd:nibi1zaavvzxez0elundtn32qnk9lkm8kmcsz44g7xl ueth:unusd:nibi1zaavvzxez0elundtn32qnk9lkm8kmcsz44g7xl - `, version.AppName), - ), - Args: cobra.MinimumNArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - liquidations := make([]*types.MsgMultiLiquidate_Liquidation, len(args)) - - for i, arg := range args { - parts := strings.Split(arg, ":") - if len(parts) != 3 { - return fmt.Errorf("invalid liquidation format: %s", arg) - } - - pair, err := asset.TryNewPair(fmt.Sprintf("%s:%s", parts[0], parts[1])) - if err != nil { - return err - } - - traderAddr, err := sdk.AccAddressFromBech32(parts[2]) - if err != nil { - return err - } - - liquidations[i] = &types.MsgMultiLiquidate_Liquidation{ - Pair: pair, - Trader: traderAddr.String(), - } - } - - msg := &types.MsgMultiLiquidate{ - Sender: clientCtx.GetFromAddress().String(), - Liquidations: liquidations, - } - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -func MarketOrderCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "open-position [buy/sell] [pair] [leverage] [quoteAmt / sdk.Dec] [baseAmtLimit / sdk.Dec]", - Short: "Opens a position", - Args: cobra.ExactArgs(5), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - var side types.Direction - switch args[0] { - case "buy": - side = types.Direction_LONG - case "sell": - side = types.Direction_SHORT - default: - return fmt.Errorf("invalid side: %s", args[0]) - } - - assetPair, err := asset.TryNewPair(args[1]) - if err != nil { - return err - } - - leverage := sdk.MustNewDecFromStr(args[2]) - - amount, ok := sdk.NewIntFromString(args[3]) - if !ok { - return fmt.Errorf("invalid quote amount: %s", args[3]) - } - - baseAmtLimit := sdk.MustNewDecFromStr(args[4]) - - msg := &types.MsgMarketOrder{ - Sender: clientCtx.GetFromAddress().String(), - Pair: assetPair, - Side: side, - QuoteAssetAmount: amount, - Leverage: leverage, - BaseAssetAmountLimit: baseAmtLimit.RoundInt(), - } - - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -func ClosePositionCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "close-position [pair]", - Short: "Closes a position", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - pair, err := asset.TryNewPair(args[0]) - if err != nil { - return err - } - - msg := &types.MsgClosePosition{ - Sender: clientCtx.GetFromAddress().String(), - Pair: pair, - } - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -func PartialCloseCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "partial-close [pair] [size]", - Short: "Partially closes a position", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - pair, err := asset.TryNewPair(args[0]) - if err != nil { - return err - } - - size, err := sdk.NewDecFromStr(args[1]) - if err != nil { - return err - } - - msg := &types.MsgPartialClose{ - Sender: clientCtx.GetFromAddress().String(), - Pair: pair, - Size_: size, - } - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -/* -RemoveMarginCmd is a CLI command that removes margin from a position, -realizing any outstanding funding payments and decreasing the margin ratio. -*/ -func RemoveMarginCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "remove-margin [market] [margin]", - Short: "Removes margin from a position, decreasing its margin ratio", - Long: strings.TrimSpace( - fmt.Sprintf(` - $ %s tx perp remove-margin osmo:nusd 100nusd - `, version.AppName), - ), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - marginToRemove, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - pair, err := asset.TryNewPair(args[0]) - if err != nil { - return err - } - - msg := &types.MsgRemoveMargin{ - Sender: clientCtx.GetFromAddress().String(), - Pair: pair, - Margin: marginToRemove, - } - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -func AddMarginCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "add-margin [market] [margin]", - Short: "Adds margin to a position, increasing its margin ratio", - Long: strings.TrimSpace( - fmt.Sprintf(` - $ %s tx perp add-margin osmo:nusd 100nusd - `, version.AppName), - ), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - marginToAdd, err := sdk.ParseCoinNormalized(args[1]) - if err != nil { - return err - } - - pair, err := asset.TryNewPair(args[0]) - if err != nil { - return err - } - - msg := &types.MsgAddMargin{ - Sender: clientCtx.GetFromAddress().String(), - Pair: pair, - Margin: marginToAdd, - } - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -func SettlePositionCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "settle [market] [version]", - Short: "Settle position in a specific market version when the market is disabled", - Long: strings.TrimSpace( - fmt.Sprintf(` - $ %s tx perp settle osmo:nusd 1 - `, version.AppName), - ), - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - version, err := strconv.ParseUint(args[1], 10, 64) - if err != nil { - return err - } - - pair, err := asset.TryNewPair(args[0]) - if err != nil { - return err - } - - msg := &types.MsgSettlePosition{ - Sender: clientCtx.GetFromAddress().String(), - Pair: pair, - Version: version, - } - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -func DonateToEcosystemFundCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "donate-ef [amount]", - Short: "Donates of coins to the Ecosystem Fund.", - Long: strings.TrimSpace( - fmt.Sprintf(` - $ %s tx perp donate-ef 100unusd - `, version.AppName), - ), - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - donation, err := sdk.ParseCoinNormalized(args[0]) - if err != nil { - return err - } - - msg := &types.MsgDonateToEcosystemFund{ - Sender: clientCtx.GetFromAddress().String(), - Donation: donation, - } - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} diff --git a/x/perp/v2/integration/action/dnr.go b/x/perp/v2/integration/action/dnr.go deleted file mode 100644 index 7940f4795..000000000 --- a/x/perp/v2/integration/action/dnr.go +++ /dev/null @@ -1,317 +0,0 @@ -package action - -import ( - "fmt" - - "cosmossdk.io/math" - "github.com/NibiruChain/collections" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/testutil" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/testutil/action" - perpkeeper "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func DnREpochIs(epoch uint64) action.Action { - return &setEpochAction{ - Epoch: epoch, - } -} - -type setEpochAction struct { - Epoch uint64 -} - -func (s setEpochAction) Do(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) { - app.PerpKeeperV2.DnREpoch.Set(ctx, s.Epoch) - return ctx, nil -} - -func DnRCurrentVolumeIs(user sdk.AccAddress, wantVolume math.Int) action.Action { - return &expectVolumeAction{ - User: user, - Volume: wantVolume, - } -} - -type expectVolumeAction struct { - User sdk.AccAddress - Volume math.Int -} - -func (e expectVolumeAction) Do(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) { - currentEpoch, err := app.PerpKeeperV2.DnREpoch.Get(ctx) - if err != nil { - return ctx, err - } - volume, err := app.PerpKeeperV2.TraderVolumes.Get(ctx, collections.Join(e.User, currentEpoch)) - if err != nil { - return ctx, err - } - if !volume.Equal(e.Volume) { - return ctx, fmt.Errorf("unexpected user dnr volume, wanted %s, got %s", e.Volume, volume) - } - return ctx, nil -} - -func DnRPreviousVolumeIs(user sdk.AccAddress, wantVolume math.Int) action.Action { - return &expectPreviousVolumeAction{ - User: user, - Volume: wantVolume, - } -} - -type expectPreviousVolumeAction struct { - User sdk.AccAddress - Volume math.Int -} - -func (e expectPreviousVolumeAction) Do(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) { - currentEpoch, err := app.PerpKeeperV2.DnREpoch.Get(ctx) - if err != nil { - return ctx, err - } - - v := app.PerpKeeperV2.GetTraderVolumeLastEpoch(ctx, currentEpoch, e.User) - if !v.Equal(e.Volume) { - return ctx, fmt.Errorf("unexpected user dnr volume, wanted %s, got %s", e.Volume, v) - } - return ctx, nil -} - -func DnRVolumeNotExist(user sdk.AccAddress, epoch uint64) action.Action { - return &expectVolumeNotExistAction{ - Epoch: epoch, - User: user, - } -} - -type expectVolumeNotExistAction struct { - Epoch uint64 - User sdk.AccAddress -} - -func (e expectVolumeNotExistAction) Do(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) { - v, err := app.PerpKeeperV2.TraderVolumes.Get(ctx, collections.Join(e.User, e.Epoch)) - if err == nil { - return ctx, fmt.Errorf("unexpected user dnr volume, got %s", v) - } - return ctx, nil -} - -type marketOrderFeeIs struct { - fee sdk.Dec - *openPositionAction -} - -func MarketOrderFeeIs( - fee sdk.Dec, - trader sdk.AccAddress, - pair asset.Pair, - dir types.Direction, - margin math.Int, - leverage sdk.Dec, - baseAssetLimit sdk.Dec, - responseCheckers ...MarketOrderResponseChecker, -) action.Action { - o := openPositionAction{ - trader: trader, - pair: pair, - dir: dir, - margin: margin, - leverage: leverage, - baseAssetLimit: baseAssetLimit, - responseCheckers: responseCheckers, - } - return &marketOrderFeeIs{ - fee: fee, - openPositionAction: &o, - } -} - -func (o *marketOrderFeeIs) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - collateral, err := app.PerpKeeperV2.Collateral.Get(ctx) - if err != nil { - return ctx, err - } - - balanceBefore := app.BankKeeper.GetBalance(ctx, o.trader, collateral).Amount - resp, err := app.PerpKeeperV2.MarketOrder( - ctx, o.pair, o.dir, o.trader, - o.margin, o.leverage, o.baseAssetLimit, - ) - if err != nil { - return ctx, err - } - - balanceBefore = balanceBefore.Sub(resp.MarginToVault.TruncateInt()) - - expectedFee := math.LegacyNewDecFromInt(o.margin).Mul(o.fee.Add(sdk.MustNewDecFromStr("0.001"))) // we add the ecosystem fund fee - balanceAfter := app.BankKeeper.GetBalance(ctx, o.trader, collateral).Amount - paidFees := balanceBefore.Sub(balanceAfter) - if !paidFees.Equal(expectedFee.TruncateInt()) { - return ctx, fmt.Errorf("unexpected fee, wanted %s, got %s", expectedFee, paidFees) - } - return ctx, nil -} - -func SetPreviousEpochUserVolume(user sdk.AccAddress, volume math.Int) action.Action { - return &setPreviousEpochUserVolumeAction{ - user: user, - volume: volume, - } -} - -type setPreviousEpochUserVolumeAction struct { - user sdk.AccAddress - volume math.Int -} - -func (s setPreviousEpochUserVolumeAction) Do(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) { - currentEpoch, err := app.PerpKeeperV2.DnREpoch.Get(ctx) - if err != nil { - return ctx, err - } - app.PerpKeeperV2.TraderVolumes.Insert(ctx, collections.Join(s.user, currentEpoch-1), s.volume) - return ctx, nil -} - -func SetGlobalDiscount(fee sdk.Dec, volume math.Int) action.Action { - return &setGlobalDiscountAction{ - fee: fee, - volume: volume, - } -} - -type setGlobalDiscountAction struct { - fee sdk.Dec - volume math.Int -} - -func (s setGlobalDiscountAction) Do(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) { - app.PerpKeeperV2.GlobalDiscounts.Insert(ctx, s.volume, s.fee) - return ctx, nil -} - -func SetCustomDiscount(user sdk.AccAddress, fee sdk.Dec, volume math.Int) action.Action { - return &setCustomDiscountAction{ - fee: fee, - volume: volume, - user: user, - } -} - -type setCustomDiscountAction struct { - fee sdk.Dec - volume math.Int - user sdk.AccAddress -} - -func (s *setCustomDiscountAction) Do(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) { - app.PerpKeeperV2.TraderDiscounts.Insert(ctx, collections.Join(s.user, s.volume), s.fee) - return ctx, nil -} - -type fundDnREpoch struct { - funds sdk.Coins -} - -func (f fundDnREpoch) Do(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) { - tmpAcc := testutil.AccAddress() - ctx, err = action.FundAccount(tmpAcc, f.funds).Do(app, ctx) - if err != nil { - return ctx, err - } - _, err = perpkeeper.NewMsgServerImpl(app.PerpKeeperV2).AllocateEpochRebates( - ctx, &types.MsgAllocateEpochRebates{ - Sender: tmpAcc.String(), - Rebates: f.funds, - }) - if err != nil { - return ctx, err - } - return ctx, nil -} - -func FundDnREpoch(amt sdk.Coins) action.Action { - return fundDnREpoch{amt} -} - -type startNewDnRepochAction struct{} - -func (s startNewDnRepochAction) Do(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) { - currentEpoch, err := app.PerpKeeperV2.DnREpoch.Get(ctx) - if err != nil { - return ctx, err - } - err = app.PerpKeeperV2.StartNewEpoch(ctx, currentEpoch+1) - if err != nil { - return ctx, err - } - return ctx, nil -} - -func StartNewDnREpoch() action.Action { - return &startNewDnRepochAction{} -} - -type dnrRebateIsAction struct { - user sdk.AccAddress - epoch uint64 - expectedRewards sdk.Coins -} - -func (d dnrRebateIsAction) Do(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) { - resp, err := perpkeeper.NewMsgServerImpl(app.PerpKeeperV2).WithdrawEpochRebates( - ctx, &types.MsgWithdrawEpochRebates{ - Sender: d.user.String(), - Epochs: []uint64{d.epoch}, - }) - if err != nil { - return ctx, err - } - withdrawn := resp.WithdrawnRebates - if !withdrawn.IsEqual(d.expectedRewards) { - return ctx, fmt.Errorf("expected %s, got %s", d.expectedRewards, withdrawn) - } - return ctx, nil -} - -func DnRRebateIs(user sdk.AccAddress, epoch uint64, expectedRewards sdk.Coins) action.Action { - return &dnrRebateIsAction{ - user: user, - epoch: epoch, - expectedRewards: expectedRewards, - } -} - -func DnRRebateFails(user sdk.AccAddress, epoch uint64) action.Action { - return &dnrRebateFailsAction{ - user: user, - epoch: epoch, - } -} - -type dnrRebateFailsAction struct { - user sdk.AccAddress - epoch uint64 -} - -func (d dnrRebateFailsAction) Do( - app *app.NibiruApp, ctx sdk.Context, -) (outCtx sdk.Context, err error) { - resp, err := perpkeeper.NewMsgServerImpl(app.PerpKeeperV2).WithdrawEpochRebates( - ctx, &types.MsgWithdrawEpochRebates{ - Sender: d.user.String(), - Epochs: []uint64{d.epoch}, - }) - if err == nil { - withdrawn := resp.WithdrawnRebates - return ctx, fmt.Errorf("expected withdrawal error but got instead: %s rewards", withdrawn.String()) - } - return ctx, nil -} diff --git a/x/perp/v2/integration/action/liquidation.go b/x/perp/v2/integration/action/liquidation.go deleted file mode 100644 index cf0360cd1..000000000 --- a/x/perp/v2/integration/action/liquidation.go +++ /dev/null @@ -1,73 +0,0 @@ -package action - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/testutil/action" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -type PairTraderTuple struct { - Pair asset.Pair - Trader sdk.AccAddress - Successful bool -} - -type multiLiquidate struct { - pairTraderTuples []PairTraderTuple - liquidator sdk.AccAddress - shouldAllFail bool -} - -func (m multiLiquidate) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - liquidationRequests := make([]*types.MsgMultiLiquidate_Liquidation, len(m.pairTraderTuples)) - - for i, pairTraderTuple := range m.pairTraderTuples { - liquidationRequests[i] = &types.MsgMultiLiquidate_Liquidation{ - Pair: pairTraderTuple.Pair, - Trader: pairTraderTuple.Trader.String(), - } - } - - responses, err := app.PerpKeeperV2.MultiLiquidate(ctx, m.liquidator, liquidationRequests) - - if m.shouldAllFail { - // we check if all liquidations failed - if err == nil { - return ctx, fmt.Errorf("multi liquidations should have all failed, but instead some succeeded") - } - - for i, response := range responses { - if response.Success { - return ctx, fmt.Errorf("multi liquidations should have all failed, but instead some succeeded, index %d", i) - } - } - - return ctx, nil - } - - // otherwise, some succeeded and some may have failed - if err != nil { - return ctx, err - } - - for i, response := range responses { - if response.Success != m.pairTraderTuples[i].Successful { - return ctx, fmt.Errorf("MultiLiquidate wrong assertion, expected %v, got %v, index %d", m.pairTraderTuples[i].Successful, response.Success, i) - } - } - - return ctx, nil -} - -func MultiLiquidate(liquidator sdk.AccAddress, shouldAllFail bool, pairTraderTuples ...PairTraderTuple) action.Action { - return multiLiquidate{ - pairTraderTuples: pairTraderTuples, - liquidator: liquidator, - shouldAllFail: shouldAllFail, - } -} diff --git a/x/perp/v2/integration/action/margin.go b/x/perp/v2/integration/action/margin.go deleted file mode 100644 index b83f31dda..000000000 --- a/x/perp/v2/integration/action/margin.go +++ /dev/null @@ -1,157 +0,0 @@ -package action - -import ( - "errors" - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/testutil/action" -) - -// AddMargin adds margin to the position -func AddMargin( - account sdk.AccAddress, - pair asset.Pair, - margin sdkmath.Int, -) action.Action { - return &addMarginAction{ - Account: account, - Pair: pair, - Margin: margin, - } -} - -type addMarginAction struct { - Account sdk.AccAddress - Pair asset.Pair - Margin sdkmath.Int -} - -func (a addMarginAction) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - collateral, err := app.PerpKeeperV2.Collateral.Get(ctx) - if err != nil { - return ctx, err - } - - _, err = app.PerpKeeperV2.AddMargin( - ctx, a.Pair, a.Account, sdk.NewCoin(collateral, a.Margin), - ) - if err != nil { - return ctx, err - } - - return ctx, nil -} - -// AddMarginFail adds margin to the position expecting a fail -func AddMarginFail( - account sdk.AccAddress, - pair asset.Pair, - margin sdkmath.Int, - err error, -) action.Action { - return &addMarginFailAction{ - Account: account, - Pair: pair, - Margin: margin, - ExpectedErr: err, - } -} - -type addMarginFailAction struct { - Account sdk.AccAddress - Pair asset.Pair - Margin sdkmath.Int - ExpectedErr error -} - -func (a addMarginFailAction) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - collateral, err := app.PerpKeeperV2.Collateral.Get(ctx) - if err != nil { - return ctx, err - } - - _, err = app.PerpKeeperV2.AddMargin( - ctx, a.Pair, a.Account, sdk.NewCoin(collateral, a.Margin), - ) - if !errors.Is(err, a.ExpectedErr) { - return ctx, fmt.Errorf("expected error %v, got %v", a.ExpectedErr, err) - } - - return ctx, nil -} - -func RemoveMargin( - account sdk.AccAddress, - pair asset.Pair, - margin sdkmath.Int, -) action.Action { - return &removeMarginAction{ - Account: account, - Pair: pair, - Margin: margin, - } -} - -type removeMarginAction struct { - Account sdk.AccAddress - Pair asset.Pair - Margin sdkmath.Int -} - -func (a removeMarginAction) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - collateral, err := app.PerpKeeperV2.Collateral.Get(ctx) - if err != nil { - return ctx, err - } - - _, err = app.PerpKeeperV2.RemoveMargin( - ctx, a.Pair, a.Account, sdk.NewCoin(collateral, a.Margin), - ) - if err != nil { - return ctx, err - } - - return ctx, nil -} - -func RemoveMarginFail( - account sdk.AccAddress, - pair asset.Pair, - margin sdkmath.Int, - err error, -) action.Action { - return &removeMarginActionFail{ - Account: account, - Pair: pair, - Margin: margin, - ExpectedErr: err, - } -} - -type removeMarginActionFail struct { - Account sdk.AccAddress - Pair asset.Pair - Margin sdkmath.Int - ExpectedErr error -} - -func (a removeMarginActionFail) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - collateral, err := app.PerpKeeperV2.Collateral.Get(ctx) - if err != nil { - return ctx, err - } - - _, err = app.PerpKeeperV2.RemoveMargin( - ctx, a.Pair, a.Account, sdk.NewCoin(collateral, a.Margin), - ) - if !errors.Is(err, a.ExpectedErr) { - return ctx, fmt.Errorf("expected error %v, got %v", a.ExpectedErr, err) - } - - return ctx, nil -} diff --git a/x/perp/v2/integration/action/market.go b/x/perp/v2/integration/action/market.go deleted file mode 100644 index 02b208b84..000000000 --- a/x/perp/v2/integration/action/market.go +++ /dev/null @@ -1,236 +0,0 @@ -package action - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/collections" - - "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/testutil/action" - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// createMarketAction creates a market -type createMarketAction struct { - Market types.Market - AMM types.AMM -} - -func (c createMarketAction) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - app.PerpKeeperV2.MarketLastVersion.Insert( - ctx, c.Market.Pair, types.MarketLastVersion{Version: c.Market.Version}) - app.PerpKeeperV2.SaveMarket(ctx, c.Market) - app.PerpKeeperV2.SaveAMM(ctx, c.AMM) - - app.PerpKeeperV2.ReserveSnapshots.Insert(ctx, collections.Join(c.AMM.Pair, ctx.BlockTime()), types.ReserveSnapshot{ - Amm: c.AMM, - TimestampMs: ctx.BlockTime().UnixMilli(), - }) - - app.PerpKeeperV2.Collateral.Set(ctx, types.TestingCollateralDenomNUSD) - - return ctx, nil -} - -// CreateCustomMarket creates a market with custom parameters -func CreateCustomMarket(pair asset.Pair, marketModifiers ...MarketModifier) action.Action { - market := types.DefaultMarket(pair) - amm := types.AMM{ - Pair: pair, - Version: 1, - BaseReserve: sdk.NewDec(1e12), - QuoteReserve: sdk.NewDec(1e12), - SqrtDepth: sdk.NewDec(1e12), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - } - - for _, modifier := range marketModifiers { - modifier(&market, &amm) - } - - return createMarketAction{ - Market: market, - AMM: amm, - } -} - -type MarketModifier func(market *types.Market, amm *types.AMM) - -func WithPrepaidBadDebt(amount sdkmath.Int, collateral string) MarketModifier { - return func(market *types.Market, amm *types.AMM) { - market.PrepaidBadDebt = sdk.NewCoin(collateral, amount) - } -} - -func WithPricePeg(newValue sdk.Dec) MarketModifier { - return func(market *types.Market, amm *types.AMM) { - amm.PriceMultiplier = newValue - } -} - -func WithTotalLong(amount sdk.Dec) MarketModifier { - return func(market *types.Market, amm *types.AMM) { - amm.TotalLong = amount - } -} - -func WithTotalShort(amount sdk.Dec) MarketModifier { - return func(market *types.Market, amm *types.AMM) { - amm.TotalShort = amount - } -} - -func WithSqrtDepth(amount sdk.Dec) MarketModifier { - return func(market *types.Market, amm *types.AMM) { - amm.SqrtDepth = amount - amm.BaseReserve = amount - amm.QuoteReserve = amount - } -} - -func WithLatestMarketCPF(amount sdk.Dec) MarketModifier { - return func(market *types.Market, amm *types.AMM) { - market.LatestCumulativePremiumFraction = amount - } -} - -func WithMaxFundingRate(amount sdk.Dec) MarketModifier { - return func(market *types.Market, amm *types.AMM) { - market.MaxFundingRate = amount - } -} - -func WithVersion(version uint64) MarketModifier { - return func(market *types.Market, amm *types.AMM) { - market.Version = version - amm.Version = version - } -} - -func WithEnabled(enabled bool) MarketModifier { - return func(market *types.Market, amm *types.AMM) { - market.Enabled = enabled - } -} - -type shiftPegMultiplier struct { - pair asset.Pair - newValue sdk.Dec -} - -func (e shiftPegMultiplier) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - err := app.PerpKeeperV2.Sudo().ShiftPegMultiplier( - ctx, e.pair, e.newValue, testapp.DefaultSudoRoot(), - ) - return ctx, err -} - -func ShiftPegMultiplier(pair asset.Pair, newValue sdk.Dec) action.Action { - return shiftPegMultiplier{ - pair: pair, - newValue: newValue, - } -} - -type shiftSwapInvariant struct { - pair asset.Pair - newValue sdkmath.Int -} - -func (e shiftSwapInvariant) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - err := app.PerpKeeperV2.Sudo().ShiftSwapInvariant( - ctx, e.pair, e.newValue, testapp.DefaultSudoRoot(), - ) - return ctx, err -} - -func ShiftSwapInvariant(pair asset.Pair, newValue sdkmath.Int) action.Action { - return shiftSwapInvariant{ - pair: pair, - newValue: newValue, - } -} - -type shiftSwapInvariantFail struct { - pair asset.Pair - newValue sdkmath.Int -} - -func (e shiftSwapInvariantFail) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - err := app.PerpKeeperV2.Sudo().ShiftSwapInvariant( - ctx, e.pair, e.newValue, testapp.DefaultSudoRoot(), - ) - if err == nil { - return ctx, fmt.Errorf("expected error") - } - return ctx, nil -} - -func ShiftSwapInvariantFail(pair asset.Pair, newValue sdkmath.Int) action.Action { - return shiftSwapInvariantFail{ - pair: pair, - newValue: newValue, - } -} - -type createPool struct { - pair asset.Pair - market types.Market - amm types.AMM -} - -func (c createPool) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - err := app.PerpKeeperV2.Sudo().CreateMarket(ctx, keeper.ArgsCreateMarket{ - Pair: c.pair, - PriceMultiplier: c.amm.PriceMultiplier, - SqrtDepth: c.amm.SqrtDepth, - Market: &c.market, - }) - return ctx, err -} - -func CreateMarket(pair asset.Pair, market types.Market, amm types.AMM) action.Action { - return createPool{ - pair: pair, - market: market, - amm: amm, - } -} - -type setCollateral struct { - Denom string - Sender string -} - -func (c setCollateral) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - sudoers, err := app.SudoKeeper.Sudoers.Get(ctx) - if err != nil { - return ctx, err - } - sudoers.Root = common.NIBIRU_TEAM - app.SudoKeeper.Sudoers.Set(ctx, sudoers) - - senderAddr, err := sdk.AccAddressFromBech32(c.Sender) - if err != nil { - return ctx, err - } - err = app.PerpKeeperV2.Sudo().ChangeCollateralDenom(ctx, c.Denom, senderAddr) - return ctx, err -} - -func SetCollateral(denom string) action.Action { - return setCollateral{ - Denom: denom, - Sender: common.NIBIRU_TEAM, - } -} diff --git a/x/perp/v2/integration/action/params.go b/x/perp/v2/integration/action/params.go deleted file mode 100644 index c629361e2..000000000 --- a/x/perp/v2/integration/action/params.go +++ /dev/null @@ -1,24 +0,0 @@ -package action - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/testutil/action" -) - -type changeLiquidationFeeRatio struct { - LiquidationFeeRatio sdk.Dec -} - -func (c changeLiquidationFeeRatio) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - // TODO(k-yang): implement - - return ctx, nil -} - -func ChangeLiquidationFeeRatio(liquidationFeeRatio sdk.Dec) action.Action { - return changeLiquidationFeeRatio{ - LiquidationFeeRatio: liquidationFeeRatio, - } -} diff --git a/x/perp/v2/integration/action/position.go b/x/perp/v2/integration/action/position.go deleted file mode 100644 index d10483c96..000000000 --- a/x/perp/v2/integration/action/position.go +++ /dev/null @@ -1,407 +0,0 @@ -package action - -import ( - "errors" - "fmt" - - sdkmath "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - "github.com/NibiruChain/nibiru/x/common/testutil/action" - perpkeeper "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// MarketOrder opens a position with the given parameters. -// -// responseCheckers are optional functions that can be used to check expected response. -func MarketOrder( - trader sdk.AccAddress, - pair asset.Pair, - dir types.Direction, - margin sdkmath.Int, - leverage sdk.Dec, - baseAssetLimit sdk.Dec, - responseCheckers ...MarketOrderResponseChecker, -) action.Action { - return &openPositionAction{ - trader: trader, - pair: pair, - dir: dir, - margin: margin, - leverage: leverage, - baseAssetLimit: baseAssetLimit, - responseCheckers: responseCheckers, - } -} - -type openPositionAction struct { - trader sdk.AccAddress - pair asset.Pair - dir types.Direction - margin sdkmath.Int - leverage sdk.Dec - baseAssetLimit sdk.Dec - - responseCheckers []MarketOrderResponseChecker -} - -func (o openPositionAction) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - resp, err := app.PerpKeeperV2.MarketOrder( - ctx, o.pair, o.dir, o.trader, - o.margin, o.leverage, o.baseAssetLimit, - ) - if err != nil { - return ctx, err - } - - if o.responseCheckers != nil { - for _, check := range o.responseCheckers { - err = check(resp) - if err != nil { - return ctx, err - } - } - } - - return ctx, nil -} - -type openPositionFailsAction struct { - trader sdk.AccAddress - pair asset.Pair - dir types.Direction - margin sdkmath.Int - leverage sdk.Dec - baseAssetLimit sdk.Dec - expectedErr error -} - -func (o openPositionFailsAction) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - _, err := app.PerpKeeperV2.MarketOrder( - ctx, o.pair, o.dir, o.trader, - o.margin, o.leverage, o.baseAssetLimit, - ) - - if !errors.Is(err, o.expectedErr) { - return ctx, fmt.Errorf("expected error %s, got %s", o.expectedErr, err) - } - - return ctx, nil -} - -func MarketOrderFails( - trader sdk.AccAddress, - pair asset.Pair, - dir types.Direction, - margin sdkmath.Int, - leverage sdk.Dec, - baseAssetLimit sdk.Dec, - expectedErr error, -) action.Action { - return &openPositionFailsAction{ - trader: trader, - pair: pair, - dir: dir, - margin: margin, - leverage: leverage, - baseAssetLimit: baseAssetLimit, - expectedErr: expectedErr, - } -} - -// Open Position Response Checkers -type MarketOrderResponseChecker func(resp *types.PositionResp) error - -// MarketOrderResp_PositionShouldBeEqual checks that the position included in the response is equal to the expected position response. -func MarketOrderResp_PositionShouldBeEqual(expected types.Position) MarketOrderResponseChecker { - return func(actual *types.PositionResp) error { - return types.PositionsAreEqual(&expected, &actual.Position) - } -} - -// MarketOrderResp_ExchangeNotionalValueShouldBeEqual checks that the exchanged notional value included in the response is equal to the expected value. -func MarketOrderResp_ExchangeNotionalValueShouldBeEqual(expected sdk.Dec) MarketOrderResponseChecker { - return func(actual *types.PositionResp) error { - if !actual.ExchangedNotionalValue.Equal(expected) { - return fmt.Errorf("expected exchanged notional value %s, got %s", expected, actual.ExchangedNotionalValue) - } - - return nil - } -} - -// MarketOrderResp_ExchangedPositionSizeShouldBeEqual checks that the exchanged position size included in the response is equal to the expected value. -func MarketOrderResp_ExchangedPositionSizeShouldBeEqual(expected sdk.Dec) MarketOrderResponseChecker { - return func(actual *types.PositionResp) error { - if !actual.ExchangedPositionSize.Equal(expected) { - return fmt.Errorf("expected exchanged position size %s, got %s", expected, actual.ExchangedPositionSize) - } - - return nil - } -} - -// MarketOrderResp_BadDebtShouldBeEqual checks that the bad debt included in the response is equal to the expected value. -func MarketOrderResp_BadDebtShouldBeEqual(expected sdk.Dec) MarketOrderResponseChecker { - return func(actual *types.PositionResp) error { - if !actual.BadDebt.Equal(expected) { - return fmt.Errorf("expected bad debt %s, got %s", expected, actual.BadDebt) - } - - return nil - } -} - -// MarketOrderResp_FundingPaymentShouldBeEqual checks that the funding payment included in the response is equal to the expected value. -func MarketOrderResp_FundingPaymentShouldBeEqual(expected sdk.Dec) MarketOrderResponseChecker { - return func(actual *types.PositionResp) error { - if !actual.FundingPayment.Equal(expected) { - return fmt.Errorf("expected funding payment %s, got %s", expected, actual.FundingPayment) - } - - return nil - } -} - -// MarketOrderResp_RealizedPnlShouldBeEqual checks that the realized pnl included in the response is equal to the expected value. -func MarketOrderResp_RealizedPnlShouldBeEqual(expected sdk.Dec) MarketOrderResponseChecker { - return func(actual *types.PositionResp) error { - if !actual.RealizedPnl.Equal(expected) { - return fmt.Errorf("expected realized pnl %s, got %s", expected, actual.RealizedPnl) - } - - return nil - } -} - -// MarketOrderResp_UnrealizedPnlAfterShouldBeEqual checks that the unrealized pnl after included in the response is equal to the expected value. -func MarketOrderResp_UnrealizedPnlAfterShouldBeEqual(expected sdk.Dec) MarketOrderResponseChecker { - return func(actual *types.PositionResp) error { - if !actual.UnrealizedPnlAfter.Equal(expected) { - return fmt.Errorf("expected unrealized pnl after %s, got %s", expected, actual.UnrealizedPnlAfter) - } - - return nil - } -} - -// MarketOrderResp_MarginToVaultShouldBeEqual checks that the margin to vault included in the response is equal to the expected value. -func MarketOrderResp_MarginToVaultShouldBeEqual(expected sdk.Dec) MarketOrderResponseChecker { - return func(actual *types.PositionResp) error { - if !actual.MarginToVault.Equal(expected) { - return fmt.Errorf("expected margin to vault %s, got %s", expected, actual.MarginToVault) - } - - return nil - } -} - -// MarketOrderResp_PositionNotionalShouldBeEqual checks that the position notional included in the response is equal to the expected value. -func MarketOrderResp_PositionNotionalShouldBeEqual(expected sdk.Dec) MarketOrderResponseChecker { - return func(actual *types.PositionResp) error { - if !actual.PositionNotional.Equal(expected) { - return fmt.Errorf("expected position notional %s, got %s", expected, actual.PositionNotional) - } - - return nil - } -} - -// Close Position - -type closePositionAction struct { - Account sdk.AccAddress - Pair asset.Pair -} - -func (c closePositionAction) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - _, err := app.PerpKeeperV2.ClosePosition(ctx, c.Pair, c.Account) - if err != nil { - return ctx, err - } - - return ctx, nil -} - -// ClosePosition closes a position for the given account and pair. -func ClosePosition(account sdk.AccAddress, pair asset.Pair) action.Action { - return &closePositionAction{ - Account: account, - Pair: pair, - } -} - -type closePositionFailsAction struct { - Account sdk.AccAddress - Pair asset.Pair - - expectedErr error -} - -func (c closePositionFailsAction) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - _, err := app.PerpKeeperV2.ClosePosition(ctx, c.Pair, c.Account) - - if !errors.Is(err, c.expectedErr) { - return ctx, fmt.Errorf("expected error %s, got %s", c.expectedErr, err) - } - - return ctx, nil -} - -func ClosePositionFails(account sdk.AccAddress, pair asset.Pair, expectedErr error) action.Action { - return &closePositionFailsAction{ - Account: account, - Pair: pair, - expectedErr: expectedErr, - } -} - -// Manually insert position, skipping open position logic -type insertPosition struct { - position types.Position -} - -func (i insertPosition) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - traderAddr := sdk.MustAccAddressFromBech32(i.position.TraderAddress) - app.PerpKeeperV2.SavePosition(ctx, i.position.Pair, 1, traderAddr, i.position) - return ctx, nil -} - -// InsertPosition: Adds a position into state without a corresponding market -// order. -func InsertPosition(modifiers ...positionModifier) action.Action { - position := types.Position{ - Pair: asset.Registry.Pair(denoms.BTC, denoms.USDC), - TraderAddress: testutil.AccAddress().String(), - Size_: sdk.ZeroDec(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.ZeroDec(), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - } - - for _, modifier := range modifiers { - modifier(&position) - } - - return insertPosition{ - position: position, - } -} - -type positionModifier func(position *types.Position) - -func WithPair(pair asset.Pair) positionModifier { - return func(position *types.Position) { - position.Pair = pair - } -} - -func WithTrader(addr sdk.AccAddress) positionModifier { - return func(position *types.Position) { - position.TraderAddress = addr.String() - } -} - -func WithMargin(margin sdk.Dec) positionModifier { - return func(position *types.Position) { - position.Margin = margin - } -} - -func WithOpenNotional(openNotional sdk.Dec) positionModifier { - return func(position *types.Position) { - position.OpenNotional = openNotional - } -} - -func WithSize(size sdk.Dec) positionModifier { - return func(position *types.Position) { - position.Size_ = size - } -} - -func WithLatestCumulativePremiumFraction(latestCumulativePremiumFraction sdk.Dec) positionModifier { - return func(position *types.Position) { - position.LatestCumulativePremiumFraction = latestCumulativePremiumFraction - } -} - -func WithLastUpdatedBlockNumber(lastUpdatedBlockNumber int64) positionModifier { - return func(position *types.Position) { - position.LastUpdatedBlockNumber = lastUpdatedBlockNumber - } -} - -type partialClose struct { - trader sdk.AccAddress - pair asset.Pair - amount sdk.Dec -} - -func (p partialClose) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - txMsg := &types.MsgPartialClose{ - Sender: p.trader.String(), - Pair: p.pair, - Size_: p.amount, - } - goCtx := sdk.WrapSDKContext(ctx) - _, err := perpkeeper.NewMsgServerImpl(app.PerpKeeperV2).PartialClose( - goCtx, txMsg) - if err != nil { - return ctx, err - } - - return ctx, nil -} - -func PartialClose(trader sdk.AccAddress, pair asset.Pair, amount sdk.Dec) action.Action { - return partialClose{ - trader: trader, - pair: pair, - amount: amount, - } -} - -type partialCloseFails struct { - trader sdk.AccAddress - pair asset.Pair - amount sdk.Dec - - expectedErr error -} - -func (p partialCloseFails) IsNotMandatory() {} - -func (p partialCloseFails) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - txMsg := &types.MsgPartialClose{ - Sender: p.trader.String(), - Pair: p.pair, - Size_: p.amount, - } - goCtx := sdk.WrapSDKContext(ctx) - _, err := perpkeeper.NewMsgServerImpl(app.PerpKeeperV2).PartialClose( - goCtx, txMsg, - ) - - if !errors.Is(err, p.expectedErr) { - return ctx, fmt.Errorf("expected error %s, got %s", p.expectedErr, err) - } - - return ctx, nil -} - -func PartialCloseFails(trader sdk.AccAddress, pair asset.Pair, amount sdk.Dec, expectedErr error) action.Action { - return partialCloseFails{ - trader: trader, - pair: pair, - amount: amount, - expectedErr: expectedErr, - } -} diff --git a/x/perp/v2/integration/action/query.go b/x/perp/v2/integration/action/query.go deleted file mode 100644 index 465f8eead..000000000 --- a/x/perp/v2/integration/action/query.go +++ /dev/null @@ -1,352 +0,0 @@ -package action - -import ( - "errors" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkquery "github.com/cosmos/cosmos-sdk/types/query" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/testutil/action" - "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -type queryPosition struct { - pair asset.Pair - traderAddress sdk.AccAddress - responseCheckers []QueryPositionChecker -} - -func (q queryPosition) IsNotMandatory() {} - -func (q queryPosition) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - queryServer := keeper.NewQuerier(app.PerpKeeperV2) - - resp, err := queryServer.QueryPosition(sdk.WrapSDKContext(ctx), &types.QueryPositionRequest{ - Pair: q.pair, - Trader: q.traderAddress.String(), - }) - if err != nil { - return ctx, err - } - - for _, checker := range q.responseCheckers { - if err := checker(*resp); err != nil { - return ctx, err - } - } - - return ctx, nil -} - -func QueryPosition(pair asset.Pair, traderAddress sdk.AccAddress, responseCheckers ...QueryPositionChecker) action.Action { - return queryPosition{ - pair: pair, - traderAddress: traderAddress, - responseCheckers: responseCheckers, - } -} - -type QueryPositionChecker func(resp types.QueryPositionResponse) error - -func QueryPosition_PositionEquals(expected types.Position) QueryPositionChecker { - return func(resp types.QueryPositionResponse) error { - return types.PositionsAreEqual(&expected, &resp.Position) - } -} - -func QueryPosition_PositionNotionalEquals(expected sdk.Dec) QueryPositionChecker { - return func(resp types.QueryPositionResponse) error { - if !expected.Equal(resp.PositionNotional) { - return fmt.Errorf("expected position notional %s, got %s", expected, resp.PositionNotional) - } - return nil - } -} - -func QueryPosition_UnrealizedPnlEquals(expected sdk.Dec) QueryPositionChecker { - return func(resp types.QueryPositionResponse) error { - if !expected.Equal(resp.UnrealizedPnl) { - return fmt.Errorf("expected unrealized pnl %s, got %s", expected, resp.UnrealizedPnl) - } - return nil - } -} - -func QueryPosition_MarginRatioEquals(expected sdk.Dec) QueryPositionChecker { - return func(resp types.QueryPositionResponse) error { - if !expected.Equal(resp.MarginRatio) { - return fmt.Errorf("expected margin ratio %s, got %s", expected, resp.MarginRatio) - } - return nil - } -} - -type queryAllPositions struct { - traderAddress sdk.AccAddress - allResponseCheckers [][]QueryPositionChecker -} - -func (q queryAllPositions) IsNotMandatory() {} - -func (q queryAllPositions) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - queryServer := keeper.NewQuerier(app.PerpKeeperV2) - - resp, err := queryServer.QueryPositions(sdk.WrapSDKContext(ctx), &types.QueryPositionsRequest{ - Trader: q.traderAddress.String(), - }) - if err != nil { - return ctx, err - } - - for i, positionCheckers := range q.allResponseCheckers { - for _, checker := range positionCheckers { - if err := checker(resp.Positions[i]); err != nil { - return ctx, err - } - } - } - - return ctx, nil -} - -func QueryPositions(traderAddress sdk.AccAddress, responseCheckers ...[]QueryPositionChecker) action.Action { - return queryAllPositions{ - traderAddress: traderAddress, - allResponseCheckers: responseCheckers, - } -} - -type queryPositionNotFound struct { - pair asset.Pair - traderAddress sdk.AccAddress -} - -func (q queryPositionNotFound) IsNotMandatory() {} - -func (q queryPositionNotFound) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - queryServer := keeper.NewQuerier(app.PerpKeeperV2) - - _, err := queryServer.QueryPosition(sdk.WrapSDKContext(ctx), &types.QueryPositionRequest{ - Pair: q.pair, - Trader: q.traderAddress.String(), - }) - if !errors.Is(err, types.ErrPositionNotFound) { - return ctx, fmt.Errorf( - "expected position not found, but found a position for pair %s, trader %s", - q.pair, - q.traderAddress, - ) - } - - return ctx, nil -} - -func QueryPositionNotFound(pair asset.Pair, traderAddress sdk.AccAddress) action.Action { - return queryPositionNotFound{ - pair: pair, - traderAddress: traderAddress, - } -} - -type queryMarkets struct { - versioned bool - allResponseCheckers []QueryMarketsChecker -} - -func (q queryMarkets) IsNotMandatory() {} - -func (q queryMarkets) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - queryServer := keeper.NewQuerier(app.PerpKeeperV2) - - resp, err := queryServer.QueryMarkets(sdk.WrapSDKContext(ctx), &types.QueryMarketsRequest{ - Versioned: q.versioned, - }) - if err != nil { - return ctx, err - } - - for _, marketsCheckers := range q.allResponseCheckers { - if err := marketsCheckers(resp.AmmMarkets); err != nil { - return ctx, err - } - } - - return ctx, nil -} - -// QueryMarkets queries all markets, versioned contains active and inactive markets -func QueryMarkets(versioned bool, responseCheckers ...QueryMarketsChecker) action.Action { - return queryMarkets{ - versioned: versioned, - allResponseCheckers: responseCheckers, - } -} - -type QueryMarketsChecker func(resp []types.AmmMarket) error - -func QueryMarkets_MarketsShouldContain(expectedMarket types.Market) QueryMarketsChecker { - return func(resp []types.AmmMarket) error { - for _, market := range resp { - if types.MarketsAreEqual(expectedMarket, market.Market) == nil { - return nil - } - } - marketsStr := make([]string, len(resp)) - for i, market := range resp { - marketsStr[i] = market.Market.String() - } - return fmt.Errorf("expected markets to contain %s but found %s", expectedMarket.String(), marketsStr) - } -} - -func QueryMarkets_ShouldLength(length int) QueryMarketsChecker { - return func(resp []types.AmmMarket) error { - if len(resp) != length { - return fmt.Errorf("expected markets to have length %d, got %d", length, len(resp)) - } - - return nil - } -} - -type queryModuleAccounts struct { - allResponseCheckers []QueryModuleAccountsChecker -} - -func (q queryModuleAccounts) IsNotMandatory() {} - -func (q queryModuleAccounts) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - queryServer := keeper.NewQuerier(app.PerpKeeperV2) - - resp, err := queryServer.ModuleAccounts(sdk.WrapSDKContext(ctx), &types.QueryModuleAccountsRequest{}) - if err != nil { - return ctx, err - } - - for _, accountsCheckers := range q.allResponseCheckers { - if err := accountsCheckers(resp.Accounts); err != nil { - return ctx, err - } - } - - return ctx, nil -} - -func QueryModuleAccounts(responseCheckers ...QueryModuleAccountsChecker) action.Action { - return queryModuleAccounts{allResponseCheckers: responseCheckers} -} - -type QueryModuleAccountsChecker func(resp []types.AccountWithBalance) error - -func QueryModuleAccounts_ModulesBalanceShouldBe(expectedBalance map[string]sdk.Coins) QueryModuleAccountsChecker { - return func(resp []types.AccountWithBalance) error { - for name, balance := range expectedBalance { - found := false - for _, account := range resp { - if account.Name == name { - found = true - if !account.Balance.IsEqual(balance) { - return fmt.Errorf("expected module %s to have balance %s, got %s", name, balance, account.Balance) - } - } - } - if !found { - return fmt.Errorf("expected module %s to have balance %s but not found", name, balance) - } - } - return nil - } -} - -// --------------------------------------------------------- -// QueryPositionStore -// --------------------------------------------------------- - -func QueryPositionStore( - pageReq *sdkquery.PageRequest, wantErr bool, checks ...QueryPositionStoreChecks, -) action.Action { - return queryPositionStore{ - pageReq: pageReq, - wantErr: wantErr, - checks: checks, - } -} - -func (q queryPositionStore) IsNotMandatory() {} - -func (q queryPositionStore) Do( - app *app.NibiruApp, ctx sdk.Context, -) (newCtx sdk.Context, err error) { - queryServer := keeper.NewQuerier(app.PerpKeeperV2) - - gotResp, err := queryServer.QueryPositionStore( - sdk.WrapSDKContext(ctx), - &types.QueryPositionStoreRequest{Pagination: q.pageReq}, - ) - if q.wantErr && err != nil { - return action.ActionResp(ctx, nil) // pass - } else if !q.wantErr && err != nil { - return action.ActionResp(ctx, err) // fail - } - - for _, checker := range q.checks { - if err := checker(*gotResp); err != nil { - return action.ActionResp(ctx, err) - } - } - return action.ActionResp(ctx, nil) -} - -type queryPositionStore struct { - pageReq *sdkquery.PageRequest - wantErr bool - checks []QueryPositionStoreChecks -} - -type QueryPositionStoreChecks func(resp types.QueryPositionStoreResponse) error - -func CheckPositionStore_NumPositions(num int) QueryPositionStoreChecks { - return func(got types.QueryPositionStoreResponse) error { - gotNumPos := len(got.Positions) - if num != gotNumPos { - return fmt.Errorf("expected num positions: %v, got: %v", num, gotNumPos) - } - return nil - } -} - -// --------------------------------------------------------- -// QueryCollateral -// --------------------------------------------------------- - -type queryCollateral struct { - wantDenom string -} - -func (q queryCollateral) IsNotMandatory() {} - -func (q queryCollateral) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - queryServer := keeper.NewQuerier(app.PerpKeeperV2) - - resp, _ := queryServer.QueryCollateral(sdk.WrapSDKContext(ctx), &types.QueryCollateralRequest{}) - if resp.CollateralDenom != q.wantDenom { - return ctx, fmt.Errorf( - "expected collateral denom %s, got %s", - q.wantDenom, - resp.CollateralDenom, - ) - } - - return ctx, nil -} - -// QueryCollateral: Action for the Query/Collateral gRPC query. -func QueryCollateral(expectDenom string) action.Action { - return queryCollateral{ - wantDenom: expectDenom, - } -} diff --git a/x/perp/v2/integration/action/settlement.go b/x/perp/v2/integration/action/settlement.go deleted file mode 100644 index 712ce2a87..000000000 --- a/x/perp/v2/integration/action/settlement.go +++ /dev/null @@ -1,125 +0,0 @@ -package action - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/testutil/action" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// closeMarket -type closeMarket struct { - pair asset.Pair - sender sdk.AccAddress -} - -func (c closeMarket) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - err := app.PerpKeeperV2.Sudo().CloseMarket(ctx, c.pair, c.sender) - if err != nil { - return ctx, err - } - - return ctx, nil -} - -func CloseMarket(pair asset.Pair, adminAccount sdk.AccAddress) action.Action { - return closeMarket{pair: pair, sender: adminAccount} -} - -// closeMarketShouldFail -type closeMarketShouldFail struct { - pair asset.Pair - sender sdk.AccAddress -} - -func (c closeMarketShouldFail) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - err := app.PerpKeeperV2.Sudo().CloseMarket(ctx, c.pair, c.sender) - if err == nil { - return ctx, err - } - - return ctx, nil -} - -func CloseMarketShouldFail(pair asset.Pair, adminAccount sdk.AccAddress) action.Action { - return closeMarketShouldFail{pair: pair, sender: adminAccount} -} - -// settlePosition -type settlePosition struct { - pair asset.Pair - version uint64 - trader sdk.AccAddress - responseCheckers []SettlePositionChecker -} - -func (c settlePosition) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - resp, err := app.PerpKeeperV2.SettlePosition(ctx, c.pair, c.version, c.trader) - if err != nil { - return ctx, err - } - - for _, checker := range c.responseCheckers { - if err := checker(*resp); err != nil { - return ctx, err - } - } - - return ctx, nil -} - -func SettlePosition(pair asset.Pair, version uint64, trader sdk.AccAddress, responseCheckers ...SettlePositionChecker) action.Action { - return settlePosition{pair: pair, version: version, trader: trader, responseCheckers: responseCheckers} -} - -type SettlePositionChecker func(resp types.PositionResp) error - -func SettlePositionChecker_PositionEquals(expected types.Position) SettlePositionChecker { - return func(resp types.PositionResp) error { - return types.PositionsAreEqual(&expected, &resp.Position) - } -} - -func SettlePositionChecker_MarginToVault(expectedMarginToVault sdk.Dec) SettlePositionChecker { - return func(resp types.PositionResp) error { - if expectedMarginToVault.Equal(resp.MarginToVault) { - return nil - } else { - return fmt.Errorf("expected margin to vault %s, got %s", expectedMarginToVault, resp.MarginToVault) - } - } -} - -func SettlePositionChecker_BadDebt(expectedBadDebt sdk.Dec) SettlePositionChecker { - return func(resp types.PositionResp) error { - if expectedBadDebt.Equal(resp.BadDebt) { - return nil - } else { - return fmt.Errorf("expected bad debt %s, got %s", expectedBadDebt, resp.BadDebt) - } - } -} - -// settlePositionShouldFail -type settlePositionShouldFail struct { - pair asset.Pair - version uint64 - trader sdk.AccAddress -} - -func (c settlePositionShouldFail) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - _, err := app.PerpKeeperV2.SettlePosition(ctx, c.pair, c.version, c.trader) - if err == nil { - return ctx, err - } - - return ctx, nil -} - -func SettlePositionShouldFail(pair asset.Pair, version uint64, trader sdk.AccAddress) action.Action { - return settlePositionShouldFail{pair: pair, version: version, trader: trader} -} diff --git a/x/perp/v2/integration/action/snapshot.go b/x/perp/v2/integration/action/snapshot.go deleted file mode 100644 index c123907b5..000000000 --- a/x/perp/v2/integration/action/snapshot.go +++ /dev/null @@ -1,60 +0,0 @@ -package action - -import ( - "time" - - "github.com/NibiruChain/collections" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/testutil/action" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -type insertReserveSnapshot struct { - pair asset.Pair - time time.Time - - modifiers []reserveSnapshotModifier -} - -func (i insertReserveSnapshot) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - amm := app.PerpKeeperV2.AMMs.GetOr(ctx, collections.Join(i.pair, uint64(1)), types.AMM{ - Pair: i.pair, - Version: uint64(1), - BaseReserve: sdk.ZeroDec(), - QuoteReserve: sdk.ZeroDec(), - SqrtDepth: sdk.ZeroDec(), - PriceMultiplier: sdk.ZeroDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }) - - for _, modifier := range i.modifiers { - modifier(&amm) - } - - app.PerpKeeperV2.ReserveSnapshots.Insert(ctx, collections.Join(i.pair, i.time), types.ReserveSnapshot{ - TimestampMs: i.time.UnixMilli(), - Amm: amm, - }) - - return ctx, nil -} - -func InsertReserveSnapshot(pair asset.Pair, time time.Time, modifiers ...reserveSnapshotModifier) action.Action { - return insertReserveSnapshot{ - pair: pair, - time: time, - modifiers: modifiers, - } -} - -type reserveSnapshotModifier func(amm *types.AMM) - -func WithPriceMultiplier(multiplier sdk.Dec) reserveSnapshotModifier { - return func(amm *types.AMM) { - amm.PriceMultiplier = multiplier - } -} diff --git a/x/perp/v2/integration/action/tx.go b/x/perp/v2/integration/action/tx.go deleted file mode 100644 index 81af0d908..000000000 --- a/x/perp/v2/integration/action/tx.go +++ /dev/null @@ -1,316 +0,0 @@ -package action - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/testutil/action" - "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -type msgServerMarketOrder struct { - pair asset.Pair - traderAddress sdk.AccAddress - dir types.Direction - quoteAssetAmt sdkmath.Int - leverage sdk.Dec - baseAssetAmtLimit sdkmath.Int -} - -func (m msgServerMarketOrder) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - msgServer := keeper.NewMsgServerImpl(app.PerpKeeperV2) - - // don't need to check response because it's already checked in clearing_house tests - _, err := msgServer.MarketOrder(sdk.WrapSDKContext(ctx), &types.MsgMarketOrder{ - Pair: m.pair, - Sender: m.traderAddress.String(), - Side: m.dir, - QuoteAssetAmount: m.quoteAssetAmt, - Leverage: m.leverage, - BaseAssetAmountLimit: m.baseAssetAmtLimit, - }) - - return ctx, err -} - -func MsgServerMarketOrder( - traderAddress sdk.AccAddress, - pair asset.Pair, - dir types.Direction, - quoteAssetAmt sdkmath.Int, - leverage sdk.Dec, - baseAssetAmtLimit sdkmath.Int, -) action.Action { - return msgServerMarketOrder{ - pair: pair, - traderAddress: traderAddress, - dir: dir, - quoteAssetAmt: quoteAssetAmt, - leverage: leverage, - baseAssetAmtLimit: baseAssetAmtLimit, - } -} - -type msgServerClosePosition struct { - pair asset.Pair - traderAddress sdk.AccAddress -} - -func (m msgServerClosePosition) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - msgServer := keeper.NewMsgServerImpl(app.PerpKeeperV2) - - // don't need to check response because it's already checked in clearing_house tests - _, err := msgServer.ClosePosition(sdk.WrapSDKContext(ctx), &types.MsgClosePosition{ - Pair: m.pair, - Sender: m.traderAddress.String(), - }) - - return ctx, err -} - -func MsgServerClosePosition( - traderAddress sdk.AccAddress, - pair asset.Pair, -) action.Action { - return msgServerClosePosition{ - pair: pair, - traderAddress: traderAddress, - } -} - -type msgServerPartialClose struct { - pair asset.Pair - traderAddress sdk.AccAddress - size sdk.Dec -} - -func (m msgServerPartialClose) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - msgServer := keeper.NewMsgServerImpl(app.PerpKeeperV2) - - // don't need to check response because it's already checked in clearing_house tests - _, err := msgServer.PartialClose(sdk.WrapSDKContext(ctx), &types.MsgPartialClose{ - Pair: m.pair, - Sender: m.traderAddress.String(), - Size_: m.size, - }) - - return ctx, err -} - -func MsgServerPartialClosePosition( - traderAddress sdk.AccAddress, - pair asset.Pair, - size sdk.Dec, -) action.Action { - return msgServerPartialClose{ - pair: pair, - traderAddress: traderAddress, - size: size, - } -} - -type msgServerAddmargin struct { - pair asset.Pair - traderAddress sdk.AccAddress - amount sdkmath.Int -} - -func (m msgServerAddmargin) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - msgServer := keeper.NewMsgServerImpl(app.PerpKeeperV2) - - collateral, err := app.PerpKeeperV2.Collateral.Get(ctx) - if err != nil { - return ctx, err - } - - // don't need to check response because it's already checked in clearing_house tests - _, err = msgServer.AddMargin(sdk.WrapSDKContext(ctx), &types.MsgAddMargin{ - Pair: m.pair, - Sender: m.traderAddress.String(), - Margin: sdk.NewCoin(collateral, m.amount), - }) - - return ctx, err -} - -func MsgServerAddMargin( - traderAddress sdk.AccAddress, - pair asset.Pair, - amount sdkmath.Int, -) action.Action { - return msgServerAddmargin{ - pair: pair, - traderAddress: traderAddress, - amount: amount, - } -} - -type msgServerRemoveMargin struct { - pair asset.Pair - traderAddress sdk.AccAddress - amount sdkmath.Int -} - -func (m msgServerRemoveMargin) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - msgServer := keeper.NewMsgServerImpl(app.PerpKeeperV2) - - collateral, err := app.PerpKeeperV2.Collateral.Get(ctx) - if err != nil { - return ctx, err - } - - // don't need to check response because it's already checked in clearing_house tests - _, err = msgServer.RemoveMargin(sdk.WrapSDKContext(ctx), &types.MsgRemoveMargin{ - Pair: m.pair, - Sender: m.traderAddress.String(), - Margin: sdk.NewCoin(collateral, m.amount), - }) - - return ctx, err -} - -func MsgServerRemoveMargin( - traderAddress sdk.AccAddress, - pair asset.Pair, - amount sdkmath.Int, -) action.Action { - return msgServerRemoveMargin{ - pair: pair, - traderAddress: traderAddress, - amount: amount, - } -} - -type msgServerSettlePosition struct { - pair asset.Pair - traderAddress sdk.AccAddress - Version uint64 -} - -func (m msgServerSettlePosition) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - msgServer := keeper.NewMsgServerImpl(app.PerpKeeperV2) - - // don't need to check response because it's already checked in clearing_house tests - _, err := msgServer.SettlePosition(sdk.WrapSDKContext(ctx), &types.MsgSettlePosition{ - Pair: m.pair, - Sender: m.traderAddress.String(), - Version: m.Version, - }) - - return ctx, err -} - -func MsgServerSettlePosition( - traderAddress sdk.AccAddress, - pair asset.Pair, - version uint64, -) action.Action { - return msgServerSettlePosition{ - pair: pair, - traderAddress: traderAddress, - Version: version, - } -} - -type msgServerSettlePositionShouldFail struct { - pair asset.Pair - traderAddress sdk.AccAddress - Version uint64 -} - -func (m msgServerSettlePositionShouldFail) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - msgServer := keeper.NewMsgServerImpl(app.PerpKeeperV2) - - // don't need to check response because it's already checked in clearing_house tests - _, err := msgServer.SettlePosition(sdk.WrapSDKContext(ctx), &types.MsgSettlePosition{ - Pair: m.pair, - Sender: m.traderAddress.String(), - Version: m.Version, - }) - if err == nil { - return ctx, fmt.Errorf("should fail but no error returned") - } - - return ctx, nil -} - -func MsgServerSettlePositionShouldFail( - traderAddress sdk.AccAddress, - pair asset.Pair, - version uint64, -) action.Action { - return msgServerSettlePositionShouldFail{ - pair: pair, - traderAddress: traderAddress, - Version: version, - } -} - -type msgServerDonateToPerpEf struct { - sender sdk.AccAddress - amount sdkmath.Int -} - -func (m msgServerDonateToPerpEf) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - msgServer := keeper.NewMsgServerImpl(app.PerpKeeperV2) - - collateral, err := app.PerpKeeperV2.Collateral.Get(ctx) - if err != nil { - return ctx, err - } - - _, err = msgServer.DonateToEcosystemFund(sdk.WrapSDKContext(ctx), &types.MsgDonateToEcosystemFund{ - Sender: m.sender.String(), - Donation: sdk.NewCoin(collateral, m.amount), - }) - - return ctx, err -} - -func MsgServerDonateToPerpEf( - traderAddress sdk.AccAddress, - amount sdkmath.Int, -) action.Action { - return msgServerDonateToPerpEf{ - sender: traderAddress, - amount: amount, - } -} - -type msgServerMultiLiquidate struct { - pairTraderTuples []PairTraderTuple - liquidator sdk.AccAddress - shouldAllFail bool -} - -func (m msgServerMultiLiquidate) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - msgServer := keeper.NewMsgServerImpl(app.PerpKeeperV2) - - liquidateMsgs := make([]*types.MsgMultiLiquidate_Liquidation, len(m.pairTraderTuples)) - for i, pairTraderTuple := range m.pairTraderTuples { - liquidateMsgs[i] = &types.MsgMultiLiquidate_Liquidation{ - Pair: pairTraderTuple.Pair, - Trader: pairTraderTuple.Trader.String(), - } - } - - _, err := msgServer.MultiLiquidate(sdk.WrapSDKContext(ctx), &types.MsgMultiLiquidate{ - Sender: m.liquidator.String(), - Liquidations: liquidateMsgs, - }) - - return ctx, err -} - -func MsgServerMultiLiquidate(liquidator sdk.AccAddress, shouldAllFail bool, pairTraderTuples ...PairTraderTuple) action.Action { - return msgServerMultiLiquidate{ - pairTraderTuples: pairTraderTuples, - liquidator: liquidator, - shouldAllFail: shouldAllFail, - } -} diff --git a/x/perp/v2/integration/action/withdraw.go b/x/perp/v2/integration/action/withdraw.go deleted file mode 100644 index 22cd28891..000000000 --- a/x/perp/v2/integration/action/withdraw.go +++ /dev/null @@ -1,36 +0,0 @@ -package action - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/testutil/action" -) - -type withdraw struct { - Account sdk.AccAddress - Amount sdkmath.Int - Pair asset.Pair -} - -func (w withdraw) Do(app *app.NibiruApp, ctx sdk.Context) ( - outCtx sdk.Context, err error, -) { - market, err := app.PerpKeeperV2.GetMarket(ctx, w.Pair) - if err != nil { - return ctx, err - } - - err = app.PerpKeeperV2.WithdrawFromVault(ctx, market, w.Account, w.Amount) - return ctx, err -} - -func WithdrawFromVault(pair asset.Pair, account sdk.AccAddress, amount sdkmath.Int) action.Action { - return withdraw{ - Account: account, - Amount: amount, - Pair: pair, - } -} diff --git a/x/perp/v2/integration/assertion/bank.go b/x/perp/v2/integration/assertion/bank.go deleted file mode 100644 index 53b5955c9..000000000 --- a/x/perp/v2/integration/assertion/bank.go +++ /dev/null @@ -1,34 +0,0 @@ -package assertion - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/testutil/action" -) - -type moduleBalanceShouldBeEqual struct { - module string - expectedBalance sdk.Coins -} - -func (p moduleBalanceShouldBeEqual) IsNotMandatory() {} - -func (p moduleBalanceShouldBeEqual) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - balance := app.BankKeeper.GetAllBalances(ctx, app.AccountKeeper.GetModuleAddress(p.module)) - - if !balance.IsEqual(p.expectedBalance) { - return ctx, fmt.Errorf("balance expected for %s to be %s, received %s", p.module, p.expectedBalance.String(), balance.String()) - } - - return ctx, nil -} - -func ModuleBalanceShouldBeEqualTo(module string, expectedBalance sdk.Coins) action.Action { - return moduleBalanceShouldBeEqual{ - module: module, - expectedBalance: expectedBalance, - } -} diff --git a/x/perp/v2/integration/assertion/event.go b/x/perp/v2/integration/assertion/event.go deleted file mode 100644 index 888a11d23..000000000 --- a/x/perp/v2/integration/assertion/event.go +++ /dev/null @@ -1,148 +0,0 @@ -package assertion - -import ( - "errors" - "fmt" - "reflect" - "strings" - - abci "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/gogoproto/proto" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/testutil/action" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -var ( - _ action.Action = (*containsLiquidateEvent)(nil) - _ action.Action = (*positionChangedEventShouldBeEqual)(nil) -) - -// TODO test(perp): Add action for testing the appearance of of successful -// liquidation events. - -// -------------------------------------------------- -// -------------------------------------------------- - -type containsLiquidateEvent struct { - expectedEvent *types.LiquidationFailedEvent -} - -func (act containsLiquidateEvent) Do(_ *app.NibiruApp, ctx sdk.Context) ( - outCtx sdk.Context, err error, -) { - foundEvent := false - matchingEvents := []abci.Event{} - - for _, sdkEvent := range ctx.EventManager().Events() { - if sdkEvent.Type != proto.MessageName(act.expectedEvent) { - continue - } - - abciEvent := abci.Event{ - Type: sdkEvent.Type, - Attributes: sdkEvent.Attributes, - } - - typedEvent, err := sdk.ParseTypedEvent(abciEvent) - if err != nil { - return ctx, err - } - - liquidationFailedEvent, ok := typedEvent.(*types.LiquidationFailedEvent) - if !ok { - return ctx, - fmt.Errorf("expected event of type %s, got %s", proto.MessageName(act.expectedEvent), abciEvent.Type) - } - - if reflect.DeepEqual(act.expectedEvent, liquidationFailedEvent) { - foundEvent = true - break - } - - matchingEvents = append(matchingEvents, abciEvent) - } - - if foundEvent { - // happy path - return ctx, nil - } - - // Show descriptive error messages if the expected event is missing - expected, _ := sdk.TypedEventToEvent(act.expectedEvent) - return ctx, errors.New( - strings.Join([]string{ - fmt.Sprintf("expected: %+v.", sdk.StringifyEvents([]abci.Event{abci.Event(expected)})), - fmt.Sprintf("found %v events:", len(ctx.EventManager().Events())), - fmt.Sprintf("events of matching type:\n%v", sdk.StringifyEvents(matchingEvents).String()), - }, "\n"), - ) -} - -// ContainsLiquidateEvent checks if a typed event (proto.Message) is contained in the -// event manager of the app context. -func ContainsLiquidateEvent( - expectedEvent *types.LiquidationFailedEvent, -) action.Action { - return containsLiquidateEvent{ - expectedEvent: expectedEvent, - } -} - -type positionChangedEventShouldBeEqual struct { - expectedEvent *types.PositionChangedEvent -} - -func (p positionChangedEventShouldBeEqual) IsNotMandatory() {} - -func (p positionChangedEventShouldBeEqual) Do(_ *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - for _, sdkEvent := range ctx.EventManager().Events() { - if sdkEvent.Type != proto.MessageName(p.expectedEvent) { - continue - } - - abciEvent := abci.Event{ - Type: sdkEvent.Type, - Attributes: sdkEvent.Attributes, - } - - typedEvent, err := sdk.ParseTypedEvent(abciEvent) - if err != nil { - return ctx, err - } - - positionChangedEvent, ok := typedEvent.(*types.PositionChangedEvent) - if !ok { - return ctx, fmt.Errorf("expected event is not of type PositionChangedEvent") - } - - if err := types.PositionsAreEqual(&p.expectedEvent.FinalPosition, &positionChangedEvent.FinalPosition); err != nil { - return ctx, err - } - - if !reflect.DeepEqual(p.expectedEvent, positionChangedEvent) { - expected, _ := sdk.TypedEventToEvent(p.expectedEvent) - return ctx, fmt.Errorf(`expected event is not equal to the actual event. -want: -%+v -got: -%+v`, sdk.StringifyEvents([]abci.Event{abci.Event(expected)}), sdk.StringifyEvents([]abci.Event{abciEvent})) - } - - return ctx, nil - } - - return ctx, fmt.Errorf("unable to find desired event of type %s", proto.MessageName(p.expectedEvent)) -} - -// PositionChangedEventShouldBeEqual checks that the position changed event is -// equal to the expected event. -func PositionChangedEventShouldBeEqual( - expectedEvent *types.PositionChangedEvent, -) action.Action { - return positionChangedEventShouldBeEqual{ - expectedEvent: expectedEvent, - } -} diff --git a/x/perp/v2/integration/assertion/market.go b/x/perp/v2/integration/assertion/market.go deleted file mode 100644 index d18ddcc11..000000000 --- a/x/perp/v2/integration/assertion/market.go +++ /dev/null @@ -1,178 +0,0 @@ -package assertion - -import ( - "fmt" - - "github.com/NibiruChain/nibiru/x/common/testutil/action" - - sdkmath "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/asset" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -type MarketChecker func(resp types.Market) error - -type marketShouldBeEqual struct { - Pair asset.Pair - Checkers []MarketChecker -} - -func (m marketShouldBeEqual) IsNotMandatory() {} - -func (m marketShouldBeEqual) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - market, err := app.PerpKeeperV2.GetMarket(ctx, m.Pair) - if err != nil { - return ctx, err - } - - for _, checker := range m.Checkers { - if err := checker(market); err != nil { - return ctx, err - } - } - - return ctx, nil -} - -func MarketShouldBeEqual(pair asset.Pair, marketCheckers ...MarketChecker) action.Action { - return marketShouldBeEqual{ - Pair: pair, - Checkers: marketCheckers, - } -} - -func Market_LatestCPFShouldBeEqualTo(expectedCPF sdk.Dec) MarketChecker { - return func(market types.Market) error { - if !market.LatestCumulativePremiumFraction.Equal(expectedCPF) { - return fmt.Errorf("expected latest cumulative premium fraction to be %s, got %s", expectedCPF, market.LatestCumulativePremiumFraction) - } - return nil - } -} - -func Market_PrepaidBadDebtShouldBeEqualTo(expectedAmount sdkmath.Int, collateral string) MarketChecker { - return func(market types.Market) error { - expectedBadDebt := sdk.NewCoin(collateral, expectedAmount) - if !market.PrepaidBadDebt.Equal(expectedBadDebt) { - return fmt.Errorf("expected prepaid bad debt to be %s, got %s", expectedBadDebt, market.PrepaidBadDebt) - } - return nil - } -} - -func Market_EnableShouldBeEqualTo(expectedEnabled bool) MarketChecker { - return func(market types.Market) error { - if market.Enabled != expectedEnabled { - return fmt.Errorf("expected enabled to be %t, got %t", expectedEnabled, market.Enabled) - } - return nil - } -} - -type ammShouldBeEqual struct { - Pair asset.Pair - Checkers []AMMChecker -} - -type AMMChecker func(amm types.AMM) error - -func (a ammShouldBeEqual) IsNotMandatory() {} - -func (a ammShouldBeEqual) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - amm, err := app.PerpKeeperV2.GetAMM(ctx, a.Pair) - if err != nil { - return ctx, err - } - - for _, checker := range a.Checkers { - if err := checker(amm); err != nil { - return ctx, err - } - } - - return ctx, nil -} - -func AMMShouldBeEqual(pair asset.Pair, ammCheckers ...AMMChecker) action.Action { - return ammShouldBeEqual{ - Pair: pair, - Checkers: ammCheckers, - } -} - -func AMM_BaseReserveShouldBeEqual(expectedBaseReserve sdk.Dec) AMMChecker { - return func(amm types.AMM) error { - if !amm.BaseReserve.Equal(expectedBaseReserve) { - return fmt.Errorf("expected base reserve to be %s, got %s", expectedBaseReserve, amm.BaseReserve) - } - return nil - } -} - -func AMM_QuoteReserveShouldBeEqual(expectedQuoteReserve sdk.Dec) AMMChecker { - return func(amm types.AMM) error { - if !amm.QuoteReserve.Equal(expectedQuoteReserve) { - return fmt.Errorf("expected quote reserve to be %s, got %s", expectedQuoteReserve, amm.QuoteReserve) - } - return nil - } -} - -func AMM_SqrtDepthShouldBeEqual(expectedSqrtDepth sdk.Dec) AMMChecker { - return func(amm types.AMM) error { - if !amm.SqrtDepth.Equal(expectedSqrtDepth) { - return fmt.Errorf("expected sqrt depth to be %s, got %s", expectedSqrtDepth, amm.SqrtDepth) - } - return nil - } -} - -func AMM_SwapInvariantShouldBeEqual(expectedSwapInvariant sdk.Dec) AMMChecker { - return func(amm types.AMM) error { - swapInvariant := amm.BaseReserve.Mul(amm.QuoteReserve) - if !swapInvariant.Equal(expectedSwapInvariant) { - return fmt.Errorf("expected swap invariant to be %s, got %s", expectedSwapInvariant, swapInvariant) - } - return nil - } -} - -func AMM_PriceMultiplierShouldBeEqual(expectedPriceMultiplier sdk.Dec) AMMChecker { - return func(amm types.AMM) error { - if !amm.PriceMultiplier.Equal(expectedPriceMultiplier) { - return fmt.Errorf("expected price multiplier to be %s, got %s", expectedPriceMultiplier, amm.PriceMultiplier) - } - return nil - } -} - -func AMM_BiasShouldBeEqual(expectedBias sdk.Dec) AMMChecker { - return func(amm types.AMM) error { - if !amm.Bias().Equal(expectedBias) { - return fmt.Errorf("expected bias to be %s, got %s", expectedBias, amm.Bias()) - } - return nil - } -} - -func AMM_VersionShouldBeEqual(expectedVersion uint64) AMMChecker { - return func(amm types.AMM) error { - if amm.Version != expectedVersion { - return fmt.Errorf("expected version to be %d, got %d", expectedVersion, amm.Version) - } - return nil - } -} - -func AMM_SettlementPriceShoulBeEqual(expectedPrice sdk.Dec) AMMChecker { - return func(amm types.AMM) error { - if !amm.SettlementPrice.Equal(expectedPrice) { - return fmt.Errorf("expected settlement price to be %s, got %s", expectedPrice, amm.SettlementPrice) - } - return nil - } -} diff --git a/x/perp/v2/integration/assertion/notional.go b/x/perp/v2/integration/assertion/notional.go deleted file mode 100644 index 8fe14fc8a..000000000 --- a/x/perp/v2/integration/assertion/notional.go +++ /dev/null @@ -1,48 +0,0 @@ -package assertion - -import ( - "fmt" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/testutil/action" -) - -type positionNotionalTwapShouldBeEqualTo struct { - pair asset.Pair - trader sdk.AccAddress - twapLookbackWindow time.Duration - expectedNotionalValue sdk.Dec -} - -func (p positionNotionalTwapShouldBeEqualTo) IsNotMandatory() {} - -func (p positionNotionalTwapShouldBeEqualTo) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - position, err := app.PerpKeeperV2.GetPosition(ctx, p.pair, 1, p.trader) - if err != nil { - return ctx, err - } - - notionalValue, err := app.PerpKeeperV2.PositionNotionalTWAP(ctx, position, p.twapLookbackWindow) - if err != nil { - return ctx, err - } - - if !notionalValue.Equal(p.expectedNotionalValue) { - return ctx, fmt.Errorf("notional value expected to be %s, received %s", p.expectedNotionalValue, notionalValue) - } - - return ctx, nil -} - -func PositionNotionalTWAPShouldBeEqualTo(pair asset.Pair, trader sdk.AccAddress, twapLookbackWindow time.Duration, expectedNotionalValue sdk.Dec) action.Action { - return positionNotionalTwapShouldBeEqualTo{ - pair: pair, - trader: trader, - twapLookbackWindow: twapLookbackWindow, - expectedNotionalValue: expectedNotionalValue, - } -} diff --git a/x/perp/v2/integration/assertion/position.go b/x/perp/v2/integration/assertion/position.go deleted file mode 100644 index f37b939f5..000000000 --- a/x/perp/v2/integration/assertion/position.go +++ /dev/null @@ -1,111 +0,0 @@ -package assertion - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/testutil/action" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -type PositionChecker func(resp types.Position) error - -type positionShouldBeEqual struct { - Account sdk.AccAddress - Pair asset.Pair - - PositionCheckers []PositionChecker -} - -func (p positionShouldBeEqual) IsNotMandatory() {} - -func (p positionShouldBeEqual) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - position, err := app.PerpKeeperV2.GetPosition(ctx, p.Pair, 1, p.Account) - if err != nil { - return ctx, err - } - for _, checker := range p.PositionCheckers { - if err := checker(position); err != nil { - return ctx, err - } - } - - return ctx, nil -} - -func PositionShouldBeEqual( - account sdk.AccAddress, pair asset.Pair, positionCheckers ...PositionChecker, -) action.Action { - return positionShouldBeEqual{ - Account: account, - Pair: pair, - - PositionCheckers: positionCheckers, - } -} - -// PositionCheckers - -// Position_PositionShouldBeEqualTo checks if the position is equal to the expected position -func Position_PositionShouldBeEqualTo(expectedPosition types.Position) PositionChecker { - return func(position types.Position) error { - if err := types.PositionsAreEqual(&expectedPosition, &position); err != nil { - return err - } - - return nil - } -} - -type positionShouldNotExist struct { - Account sdk.AccAddress - Pair asset.Pair - Version uint64 -} - -func (p positionShouldNotExist) IsNotMandatory() {} - -func (p positionShouldNotExist) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - _, err := app.PerpKeeperV2.GetPosition(ctx, p.Pair, p.Version, p.Account) - if err == nil { - return ctx, fmt.Errorf("position should not exist, but it does with pair %s", p.Pair) - } - - return ctx, nil -} - -func PositionShouldNotExist(account sdk.AccAddress, pair asset.Pair, version uint64) action.Action { - return positionShouldNotExist{ - Account: account, - Pair: pair, - Version: version, - } -} - -type positionShouldExist struct { - Account sdk.AccAddress - Pair asset.Pair - Version uint64 -} - -func (p positionShouldExist) IsNotMandatory() {} - -func (p positionShouldExist) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - _, err := app.PerpKeeperV2.GetPosition(ctx, p.Pair, p.Version, p.Account) - if err != nil { - return ctx, fmt.Errorf("position should exist, but it does not with pair %s", p.Pair) - } - - return ctx, nil -} - -func PositionShouldExist(account sdk.AccAddress, pair asset.Pair, version uint64) action.Action { - return positionShouldExist{ - Account: account, - Pair: pair, - Version: version, - } -} diff --git a/x/perp/v2/integration/assertion/twap.go b/x/perp/v2/integration/assertion/twap.go deleted file mode 100644 index 124d04d46..000000000 --- a/x/perp/v2/integration/assertion/twap.go +++ /dev/null @@ -1,49 +0,0 @@ -package assertion - -import ( - "fmt" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/testutil/action" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -type twalShouldBe struct { - pair asset.Pair - twapCalcOpt types.TwapCalcOption - dir types.Direction - assetAmt sdk.Dec - twapLookbackWindow time.Duration - - expectedTwap sdk.Dec -} - -func (c twalShouldBe) IsNotMandatory() {} - -func (c twalShouldBe) Do(app *app.NibiruApp, ctx sdk.Context) (sdk.Context, error) { - twap, err := app.PerpKeeperV2.CalcTwap(ctx, c.pair, c.twapCalcOpt, c.dir, c.assetAmt, c.twapLookbackWindow) - if err != nil { - return ctx, err - } - - if !twap.Equal(c.expectedTwap) { - return ctx, fmt.Errorf("invalid twap, expected %s, received %s", c.expectedTwap, twap) - } - - return ctx, nil -} - -func TwapShouldBe(pair asset.Pair, twapCalcOpt types.TwapCalcOption, dir types.Direction, assetAmt sdk.Dec, twapLookbackWindow time.Duration, expectedTwap sdk.Dec) action.Action { - return twalShouldBe{ - pair: pair, - twapCalcOpt: twapCalcOpt, - dir: dir, - assetAmt: assetAmt, - twapLookbackWindow: twapLookbackWindow, - expectedTwap: expectedTwap, - } -} diff --git a/x/perp/v2/keeper/amm.go b/x/perp/v2/keeper/amm.go deleted file mode 100644 index fe94ad4be..000000000 --- a/x/perp/v2/keeper/amm.go +++ /dev/null @@ -1,127 +0,0 @@ -package keeper - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - "github.com/NibiruChain/collections" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func (k Keeper) handleMarketUpdateCost( - ctx sdk.Context, pair asset.Pair, costAmt sdkmath.Int, -) (costPaid sdk.Coin, err error) { - collateral, err := k.Collateral.Get(ctx) - if err != nil { - return costPaid, err - } - - if costAmt.IsZero() { - costPaid = sdk.NewCoin(collateral, costAmt) - } else if costAmt.IsPositive() { - // Positive cost, send from perp EF to vault - cost := sdk.NewCoins( - sdk.NewCoin(collateral, costAmt), - ) - err = k.BankKeeper.SendCoinsFromModuleToModule( - ctx, - types.PerpFundModuleAccount, - types.VaultModuleAccount, - cost, - ) - if err != nil { - return costPaid, types.ErrNotEnoughFundToPayAction.Wrapf( - "need %s, got %s", - cost.String(), - k.BankKeeper.GetBalance(ctx, k.AccountKeeper.GetModuleAddress(types.PerpFundModuleAccount), collateral).String(), - ) - } else { - costPaid = cost[0] - } - } else if costAmt.IsNegative() { - // Negative cost, send from margin vault to perp ef. - err = k.BankKeeper.SendCoinsFromModuleToModule( - ctx, - types.VaultModuleAccount, - types.PerpFundModuleAccount, - sdk.NewCoins( - sdk.NewCoin(collateral, costAmt.Neg()), - ), - ) - if err != nil { // nolint:staticcheck - costPaid = sdk.NewInt64Coin(collateral, 0) - // Explanation: If there's no money in the vault to pay for the - // operation, the execution should still be successful. It's - // surprising if it's happening on mainnet, but it's not a problem. - // It means there's bad debt in the system, and it's preventing to - // pay for the repeg down. But the bad debt end up being paid up by - // the perp EF anyway. - } else { - costPaid = sdk.NewCoin(collateral, costAmt.Abs()) - } - } - return costPaid, nil -} - -// GetMarket returns the market that is enabled. It is the last version of the market. -func (k Keeper) GetMarket(ctx sdk.Context, pair asset.Pair) (types.Market, error) { - lastVersion, err := k.MarketLastVersion.Get(ctx, pair) - if err != nil { - return types.Market{}, fmt.Errorf("market %s not found", pair) - } - - market, err := k.Markets.Get(ctx, collections.Join(pair, lastVersion.Version)) - if err != nil { - return types.Market{}, fmt.Errorf("market %s not found", pair) - } - - return market, nil -} - -// GetMarketByPairAndVersion this function returns the market by pair and version. It can be enabled or disabled. -func (k Keeper) GetMarketByPairAndVersion(ctx sdk.Context, pair asset.Pair, version uint64) (types.Market, error) { - market, err := k.Markets.Get(ctx, collections.Join(pair, version)) - if err != nil { - return types.Market{}, fmt.Errorf("market with pair %s and version %d not found", pair, version) - } - - return market, nil -} - -// SaveMarket saves the market by pair and version. -func (k Keeper) SaveMarket(ctx sdk.Context, market types.Market) { - k.Markets.Insert(ctx, collections.Join(market.Pair, market.Version), market) -} - -// GetAMM returns the amm with last version. -func (k Keeper) GetAMM(ctx sdk.Context, pair asset.Pair) (types.AMM, error) { - lastVersion, err := k.MarketLastVersion.Get(ctx, pair) - if err != nil { - return types.AMM{}, fmt.Errorf("market %s not found", pair) - } - - amm, err := k.AMMs.Get(ctx, collections.Join(pair, lastVersion.Version)) - if err != nil { - return types.AMM{}, fmt.Errorf("market %s not found", pair) - } - - return amm, nil -} - -// GetAMMByPairAndVersion returns the amm by pair and version. -func (k Keeper) GetAMMByPairAndVersion(ctx sdk.Context, pair asset.Pair, version uint64) (types.AMM, error) { - amm, err := k.AMMs.Get(ctx, collections.Join(pair, version)) - if err != nil { - return types.AMM{}, fmt.Errorf("amm with pair %s and version %d not found", pair, version) - } - - return amm, nil -} - -// SaveAMM saves the amm by pair and version. -func (k Keeper) SaveAMM(ctx sdk.Context, amm types.AMM) { - k.AMMs.Insert(ctx, collections.Join(amm.Pair, amm.Version), amm) -} diff --git a/x/perp/v2/keeper/amm_test.go b/x/perp/v2/keeper/amm_test.go deleted file mode 100644 index 0136778f9..000000000 --- a/x/perp/v2/keeper/amm_test.go +++ /dev/null @@ -1,483 +0,0 @@ -package keeper_test - -import ( - "fmt" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/collections" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - . "github.com/NibiruChain/nibiru/x/common/testutil/action" - . "github.com/NibiruChain/nibiru/x/common/testutil/assertion" - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/assertion" - "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func TestShiftPegMultiplier(t *testing.T) { - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - - tests := TestCases{ - TC("same price multiplier"). - Given( - CreateCustomMarket(pair, WithTotalLong(sdk.NewDec(1000)), WithTotalShort(sdk.NewDec(500))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - ShiftPegMultiplier(pair, sdk.OneDec()), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)), - AMMShouldBeEqual(pair, - AMM_SqrtDepthShouldBeEqual(sdk.NewDec(1e12)), - AMM_BaseReserveShouldBeEqual(sdk.NewDec(1e12)), - AMM_QuoteReserveShouldBeEqual(sdk.NewDec(1e12)), - AMM_PriceMultiplierShouldBeEqual(sdk.OneDec()), - ), - ), - - TC("net bias zero"). - Given( - CreateCustomMarket(pair, - WithTotalLong(sdk.NewDec(1000)), WithTotalShort(sdk.NewDec(1000)), - WithEnabled(true), - ), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - ShiftPegMultiplier(pair, sdk.NewDec(10)), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)), - AMMShouldBeEqual(pair, - AMM_SqrtDepthShouldBeEqual(sdk.NewDec(1e12)), - AMM_BaseReserveShouldBeEqual(sdk.NewDec(1e12)), - AMM_QuoteReserveShouldBeEqual(sdk.NewDec(1e12)), - AMM_PriceMultiplierShouldBeEqual(sdk.NewDec(10)), - ), - ), - - TC("long bias, increase price multiplier"). - Given( - CreateCustomMarket(pair, WithTotalLong(sdk.NewDec(1000)), WithTotalShort(sdk.NewDec(500))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - ShiftPegMultiplier(pair, sdk.NewDec(10)), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1004500)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(995500)), - AMMShouldBeEqual(pair, - AMM_SqrtDepthShouldBeEqual(sdk.NewDec(1e12)), - AMM_BaseReserveShouldBeEqual(sdk.NewDec(1e12)), - AMM_QuoteReserveShouldBeEqual(sdk.NewDec(1e12)), - AMM_PriceMultiplierShouldBeEqual(sdk.NewDec(10)), - ), - ), - - TC("long bias, decrease price multiplier"). - Given( - CreateCustomMarket(pair, WithTotalLong(sdk.NewDec(1000)), WithTotalShort(sdk.NewDec(500))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - ShiftPegMultiplier(pair, sdk.MustNewDecFromStr("0.25")), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(999626)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1000374)), - AMMShouldBeEqual(pair, - AMM_SqrtDepthShouldBeEqual(sdk.NewDec(1e12)), - AMM_BaseReserveShouldBeEqual(sdk.NewDec(1e12)), - AMM_QuoteReserveShouldBeEqual(sdk.NewDec(1e12)), - AMM_PriceMultiplierShouldBeEqual(sdk.MustNewDecFromStr("0.25")), - ), - ), - - TC("short bias, increase price multiplier"). - Given( - CreateCustomMarket(pair, WithTotalLong(sdk.NewDec(500)), WithTotalShort(sdk.NewDec(1000))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - ShiftPegMultiplier(pair, sdk.NewDec(10)), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(995500)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1004500)), - AMMShouldBeEqual(pair, - AMM_SqrtDepthShouldBeEqual(sdk.NewDec(1e12)), - AMM_BaseReserveShouldBeEqual(sdk.NewDec(1e12)), - AMM_QuoteReserveShouldBeEqual(sdk.NewDec(1e12)), - AMM_PriceMultiplierShouldBeEqual(sdk.NewDec(10)), - ), - ), - - TC("short bias, decrease price multiplier"). - Given( - CreateCustomMarket(pair, WithTotalLong(sdk.NewDec(500)), WithTotalShort(sdk.NewDec(1000))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - ShiftPegMultiplier(pair, sdk.MustNewDecFromStr("0.25")), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1000376)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(999624)), - AMMShouldBeEqual(pair, - AMM_SqrtDepthShouldBeEqual(sdk.NewDec(1e12)), - AMM_BaseReserveShouldBeEqual(sdk.NewDec(1e12)), - AMM_QuoteReserveShouldBeEqual(sdk.NewDec(1e12)), - AMM_PriceMultiplierShouldBeEqual(sdk.MustNewDecFromStr("0.25")), - ), - ), - } - - NewTestSuite(t).WithTestCases(tests...).Run() -} - -// TestShiftPegMultiplier_Fail: Test scenarios for the `ShiftPegMultiplier` -// function that should error. -func TestShiftPegMultiplier_Fail(t *testing.T) { - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - app, ctx := testapp.NewNibiruTestAppAndContext() - - account := testutil.AccAddress() - - err := app.PerpKeeperV2.Sudo().CreateMarket( - ctx, - keeper.ArgsCreateMarket{ - Pair: pair, - PriceMultiplier: sdk.NewDec(2), - SqrtDepth: sdk.NewDec(1_000_000), - EnableMarket: true, - }, - ) - app.PerpKeeperV2.ReserveSnapshots.Insert( - ctx, - collections.Join(pair, ctx.BlockTime()), - types.ReserveSnapshot{ - Amm: types.AMM{ - Pair: pair, - BaseReserve: sdk.NewDec(1_000), - QuoteReserve: sdk.NewDec(1_000), - SqrtDepth: sdk.NewDec(1_000_000), - PriceMultiplier: sdk.NewDec(2), - TotalLong: sdk.NewDec(100), - TotalShort: sdk.ZeroDec(), - }, - TimestampMs: ctx.BlockTime().UnixMilli(), - }) - require.NoError(t, err) - - adminAddr := testapp.DefaultSudoRoot() - // Error because of invalid pair - err = app.PerpKeeperV2.Sudo().ShiftPegMultiplier( - ctx, asset.MustNewPair("luna:usdt"), sdk.NewDec(-1), adminAddr) - require.ErrorContains(t, err, "market luna:usdt not found") - - // Error because of invalid price multiplier - err = app.PerpKeeperV2.Sudo().ShiftPegMultiplier(ctx, pair, sdk.NewDec(-1), adminAddr) - require.ErrorIs(t, err, types.ErrAmmNonPositivePegMult) - - // Add market activity - err = app.BankKeeper.MintCoins(ctx, "inflation", sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1020)))) - require.NoError(t, err) - - err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, "inflation", account, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1020)))) - require.NoError(t, err) - - _, err = app.PerpKeeperV2.MarketOrder( - ctx, - pair, - types.Direction_LONG, - account, - sdk.NewInt(1000), - sdk.OneDec(), - sdk.ZeroDec(), - ) - require.NoError(t, err) - - // Error because no money in perp ef fund - err = app.PerpKeeperV2.Sudo().ShiftPegMultiplier(ctx, pair, sdk.NewDec(3), adminAddr) - require.ErrorContains(t, err, types.ErrNotEnoughFundToPayAction.Error()) - - // Works because it goes in the other way - err = app.PerpKeeperV2.Sudo().ShiftPegMultiplier(ctx, pair, sdk.NewDec(1), adminAddr) - require.NoError(t, err) -} - -// TestShiftSwapInvariant_Fail: Test scenarios for the `ShiftSwapInvariant` -// function that should error -func TestShiftSwapInvariant_Fail(t *testing.T) { - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - app, ctx := testapp.NewNibiruTestAppAndContext() - account := testutil.AccAddress() - - err := app.PerpKeeperV2.Sudo().CreateMarket( - ctx, - keeper.ArgsCreateMarket{ - Pair: pair, - PriceMultiplier: sdk.NewDec(2), - SqrtDepth: sdk.NewDec(1_000), - EnableMarket: true, - }, - ) - app.PerpKeeperV2.ReserveSnapshots.Insert( - ctx, - collections.Join(pair, ctx.BlockTime()), - types.ReserveSnapshot{ - Amm: types.AMM{ - Pair: pair, - BaseReserve: sdk.NewDec(1_000), - QuoteReserve: sdk.NewDec(1_000), - SqrtDepth: sdk.NewDec(1_000), - PriceMultiplier: sdk.NewDec(2), - TotalLong: sdk.NewDec(100), - TotalShort: sdk.ZeroDec(), - }, - TimestampMs: ctx.BlockTime().UnixMilli(), - }) - require.NoError(t, err) - - adminAddr := testapp.DefaultSudoRoot() - // Error because of invalid price multiplier - err = app.PerpKeeperV2.Sudo().ShiftSwapInvariant(ctx, asset.MustNewPair("luna:usdt"), sdk.NewInt(-1), adminAddr) - require.ErrorContains(t, err, "market luna:usdt not found") - - // Error because of invalid price multiplier - err = app.PerpKeeperV2.Sudo().ShiftSwapInvariant(ctx, pair, sdk.NewInt(-1), adminAddr) - require.ErrorIs(t, err, types.ErrAmmNonPositiveSwapInvariant) - - // Add market activity - err = app.BankKeeper.MintCoins(ctx, "inflation", sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(102)))) - require.NoError(t, err) - - err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, "inflation", account, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(102)))) - require.NoError(t, err) - - _, err = app.PerpKeeperV2.MarketOrder( - ctx, - pair, - types.Direction_LONG, - account, - sdk.NewInt(100), - sdk.OneDec(), - sdk.ZeroDec(), - ) - require.NoError(t, err) - - // Error because no money in perp ef fund - err = app.PerpKeeperV2.Sudo().ShiftSwapInvariant(ctx, pair, sdk.NewInt(2_000_000), adminAddr) - require.ErrorContains(t, err, types.ErrNotEnoughFundToPayAction.Error()) - - // Fail at validate - err = app.PerpKeeperV2.Sudo().ShiftSwapInvariant(ctx, pair, sdk.NewInt(0), adminAddr) - require.ErrorContains(t, err, types.ErrAmmNonPositiveSwapInvariant.Error()) - - // Works because it goes in the other way - err = app.PerpKeeperV2.Sudo().ShiftSwapInvariant(ctx, pair, sdk.NewInt(500_000), adminAddr) - require.NoError(t, err) -} - -func TestShiftSwapInvariant(t *testing.T) { - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - - tests := TestCases{ - TC("same swap invariant"). - Given( - CreateCustomMarket(pair, - WithTotalLong(sdk.NewDec(1000)), - WithTotalShort(sdk.NewDec(500)), - WithSqrtDepth(sdk.NewDec(1e6)), - ), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - ShiftSwapInvariant(pair, sdk.NewInt(1e12)), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)), - AMMShouldBeEqual(pair, - AMM_SqrtDepthShouldBeEqual(sdk.NewDec(1e6)), - AMM_BaseReserveShouldBeEqual(sdk.NewDec(1e6)), - AMM_QuoteReserveShouldBeEqual(sdk.NewDec(1e6)), - AMM_PriceMultiplierShouldBeEqual(sdk.OneDec()), - ), - ), - - TC("net bias zero"). - Given( - CreateCustomMarket(pair, - WithTotalLong(sdk.NewDec(1000)), - WithTotalShort(sdk.NewDec(1000)), - WithSqrtDepth(sdk.NewDec(1e6)), - ), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - ShiftSwapInvariant(pair, sdk.NewInt(1e18)), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)), - AMMShouldBeEqual(pair, - AMM_SqrtDepthShouldBeEqual(sdk.NewDec(1e9)), - AMM_BaseReserveShouldBeEqual(sdk.NewDec(1e9)), - AMM_QuoteReserveShouldBeEqual(sdk.NewDec(1e9)), - AMM_PriceMultiplierShouldBeEqual(sdk.OneDec()), - ), - ), - - TC("long bias, increase swap invariant"). - Given( - CreateCustomMarket(pair, WithTotalLong(sdk.NewDec(1e5)), WithSqrtDepth(sdk.NewDec(1e6))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - ShiftSwapInvariant(pair, sdk.NewInt(1e14)), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1008101)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(991899)), - AMMShouldBeEqual(pair, - AMM_SqrtDepthShouldBeEqual(sdk.NewDec(1e7)), - AMM_BaseReserveShouldBeEqual(sdk.NewDec(1e7)), - AMM_QuoteReserveShouldBeEqual(sdk.NewDec(1e7)), - AMM_PriceMultiplierShouldBeEqual(sdk.OneDec()), - ), - ), - - TC("long bias, decrease swap invariant"). - Given( - CreateCustomMarket(pair, WithTotalLong(sdk.NewDec(1e2)), WithSqrtDepth(sdk.NewDec(1e6))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - ShiftSwapInvariant(pair, sdk.NewInt(1e6)), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(999991)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1000009)), - AMMShouldBeEqual(pair, - AMM_SqrtDepthShouldBeEqual(sdk.NewDec(1e3)), - AMM_BaseReserveShouldBeEqual(sdk.NewDec(1e3)), - AMM_QuoteReserveShouldBeEqual(sdk.NewDec(1e3)), - AMM_PriceMultiplierShouldBeEqual(sdk.OneDec()), - ), - ), - - TC("short bias, increase swap invariant"). - Given( - CreateCustomMarket(pair, WithTotalShort(sdk.NewDec(1e5)), WithSqrtDepth(sdk.NewDec(1e6))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - ShiftSwapInvariant(pair, sdk.NewInt(1e14)), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1010102)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(989898)), - AMMShouldBeEqual(pair, - AMM_SqrtDepthShouldBeEqual(sdk.NewDec(1e7)), - AMM_BaseReserveShouldBeEqual(sdk.NewDec(1e7)), - AMM_QuoteReserveShouldBeEqual(sdk.NewDec(1e7)), - AMM_PriceMultiplierShouldBeEqual(sdk.OneDec()), - ), - ), - - TC("short bias, decrease swap invariant"). - Given( - CreateCustomMarket(pair, WithTotalShort(sdk.NewDec(1e2)), WithSqrtDepth(sdk.NewDec(1e6))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - ShiftSwapInvariant(pair, sdk.NewInt(1e6)), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(999989)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1000011)), - AMMShouldBeEqual(pair, - AMM_SqrtDepthShouldBeEqual(sdk.NewDec(1e3)), - AMM_BaseReserveShouldBeEqual(sdk.NewDec(1e3)), - AMM_QuoteReserveShouldBeEqual(sdk.NewDec(1e3)), - AMM_PriceMultiplierShouldBeEqual(sdk.OneDec()), - ), - ), - } - - NewTestSuite(t).WithTestCases(tests...).Run() -} - -func TestKeeper_GetMarketByPairAndVersion(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - - err := app.PerpKeeperV2.Sudo().CreateMarket( - ctx, - keeper.ArgsCreateMarket{ - Pair: pair, - PriceMultiplier: sdk.NewDec(2), - SqrtDepth: sdk.NewDec(1_000_000), - EnableMarket: true, - }, - ) - require.NoError(t, err) - - market, err := app.PerpKeeperV2.Sudo().GetMarketByPairAndVersion(ctx, pair, 1) - require.NoError(t, err) - require.Equal(t, market.Version, uint64(1)) - require.Equal(t, market.Pair, pair) - - market, err = app.PerpKeeperV2.Sudo().GetMarketByPairAndVersion(ctx, pair, 2) - require.ErrorContains(t, err, fmt.Sprintf("market with pair %s and version 2 not found", pair.String())) -} - -func TestKeeper_GetAMMByPairAndVersion(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - - err := app.PerpKeeperV2.Sudo().CreateMarket( - ctx, - keeper.ArgsCreateMarket{ - Pair: pair, - PriceMultiplier: sdk.NewDec(2), - SqrtDepth: sdk.NewDec(1_000_000), - EnableMarket: true, - }, - ) - require.NoError(t, err) - - amm, err := app.PerpKeeperV2.Sudo().GetAMMByPairAndVersion(ctx, pair, 1) - require.NoError(t, err) - require.Equal(t, amm.Version, uint64(1)) - require.Equal(t, amm.Pair, pair) - - amm, err = app.PerpKeeperV2.Sudo().GetAMMByPairAndVersion(ctx, pair, 2) - require.ErrorContains(t, err, fmt.Sprintf("amm with pair %s and version 2 not found", pair.String())) -} diff --git a/x/perp/v2/keeper/calc.go b/x/perp/v2/keeper/calc.go deleted file mode 100644 index d09e19f97..000000000 --- a/x/perp/v2/keeper/calc.go +++ /dev/null @@ -1,98 +0,0 @@ -package keeper - -import ( - "fmt" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// PositionNotionalSpot returns the position's notional value based on the spot price. -func PositionNotionalSpot(amm types.AMM, position types.Position) (positionNotional sdk.Dec, err error) { - // we want to know the price if the user closes their position - // e.g. if the user has positive size, we want to short - if position.Size_.IsNil() { - return sdk.Dec{}, fmt.Errorf("input base amt is nil") - } - - var dir types.Direction - if position.Size_.IsPositive() { - dir = types.Direction_SHORT - } else { - dir = types.Direction_LONG - } - - quoteReserve, err := amm.GetQuoteReserveAmt(position.Size_.Abs(), dir) - if err != nil { - return sdk.Dec{}, err - } - return amm.QuoteReserveToAsset(quoteReserve), nil -} - -// PositionNotionalTWAP returns the position's notional value based on the TWAP price. -func (k Keeper) PositionNotionalTWAP(ctx sdk.Context, - position types.Position, - twapLookbackWindow time.Duration, -) (positionNotional sdk.Dec, err error) { - // we want to know the price if the user closes their position - // e.g. if the user has positive size, we want to short - var dir types.Direction - if position.Size_.IsPositive() { - dir = types.Direction_SHORT - } else { - dir = types.Direction_LONG - } - - return k.CalcTwap( - ctx, - position.Pair, - types.TwapCalcOption_BASE_ASSET_SWAP, - dir, - position.Size_.Abs(), - /*lookbackInterval=*/ twapLookbackWindow, - ) -} - -// UnrealizedPnl calculates the unrealized profits and losses (PnL) of a position. -func UnrealizedPnl(position types.Position, positionNotional sdk.Dec) (unrealizedPnlSigned sdk.Dec) { - if position.Size_.IsPositive() { - // LONG - return positionNotional.Sub(position.OpenNotional) - } else { - // SHORT - return position.OpenNotional.Sub(positionNotional) - } -} - -// MarginRatio Given a position and it's notional value, returns the margin ratio. -func MarginRatio( - position types.Position, - positionNotional sdk.Dec, - marketLatestCumulativePremiumFraction sdk.Dec, -) sdk.Dec { - if position.Size_.IsZero() || positionNotional.IsZero() { - return sdk.ZeroDec() - } - - unrealizedPnl := UnrealizedPnl(position, positionNotional) - fundingPayment := FundingPayment(position, marketLatestCumulativePremiumFraction) - remainingMargin := position.Margin.Add(unrealizedPnl).Sub(fundingPayment) - - return remainingMargin.Quo(positionNotional) -} - -// FundingPayment calculates the funding payment of a position. -// -// args: -// - position: the position to calculate funding payment for -// - marketLatestCumulativePremiumFraction: the latest cumulative premium fraction of the market -// -// returns: -// - fundingPayment: the funding payment of the position, signed -func FundingPayment(position types.Position, marketLatestCumulativePremiumFraction sdk.Dec) sdk.Dec { - return marketLatestCumulativePremiumFraction. - Sub(position.LatestCumulativePremiumFraction). - Mul(position.Size_) -} diff --git a/x/perp/v2/keeper/calc_test.go b/x/perp/v2/keeper/calc_test.go deleted file mode 100644 index dade53d60..000000000 --- a/x/perp/v2/keeper/calc_test.go +++ /dev/null @@ -1,395 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - "github.com/NibiruChain/nibiru/x/common/testutil/mock" - "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" - - . "github.com/NibiruChain/nibiru/x/common/testutil/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/assertion" -) - -func TestPositionNotionalSpot(t *testing.T) { - tests := []struct { - name string - amm *types.AMM - position types.Position - expectedNotional sdk.Dec - }{ - { - name: "long position", - amm: mock.TestAMM(sdk.NewDec(1_000), sdk.NewDec(2)), - position: types.Position{ - Size_: sdk.NewDec(10), - }, - expectedNotional: sdk.MustNewDecFromStr("19.801980198019801980"), - }, - { - name: "short position", - amm: mock.TestAMM(sdk.NewDec(1_000), sdk.NewDec(2)), - position: types.Position{ - Size_: sdk.NewDec(-10), - }, - expectedNotional: sdk.MustNewDecFromStr("20.202020202020202020"), - }, - { - name: "zero position", - amm: mock.TestAMM(sdk.NewDec(1_000), sdk.NewDec(2)), - position: types.Position{ - Size_: sdk.ZeroDec(), - }, - expectedNotional: sdk.ZeroDec(), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - notional, err := keeper.PositionNotionalSpot(*tc.amm, tc.position) - require.NoError(t, err) - assert.EqualValues(t, tc.expectedNotional, notional) - }) - } -} - -func TestPositionNotionalTWAP(t *testing.T) { - alice := testutil.AccAddress() - pair := asset.Registry.Pair(denoms.BTC, denoms.USDC) - startTime := time.Now() - - tc := TestCases{ - TC("long position"). - Given( - SetBlockTime(startTime), - SetBlockNumber(1), - CreateCustomMarket(pair), - InsertPosition(WithSize(sdk.NewDec(10)), WithTrader(alice)), - InsertReserveSnapshot(pair, startTime, WithPriceMultiplier(sdk.NewDec(9))), - InsertReserveSnapshot(pair, startTime.Add(10*time.Second), WithPriceMultiplier(sdk.MustNewDecFromStr("8.5"))), - InsertReserveSnapshot(pair, startTime.Add(20*time.Second), WithPriceMultiplier(sdk.MustNewDecFromStr("9.5"))), - ). - When( - MoveToNextBlockWithDuration(30 * time.Second), - ). - Then( - PositionNotionalTWAPShouldBeEqualTo(pair, alice, 30*time.Second, sdk.MustNewDecFromStr("89.999999999100000000")), - ), - - TC("short position"). - Given( - SetBlockTime(startTime), - SetBlockNumber(1), - CreateCustomMarket(pair), - InsertPosition(WithSize(sdk.NewDec(-10)), WithTrader(alice)), - InsertReserveSnapshot(pair, startTime, WithPriceMultiplier(sdk.NewDec(9))), - InsertReserveSnapshot(pair, startTime.Add(10*time.Second), WithPriceMultiplier(sdk.MustNewDecFromStr("8.5"))), - InsertReserveSnapshot(pair, startTime.Add(20*time.Second), WithPriceMultiplier(sdk.MustNewDecFromStr("9.5"))), - ). - When( - MoveToNextBlockWithDuration(30 * time.Second), - ). - Then( - PositionNotionalTWAPShouldBeEqualTo(pair, alice, 30*time.Second, sdk.MustNewDecFromStr("90.000000000900000000")), - ), - - TC("zero position"). - Given( - SetBlockTime(startTime), - SetBlockNumber(1), - CreateCustomMarket(pair), - InsertPosition(WithSize(sdk.ZeroDec()), WithTrader(alice)), - InsertReserveSnapshot(pair, startTime, WithPriceMultiplier(sdk.NewDec(9))), - InsertReserveSnapshot(pair, startTime.Add(10*time.Second), WithPriceMultiplier(sdk.MustNewDecFromStr("8.5"))), - InsertReserveSnapshot(pair, startTime.Add(20*time.Second), WithPriceMultiplier(sdk.MustNewDecFromStr("9.5"))), - ). - When( - MoveToNextBlockWithDuration(30 * time.Second), - ). - Then( - PositionNotionalTWAPShouldBeEqualTo(pair, alice, 30*time.Second, sdk.ZeroDec()), - ), - - TC("single snapshot"). - Given( - SetBlockTime(startTime), - SetBlockNumber(1), - CreateCustomMarket(pair), - ). - When( - InsertPosition(WithSize(sdk.NewDec(100)), WithTrader(alice)), - InsertReserveSnapshot(pair, startTime, WithPriceMultiplier(sdk.NewDec(9))), - ). - Then( - PositionNotionalTWAPShouldBeEqualTo(pair, alice, 30*time.Second, sdk.MustNewDecFromStr("899.999999910000000009")), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} - -func TestUnrealizedPnl(t *testing.T) { - tests := []struct { - name string - position types.Position - positionNotional sdk.Dec - expectedUnrealizedPnl sdk.Dec - }{ - { - name: "long position positive pnl", - position: types.Position{ - Size_: sdk.NewDec(10), - OpenNotional: sdk.NewDec(10), - }, - positionNotional: sdk.NewDec(15), - expectedUnrealizedPnl: sdk.NewDec(5), - }, - { - name: "long position negative pnl", - position: types.Position{ - Size_: sdk.NewDec(10), - OpenNotional: sdk.NewDec(10), - }, - positionNotional: sdk.NewDec(5), - expectedUnrealizedPnl: sdk.NewDec(-5), - }, - { - name: "short position positive pnl", - position: types.Position{ - Size_: sdk.NewDec(-10), - OpenNotional: sdk.NewDec(10), - }, - positionNotional: sdk.NewDec(5), - expectedUnrealizedPnl: sdk.NewDec(5), - }, - { - name: "short position negative pnl", - position: types.Position{ - Size_: sdk.NewDec(-10), - OpenNotional: sdk.NewDec(10), - }, - positionNotional: sdk.NewDec(15), - expectedUnrealizedPnl: sdk.NewDec(-5), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - assert.EqualValues(t, tc.expectedUnrealizedPnl, keeper.UnrealizedPnl(tc.position, tc.positionNotional)) - }) - } -} - -func TestMarginRatio(t *testing.T) { - tests := []struct { - name string - position types.Position - positionNotional sdk.Dec - latestCPF sdk.Dec - expectedMarginRatio sdk.Dec - }{ - { - name: "long position, no change", - position: types.Position{ - Margin: sdk.NewDec(100), - Size_: sdk.OneDec(), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - OpenNotional: sdk.NewDec(100), - }, - positionNotional: sdk.NewDec(100), - latestCPF: sdk.ZeroDec(), - expectedMarginRatio: sdk.OneDec(), - }, - { - name: "long position, positive PnL, positive cumulative premium fraction", - position: types.Position{ - Margin: sdk.NewDec(100), - Size_: sdk.OneDec(), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - OpenNotional: sdk.NewDec(100), - }, - positionNotional: sdk.NewDec(110), - latestCPF: sdk.NewDec(2), - expectedMarginRatio: sdk.MustNewDecFromStr("0.981818181818181818"), // 108 / 110 - }, - { - name: "long position, positive PnL, negative cumulative premium fraction", - position: types.Position{ - Margin: sdk.NewDec(100), - Size_: sdk.OneDec(), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - OpenNotional: sdk.NewDec(100), - }, - positionNotional: sdk.NewDec(110), - latestCPF: sdk.NewDec(-2), - expectedMarginRatio: sdk.MustNewDecFromStr("1.018181818181818182"), // 112 / 110 - }, - { - name: "long position, negative PnL, positive cumulative premium fraction", - position: types.Position{ - Margin: sdk.NewDec(100), - Size_: sdk.OneDec(), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - OpenNotional: sdk.NewDec(100), - }, - positionNotional: sdk.NewDec(90), - latestCPF: sdk.NewDec(2), - expectedMarginRatio: sdk.MustNewDecFromStr("0.977777777777777778"), // 88 / 90 - }, - { - name: "long position, negative PnL, negative cumulative premium fraction", - position: types.Position{ - Margin: sdk.NewDec(100), - Size_: sdk.OneDec(), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - OpenNotional: sdk.NewDec(100), - }, - positionNotional: sdk.NewDec(90), - latestCPF: sdk.NewDec(-2), - expectedMarginRatio: sdk.MustNewDecFromStr("1.022222222222222222"), // 92 / 90 - }, - { - name: "short position, no change", - position: types.Position{ - Margin: sdk.NewDec(100), - Size_: sdk.NewDec(-1), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - OpenNotional: sdk.NewDec(100), - }, - positionNotional: sdk.NewDec(100), - latestCPF: sdk.ZeroDec(), - expectedMarginRatio: sdk.OneDec(), - }, - { - name: "short position, positive PnL, positive cumulative premium fraction", - position: types.Position{ - Margin: sdk.NewDec(100), - Size_: sdk.NewDec(-1), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - OpenNotional: sdk.NewDec(100), - }, - positionNotional: sdk.NewDec(90), - latestCPF: sdk.NewDec(2), - expectedMarginRatio: sdk.MustNewDecFromStr("1.244444444444444444"), // 112 / 90 - }, - { - name: "short position, positive PnL, negative cumulative premium fraction", - position: types.Position{ - Margin: sdk.NewDec(100), - Size_: sdk.NewDec(-1), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - OpenNotional: sdk.NewDec(100), - }, - positionNotional: sdk.NewDec(90), - latestCPF: sdk.NewDec(-2), - expectedMarginRatio: sdk.MustNewDecFromStr("1.2"), // 108 / 90 - }, - { - name: "short position, negative PnL, positive cumulative premium fraction", - position: types.Position{ - Margin: sdk.NewDec(100), - Size_: sdk.NewDec(-1), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - OpenNotional: sdk.NewDec(100), - }, - positionNotional: sdk.NewDec(110), - latestCPF: sdk.NewDec(2), - expectedMarginRatio: sdk.MustNewDecFromStr("0.836363636363636364"), // 92 / 110 - }, - { - name: "short position, negative PnL, negative cumulative premium fraction", - position: types.Position{ - Margin: sdk.NewDec(100), - Size_: sdk.NewDec(-1), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - OpenNotional: sdk.NewDec(100), - }, - positionNotional: sdk.NewDec(110), - latestCPF: sdk.NewDec(-2), - expectedMarginRatio: sdk.MustNewDecFromStr("0.8"), // 88 / 110 - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - assert.EqualValues(t, tc.expectedMarginRatio, keeper.MarginRatio(tc.position, tc.positionNotional, tc.latestCPF)) - }) - } -} - -func TestFundingPayment(t *testing.T) { - tests := []struct { - name string - position types.Position - marketLatestCPF sdk.Dec - expectedFundingPayment sdk.Dec - }{ - { - name: "long position, positive cumulative premium fraction", - position: types.Position{ - Size_: sdk.NewDec(10), - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.001"), - }, - marketLatestCPF: sdk.MustNewDecFromStr("0.002"), - expectedFundingPayment: sdk.MustNewDecFromStr("0.010"), - }, - { - name: "long position, negative cumulative premium fraction", - position: types.Position{ - Size_: sdk.NewDec(10), - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.002"), - }, - marketLatestCPF: sdk.MustNewDecFromStr("0.001"), - expectedFundingPayment: sdk.MustNewDecFromStr("-0.010"), - }, - { - name: "short position, positive cumulative premium fraction", - position: types.Position{ - Size_: sdk.NewDec(-10), - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.002"), - }, - marketLatestCPF: sdk.MustNewDecFromStr("0.001"), - expectedFundingPayment: sdk.MustNewDecFromStr("0.010"), - }, - { - name: "short position, negative cumulative premium fraction", - position: types.Position{ - Size_: sdk.NewDec(-10), - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.001"), - }, - marketLatestCPF: sdk.MustNewDecFromStr("0.002"), - expectedFundingPayment: sdk.MustNewDecFromStr("-0.010"), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - fundingPayment := keeper.FundingPayment(tc.position, tc.marketLatestCPF) - assert.EqualValues(t, tc.expectedFundingPayment, fundingPayment) - }) - } -} - -func TestMarginRatioFail(t *testing.T) { - val := keeper.MarginRatio(types.Position{Size_: sdk.ZeroDec()}, sdk.ZeroDec(), sdk.ZeroDec()) - require.Equal(t, sdk.ZeroDec(), val) - - _, err := keeper.PositionNotionalSpot(types.AMM{PriceMultiplier: sdk.OneDec()}, types.Position{Size_: sdk.ZeroDec()}) - require.NoError(t, err) - - _, err = keeper.PositionNotionalSpot(types.AMM{}, types.Position{}) - require.ErrorContains(t, err, "input base amt is nil") -} diff --git a/x/perp/v2/keeper/clearing_house.go b/x/perp/v2/keeper/clearing_house.go deleted file mode 100644 index 1dedae8b0..000000000 --- a/x/perp/v2/keeper/clearing_house.go +++ /dev/null @@ -1,941 +0,0 @@ -package keeper - -import ( - "errors" - "fmt" - - sdkmath "cosmossdk.io/math" - - "github.com/NibiruChain/collections" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// MarketOrder opens a position on the selected pair. -// -// args: -// - ctx: cosmos-sdk context -// - pair: pair to open position on -// - dir: direction the user is taking -// - traderAddr: address of the trader -// - quoteAssetAmt: amount of quote asset to open position with -// - leverage: leverage to open position with -// - baseAmtLimit: minimum base asset amount to open position with -// -// ret: -// - positionResp: contains the result of the open position and the new position -// - err: error -func (k Keeper) MarketOrder( - ctx sdk.Context, - pair asset.Pair, - dir types.Direction, - traderAddr sdk.AccAddress, - quoteAssetAmt sdkmath.Int, - leverage sdk.Dec, - baseAmtLimit sdk.Dec, -) (positionResp *types.PositionResp, err error) { - market, err := k.GetMarket(ctx, pair) - if err != nil { - return nil, types.ErrPairNotFound.Wrapf("pair %s not found", pair) - } - - if !market.Enabled { - return nil, types.ErrMarketNotEnabled.Wrapf("market pair %s not enabled", pair) - } - - amm, err := k.GetAMM(ctx, pair) - if err != nil { - return nil, types.ErrPairNotFound.Wrapf("pair %s not found", pair) - } - - err = checkMarketOrderRequirements(market, quoteAssetAmt, leverage) - if err != nil { - return nil, err - } - - position, err := k.GetPosition(ctx, pair, market.Version, traderAddr) - isNewPosition := errors.Is(err, types.ErrPositionNotFound) - if isNewPosition { - position = types.ZeroPosition(ctx, pair, traderAddr) - } - - sameSideLong := position.Size_.IsPositive() && dir == types.Direction_LONG - sameSideShort := position.Size_.IsNegative() && dir == types.Direction_SHORT - - openNotionalPreFees := leverage.MulInt(quoteAssetAmt) - transferredFee, err := k.transferFee(ctx, market.Pair, traderAddr, openNotionalPreFees, - market.ExchangeFeeRatio, market.EcosystemFundFeeRatio, - ) - if err != nil { - return nil, err - } - quoteAssetAmtMinusFees := quoteAssetAmt.Sub(transferredFee) - - var updatedAMM *types.AMM - openSideMatchesPosition := sameSideLong || sameSideShort - if isNewPosition || openSideMatchesPosition { - updatedAMM, positionResp, err = k.increasePosition( - ctx, - market, - amm, - position, - dir, - /* openNotional */ leverage.MulInt(quoteAssetAmtMinusFees), - /* minPositionSize */ baseAmtLimit, - /* leverage */ leverage) - if err != nil { - return nil, err - } - } else { - quoteAssetAmtToDec := sdk.NewDecFromInt(quoteAssetAmtMinusFees) - updatedAMM, positionResp, err = k.openReversePosition( - ctx, - market, - amm, - position, - /* quoteAssetAmount */ quoteAssetAmtToDec, - /* leverage */ leverage, - /* baseAmtLimit */ baseAmtLimit, - ) - if err != nil { - return nil, err - } - } - - // check bad debt - if !positionResp.Position.Size_.IsZero() { - if positionResp.BadDebt.IsPositive() { - return nil, types.ErrBadDebt.Wrapf("position has bad debt %s", positionResp.BadDebt) - } - - err = k.checkMarginRatio(ctx, market, *updatedAMM, positionResp.Position) - if err != nil { - return nil, err - } - } - - if err = k.afterPositionUpdate( - ctx, market, traderAddr, *positionResp, types.ChangeReason_MarketOrder, transferredFee, position, - ); err != nil { - return nil, err - } - - return positionResp, nil -} - -// increases a position by increasedNotional amount in margin units. -// Calculates the amount of margin required given the leverage parameter. -// Recalculates the remaining margin after applying a funding payment. -// Does not realize PnL. -// -// For example, a long position with position notional value of 150 NUSD and unrealized PnL of 50 NUSD -// could increase their position by 30 NUSD using 10x leverage. -// This would be: -// - 3 NUSD as margin requirement -// - new open notional value of 130 NUSD -// - new position notional value of 150 NUSD -// - unrealized PnL remains unchanged at 50 NUSD -// - remaining margin is calculated by applying the funding payment -// -// args: -// - ctx: sdk.Context -// - market: the perp market -// - amm: the amm reserves -// - currentPosition: the current position -// - dir: the direction the user is taking -// - increasedNotional: the amount of notional the user is increasing by, must be positive -// - baseAmtLimit: the user-specified limit on the base reserves -// - leverage: the leverage the user is taking -// -// returns: -// - updatedAMM: the updated AMM reserves -// - positionResp: updated position information -// - err: error -func (k Keeper) increasePosition( - ctx sdk.Context, - market types.Market, - amm types.AMM, - currentPosition types.Position, - dir types.Direction, - increasedNotional sdk.Dec, // unsigned - baseAmtLimit sdk.Dec, // unsigned - leverage sdk.Dec, // unsigned -) (updatedAMM *types.AMM, positionResp *types.PositionResp, err error) { - positionNotional, err := PositionNotionalSpot(amm, currentPosition) - if err != nil { - return nil, nil, err - } - - positionResp = &types.PositionResp{ - RealizedPnl: sdk.ZeroDec(), - MarginToVault: increasedNotional.Quo(leverage), // unsigned - FundingPayment: FundingPayment(currentPosition, market.LatestCumulativePremiumFraction), // signed - ExchangedNotionalValue: increasedNotional, // unsigned - PositionNotional: positionNotional.Add(increasedNotional), // unsigned - } - - remainingMargin := currentPosition.Margin.Add(positionResp.MarginToVault).Sub(positionResp.FundingPayment) // signed - - updatedAMM, baseAssetDeltaAbs, err := k.SwapQuoteAsset( - ctx, - amm, - dir, - increasedNotional, - baseAmtLimit, - ) - if err != nil { - return nil, nil, err - } - - if dir == types.Direction_LONG { - positionResp.ExchangedPositionSize = baseAssetDeltaAbs - } else if dir == types.Direction_SHORT { - positionResp.ExchangedPositionSize = baseAssetDeltaAbs.Neg() - } - - positionResp.BadDebt = sdk.MinDec(sdk.ZeroDec(), remainingMargin).Abs() - positionResp.Position = types.Position{ - TraderAddress: currentPosition.TraderAddress, - Pair: currentPosition.Pair, - Size_: currentPosition.Size_.Add(positionResp.ExchangedPositionSize), - Margin: sdk.MaxDec(sdk.ZeroDec(), remainingMargin).Abs(), - OpenNotional: currentPosition.OpenNotional.Add(increasedNotional), - LatestCumulativePremiumFraction: market.LatestCumulativePremiumFraction, - LastUpdatedBlockNumber: ctx.BlockHeight(), - } - positionResp.UnrealizedPnlAfter = UnrealizedPnl(positionResp.Position, positionResp.PositionNotional) - - return updatedAMM, positionResp, nil -} - -// decreases a position by decreasedNotional amount in margin units. -// Calculates the amount of margin required given the leverage parameter. -// Recalculates the remaining margin after applying a funding payment. -// -// args: -// - ctx: sdk.Context -// - market: the perp market -// - amm: the amm reserves -// - currentPosition: the current position -// - decreasedNotional: the amount of notional the user is decreasing by -// - baseAmtLimit: the user-specified limit on the base reserves -// -// returns: -// - updatedAMM: the updated AMM reserves -// - positionResp: updated position information -// - err: error -func (k Keeper) openReversePosition( - ctx sdk.Context, - market types.Market, - amm types.AMM, - currentPosition types.Position, - quoteAssetAmount sdk.Dec, - leverage sdk.Dec, - baseAmtLimit sdk.Dec, -) (updatedAMM *types.AMM, positionResp *types.PositionResp, err error) { - notionalToDecreaseBy := leverage.Mul(quoteAssetAmount) - currentPositionNotional, err := PositionNotionalSpot(amm, currentPosition) - if err != nil { - return nil, nil, err - } - - if currentPositionNotional.GT(notionalToDecreaseBy) { - // position reduction - return k.decreasePosition( - ctx, - market, - amm, - currentPosition, - notionalToDecreaseBy, - baseAmtLimit, - ) - } else { - // close and reverse - return k.closeAndOpenReversePosition( - ctx, - market, - amm, - currentPosition, - quoteAssetAmount, - leverage, - baseAmtLimit, - ) - } -} - -// Decreases a position by decreasedNotional amount in margin units. -// Realizes PnL and calculates remaining margin after applying a funding payment. -// -// For example, a long position with position notional value of 150 NUSD and PnL of 50 NUSD -// could decrease their position by 30 NUSD. This would realize a PnL of 10 NUSD (50NUSD * 30/150) -// and update their margin (old margin + realized PnL - funding payment). -// Their new position notional value would be 120 NUSD and their position size would -// shrink by 20%. -// -// args: -// - ctx: cosmos-sdk context -// - market: the perp market -// - amm: the amm reserves -// - currentPosition: the current position -// - decreasedNotional: the amount of notional the user is decreasing by -// - baseAmtLimit: the user-specified limit on the base reserves -// -// returns: -// - updatedAMM: the updated AMM reserves -// - positionResp: updated position information -// - err: error -func (k Keeper) decreasePosition( - ctx sdk.Context, - market types.Market, - amm types.AMM, - currentPosition types.Position, - decreasedNotional sdk.Dec, - baseAmtLimit sdk.Dec, -) (updatedAMM *types.AMM, positionResp *types.PositionResp, err error) { - if currentPosition.Size_.IsZero() { - return nil, nil, fmt.Errorf("current position size is zero, nothing to decrease") - } - - trader, err := sdk.AccAddressFromBech32(currentPosition.TraderAddress) - if err != nil { - return nil, nil, err - } - - var dir types.Direction - if currentPosition.Size_.IsPositive() { - dir = types.Direction_SHORT - } else { - dir = types.Direction_LONG - } - - positionResp = &types.PositionResp{ - MarginToVault: sdk.ZeroDec(), - } - - currentPositionNotional, err := PositionNotionalSpot(amm, currentPosition) - if err != nil { - return nil, nil, err - } - currentUnrealizedPnl := UnrealizedPnl(currentPosition, currentPositionNotional) - - updatedAMM, baseAssetDeltaAbs, err := k.SwapQuoteAsset( - ctx, - amm, - dir, - decreasedNotional, - baseAmtLimit, - ) - if err != nil { - return nil, nil, err - } - - if dir == types.Direction_LONG { - positionResp.ExchangedPositionSize = baseAssetDeltaAbs - } else { - positionResp.ExchangedPositionSize = baseAssetDeltaAbs.Neg() - } - - positionResp.RealizedPnl = currentUnrealizedPnl.Mul( - positionResp.ExchangedPositionSize.Abs(). - Quo(currentPosition.Size_.Abs()), - ) - - fundingPayment := FundingPayment(currentPosition, market.LatestCumulativePremiumFraction) - remainingMargin := currentPosition.Margin.Add(positionResp.RealizedPnl).Sub(fundingPayment) - - positionResp.BadDebt = sdk.MinDec(sdk.ZeroDec(), remainingMargin).Abs() - positionResp.FundingPayment = fundingPayment - positionResp.UnrealizedPnlAfter = currentUnrealizedPnl.Sub(positionResp.RealizedPnl) - positionResp.ExchangedNotionalValue = decreasedNotional - positionResp.PositionNotional = currentPositionNotional.Sub(decreasedNotional) - - // calculate openNotional (it's different depends on long or short side) - // long: unrealizedPnl = positionNotional - openNotional => openNotional = positionNotional - unrealizedPnl - // short: unrealizedPnl = openNotional - positionNotional => openNotional = positionNotional + unrealizedPnl - // positionNotional = oldPositionNotional - notionalValueToDecrease - var remainOpenNotional sdk.Dec - if currentPosition.Size_.IsPositive() { - remainOpenNotional = positionResp.PositionNotional.Sub(positionResp.UnrealizedPnlAfter) - } else { - remainOpenNotional = positionResp.PositionNotional.Add(positionResp.UnrealizedPnlAfter) - } - - if remainOpenNotional.IsNegative() { - return nil, nil, fmt.Errorf("value of open notional < 0") - } - - positionResp.Position = types.Position{ - TraderAddress: currentPosition.TraderAddress, - Pair: currentPosition.Pair, - Size_: currentPosition.Size_.Add(positionResp.ExchangedPositionSize), - Margin: sdk.MaxDec(sdk.ZeroDec(), remainingMargin).Abs(), - OpenNotional: remainOpenNotional, - LatestCumulativePremiumFraction: market.LatestCumulativePremiumFraction, - LastUpdatedBlockNumber: ctx.BlockHeight(), - } - - if positionResp.Position.Size_.IsZero() { - err := k.Positions.Delete(ctx, collections.Join(collections.Join(currentPosition.Pair, amm.Version), trader)) - if err != nil { - return nil, nil, err - } - } - - return updatedAMM, positionResp, nil -} - -// Closes a position and realizes PnL and funding payments. -// Opens a position in the opposite direction if there is notional value remaining. -// Errors out if the provided notional value is not greater than the existing position's notional value. -// Errors out if there is bad debt. -// -// args: -// - ctx: cosmos-sdk context -// - market: the perp market -// - amm: the amm reserves -// - existingPosition: the existing position -// - quoteAssetAmount: the amount of quote asset to close -// - leverage: the leverage to open the new position with -// - baseAmtLimit: the user-specified limit on the base reserves -// -// returns: -// - updatedAMM: the updated AMM reserves -// - positionResp: updated position information -// - err: error -func (k Keeper) closeAndOpenReversePosition( - ctx sdk.Context, - market types.Market, - amm types.AMM, - existingPosition types.Position, - quoteAssetAmount sdk.Dec, - leverage sdk.Dec, - baseAmtLimit sdk.Dec, -) (updatedAMM *types.AMM, positionResp *types.PositionResp, err error) { - trader, err := sdk.AccAddressFromBech32(existingPosition.TraderAddress) - if err != nil { - return nil, nil, err - } - - updatedAMM, closePositionResp, err := k.closePositionEntirely( - ctx, - market, - amm, - existingPosition, - /* quoteAssetAmountLimit */ sdk.ZeroDec(), - ) - if err != nil { - return nil, nil, err - } - - if closePositionResp.BadDebt.IsPositive() { - // if there's already bad debt, then we don't allow the user to continue and just early return - return updatedAMM, closePositionResp, nil - } - - reverseNotionalValue := leverage.Mul(quoteAssetAmount) - remainingReverseNotionalValue := reverseNotionalValue.Sub( - closePositionResp.ExchangedNotionalValue) - if remainingReverseNotionalValue.IsNegative() { - // should never happen as openReversePosition should have checked this - return nil, nil, fmt.Errorf( - "provided quote asset amount and leverage not large enough to close position. need %s but got %s", - closePositionResp.ExchangedNotionalValue, reverseNotionalValue) - } - - var dir types.Direction - // flipped since we are going against the current position - if existingPosition.Size_.IsPositive() { - dir = types.Direction_SHORT - } else { - dir = types.Direction_LONG - } - - // check if it's worth continuing with the increase position - quoteReserveAmt := updatedAMM.QuoteAssetToReserve(remainingReverseNotionalValue) - possibleNextSize, err := updatedAMM.GetBaseReserveAmt(quoteReserveAmt, dir) - if err != nil { - return nil, nil, err - } - if possibleNextSize.IsZero() { - // nothing to do, early return - return updatedAMM, closePositionResp, nil - } - - if baseAmtLimit.IsPositive() { - baseAmtLimit = baseAmtLimit.Sub(closePositionResp.ExchangedPositionSize.Abs()) - } - if baseAmtLimit.IsNegative() { - return nil, nil, fmt.Errorf( - "position size changed by greater than the specified base limit: %s", - baseAmtLimit, - ) - } - - newPosition := types.ZeroPosition( - ctx, - existingPosition.Pair, - trader, - ) - updatedAMM, increasePositionResp, err := k.increasePosition( - ctx, - market, - *updatedAMM, - newPosition, - dir, - remainingReverseNotionalValue, - baseAmtLimit, - leverage, - ) - if err != nil { - return nil, nil, err - } - - positionResp = &types.PositionResp{ - Position: increasePositionResp.Position, - PositionNotional: increasePositionResp.PositionNotional, - ExchangedNotionalValue: closePositionResp.ExchangedNotionalValue.Add(increasePositionResp.ExchangedNotionalValue), - BadDebt: closePositionResp.BadDebt.Add(increasePositionResp.BadDebt), - ExchangedPositionSize: closePositionResp.ExchangedPositionSize.Add(increasePositionResp.ExchangedPositionSize), - FundingPayment: closePositionResp.FundingPayment.Add(increasePositionResp.FundingPayment), - RealizedPnl: closePositionResp.RealizedPnl.Add(increasePositionResp.RealizedPnl), - MarginToVault: closePositionResp.MarginToVault.Add(increasePositionResp.MarginToVault), - UnrealizedPnlAfter: sdk.ZeroDec(), - } - - return updatedAMM, positionResp, nil -} - -// checkMarketOrderRequirements checks the minimum requirements to open a position. -// -// - Checks that quote asset is not zero. -// - Checks that leverage is not zero. -// - Checks that leverage is below requirement. -// -// args: -// - market: the market where the position will be opened -// - quoteAssetAmt: the amount of quote asset -// - leverage: the amount of leverage to take, as sdk.Dec -// -// returns: -// - error: if any of the requirements is not met -func checkMarketOrderRequirements(market types.Market, quoteAssetAmt sdkmath.Int, userLeverage sdk.Dec) error { - if !quoteAssetAmt.IsPositive() { - return types.ErrInputQuoteAmtNegative - } - - if !userLeverage.IsPositive() { - return types.ErrUserLeverageNegative - } - - if userLeverage.GT(market.MaxLeverage) { - return types.ErrLeverageIsTooHigh - } - - return nil -} - -// afterPositionUpdate is called when a position has been updated. -func (k Keeper) afterPositionUpdate( - ctx sdk.Context, - market types.Market, - traderAddr sdk.AccAddress, - positionResp types.PositionResp, - changeType types.ChangeReason, - transferredFee sdkmath.Int, - existingPosition types.Position, -) (err error) { - // transfer trader <=> vault - marginToVault := positionResp.MarginToVault.RoundInt() - - collateral, err := k.Collateral.Get(ctx) - if errors.Is(err, collections.ErrNotFound) { - return types.ErrCollateralDenomNotSet - } - - switch { - case marginToVault.IsPositive(): - coinToSend := sdk.NewCoin(collateral, marginToVault) - if err = k.BankKeeper.SendCoinsFromAccountToModule( - ctx, traderAddr, types.VaultModuleAccount, sdk.NewCoins(coinToSend)); err != nil { - return err - } - case marginToVault.IsNegative(): - if err = k.WithdrawFromVault(ctx, market, traderAddr, marginToVault.Abs()); err != nil { - return err - } - } - - if !positionResp.Position.Size_.IsZero() { - k.SavePosition(ctx, market.Pair, market.Version, traderAddr, positionResp.Position) - } - - // calculate positionNotional (it's different depends on long or short side) - // long: unrealizedPnl = positionNotional - openNotional => positionNotional = openNotional + unrealizedPnl - // short: unrealizedPnl = openNotional - positionNotional => positionNotional = openNotional - unrealizedPnl - positionNotional := sdk.ZeroDec() - if positionResp.Position.Size_.IsPositive() { - positionNotional = positionResp.Position.OpenNotional.Add(positionResp.UnrealizedPnlAfter) - } else if positionResp.Position.Size_.IsNegative() { - positionNotional = positionResp.Position.OpenNotional.Sub(positionResp.UnrealizedPnlAfter) - } - - // This means that the position has been closed entirely. - if transferredFee.IsZero() { - // If the position has margin to be transferred to the user, we get the fees from it. - if positionResp.MarginToVault.IsNegative() { - transferredFee, err = k.transferFee(ctx, market.Pair, traderAddr, positionResp.MarginToVault.Abs(), market.ExchangeFeeRatio, market.EcosystemFundFeeRatio) - if err != nil { - return err - } - } - } - - _ = ctx.EventManager().EmitTypedEvents( - &types.PositionChangedEvent{ - FinalPosition: positionResp.Position, - PositionNotional: positionNotional, - TransactionFee: sdk.NewCoin(collateral, transferredFee), - RealizedPnl: positionResp.RealizedPnl, - BadDebt: sdk.NewCoin(collateral, positionResp.BadDebt.RoundInt()), - FundingPayment: positionResp.FundingPayment, - BlockHeight: ctx.BlockHeight(), - MarginToUser: marginToVault.Neg().Sub(transferredFee), - ChangeReason: changeType, - ExchangedSize: positionResp.Position.Size_.Sub(existingPosition.Size_), - ExchangedNotional: positionResp.PositionNotional.Sub(existingPosition.OpenNotional), - }, - ) - - return nil -} - -// checkMarginRatio checks if the margin ratio of the position is below the liquidation threshold. -func (k Keeper) checkMarginRatio(ctx sdk.Context, market types.Market, amm types.AMM, position types.Position) (err error) { - spotNotional, err := PositionNotionalSpot(amm, position) - if err != nil { - return - } - twapNotional, err := k.PositionNotionalTWAP(ctx, position, market.TwapLookbackWindow) - if err != nil { - return - } - var preferredPositionNotional sdk.Dec - if position.Size_.IsPositive() { - preferredPositionNotional = sdk.MaxDec(spotNotional, twapNotional) - } else { - preferredPositionNotional = sdk.MinDec(spotNotional, twapNotional) - } - - marginRatio := MarginRatio(position, preferredPositionNotional, market.LatestCumulativePremiumFraction) - if marginRatio.LT(market.MaintenanceMarginRatio) { - return types.ErrMarginRatioTooLow.Wrapf("position margin ratio: %s, maintenance margin ratio: %s", marginRatio, market.MaintenanceMarginRatio) - } - return -} - -// transfers the fee to the exchange fee pool -// -// args: -// - ctx: the cosmos-sdk context -// - pair: the trading pair -// - trader: the trader's address -// - positionNotional: the position's notional value -// -// returns: -// - fees: the fees to be transferred -// - err: error if any -func (k Keeper) transferFee( - ctx sdk.Context, - pair asset.Pair, - trader sdk.AccAddress, - positionNotional sdk.Dec, - exchangeFeeRatio sdk.Dec, - ecosystemFundFeeRatio sdk.Dec, -) (fees sdkmath.Int, err error) { - collateral, err := k.Collateral.Get(ctx) - if err != nil { - return sdkmath.Int{}, err - } - - exchangeFeeRatio, err = k.calculateDiscount(ctx, pair, trader, positionNotional, exchangeFeeRatio) - if err != nil { - return sdkmath.Int{}, err - } - feeToExchangeFeePool := exchangeFeeRatio.Mul(positionNotional).RoundInt() - if feeToExchangeFeePool.IsPositive() { - if err = k.BankKeeper.SendCoinsFromAccountToModule( - ctx, - /* from */ trader, - /* to */ types.FeePoolModuleAccount, - /* coins */ sdk.NewCoins( - sdk.NewCoin( - collateral, - feeToExchangeFeePool, - ), - ), - ); err != nil { - return sdkmath.Int{}, err - } - } - - feeToEcosystemFund := ecosystemFundFeeRatio.Mul(positionNotional).RoundInt() - if feeToEcosystemFund.IsPositive() { - if err = k.BankKeeper.SendCoinsFromAccountToModule( - ctx, - /* from */ trader, - /* to */ types.PerpFundModuleAccount, - /* coins */ sdk.NewCoins( - sdk.NewCoin( - collateral, - feeToEcosystemFund, - ), - ), - ); err != nil { - return sdkmath.Int{}, err - } - } - - return feeToExchangeFeePool.Add(feeToEcosystemFund), nil -} - -// ClosePosition closes a position entirely and transfers the remaining margin back to the user. -// Errors if the position has bad debt. -// -// args: -// - ctx: the cosmos-sdk context -// - pair: the pair of the position -// - traderAddr: the address of the trader -// -// returns: -// - positionResp: response object containing information about the position change -// - err: error if any -func (k Keeper) ClosePosition(ctx sdk.Context, pair asset.Pair, traderAddr sdk.AccAddress) (*types.PositionResp, error) { - market, err := k.GetMarket(ctx, pair) - if err != nil { - return nil, fmt.Errorf("%w: %s", types.ErrPairNotFound, pair) - } - - if !market.Enabled { - return nil, fmt.Errorf("%w: this position can be only closed by Settlement", types.ErrMarketNotEnabled) - } - - amm, err := k.GetAMM(ctx, pair) - if err != nil { - return nil, fmt.Errorf("%w: %s", types.ErrPairNotFound, pair) - } - - position, err := k.GetPosition(ctx, pair, market.Version, traderAddr) - if err != nil { - return nil, err - } - - _, positionResp, err := k.closePositionEntirely( - ctx, - market, - amm, - position, - /* quoteAssetAmountLimit */ sdk.ZeroDec(), - ) - if err != nil { - return nil, err - } - - if positionResp.BadDebt.IsPositive() { - if err = k.realizeBadDebt( - ctx, - market, - positionResp.BadDebt.RoundInt(), - ); err != nil { - return nil, err - } - } - - if err = k.afterPositionUpdate( - ctx, - market, - traderAddr, - *positionResp, - types.ChangeReason_ClosePosition, - sdk.ZeroInt(), - position, - ); err != nil { - return nil, err - } - - return positionResp, nil -} - -// Closes a position and realizes PnL and funding payments. -// Does not error out if there is bad debt, that is for callers to decide. -// -// args: -// - ctx: cosmos-sdk context -// - market: the perp market -// - amm: the amm reserves -// - currentPosition: the existing position -// - quoteAssetAmountLimit: the user-specified limit on the quote asset reserves -// -// returns: -// - updatedAMM: updated AMM reserves -// - positionResp: response object containing information about the position change -// - err: error -func (k Keeper) closePositionEntirely( - ctx sdk.Context, - market types.Market, - amm types.AMM, - currentPosition types.Position, - quoteAssetAmountLimit sdk.Dec, -) (updatedAMM *types.AMM, resp *types.PositionResp, err error) { - if currentPosition.Size_.IsZero() { - return nil, nil, fmt.Errorf("zero position size") - } - positionNotional, err := PositionNotionalSpot(amm, currentPosition) - if err != nil { - return nil, nil, err - } - - trader, err := sdk.AccAddressFromBech32(currentPosition.TraderAddress) - if err != nil { - return nil, nil, err - } - - resp = &types.PositionResp{ - ExchangedPositionSize: currentPosition.Size_.Neg(), - PositionNotional: sdk.ZeroDec(), - FundingPayment: FundingPayment(currentPosition, market.LatestCumulativePremiumFraction), - RealizedPnl: UnrealizedPnl(currentPosition, positionNotional), - UnrealizedPnlAfter: sdk.ZeroDec(), - } - - remainingMargin := currentPosition.Margin.Add(resp.RealizedPnl).Sub(resp.FundingPayment) - - if remainingMargin.IsPositive() { - resp.BadDebt = sdk.ZeroDec() - resp.MarginToVault = remainingMargin.Neg() - } else { - resp.BadDebt = remainingMargin.Abs() - resp.MarginToVault = sdk.ZeroDec() - } - - var dir types.Direction - // flipped since we are going against the current position - if currentPosition.Size_.IsPositive() { - dir = types.Direction_SHORT - } else { - dir = types.Direction_LONG - } - updatedAMM, exchangedNotionalValue, err := k.SwapBaseAsset( - ctx, - amm, - dir, - currentPosition.Size_.Abs(), - quoteAssetAmountLimit, - ) - if err != nil { - return nil, nil, err - } - - resp.ExchangedNotionalValue = exchangedNotionalValue - resp.Position = types.Position{ - TraderAddress: currentPosition.TraderAddress, - Pair: currentPosition.Pair, - Size_: sdk.ZeroDec(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.ZeroDec(), - LatestCumulativePremiumFraction: market.LatestCumulativePremiumFraction, - LastUpdatedBlockNumber: ctx.BlockHeight(), - } - - err = k.DeletePosition(ctx, currentPosition.Pair, market.Version, trader) - if err != nil { - return nil, nil, err - } - - return updatedAMM, resp, nil -} - -func (k Keeper) PartialClose( - ctx sdk.Context, - pair asset.Pair, - traderAddr sdk.AccAddress, - sizeAmt sdk.Dec, // unsigned -) (*types.PositionResp, error) { - market, err := k.GetMarket(ctx, pair) - if err != nil { - return nil, types.ErrPairNotFound.Wrapf("pair: %s", pair) - } - - if !market.Enabled { - return nil, fmt.Errorf("%w: this position can be only closed by Settlement", types.ErrMarketNotEnabled) - } - - amm, err := k.GetAMM(ctx, pair) - if err != nil { - return nil, types.ErrPairNotFound.Wrapf("pair: %s", pair) - } - - position, err := k.GetPosition(ctx, pair, market.Version, traderAddr) - if err != nil { - return nil, err - } - - if position.Size_.IsZero() { - return nil, fmt.Errorf("zero position size") - } - - if sizeAmt.Abs().GT(position.Size_.Abs()) { - return nil, fmt.Errorf("position size is smaller than the amount to close") - } - - var dir types.Direction - if position.Size_.IsPositive() { - dir = types.Direction_SHORT - } else { - dir = types.Direction_LONG - } - - reverseNotionalAmt, err := amm.GetQuoteReserveAmt(sizeAmt.Abs(), dir) - if err != nil { - return nil, err - } - reverseNotionalAmt = amm.QuoteReserveToAsset(reverseNotionalAmt) - - feesTransferred, err := k.transferFee(ctx, market.Pair, traderAddr, reverseNotionalAmt, market.ExchangeFeeRatio, market.EcosystemFundFeeRatio) - if err != nil { - return nil, err - } - - reverseNotionalAmtWithoutFees := reverseNotionalAmt.Sub(feesTransferred.ToLegacyDec()) - - _, positionResp, err := k.decreasePosition(ctx, market, amm, position, reverseNotionalAmtWithoutFees, sdk.ZeroDec()) - if err != nil { - return nil, err - } - - if positionResp.BadDebt.IsPositive() { - if err = k.realizeBadDebt( - ctx, - market, - positionResp.BadDebt.RoundInt(), - ); err != nil { - return nil, err - } - } - - err = k.afterPositionUpdate( - ctx, - market, - traderAddr, - *positionResp, - types.ChangeReason_PartialClose, - feesTransferred, - position, - ) - if err != nil { - return nil, err - } - - return positionResp, nil -} diff --git a/x/perp/v2/keeper/clearing_house_test.go b/x/perp/v2/keeper/clearing_house_test.go deleted file mode 100644 index 467cf54af..000000000 --- a/x/perp/v2/keeper/clearing_house_test.go +++ /dev/null @@ -1,2051 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkmath "cosmossdk.io/math" - "github.com/NibiruChain/collections" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - . "github.com/NibiruChain/nibiru/x/common/testutil/action" - . "github.com/NibiruChain/nibiru/x/common/testutil/assertion" - "github.com/NibiruChain/nibiru/x/common/testutil/mock" - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/assertion" - - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func TestMarketOrder(t *testing.T) { - alice := testutil.AccAddress() - bob := testutil.AccAddress() - pairBtcNusd := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - startBlockTime := time.Now() - - adminUser, err := sdk.AccAddressFromBech32(testutil.ADDR_SUDO_ROOT) - require.NoError(t, err) - - tc := TestCases{ - TC("open big short position and then close after reducing swap invariant"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200)))), - FundAccount(bob, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100_000_000)))), - - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(10_000), sdk.OneDec(), sdk.ZeroDec()), - MarketOrder(bob, pairBtcNusd, types.Direction_LONG, sdk.NewInt(10_000), sdk.OneDec(), sdk.ZeroDec()), - - ShiftSwapInvariantFail(pairBtcNusd, sdk.NewInt(1)), - ), - - TC("new long position"). - Given( - CreateCustomMarket(pairBtcNusd, - WithEnabled(true), - ), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1020)))), - ). - When( - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(1000), sdk.NewDec(10), sdk.ZeroDec(), - MarketOrderResp_PositionShouldBeEqual( - types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(980), - OpenNotional: sdk.NewDec(9_800), - Size_: sdk.MustNewDecFromStr("9799.999903960000941192"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }), - MarketOrderResp_ExchangeNotionalValueShouldBeEqual(sdk.NewDec(9_800)), // margin * leverage - MarketOrderResp_ExchangedPositionSizeShouldBeEqual(sdk.MustNewDecFromStr("9799.999903960000941192")), - MarketOrderResp_BadDebtShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_FundingPaymentShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_RealizedPnlShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_UnrealizedPnlAfterShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_MarginToVaultShouldBeEqual(sdk.NewDec(980)), - MarketOrderResp_PositionNotionalShouldBeEqual(sdk.NewDec(9800)), - ), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, Position_PositionShouldBeEqualTo(types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(980), - OpenNotional: sdk.NewDec(9800), - Size_: sdk.MustNewDecFromStr("9799.999903960000941192"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - })), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(980), - OpenNotional: sdk.NewDec(9800), - Size_: sdk.MustNewDecFromStr("9799.999903960000941192"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }, - PositionNotional: sdk.NewDec(9800), - RealizedPnl: sdk.ZeroDec(), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.ZeroDec(), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(20)), - BlockHeight: 1, - // exchangedMargin = - marginToVault - transferredFee - MarginToUser: sdk.NewInt(980 + 20).Neg(), - ChangeReason: types.ChangeReason_MarketOrder, - ExchangedNotional: sdk.NewDec(9800), - ExchangedSize: sdk.MustNewDecFromStr("9799.999903960000941192"), - }), - ), - - TC("existing long position, go more long"). - Given( - SetBlockNumber(1), - SetBlockTime(startBlockTime), - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(2040)))), - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(1000), sdk.NewDec(10), sdk.ZeroDec()), - ). - When( - MoveToNextBlock(), - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(1000), sdk.NewDec(10), sdk.ZeroDec(), - MarketOrderResp_PositionShouldBeEqual( - types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(1_960), - OpenNotional: sdk.NewDec(19_600), - Size_: sdk.MustNewDecFromStr("19599.999615840007529536"), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }), - MarketOrderResp_ExchangeNotionalValueShouldBeEqual(sdk.NewDec(9_800)), // margin * leverage - MarketOrderResp_ExchangedPositionSizeShouldBeEqual(sdk.MustNewDecFromStr("9799.999711880006588344")), - MarketOrderResp_BadDebtShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_FundingPaymentShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_RealizedPnlShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_UnrealizedPnlAfterShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_MarginToVaultShouldBeEqual(sdk.NewDec(980)), - MarketOrderResp_PositionNotionalShouldBeEqual(sdk.NewDec(19_600)), - ), - ). - Then( - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(1_960), - OpenNotional: sdk.NewDec(19_600), - Size_: sdk.MustNewDecFromStr("19599.999615840007529536"), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }, - PositionNotional: sdk.NewDec(19_600), - RealizedPnl: sdk.ZeroDec(), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.ZeroDec(), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(20)), // 20 bps - BlockHeight: 2, - // exchangedMargin = - marginToVault - transferredFee - MarginToUser: sdk.NewInt(980 + 20).Neg(), - ChangeReason: types.ChangeReason_MarketOrder, - ExchangedNotional: sdk.MustNewDecFromStr("9800.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("9799.999711880006588344"), - }), - ), - - TC("existing long position, go more long but there's bad debt"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.89")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(18)))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithMargin(sdk.NewDec(1_000)), - WithSize(sdk.NewDec(10_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - MoveToNextBlock(), - MarketOrderFails(alice, pairBtcNusd, types.Direction_LONG, sdk.OneInt(), sdk.OneDec(), sdk.ZeroDec(), - types.ErrMarginRatioTooLow, - ), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, Position_PositionShouldBeEqualTo(types.Position{ - TraderAddress: alice.String(), - Pair: pairBtcNusd, - Size_: sdk.NewDec(10_000), - Margin: sdk.NewDec(1_000), - OpenNotional: sdk.NewDec(10_000), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - })), - ), - - TC("existing long position, close a bit but there's bad debt"). - Given( - CreateCustomMarket( - pairBtcNusd, WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.89")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(18)))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithMargin(sdk.NewDec(1_000)), - WithSize(sdk.NewDec(10_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - MoveToNextBlock(), - MarketOrderFails(alice, pairBtcNusd, types.Direction_SHORT, sdk.OneInt(), sdk.OneDec(), sdk.ZeroDec(), - types.ErrMarginRatioTooLow, - ), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, Position_PositionShouldBeEqualTo(types.Position{ - TraderAddress: alice.String(), - Pair: pairBtcNusd, - Size_: sdk.NewDec(10_000), - Margin: sdk.NewDec(1_000), - OpenNotional: sdk.NewDec(10_000), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - })), - ), - - TC("open big long position and then close after reducing swap invariant"). - Given( - CreateCustomMarket( - pairBtcNusd, WithEnabled(true), - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_000)))), - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(9_000), sdk.NewDec(10), sdk.ZeroDec()), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100_000_000)))), - ShiftSwapInvariant(pairBtcNusd, sdk.NewInt(1)), - ). - When( - ClosePosition(alice, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - ), - - TC("existing long position, decrease a bit"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1030)))), - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(1000), sdk.NewDec(10), sdk.ZeroDec()), - ). - When( - MoveToNextBlock(), - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(500), sdk.NewDec(10), sdk.ZeroDec(), - MarketOrderResp_PositionShouldBeEqual( - types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(980), - OpenNotional: sdk.NewDec(4_900), - Size_: sdk.MustNewDecFromStr("4899.999975990000117649"), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }, - ), - MarketOrderResp_ExchangeNotionalValueShouldBeEqual(sdk.NewDec(4_900)), // (margin - fees) * leverage - MarketOrderResp_ExchangedPositionSizeShouldBeEqual(sdk.MustNewDecFromStr("-4899.999927970000823543")), - MarketOrderResp_BadDebtShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_FundingPaymentShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_RealizedPnlShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_UnrealizedPnlAfterShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_MarginToVaultShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_PositionNotionalShouldBeEqual(sdk.NewDec(4_900)), - ), - ). - Then( - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(980), - OpenNotional: sdk.NewDec(4_900), - Size_: sdk.MustNewDecFromStr("4899.999975990000117649"), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }, - PositionNotional: sdk.NewDec(4_900), - RealizedPnl: sdk.ZeroDec(), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.ZeroDec(), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10)), // 20 bps - BlockHeight: 2, - // exchangedMargin = - marginToVault - transferredFee - MarginToUser: sdk.NewInt(0 + 10).Neg(), - ChangeReason: types.ChangeReason_MarketOrder, - ExchangedNotional: sdk.MustNewDecFromStr("-4900.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("-4899.999927970000823543"), - }), - ), - - TC("existing long position, decrease a bit but there's bad debt"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.89")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(18)))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithMargin(sdk.NewDec(1_000)), - WithSize(sdk.NewDec(10_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - MoveToNextBlock(), - MarketOrderFails(alice, pairBtcNusd, types.Direction_LONG, sdk.OneInt(), sdk.OneDec(), sdk.ZeroDec(), - types.ErrMarginRatioTooLow, - ), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, Position_PositionShouldBeEqualTo(types.Position{ - TraderAddress: alice.String(), - Pair: pairBtcNusd, - Size_: sdk.NewDec(10_000), - Margin: sdk.NewDec(1_000), - OpenNotional: sdk.NewDec(10_000), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - })), - ), - - TC("existing long position, decrease a lot"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(4080)))), - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(1000), sdk.NewDec(10), sdk.ZeroDec()), - ). - When( - MoveToNextBlock(), - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(3000), sdk.NewDec(10), sdk.ZeroDec(), - MarketOrderResp_PositionShouldBeEqual( - types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(1960), - OpenNotional: sdk.NewDec(19_600), - Size_: sdk.MustNewDecFromStr("-19600.000384160007529536"), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }, - ), - MarketOrderResp_ExchangeNotionalValueShouldBeEqual(sdk.NewDec(29_400)), // margin * leverage - MarketOrderResp_ExchangedPositionSizeShouldBeEqual(sdk.MustNewDecFromStr("-29400.000288120008470728")), - MarketOrderResp_BadDebtShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_FundingPaymentShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_RealizedPnlShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_UnrealizedPnlAfterShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_MarginToVaultShouldBeEqual(sdk.NewDec(980)), - MarketOrderResp_PositionNotionalShouldBeEqual(sdk.NewDec(19_600)), - ), - ). - Then( - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(1960), - OpenNotional: sdk.NewDec(19_600), - Size_: sdk.MustNewDecFromStr("-19600.000384160007529536"), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }, - PositionNotional: sdk.NewDec(19_600), - RealizedPnl: sdk.ZeroDec(), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.ZeroDec(), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(60)), // 20 bps - BlockHeight: 2, - // exchangedMargin = - marginToVault - transferredFee - MarginToUser: sdk.NewInt(980 + 60).Neg(), - ChangeReason: types.ChangeReason_MarketOrder, - ExchangedNotional: sdk.MustNewDecFromStr("9800.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("-29400.000288120008470728"), - }), - ), - - TC("existing long position, decrease a lot but there's bad debt"). - Given( - CreateCustomMarket( - pairBtcNusd, WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.89")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(150)))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithMargin(sdk.NewDec(1_000)), - WithSize(sdk.NewDec(10_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - MoveToNextBlock(), - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(3000), sdk.NewDec(10), sdk.ZeroDec(), - MarketOrderResp_PositionShouldBeEqual( - types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.ZeroDec(), - Size_: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - ), - MarketOrderResp_ExchangeNotionalValueShouldBeEqual(sdk.MustNewDecFromStr("8899.999911000000890000")), - MarketOrderResp_ExchangedPositionSizeShouldBeEqual(sdk.MustNewDecFromStr("-10000")), - MarketOrderResp_BadDebtShouldBeEqual(sdk.MustNewDecFromStr("102.000088999999110000")), - MarketOrderResp_FundingPaymentShouldBeEqual(sdk.NewDec(2)), - MarketOrderResp_RealizedPnlShouldBeEqual(sdk.MustNewDecFromStr("-1100.000088999999110000")), - MarketOrderResp_UnrealizedPnlAfterShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_MarginToVaultShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_PositionNotionalShouldBeEqual(sdk.ZeroDec()), - ), - ). - Then( - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.ZeroDec(), - Size_: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - PositionNotional: sdk.ZeroDec(), - RealizedPnl: sdk.MustNewDecFromStr("-1100.000088999999110000"), - BadDebt: sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 102), - FundingPayment: sdk.NewDec(2), - TransactionFee: sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 60), // 20 bps - BlockHeight: 2, - MarginToUser: sdk.NewInt(-60), - ChangeReason: types.ChangeReason_MarketOrder, - ExchangedNotional: sdk.MustNewDecFromStr("-10000.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("-10000.000000000000000000"), - }), - ), - - TC("new short position"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1020)))), - ). - When( - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(1000), sdk.NewDec(10), sdk.ZeroDec(), - MarketOrderResp_PositionShouldBeEqual( - types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(980), - OpenNotional: sdk.NewDec(9_800), - Size_: sdk.MustNewDecFromStr("-9800.000096040000941192"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }), - MarketOrderResp_ExchangeNotionalValueShouldBeEqual(sdk.NewDec(9_800)), // margin * leverage - MarketOrderResp_ExchangedPositionSizeShouldBeEqual(sdk.MustNewDecFromStr("-9800.000096040000941192")), - MarketOrderResp_BadDebtShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_FundingPaymentShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_RealizedPnlShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_UnrealizedPnlAfterShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_MarginToVaultShouldBeEqual(sdk.NewDec(980)), - MarketOrderResp_PositionNotionalShouldBeEqual(sdk.NewDec(9_800)), - ), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, - Position_PositionShouldBeEqualTo(types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(980), - OpenNotional: sdk.NewDec(9_800), - Size_: sdk.MustNewDecFromStr("-9800.000096040000941192"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }), - ), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(980), - OpenNotional: sdk.NewDec(9_800), - Size_: sdk.MustNewDecFromStr("-9800.000096040000941192"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }, - PositionNotional: sdk.NewDec(9_800), - RealizedPnl: sdk.ZeroDec(), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.ZeroDec(), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(20)), - BlockHeight: 1, - // exchangedMargin = - marginToVault - transferredFee - MarginToUser: sdk.NewInt(980 + 20).Neg(), - ChangeReason: types.ChangeReason_MarketOrder, - ExchangedNotional: sdk.MustNewDecFromStr("9800.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("-9800.000096040000941192"), - }), - ), - - TC("existing short position, go more short"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(2040)))), - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(1000), sdk.NewDec(10), sdk.ZeroDec()), - ). - When( - MoveToNextBlock(), - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(1000), sdk.NewDec(10), sdk.ZeroDec(), - MarketOrderResp_PositionShouldBeEqual( - types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(1_960), - OpenNotional: sdk.NewDec(19_600), - Size_: sdk.MustNewDecFromStr("-19600.000384160007529536"), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }, - ), - MarketOrderResp_ExchangeNotionalValueShouldBeEqual(sdk.NewDec(9_800)), // margin * leverage - MarketOrderResp_ExchangedPositionSizeShouldBeEqual(sdk.MustNewDecFromStr("-9800.000288120006588344")), - MarketOrderResp_BadDebtShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_FundingPaymentShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_RealizedPnlShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_UnrealizedPnlAfterShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_MarginToVaultShouldBeEqual(sdk.NewDec(980)), - MarketOrderResp_PositionNotionalShouldBeEqual(sdk.NewDec(19_600)), - ), - ). - Then( - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(1_960), - OpenNotional: sdk.NewDec(19_600), - Size_: sdk.MustNewDecFromStr("-19600.000384160007529536"), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }, - PositionNotional: sdk.NewDec(19_600), - RealizedPnl: sdk.ZeroDec(), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.ZeroDec(), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(20)), // 20 bps - BlockHeight: 2, - // exchangedMargin = - marginToVault - transferredFee - MarginToUser: sdk.NewInt(980 + 20).Neg(), - ChangeReason: types.ChangeReason_MarketOrder, - ExchangedNotional: sdk.MustNewDecFromStr("9800.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("-9800.000288120006588344"), - }), - ), - - TC("existing short position, go more short but there's bad debt"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("1.11")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(22)))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithMargin(sdk.NewDec(1_000)), - WithSize(sdk.NewDec(-10_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - MoveToNextBlock(), - MarketOrderFails(alice, pairBtcNusd, types.Direction_SHORT, sdk.OneInt(), sdk.OneDec(), sdk.ZeroDec(), - types.ErrMarginRatioTooLow, - ), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, Position_PositionShouldBeEqualTo(types.Position{ - TraderAddress: alice.String(), - Pair: pairBtcNusd, - Size_: sdk.NewDec(-10_000), - Margin: sdk.NewDec(1_000), - OpenNotional: sdk.NewDec(10_000), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - })), - ), - - TC("existing short position, decrease a bit"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1030)))), - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(1000), sdk.NewDec(10), sdk.ZeroDec()), - ). - When( - MoveToNextBlock(), - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(500), sdk.NewDec(10), sdk.ZeroDec(), - MarketOrderResp_PositionShouldBeEqual( - types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(980), - OpenNotional: sdk.NewDec(4_900), - Size_: sdk.MustNewDecFromStr("-4900.000024010000117649"), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }, - ), - MarketOrderResp_ExchangeNotionalValueShouldBeEqual(sdk.NewDec(4_900)), // margin * leverage - MarketOrderResp_ExchangedPositionSizeShouldBeEqual(sdk.MustNewDecFromStr("4900.000072030000823543")), - MarketOrderResp_BadDebtShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_FundingPaymentShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_RealizedPnlShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_UnrealizedPnlAfterShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_MarginToVaultShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_PositionNotionalShouldBeEqual(sdk.NewDec(4900)), - ), - ). - Then( - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(980), - OpenNotional: sdk.NewDec(4_900), - Size_: sdk.MustNewDecFromStr("-4900.000024010000117649"), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }, - PositionNotional: sdk.NewDec(4_900), - RealizedPnl: sdk.ZeroDec(), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.ZeroDec(), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10)), // 20 bps - BlockHeight: 2, - // exchangedMargin = - marginToVault - transferredFee - MarginToUser: sdk.NewInt(0 + 10).Neg(), - ChangeReason: types.ChangeReason_MarketOrder, - ExchangedNotional: sdk.MustNewDecFromStr("-4900.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("4900.000072030000823543"), - }), - ), - - TC("existing short position, decrease a bit but there's bad debt"). - Given( - CreateCustomMarket(pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("1.11")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(22)))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithMargin(sdk.NewDec(1_000)), - WithSize(sdk.NewDec(-10_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - MoveToNextBlock(), - MarketOrderFails(alice, pairBtcNusd, types.Direction_LONG, sdk.OneInt(), sdk.OneDec(), sdk.ZeroDec(), - types.ErrMarginRatioTooLow, - ), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, Position_PositionShouldBeEqualTo(types.Position{ - TraderAddress: alice.String(), - Pair: pairBtcNusd, - Size_: sdk.NewDec(-10_000), - Margin: sdk.NewDec(1_000), - OpenNotional: sdk.NewDec(10_000), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - })), - ), - - TC("existing short position, decrease a lot"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(4080)))), - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(1000), sdk.NewDec(10), sdk.ZeroDec()), - ). - When( - MoveToNextBlock(), - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(3000), sdk.NewDec(10), sdk.ZeroDec(), - MarketOrderResp_PositionShouldBeEqual( - types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(1960), - OpenNotional: sdk.NewDec(19_600), - Size_: sdk.MustNewDecFromStr("19599.999615840007529536"), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }, - ), - MarketOrderResp_ExchangeNotionalValueShouldBeEqual(sdk.NewDec(29_400)), // margin * leverage - MarketOrderResp_ExchangedPositionSizeShouldBeEqual(sdk.MustNewDecFromStr("29399.999711880008470728")), - MarketOrderResp_BadDebtShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_FundingPaymentShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_RealizedPnlShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_UnrealizedPnlAfterShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_MarginToVaultShouldBeEqual(sdk.NewDec(980)), - MarketOrderResp_PositionNotionalShouldBeEqual(sdk.NewDec(19_600)), - ), - ). - Then( - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.NewDec(1960), - OpenNotional: sdk.NewDec(19_600), - Size_: sdk.MustNewDecFromStr("19599.999615840007529536"), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - }, - PositionNotional: sdk.NewDec(19_600), - RealizedPnl: sdk.ZeroDec(), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.ZeroDec(), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(60)), // 20 bps - BlockHeight: 2, - // exchangedMargin = - marginToVault - transferredFee - MarginToUser: sdk.NewInt(980 + 60).Neg(), - ChangeReason: types.ChangeReason_MarketOrder, - ExchangedNotional: sdk.MustNewDecFromStr("9800.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("29399.999711880008470728"), - }), - ), - - TC("existing short position, decrease a lot but there's bad debt"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("1.11")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(150)))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithMargin(sdk.NewDec(1_000)), - WithSize(sdk.NewDec(-10_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - MoveToNextBlock(), - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(3000), sdk.NewDec(10), sdk.ZeroDec(), - MarketOrderResp_PositionShouldBeEqual( - types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.ZeroDec(), - Size_: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - ), - MarketOrderResp_ExchangeNotionalValueShouldBeEqual(sdk.MustNewDecFromStr("11100.000111000001110000")), - MarketOrderResp_ExchangedPositionSizeShouldBeEqual(sdk.MustNewDecFromStr("10000")), - MarketOrderResp_BadDebtShouldBeEqual(sdk.MustNewDecFromStr("98.000111000001110000")), - MarketOrderResp_FundingPaymentShouldBeEqual(sdk.NewDec(-2)), - MarketOrderResp_RealizedPnlShouldBeEqual(sdk.MustNewDecFromStr("-1100.000111000001110000")), - MarketOrderResp_UnrealizedPnlAfterShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_MarginToVaultShouldBeEqual(sdk.ZeroDec()), - MarketOrderResp_PositionNotionalShouldBeEqual(sdk.ZeroDec()), - ), - ). - Then( - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.ZeroDec(), - Size_: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - PositionNotional: sdk.ZeroDec(), - RealizedPnl: sdk.MustNewDecFromStr("-1100.000111000001110000"), - BadDebt: sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 98), - FundingPayment: sdk.NewDec(-2), - TransactionFee: sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 60), // 20 bps - BlockHeight: 2, - // exchangedMargin = - marginToVault - transferredFee - MarginToUser: sdk.NewInt(-60), - ChangeReason: types.ChangeReason_MarketOrder, - ExchangedNotional: sdk.MustNewDecFromStr("-10000.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("10000.000000000000000000"), - }), - ), - - TC("user has insufficient funds"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(99)))), - ). - When( - MarketOrderFails( - alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(100), sdk.OneDec(), sdk.ZeroDec(), - sdkerrors.ErrInsufficientFunds), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - ), - - TC("new long position, can not open new position after market is not enabled"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(47_714_285_715)))), - CloseMarket(pairBtcNusd, adminUser), - ). - When( - MarketOrderFails(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(47_619_047_619), sdk.OneDec(), sdk.ZeroDec(), - types.ErrMarketNotEnabled), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - ), - - TC("market doesn't exist"). - Given( - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(47_714_285_715)))), - ). - When( - MarketOrderFails(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(47_619_047_619), sdk.OneDec(), sdk.ZeroDec(), - types.ErrPairNotFound), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - ), - - TC("zero quote asset amount"). - Given( - SetBlockTime(startBlockTime), - SetBlockNumber(1), - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(47_714_285_715)))), - ). - When( - MarketOrderFails(alice, pairBtcNusd, types.Direction_LONG, sdk.ZeroInt(), sdk.OneDec(), sdk.ZeroDec(), - types.ErrInputQuoteAmtNegative), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - ), - - TC("zero leverage"). - Given( - SetBlockTime(startBlockTime), - SetBlockNumber(1), - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - MarketOrderFails(alice, pairBtcNusd, types.Direction_LONG, sdk.OneInt(), sdk.ZeroDec(), sdk.ZeroDec(), - types.ErrUserLeverageNegative), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - ), - - TC("user leverage greater than market max leverage"). - Given( - SetBlockTime(startBlockTime), - SetBlockNumber(1), - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - MarketOrderFails(alice, pairBtcNusd, types.Direction_LONG, sdk.OneInt(), sdk.NewDec(11), sdk.ZeroDec(), - types.ErrLeverageIsTooHigh), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} - -func TestMarketOrderError(t *testing.T) { - testCases := []struct { - name string - traderFunds sdk.Coins - - initialPosition *types.Position - - // position arguments - side types.Direction - margin sdkmath.Int - leverage sdk.Dec - baseLimit sdk.Dec - - expectedErr error - }{ - { - name: "not enough trader funds", - traderFunds: sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 999)), - initialPosition: nil, - side: types.Direction_LONG, - margin: sdk.NewInt(1000), - leverage: sdk.NewDec(10), - baseLimit: sdk.ZeroDec(), - expectedErr: sdkerrors.ErrInsufficientFunds, - }, - { - name: "position has bad debt", - traderFunds: sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 999)), - initialPosition: &types.Position{ - Pair: asset.Registry.Pair(denoms.BTC, denoms.NUSD), - Size_: sdk.OneDec(), - Margin: sdk.NewDec(1000), - OpenNotional: sdk.NewDec(10_000), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 1, - }, - side: types.Direction_LONG, - margin: sdk.OneInt(), - leverage: sdk.OneDec(), - baseLimit: sdk.ZeroDec(), - expectedErr: types.ErrMarginRatioTooLow, - }, - { - name: "new long position not over base limit", - traderFunds: sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1020)), - initialPosition: nil, - side: types.Direction_LONG, - margin: sdk.NewInt(1000), - leverage: sdk.NewDec(10), - baseLimit: sdk.NewDec(10_000), - expectedErr: types.ErrAssetFailsUserLimit, - }, - { - name: "new short position not under base limit", - traderFunds: sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1020)), - initialPosition: nil, - side: types.Direction_SHORT, - margin: sdk.NewInt(1000), - leverage: sdk.NewDec(10), - baseLimit: sdk.NewDec(9_800), - expectedErr: types.ErrAssetFailsUserLimit, - }, - { - name: "quote asset amount is zero", - traderFunds: sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1020)), - initialPosition: nil, - side: types.Direction_SHORT, - margin: sdk.ZeroInt(), - leverage: sdk.NewDec(10), - baseLimit: sdk.NewDec(10_000), - expectedErr: types.ErrInputQuoteAmtNegative, - }, - { - name: "leverage amount is zero", - traderFunds: sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1020)), - initialPosition: nil, - side: types.Direction_SHORT, - margin: sdk.NewInt(1000), - leverage: sdk.ZeroDec(), - baseLimit: sdk.NewDec(10_000), - expectedErr: types.ErrUserLeverageNegative, - }, - { - name: "leverage amount is too high - SELL", - traderFunds: sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1020)), - initialPosition: nil, - side: types.Direction_SHORT, - margin: sdk.NewInt(100), - leverage: sdk.NewDec(100), - baseLimit: sdk.NewDec(11_000), - expectedErr: types.ErrLeverageIsTooHigh, - }, - { - name: "leverage amount is too high - BUY", - traderFunds: sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1020)), - initialPosition: nil, - side: types.Direction_LONG, - margin: sdk.NewInt(100), - leverage: sdk.NewDec(16), - baseLimit: sdk.ZeroDec(), - expectedErr: types.ErrLeverageIsTooHigh, - }, - } - - for _, testCase := range testCases { - tc := testCase - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - traderAddr := testutil.AccAddress() - - market := mock.TestMarket() - app.PerpKeeperV2.SaveMarket(ctx, *market) - app.PerpKeeperV2.MarketLastVersion.Insert(ctx, asset.Registry.Pair(denoms.BTC, denoms.NUSD), types.MarketLastVersion{Version: market.Version}) - amm := mock.TestAMMDefault() - app.PerpKeeperV2.SaveAMM(ctx, *amm) - app.PerpKeeperV2.ReserveSnapshots.Insert(ctx, collections.Join(amm.Pair, ctx.BlockTime()), types.ReserveSnapshot{ - Amm: *amm, - TimestampMs: ctx.BlockTime().UnixMilli(), - }) - require.NoError(t, testapp.FundAccount(app.BankKeeper, ctx, traderAddr, tc.traderFunds)) - - if tc.initialPosition != nil { - tc.initialPosition.TraderAddress = traderAddr.String() - app.PerpKeeperV2.SavePosition(ctx, tc.initialPosition.Pair, 1, traderAddr, *tc.initialPosition) - } - - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1).WithBlockTime(ctx.BlockTime().Add(time.Second * 5)) - resp, err := app.PerpKeeperV2.MarketOrder(ctx, asset.Registry.Pair(denoms.BTC, denoms.NUSD), tc.side, traderAddr, tc.margin, tc.leverage, tc.baseLimit) - require.ErrorContains(t, err, tc.expectedErr.Error()) - require.Nil(t, resp) - }) - } -} - -func TestPartialClose(t *testing.T) { - alice := testutil.AccAddress() - pairBtcNusd := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - startBlockTime := time.Now() - - tc := TestCases{ - TC("partial close long position with positive PnL"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.NewDec(2)), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1000)))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithSize(sdk.NewDec(10_000)), - WithMargin(sdk.NewDec(1_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - PartialClose(alice, pairBtcNusd, sdk.NewDec(2_500)), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, Position_PositionShouldBeEqualTo(types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.MustNewDecFromStr("3492.999950075025499499"), - OpenNotional: sdk.MustNewDecFromStr("7504.999962575025468249"), - Size_: sdk.MustNewDecFromStr("7505.000000024975000031"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - })), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.MustNewDecFromStr("3492.999950075025499499"), - OpenNotional: sdk.MustNewDecFromStr("7504.999962575025468249"), - Size_: sdk.MustNewDecFromStr("7505.000000024975000031"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - PositionNotional: sdk.MustNewDecFromStr("15009.999812500001968750"), - RealizedPnl: sdk.MustNewDecFromStr("2494.999950075025499499"), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.NewDec(2), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10)), - BlockHeight: 1, - MarginToUser: sdk.NewInt(-10), - ChangeReason: types.ChangeReason_PartialClose, - ExchangedNotional: sdk.MustNewDecFromStr("5009.999812500001968750"), - ExchangedSize: sdk.MustNewDecFromStr("-2494.999999975024999969"), - }), - ), - - TC("partial close long position with negative PnL"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.95")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(4)))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithSize(sdk.NewDec(10_000)), - WithMargin(sdk.NewDec(1_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - PartialClose(alice, pairBtcNusd, sdk.NewDec(2_500)), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, Position_PositionShouldBeEqualTo(types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.MustNewDecFromStr("873.210502606841456300"), - OpenNotional: sdk.MustNewDecFromStr("7504.210508544341441456"), - Size_: sdk.MustNewDecFromStr("7504.210526336824376757"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - })), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.MustNewDecFromStr("873.210502606841456300"), - OpenNotional: sdk.MustNewDecFromStr("7504.210508544341441456"), - Size_: sdk.MustNewDecFromStr("7504.210526336824376757"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - PositionNotional: sdk.MustNewDecFromStr("7128.999910937500935156"), - RealizedPnl: sdk.MustNewDecFromStr("-124.789497393158543700"), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.NewDec(2), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(4)), - BlockHeight: 1, - MarginToUser: sdk.NewInt(-4), - ChangeReason: types.ChangeReason_PartialClose, - ExchangedNotional: sdk.MustNewDecFromStr("-2871.000089062499064844"), - ExchangedSize: sdk.MustNewDecFromStr("-2495.789473663175623243"), - }), - ), - - TC("partial close long position without bad debt but below maintenance margin ratio"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.94")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(4)))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithSize(sdk.NewDec(10_000)), - WithMargin(sdk.NewDec(1_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - PartialClose(alice, pairBtcNusd, sdk.NewDec(2_500)), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, Position_PositionShouldBeEqualTo(types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.MustNewDecFromStr("848.255295690211914400"), - OpenNotional: sdk.MustNewDecFromStr("7504.255301565211899712"), - Size_: sdk.MustNewDecFromStr("7504.255319170194658242"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - })), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.MustNewDecFromStr("848.255295690211914400"), - OpenNotional: sdk.MustNewDecFromStr("7504.255301565211899712"), - Size_: sdk.MustNewDecFromStr("7504.255319170194658242"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - PositionNotional: sdk.MustNewDecFromStr("7053.999911875000925312"), - RealizedPnl: sdk.MustNewDecFromStr("-149.744704309788085600"), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.NewDec(2), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(4)), - BlockHeight: 1, - MarginToUser: sdk.NewInt(-4), - ChangeReason: types.ChangeReason_PartialClose, - ExchangedNotional: sdk.MustNewDecFromStr("-2946.000088124999074688"), - ExchangedSize: sdk.MustNewDecFromStr("-2495.744680829805341758"), - })), - - TC("partial close long position with bad debt"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.59")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 2))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 27))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithSize(sdk.NewDec(10_000)), - WithMargin(sdk.NewDec(1_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - PartialClose(alice, pairBtcNusd, sdk.NewDec(2_500)), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, Position_PositionShouldBeEqualTo(types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.MustNewDecFromStr("7503.389819472919156581"), - Size_: sdk.MustNewDecFromStr("7503.389830525412237884"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - })), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.MustNewDecFromStr("7503.389819472919156581"), - Size_: sdk.MustNewDecFromStr("7503.389830525412237884"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - PositionNotional: sdk.MustNewDecFromStr("4426.999944687500580781"), - RealizedPnl: sdk.MustNewDecFromStr("-1023.610184214580834200"), - BadDebt: sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 26), - FundingPayment: sdk.NewDec(2), - TransactionFee: sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 2), - BlockHeight: 1, - MarginToUser: sdk.NewInt(-2), - ChangeReason: types.ChangeReason_PartialClose, - ExchangedNotional: sdk.MustNewDecFromStr("-5573.000055312499419219"), - ExchangedSize: sdk.MustNewDecFromStr("-2496.610169474587762116"), - })), - - TC("partial close short position with positive PnL"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.10")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(2)))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithSize(sdk.NewDec(-10_000)), - WithMargin(sdk.NewDec(1_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - PartialClose(alice, pairBtcNusd, sdk.NewDec(7_500)), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, Position_PositionShouldBeEqualTo(types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.MustNewDecFromStr("7733.999992789639924900"), - OpenNotional: sdk.MustNewDecFromStr("2520.000001585360032912"), - Size_: sdk.MustNewDecFromStr("-2519.999999700400001111"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - })), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.MustNewDecFromStr("7733.999992789639924900"), - OpenNotional: sdk.MustNewDecFromStr("2520.000001585360032912"), - Size_: sdk.MustNewDecFromStr("-2519.999999700400001111"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - PositionNotional: sdk.MustNewDecFromStr("252.000004375000057812"), - RealizedPnl: sdk.MustNewDecFromStr("6731.999992789639924900"), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.NewDec(-2), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(2)), - BlockHeight: 1, - MarginToUser: sdk.NewInt(-2), - ChangeReason: types.ChangeReason_PartialClose, - ExchangedNotional: sdk.MustNewDecFromStr("-9747.999995624999942188"), - ExchangedSize: sdk.MustNewDecFromStr("7480.000000299599998889"), - }), - ), - - TC("partial close short position with negative PnL"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("1.05")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(16)))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithSize(sdk.NewDec(-10_000)), - WithMargin(sdk.NewDec(1_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - PartialClose(alice, pairBtcNusd, sdk.NewDec(7_500)), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, Position_PositionShouldBeEqualTo(types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.MustNewDecFromStr("627.761826160487012202"), - OpenNotional: sdk.MustNewDecFromStr("2515.238114777012544829"), - Size_: sdk.MustNewDecFromStr("-2515.238095009756009922"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - })), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.MustNewDecFromStr("627.761826160487012202"), - OpenNotional: sdk.MustNewDecFromStr("2515.238114777012544829"), - Size_: sdk.MustNewDecFromStr("-2515.238095009756009922"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - PositionNotional: sdk.MustNewDecFromStr("2641.000045937500607031"), - RealizedPnl: sdk.MustNewDecFromStr("-374.238173839512987798"), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.NewDec(-2), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(16)), - BlockHeight: 1, - MarginToUser: sdk.NewInt(-16), - ChangeReason: types.ChangeReason_PartialClose, - ExchangedNotional: sdk.MustNewDecFromStr("-7358.999954062499392969"), - ExchangedSize: sdk.MustNewDecFromStr("7484.761904990243990078"), - }), - ), - - TC("partial close short position with no bad debt but below maintenance margin ratio"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("1.09")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(16)))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithSize(sdk.NewDec(-10_000)), - WithMargin(sdk.NewDec(1_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - PartialClose(alice, pairBtcNusd, sdk.NewDec(7_500)), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, Position_PositionShouldBeEqualTo(types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.MustNewDecFromStr("328.321019307633252802"), - OpenNotional: sdk.MustNewDecFromStr("2514.678919379866287354"), - Size_: sdk.MustNewDecFromStr("-2514.678898862600792000"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - })), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.MustNewDecFromStr("328.321019307633252802"), - OpenNotional: sdk.MustNewDecFromStr("2514.678919379866287354"), - Size_: sdk.MustNewDecFromStr("-2514.678898862600792000"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - PositionNotional: sdk.MustNewDecFromStr("2741.000047687500630156"), - RealizedPnl: sdk.MustNewDecFromStr("-673.678980692366747198"), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.NewDec(-2), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(16)), - BlockHeight: 1, - MarginToUser: sdk.NewInt(-16), - ChangeReason: types.ChangeReason_PartialClose, - ExchangedNotional: sdk.MustNewDecFromStr("-7258.999952312499369844"), - ExchangedSize: sdk.MustNewDecFromStr("7485.321101137399208000"), - }), - ), - - TC("partial close short position with bad debt"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("1.14")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(18)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 48))), - InsertPosition( - WithPair(pairBtcNusd), - WithTrader(alice), - WithSize(sdk.NewDec(-10_000)), - WithMargin(sdk.NewDec(1_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - PartialClose(alice, pairBtcNusd, sdk.NewDec(7_500)), - ). - Then( - PositionShouldBeEqual(alice, pairBtcNusd, Position_PositionShouldBeEqualTo(types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.MustNewDecFromStr("2515.789494912333892759"), - Size_: sdk.MustNewDecFromStr("-2515.789473447617729414"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - })), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.MustNewDecFromStr("2515.789494912333892759"), - Size_: sdk.MustNewDecFromStr("-2515.789473447617729414"), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - PositionNotional: sdk.MustNewDecFromStr("2868.000049875000659062"), - RealizedPnl: sdk.MustNewDecFromStr("-1047.789559037334373697"), - BadDebt: sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 46), - FundingPayment: sdk.NewDec(-2), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(18)), - BlockHeight: 1, - MarginToUser: sdk.NewInt(-18), - ChangeReason: types.ChangeReason_PartialClose, - ExchangedNotional: sdk.MustNewDecFromStr("-7131.999950124999340938"), - ExchangedSize: sdk.MustNewDecFromStr("7484.210526552382270586"), - }), - ), - TC("test partial closes fail"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(10_000)), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200)))), - - PartialCloseFails(alice, pairBtcNusd, sdk.NewDec(5_000), types.ErrPositionNotFound), - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(9_000), sdk.OneDec(), sdk.ZeroDec()), - ). - When( - PartialCloseFails(alice, asset.MustNewPair("luna:usdt"), sdk.NewDec(5_000), types.ErrPairNotFound), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} - -func TestClosePosition(t *testing.T) { - alice := testutil.AccAddress() - pairBtcNusd := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - startBlockTime := time.Now() - - tc := TestCases{ - TC("close long position with positive PnL"). - Given( - CreateCustomMarket(pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.NewDec(2)), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(40)))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 10_998))), - InsertPosition( - WithTrader(alice), - WithPair(pairBtcNusd), - WithSize(sdk.NewDec(10_000)), - WithMargin(sdk.NewDec(1_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - ClosePosition(alice, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.ZeroDec(), - Size_: sdk.ZeroDec(), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - PositionNotional: sdk.ZeroDec(), - RealizedPnl: sdk.MustNewDecFromStr("9999.999800000002000000"), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.NewDec(2), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(22)), - BlockHeight: 1, - MarginToUser: sdk.NewInt(10976), - ChangeReason: types.ChangeReason_ClosePosition, - ExchangedNotional: sdk.MustNewDecFromStr("-10000.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("-10000.000000000000000000"), - }), - ), - - TC("close long position with negative PnL"). - Given( - CreateCustomMarket(pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.99")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(20)))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 898))), - InsertPosition( - WithTrader(alice), - WithPair(pairBtcNusd), - WithSize(sdk.NewDec(10_000)), - WithMargin(sdk.NewDec(1_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - ClosePosition(alice, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.ZeroDec(), - Size_: sdk.ZeroDec(), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - PositionNotional: sdk.ZeroDec(), - RealizedPnl: sdk.MustNewDecFromStr("-100.000098999999010000"), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.NewDec(2), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(2)), - BlockHeight: 1, - MarginToUser: sdk.NewInt(896), - ChangeReason: types.ChangeReason_ClosePosition, - ExchangedNotional: sdk.MustNewDecFromStr("-10000.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("-10000.000000000000000000"), - }), - ), - - TC("close long position with bad debt"). - Given( - CreateCustomMarket(pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.89")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - InsertPosition( - WithTrader(alice), - WithPair(pairBtcNusd), - WithSize(sdk.NewDec(10_000)), - WithMargin(sdk.NewDec(1_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - FundAccount(alice, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 18))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1000))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 102))), - ). - When( - MoveToNextBlock(), - ClosePosition(alice, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - TraderAddress: alice.String(), - Pair: pairBtcNusd, - Size_: sdk.ZeroDec(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.ZeroDec(), - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - LastUpdatedBlockNumber: 2, - }, - PositionNotional: sdk.ZeroDec(), - TransactionFee: sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 0), - RealizedPnl: sdk.MustNewDecFromStr("-1100.000088999999110000"), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(102)), - FundingPayment: sdk.NewDec(2), - BlockHeight: 2, - MarginToUser: sdk.NewInt(0), - ChangeReason: types.ChangeReason_ClosePosition, - ExchangedNotional: sdk.MustNewDecFromStr("-10000.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("-10000.000000000000000000"), - }), - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1102)), // 1000 + 102 from perp ef - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(0)), - ), - - TC("close short position with positive PnL"). - Given( - CreateCustomMarket(pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.10")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(2)))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 10_002))), - InsertPosition( - WithTrader(alice), - WithPair(pairBtcNusd), - WithSize(sdk.NewDec(-10_000)), - WithMargin(sdk.NewDec(1_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - ClosePosition(alice, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.ZeroDec(), - Size_: sdk.ZeroDec(), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - PositionNotional: sdk.ZeroDec(), - RealizedPnl: sdk.MustNewDecFromStr("8999.999989999999900000"), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.NewDec(-2), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(20)), - BlockHeight: 1, - MarginToUser: sdk.NewInt(9982), - ChangeReason: types.ChangeReason_ClosePosition, - ExchangedNotional: sdk.MustNewDecFromStr("-10000.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("10000.000000000000000000"), - }), - ), - - TC("close short position with negative PnL"). - Given( - CreateCustomMarket(pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("1.01")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(20)))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 902))), - InsertPosition( - WithTrader(alice), - WithPair(pairBtcNusd), - WithSize(sdk.NewDec(-10_000)), - WithMargin(sdk.NewDec(1_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - ). - When( - ClosePosition(alice, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcNusd, - TraderAddress: alice.String(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.ZeroDec(), - Size_: sdk.ZeroDec(), - LastUpdatedBlockNumber: 1, - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - }, - PositionNotional: sdk.ZeroDec(), - RealizedPnl: sdk.MustNewDecFromStr("-100.000101000001010000"), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.NewDec(-2), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(2)), - BlockHeight: 1, - MarginToUser: sdk.NewInt(900), - ChangeReason: types.ChangeReason_ClosePosition, - ExchangedNotional: sdk.MustNewDecFromStr("-10000.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("10000.000000000000000000"), - }), - ), - - TC("close short position with bad debt"). - Given( - CreateCustomMarket(pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("1.11")), - WithLatestMarketCPF(sdk.MustNewDecFromStr("0.0002")), - ), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - InsertPosition( - WithTrader(alice), - WithPair(pairBtcNusd), - WithSize(sdk.NewDec(-10_000)), - WithMargin(sdk.NewDec(1_000)), - WithOpenNotional(sdk.NewDec(10_000)), - ), - FundAccount(alice, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 22))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1000))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 98))), - ). - When( - MoveToNextBlock(), - ClosePosition(alice, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - TraderAddress: alice.String(), - Pair: pairBtcNusd, - Size_: sdk.ZeroDec(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.ZeroDec(), - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0.0002"), - LastUpdatedBlockNumber: 2, - }, - PositionNotional: sdk.ZeroDec(), - TransactionFee: sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 0), - RealizedPnl: sdk.MustNewDecFromStr("-1100.000111000001110000"), - BadDebt: sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 98), - FundingPayment: sdk.NewDec(-2), - BlockHeight: 2, - MarginToUser: sdk.NewInt(0), - ChangeReason: types.ChangeReason_ClosePosition, - ExchangedNotional: sdk.MustNewDecFromStr("-10000.000000000000000000"), - ExchangedSize: sdk.MustNewDecFromStr("10000.000000000000000000"), - }), - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(1098)), // 1000 + 98 from perp ef - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(0)), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} - -func TestUpdateSwapInvariant(t *testing.T) { - alice := testutil.AccAddress() - bob := testutil.AccAddress() - pairBtcNusd := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - startBlockTime := time.Now() - - startingSwapInvariant := sdk.NewInt(1e12).Mul(sdk.NewInt(1e12)) - - tc := TestCases{ - TC("only long position - no change to swap invariant"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200_000_000)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100000)))), - ). - When( - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(10_000_000_000), sdk.OneDec(), sdk.ZeroDec()), - ClosePosition(alice, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - ), - TC("only short position - no change to swap invariant"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200_000_000)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100000)))), - ). - When( - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(10_000_000_000), sdk.OneDec(), sdk.NewDec(10_000_000_000_000)), - ClosePosition(alice, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - ), - TC("only long position - increasing k"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200_000_000)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100_000_000)))), - ). - When( - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(10_000_000_000), sdk.OneDec(), sdk.ZeroDec()), - ShiftSwapInvariant(pairBtcNusd, startingSwapInvariant.MulRaw(100)), - AMMShouldBeEqual( - pairBtcNusd, - AMM_SwapInvariantShouldBeEqual(sdk.MustNewDecFromStr("100000000000000000000000000.000005462000000000"))), - ClosePosition(alice, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - ModuleBalanceShouldBeEqualTo(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.OneInt()))), - ), - TC("only short position - increasing k"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200_000_000)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100_000_000)))), - ). - When( - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(10_000_000_000), sdk.OneDec(), sdk.ZeroDec()), - ShiftSwapInvariant(pairBtcNusd, startingSwapInvariant.MulRaw(100)), - AMMShouldBeEqual( - pairBtcNusd, - AMM_SwapInvariantShouldBeEqual(sdk.MustNewDecFromStr("99999999999999999999999999.999996174000000000"))), - ClosePosition(alice, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - ModuleBalanceShouldBeEqualTo(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.OneInt()))), - ), - - TC("only long position - decreasing k"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200_000_000)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100_000_000)))), - ). - When( - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(10_000_000_000), sdk.OneDec(), sdk.ZeroDec()), - ShiftSwapInvariant( - pairBtcNusd, - startingSwapInvariant.QuoRaw(10)), - AMMShouldBeEqual( - pairBtcNusd, - AMM_SwapInvariantShouldBeEqual(sdk.MustNewDecFromStr("99999999999999999873578.871987765741755797"))), - ClosePosition(alice, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - ModuleBalanceShouldBeEqualTo(types.VaultModuleAccount, sdk.NewCoins()), - ), - TC("only short position - decreasing k"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200_000_000)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100_000_000)))), - ). - When( - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(10_000_000_000), sdk.OneDec(), sdk.ZeroDec()), - ShiftSwapInvariant(pairBtcNusd, - startingSwapInvariant.QuoRaw(10)), - AMMShouldBeEqual( - pairBtcNusd, - AMM_SwapInvariantShouldBeEqual(sdk.MustNewDecFromStr("99999999999999999873578.871987864651476452"))), - ClosePosition(alice, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - ModuleBalanceShouldBeEqualTo(types.VaultModuleAccount, sdk.NewCoins()), - ), - - TC("long and short position - increasing k"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200_000_000)))), - FundAccount(bob, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200_000_000)))), - ). - When( - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(10_000_000_000), sdk.OneDec(), sdk.ZeroDec()), - MarketOrder(bob, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(10_000_000_000), sdk.OneDec(), sdk.NewDec(10_000_000_000_000)), - - ShiftSwapInvariant(pairBtcNusd, - startingSwapInvariant.MulRaw(100)), - AMMShouldBeEqual( - pairBtcNusd, - AMM_BiasShouldBeEqual(sdk.ZeroDec()), - AMM_SwapInvariantShouldBeEqual(sdk.MustNewDecFromStr("100000000000000000000000000.000000000000000000"))), - - ModuleBalanceShouldBeEqualTo(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(19_960_000_000)))), - ModuleBalanceShouldBeEqualTo(types.FeePoolModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(20_000_000)))), // Fees are 10_000_000_000 * 0.0010 * 2 - - ClosePosition(alice, pairBtcNusd), - ClosePosition(bob, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - PositionShouldNotExist(bob, pairBtcNusd, 1), - - ModuleBalanceShouldBeEqualTo(types.VaultModuleAccount, sdk.NewCoins()), - ModuleBalanceShouldBeEqualTo(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(39_960_000)))), - ), - TC("long and short position - reducing k"). - Given( - CreateCustomMarket(pairBtcNusd, WithEnabled(true)), - SetBlockTime(startBlockTime), - SetBlockNumber(1), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200_000_000)))), - FundAccount(bob, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200_000_000)))), - ). - When( - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(10_000_000_000), sdk.OneDec(), sdk.ZeroDec()), - MarketOrder(bob, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(10_000_000_000), sdk.OneDec(), sdk.NewDec(10_000_000_000_000)), - - ShiftSwapInvariant(pairBtcNusd, - startingSwapInvariant.QuoRaw(10)), - AMMShouldBeEqual( - pairBtcNusd, - AMM_BiasShouldBeEqual(sdk.ZeroDec()), - AMM_SwapInvariantShouldBeEqual(sdk.MustNewDecFromStr("99999999999999999873578.871987712489000000"))), - - ModuleBalanceShouldBeEqualTo(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(19_960_000_000)))), - ModuleBalanceShouldBeEqualTo(types.FeePoolModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(20_000_000)))), // Fees are 10_000_000_000 * 0.0010 * 2 - - ClosePosition(alice, pairBtcNusd), - ClosePosition(bob, pairBtcNusd), - ). - Then( - PositionShouldNotExist(alice, pairBtcNusd, 1), - PositionShouldNotExist(bob, pairBtcNusd, 1), - - ModuleBalanceShouldBeEqualTo(types.VaultModuleAccount, sdk.NewCoins()), - ModuleBalanceShouldBeEqualTo(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(39_960_000)))), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} diff --git a/x/perp/v2/keeper/dnr.go b/x/perp/v2/keeper/dnr.go deleted file mode 100644 index e9d687191..000000000 --- a/x/perp/v2/keeper/dnr.go +++ /dev/null @@ -1,202 +0,0 @@ -package keeper - -import ( - "cosmossdk.io/math" - "github.com/NibiruChain/collections" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/perp/v2/types" - - "github.com/NibiruChain/nibiru/x/common/asset" -) - -// maybeUpdateDnREpoch checks if the current epoch hook call matches the -// epoch name that targets discounts and rebates, if it does then we simply -// invoke the StartNewEpoch function to kickstart a new epoch. -// This method is invoked by the AfterEpochEnd hook. -func (k Keeper) maybeUpdateDnREpoch(ctx sdk.Context, epochIdentifier string, number uint64) { - // if epoch name is empty, we just assume DnR is not enabled. - referenceEpochName := k.DnREpochName.GetOr(ctx, "") - if referenceEpochName != epochIdentifier { - return - } - // kickstart new epoch - k.Logger(ctx).Info("updating dnr epoch", "epochIdentifier", epochIdentifier, "number", number) - err := k.StartNewEpoch(ctx, number) - if err != nil { - // in case of error we panic in this case, because state may have been updated - // in a corrupted way. - panic(err) - } -} - -// StartNewEpoch is called by the epochs hooks when a new 30day epoch starts. -func (k Keeper) StartNewEpoch(ctx sdk.Context, identifier uint64) error { - // set the current epoch - k.DnREpoch.Set(ctx, identifier) - // we now check the rebates allocated for the previous epoch, - // and move them to the escrow such that they can be claimed lazily - // by users. - previousEpoch := identifier - 1 - allocationAddr := k.AccountKeeper.GetModuleAddress(types.DNRAllocationModuleAccount) - allocationBalance := k.BankKeeper.GetAllBalances(ctx, allocationAddr) - err := k.BankKeeper.SendCoinsFromModuleToModule(ctx, types.DNRAllocationModuleAccount, types.DNREscrowModuleAccount, allocationBalance) - if err != nil { - return err - } - k.EpochRebateAllocations.Insert(ctx, previousEpoch, types.DNRAllocation{ - Epoch: previousEpoch, - Amount: allocationBalance, - }) - return nil -} - -// IncreaseTraderVolume adds the volume to the user's volume for the current epoch. -// It also increases the global volume for the current epoch. -func (k Keeper) IncreaseTraderVolume(ctx sdk.Context, currentEpoch uint64, user sdk.AccAddress, volume math.Int) { - currentVolume := k.TraderVolumes.GetOr(ctx, collections.Join(user, currentEpoch), math.ZeroInt()) - newVolume := currentVolume.Add(volume) - k.TraderVolumes.Insert(ctx, collections.Join(user, currentEpoch), newVolume) - k.GlobalVolumes.Insert(ctx, currentEpoch, k.GlobalVolumes.GetOr(ctx, currentEpoch, math.ZeroInt()).Add(volume)) -} - -// GetTraderVolumeLastEpoch returns the user's volume for the last epoch. -// Returns zero if the user has no volume for the last epoch. -func (k Keeper) GetTraderVolumeLastEpoch(ctx sdk.Context, currentEpoch uint64, user sdk.AccAddress) math.Int { - // if it's the first epoch, we do not have any user volume. - if currentEpoch == 0 { - return math.ZeroInt() - } - // return the user's volume for the last epoch, or zero. - return k.TraderVolumes.GetOr(ctx, collections.Join(user, currentEpoch-1), math.ZeroInt()) -} - -// GetTraderDiscount will check if the trader has a custom discount for the given volume. -// If it does not have a custom discount, it will return the global discount for the given volume. -// The discount is the nearest left entry of the trader volume. -func (k Keeper) GetTraderDiscount(ctx sdk.Context, trader sdk.AccAddress, volume math.Int) (math.LegacyDec, bool) { - // we try to see if the trader has a custom discount. - customDiscountRng := collections.PairRange[sdk.AccAddress, math.Int]{}. - Prefix(trader). - EndInclusive(volume). - Descending() - - customDiscount := k.TraderDiscounts.Iterate(ctx, customDiscountRng) - defer customDiscount.Close() - - if customDiscount.Valid() { - return customDiscount.Value(), true - } - - // if it does not have a custom discount we try with global ones - globalDiscountRng := collections.Range[math.Int]{}. - EndInclusive(volume). - Descending() - - globalDiscounts := k.GlobalDiscounts.Iterate(ctx, globalDiscountRng) - defer globalDiscounts.Close() - - if globalDiscounts.Valid() { - return globalDiscounts.Value(), true - } - return math.LegacyZeroDec(), false -} - -// calculateDiscount applies the discount to the given exchange fee ratio. -// It updates the current epoch trader volume. -// It returns the new exchange fee ratio. -func (k Keeper) calculateDiscount( - ctx sdk.Context, - _ asset.Pair, - trader sdk.AccAddress, - positionNotional math.LegacyDec, - feeRatio sdk.Dec, -) (sdk.Dec, error) { - // update user volume - dnrEpoch, err := k.DnREpoch.Get(ctx) - if err != nil { - return feeRatio, err - } - k.IncreaseTraderVolume(ctx, dnrEpoch, trader, positionNotional.Abs().TruncateInt()) - - // get past epoch volume - pastVolume := k.GetTraderVolumeLastEpoch(ctx, dnrEpoch, trader) - // if the trader has no volume for the last epoch, we return the provided fee ratios. - if pastVolume.IsZero() { - return feeRatio, nil - } - - // try to apply discount - discountedFeeRatio, hasDiscount := k.GetTraderDiscount(ctx, trader, pastVolume) - // if the trader does not have any discount, we return the provided fee ratios. - if !hasDiscount { - return feeRatio, nil - } - // return discounted fee ratios - return discountedFeeRatio, nil -} - -// WithdrawEpochRebates will withdraw the user's rebates for the given epoch. -func (k Keeper) WithdrawEpochRebates(ctx sdk.Context, epoch uint64, addr sdk.AccAddress) (withdrawn sdk.Coins, err error) { - // get the allocation for the epoch, this also ensures that if the user is trying to withdraw - // from current epoch the function immediately fails. - allocationCoins, err := k.EpochRebateAllocations.Get(ctx, epoch) - if err != nil { - return nil, err - } - - // compute user weight - weight, err := k.computeUserWeight(ctx, addr, epoch) - if err != nil { - return nil, err - } - if weight.IsZero() { - return sdk.NewCoins(), nil - } - - // calculate coins to distribute based on user weight - distrCoins := sdk.NewCoins() - for _, coin := range allocationCoins.Amount { - amt := coin.Amount.ToLegacyDec().Mul(weight).TruncateInt() - distrCoins = distrCoins.Add(sdk.NewCoin(coin.Denom, amt)) - } - - // send money to user from escrow only in case there's anything to distribute. - // this should never happen, since we're checking if the user has any weight. - if !distrCoins.IsZero() { - err = k.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.DNREscrowModuleAccount, addr, distrCoins) - if err != nil { - return nil, err - } - } - - // garbage collect user volume. This ensures state is not bloated, - // and that the user cannot claim from the same allocation twice. - return distrCoins, k.TraderVolumes.Delete(ctx, collections.Join(addr, epoch)) -} - -// computeUserWeight computes the user's weight for the given epoch. -func (k Keeper) computeUserWeight(ctx sdk.Context, addr sdk.AccAddress, epoch uint64) (math.LegacyDec, error) { - // get user volume for the epoch - userVolume := k.TraderVolumes.GetOr(ctx, collections.Join(addr, epoch), math.ZeroInt()) - if userVolume.IsZero() { - return math.LegacyZeroDec(), nil - } - - // calculate the user's share - globalVolume, err := k.GlobalVolumes.Get(ctx, epoch) - if err != nil { - return math.LegacyDec{}, err - } - weight := userVolume.ToLegacyDec().Quo(globalVolume.ToLegacyDec()) - return weight, nil -} - -// AllocateEpochRebates will allocate the given amount of coins to the current epoch. -func (k Keeper) AllocateEpochRebates(ctx sdk.Context, sender sdk.AccAddress, amount sdk.Coins) (total sdk.Coins, err error) { - err = k.BankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.DNRAllocationModuleAccount, amount) - if err != nil { - return sdk.Coins{}, err - } - return k.BankKeeper.GetAllBalances(ctx, k.AccountKeeper.GetModuleAddress(types.DNRAllocationModuleAccount)), nil -} diff --git a/x/perp/v2/keeper/dnr_test.go b/x/perp/v2/keeper/dnr_test.go deleted file mode 100644 index ced828f7c..000000000 --- a/x/perp/v2/keeper/dnr_test.go +++ /dev/null @@ -1,303 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/app" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - . "github.com/NibiruChain/nibiru/x/common/testutil/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/action" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func TestUserVolumes(t *testing.T) { - alice := testutil.AccAddress() - pairBtcNusd := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - positionSize := sdk.NewInt(10_000) - startBlockTime := time.Now() - - tests := TestCases{ - TC("user volume correctly sets the first time and the second time"). - Given( - DnREpochIs(1), - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, positionSize.AddRaw(1000)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100_000_000)))), - ). - When( - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(10_000), sdk.OneDec(), sdk.ZeroDec()), - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(10_000), sdk.OneDec(), sdk.ZeroDec()), - ). - Then( - DnRCurrentVolumeIs(alice, positionSize.MulRaw(2)), - ), - TC("user volume correctly sets across epochs"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, positionSize.AddRaw(1000)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100_000_000)))), - ). - When( - DnREpochIs(1), - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(10_000), sdk.OneDec(), sdk.ZeroDec()), // open epoch 1 - DnREpochIs(2), - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(10_000), sdk.OneDec(), sdk.ZeroDec()), // close epoch 2 - ). - Then( - DnRCurrentVolumeIs(alice, positionSize), - DnRPreviousVolumeIs(alice, positionSize), - ), - TC("user volume is correctly cleaned up"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, positionSize.AddRaw(1000)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100_000_000)))), - ).When( - DnREpochIs(1), - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(10_000), sdk.OneDec(), sdk.ZeroDec()), // open epoch 1 - DnREpochIs(2), - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(5_000), sdk.OneDec(), sdk.ZeroDec()), // reduce epoch 2 - DnREpochIs(3), - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(2_000), sdk.OneDec(), sdk.ZeroDec()), // reduce epoch 3 - MarketOrder(alice, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(2_000), sdk.OneDec(), sdk.ZeroDec()), // reduce more epoch 3 - ). - Then( - DnRCurrentVolumeIs(alice, math.NewInt(4000)), // for current epoch only 4k in volume. - DnRPreviousVolumeIs(alice, math.NewInt(5000)), // for previous epoch only 5k in volume. - ), - } - NewTestSuite(t).WithTestCases(tests...).Run() -} - -func TestDiscount(t *testing.T) { - alice := testutil.AccAddress() - pairBtcNusd := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - positionSize := sdk.NewInt(10_000) - startBlockTime := time.Now() - - exchangeFee := sdk.MustNewDecFromStr("0.0010") // 0.1%, default fee taken from CreateCustomMarketAction - globalFeeDiscount := sdk.MustNewDecFromStr("0.0005") // 0.05% - fauxGlobalFeeDiscount := sdk.MustNewDecFromStr("0.0006") // 0.06% - customFeeDiscount := sdk.MustNewDecFromStr("0.0002") // 0.02% - fauxCustomFeeDiscount := sdk.MustNewDecFromStr("0.0003") // 0.03% - - tests := TestCases{ - TC("user does not have any past epoch volume: no discount applies"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, positionSize.AddRaw(1000)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100_000_000)))), - ). - When( - DnREpochIs(1), - ). - Then( - MarketOrderFeeIs(exchangeFee, alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(10_000), sdk.OneDec(), sdk.ZeroDec()), - ), - TC("user has past epoch volume: no discount applies"). - Given( - DnREpochIs(2), - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, positionSize.AddRaw(1000)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100_000_000)))), - ). - When( - SetGlobalDiscount(fauxGlobalFeeDiscount, sdk.NewInt(50_000)), - SetGlobalDiscount(globalFeeDiscount, sdk.NewInt(100_000)), - SetCustomDiscount(alice, fauxCustomFeeDiscount, sdk.NewInt(50_000)), - SetCustomDiscount(alice, customFeeDiscount, sdk.NewInt(100_000)), - SetPreviousEpochUserVolume(alice, sdk.NewInt(10_000)), // lower than 50_000 - ). - Then( - MarketOrderFeeIs(exchangeFee, alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(10_000), sdk.OneDec(), sdk.ZeroDec()), - ), - TC("user has past epoch volume: custom discount applies"). - Given( - DnREpochIs(2), - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, positionSize.AddRaw(1000)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100_000_000)))), - ). - When( - SetGlobalDiscount(globalFeeDiscount, sdk.NewInt(50_000)), - SetGlobalDiscount(fauxGlobalFeeDiscount, sdk.NewInt(100_000)), - SetCustomDiscount(alice, fauxCustomFeeDiscount, sdk.NewInt(50_000)), - SetCustomDiscount(alice, customFeeDiscount, sdk.NewInt(100_000)), - SetPreviousEpochUserVolume(alice, sdk.NewInt(100_001)), - ). - Then( - MarketOrderFeeIs(customFeeDiscount, alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(10_000), sdk.OneDec(), sdk.ZeroDec()), - ), - TC("user has past epoch volume: global discount applies"). - Given( - DnREpochIs(2), - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, positionSize.AddRaw(1000)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(100_000_000)))), - ). - When( - SetGlobalDiscount(sdk.MustNewDecFromStr("0.0004"), sdk.NewInt(50_000)), - SetGlobalDiscount(globalFeeDiscount, sdk.NewInt(100_000)), - SetPreviousEpochUserVolume(alice, sdk.NewInt(100_000)), - ). - Then( - MarketOrderFeeIs(globalFeeDiscount, alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(10_000), sdk.OneDec(), sdk.ZeroDec()), - ), - } - NewTestSuite(t).WithTestCases(tests...).Run() -} - -func TestRebates(t *testing.T) { - alice := testutil.AccAddress() - bob := testutil.AccAddress() - - pairBtcNusd := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - positionSize := sdk.NewInt(10_000) - startBlockTime := time.Now() - - allocation := sdk.NewCoins(sdk.NewCoin(denoms.NUSD, sdk.NewInt(1_000_000))) - - tests := TestCases{ - TC("rebates correctly apply"). - Given( - CreateCustomMarket( - pairBtcNusd, - WithEnabled(true), - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - ), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, positionSize.AddRaw(100_000)))), - FundAccount(bob, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, positionSize.AddRaw(100_000)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(denoms.NUSD, sdk.NewInt(100_000_000)))), - ). - When( - DnREpochIs(1), - FundDnREpoch(allocation), - MarketOrder(alice, pairBtcNusd, types.Direction_LONG, sdk.NewInt(10_000), sdk.OneDec(), sdk.ZeroDec()), - MarketOrder(bob, pairBtcNusd, types.Direction_SHORT, sdk.NewInt(30_000), sdk.OneDec(), sdk.ZeroDec()), - StartNewDnREpoch(), - ). - Then( - DnRRebateIs(alice, 1, allocation.QuoInt(sdk.NewInt(4))), // 1/4 of the allocation - DnRRebateIs(bob, 1, allocation.QuoInt(sdk.NewInt(4)).MulInt(sdk.NewInt(3))), // 3/4 of the allocation - DnRRebateIs(alice, 1, sdk.NewCoins()), // can only claim once - DnREpochIs(2), - DnRRebateIs(alice, 1, sdk.NewCoins()), // claiming again after the epoch is not possible. - ), - } - NewTestSuite(t).WithTestCases(tests...).Run() -} - -type actionFn func(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) - -func (f actionFn) Do(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) { - return f(app, ctx) -} - -func TestDnREpoch(t *testing.T) { - dnrEpochIdentifierIs := func(identifier string) actionFn { - return func(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) { - app.PerpKeeperV2.DnREpochName.Set(ctx, identifier) - return ctx, nil - } - } - - triggerEpoch := func(identifier string, epoch uint64) actionFn { - return func(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) { - app.PerpKeeperV2.AfterEpochEnd(ctx, identifier, epoch) - return ctx, nil - } - } - - expectDnREpoch := func(epoch uint64) actionFn { - return func(app *app.NibiruApp, ctx sdk.Context) (outCtx sdk.Context, err error) { - require.Equal(t, epoch, app.PerpKeeperV2.DnREpoch.GetOr(ctx, 0)) - return ctx, nil - } - } - - tests := TestCases{ - TC("DnR epoch with valid identifier"). - When( - dnrEpochIdentifierIs("monthly"), - triggerEpoch("monthly", 1)). - Then( - expectDnREpoch(1), - ), - TC("DnR epoch with invalid identifier"). - When( - dnrEpochIdentifierIs("monthly"), - triggerEpoch("weekly", 1)). - Then( - expectDnREpoch(0), - ), - } - NewTestSuite(t).WithTestCases(tests...).Run() -} diff --git a/x/perp/v2/keeper/fixture_test.go b/x/perp/v2/keeper/fixture_test.go deleted file mode 100644 index 942926490..000000000 --- a/x/perp/v2/keeper/fixture_test.go +++ /dev/null @@ -1 +0,0 @@ -package keeper_test diff --git a/x/perp/v2/keeper/grpc_query.go b/x/perp/v2/keeper/grpc_query.go deleted file mode 100644 index 6ec57c4fb..000000000 --- a/x/perp/v2/keeper/grpc_query.go +++ /dev/null @@ -1,202 +0,0 @@ -package keeper - -import ( - "context" - - "github.com/NibiruChain/collections" - - storeprefix "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkquery "github.com/cosmos/cosmos-sdk/types/query" - - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - grpccodes "google.golang.org/grpc/codes" - grpcstatus "google.golang.org/grpc/status" - - "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/common/asset" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -type queryServer struct { - k Keeper -} - -func NewQuerier(k Keeper) types.QueryServer { - return queryServer{k: k} -} - -var _ types.QueryServer = queryServer{} - -func (q queryServer) QueryPositions( - goCtx context.Context, req *types.QueryPositionsRequest, -) (*types.QueryPositionsResponse, error) { - if req == nil { - return nil, grpcstatus.Error(grpccodes.InvalidArgument, "nil request") - } - traderAddr, err := sdk.AccAddressFromBech32(req.Trader) // just for validation purposes - if err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - - markets := q.k.Markets.Iterate(ctx, collections.Range[collections.Pair[asset.Pair, uint64]]{}).Values() - - var positions []types.QueryPositionResponse - for _, market := range markets { - amm, err := q.k.GetAMM(ctx, market.Pair) - if err != nil { - return nil, err - } - position, err := q.position(ctx, market.Pair, traderAddr, market, amm) - if err == nil { - positions = append(positions, position) - } - } - - return &types.QueryPositionsResponse{ - Positions: positions, - }, nil -} - -func (q queryServer) QueryPosition( - goCtx context.Context, req *types.QueryPositionRequest, -) (*types.QueryPositionResponse, error) { - if req == nil { - return nil, grpcstatus.Error(grpccodes.InvalidArgument, "nil request") - } - traderAddr, err := sdk.AccAddressFromBech32(req.Trader) // just for validation purposes - if err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - - market, err := q.k.GetMarket(ctx, req.Pair) - if err != nil { - return nil, err - } - - amm, err := q.k.GetAMM(ctx, req.Pair) - if err != nil { - return nil, err - } - - resp, err := q.position(ctx, req.Pair, traderAddr, market, amm) - return &resp, err -} - -func (q queryServer) QueryPositionStore( - goCtx context.Context, req *types.QueryPositionStoreRequest, -) (resp *types.QueryPositionStoreResponse, err error) { - if req == nil { - return nil, grpcstatus.Error(grpccodes.InvalidArgument, "nil request") - } - - ctx := sdk.UnwrapSDKContext(goCtx) - store := storeprefix.NewStore(ctx.KVStore(q.k.storeKey), NamespacePositions.Prefix()) - - pagination, _, err := common.ParsePagination(req.Pagination) - if err != nil { - return resp, grpcstatus.Error(grpccodes.InvalidArgument, err.Error()) - } - - var respPayload []types.Position - pageRes, err := sdkquery.Paginate(store, pagination, func(key, value []byte) error { - pos := new(types.Position) - if err := q.k.cdc.Unmarshal(value, pos); err != nil { - return grpcstatus.Error(grpccodes.Internal, err.Error()) - } - respPayload = append(respPayload, *pos) - return nil - }) - if err != nil { - return resp, err - } - - return &types.QueryPositionStoreResponse{ - Positions: respPayload, - Pagination: pageRes, - }, err -} - -func (q queryServer) position(ctx sdk.Context, pair asset.Pair, trader sdk.AccAddress, market types.Market, amm types.AMM) (types.QueryPositionResponse, error) { - position, err := q.k.GetPosition(ctx, pair, market.Version, trader) - if err != nil { - return types.QueryPositionResponse{}, err - } - - positionNotional, err := PositionNotionalSpot(amm, position) - if err != nil { - return types.QueryPositionResponse{}, err - } - unrealizedPnl := UnrealizedPnl(position, positionNotional) - - return types.QueryPositionResponse{ - Position: position, - PositionNotional: positionNotional, - UnrealizedPnl: unrealizedPnl, - MarginRatio: MarginRatio(position, positionNotional, market.LatestCumulativePremiumFraction), - }, nil -} - -func (q queryServer) ModuleAccounts( - ctx context.Context, _ *types.QueryModuleAccountsRequest, -) (*types.QueryModuleAccountsResponse, error) { - sdkContext := sdk.UnwrapSDKContext(ctx) - - var moduleAccountsWithBalances []types.AccountWithBalance - for _, acc := range types.ModuleAccounts { - account := authtypes.NewModuleAddress(acc) - - balances := q.k.BankKeeper.GetAllBalances(sdkContext, account) - - accWithBalance := types.AccountWithBalance{ - Name: acc, - Address: account.String(), - Balance: balances, - } - moduleAccountsWithBalances = append(moduleAccountsWithBalances, accWithBalance) - } - - return &types.QueryModuleAccountsResponse{Accounts: moduleAccountsWithBalances}, nil -} - -func (q queryServer) QueryMarkets( - goCtx context.Context, req *types.QueryMarketsRequest, -) (*types.QueryMarketsResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - var ammMarkets []types.AmmMarket - markets := q.k.Markets.Iterate(ctx, collections.Range[collections.Pair[asset.Pair, uint64]]{}).Values() - for _, market := range markets { - // disabled markets are not returned - if !req.Versioned && !market.Enabled { - continue - } - - pair := market.Pair - amm, err := q.k.AMMs.Get(ctx, collections.Join(pair, market.Version)) - if err != nil { - return nil, err - } - duo := types.AmmMarket{ - Amm: amm, - Market: market, - } - ammMarkets = append(ammMarkets, duo) - } - - return &types.QueryMarketsResponse{AmmMarkets: ammMarkets}, nil -} - -func (q queryServer) QueryCollateral( - goCtx context.Context, req *types.QueryCollateralRequest, -) (*types.QueryCollateralResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - denom := q.k.Collateral.GetOr(ctx, "") - return &types.QueryCollateralResponse{ - CollateralDenom: denom, - }, nil -} diff --git a/x/perp/v2/keeper/grpc_query_test.go b/x/perp/v2/keeper/grpc_query_test.go deleted file mode 100644 index 80f119641..000000000 --- a/x/perp/v2/keeper/grpc_query_test.go +++ /dev/null @@ -1,488 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkquery "github.com/cosmos/cosmos-sdk/types/query" - - "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - . "github.com/NibiruChain/nibiru/x/common/testutil/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/action" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func TestQueryPositions(t *testing.T) { - alice := testutil.AccAddress() - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - pair2 := asset.Registry.Pair(denoms.ETH, denoms.NUSD) - - tc := TestCases{ - TC("positive PnL"). - Given( - CreateCustomMarket( - pair, - WithEnabled(true), - WithPricePeg(sdk.NewDec(2)), - ), - CreateCustomMarket( - pair2, - WithEnabled(true), - WithPricePeg(sdk.NewDec(3)), - ), - ). - When( - InsertPosition( - WithPair(pair), - WithTrader(alice), - WithMargin(sdk.OneDec()), - WithSize(sdk.NewDec(10)), - WithOpenNotional(sdk.NewDec(10)), - ), - InsertPosition( - WithPair(pair2), - WithTrader(alice), - WithMargin(sdk.OneDec()), - WithSize(sdk.NewDec(10)), - WithOpenNotional(sdk.NewDec(10)), - ), - ). - Then( - QueryPositions(alice, - []QueryPositionChecker{ - QueryPosition_PositionEquals(types.Position{ - Pair: pair, - TraderAddress: alice.String(), - Size_: sdk.NewDec(10), - Margin: sdk.OneDec(), - OpenNotional: sdk.NewDec(10), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - }), - QueryPosition_PositionNotionalEquals(sdk.MustNewDecFromStr("19.9999999998")), - QueryPosition_UnrealizedPnlEquals(sdk.MustNewDecFromStr("9.9999999998")), - QueryPosition_MarginRatioEquals(sdk.MustNewDecFromStr("0.5499999999955")), - }, - []QueryPositionChecker{ - QueryPosition_PositionEquals(types.Position{ - Pair: pair2, - TraderAddress: alice.String(), - Size_: sdk.NewDec(10), - Margin: sdk.OneDec(), - OpenNotional: sdk.NewDec(10), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - }), - QueryPosition_PositionNotionalEquals(sdk.MustNewDecFromStr("29.9999999997")), - QueryPosition_UnrealizedPnlEquals(sdk.MustNewDecFromStr("19.9999999997")), - QueryPosition_MarginRatioEquals(sdk.MustNewDecFromStr("0.699999999997")), - }, - ), - ), - - TC("negative PnL, positive margin ratio"). - Given( - CreateCustomMarket( - pair, - WithEnabled(true), - WithPricePeg(sdk.OneDec()), - ), - CreateCustomMarket( - pair2, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.95")), - ), - ). - When( - InsertPosition( - WithPair(pair), - WithTrader(alice), - WithMargin(sdk.OneDec()), - WithSize(sdk.NewDec(10)), - WithOpenNotional(sdk.NewDec(10)), - ), - InsertPosition( - WithPair(pair2), - WithTrader(alice), - WithMargin(sdk.OneDec()), - WithSize(sdk.NewDec(10)), - WithOpenNotional(sdk.NewDec(10)), - ), - ). - Then( - QueryPositions(alice, - []QueryPositionChecker{ - QueryPosition_PositionEquals(types.Position{ - Pair: pair, - TraderAddress: alice.String(), - Size_: sdk.NewDec(10), - Margin: sdk.OneDec(), - OpenNotional: sdk.NewDec(10), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - }), - QueryPosition_PositionNotionalEquals(sdk.MustNewDecFromStr("9.9999999999")), - QueryPosition_UnrealizedPnlEquals(sdk.MustNewDecFromStr("-0.0000000001")), - QueryPosition_MarginRatioEquals(sdk.MustNewDecFromStr("0.099999999991")), - }, - []QueryPositionChecker{ - QueryPosition_PositionEquals(types.Position{ - Pair: pair2, - TraderAddress: alice.String(), - Size_: sdk.NewDec(10), - Margin: sdk.OneDec(), - OpenNotional: sdk.NewDec(10), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - }), - QueryPosition_PositionNotionalEquals(sdk.MustNewDecFromStr("9.499999999905")), - QueryPosition_UnrealizedPnlEquals(sdk.MustNewDecFromStr("-0.500000000095")), - QueryPosition_MarginRatioEquals(sdk.MustNewDecFromStr("0.052631578937894737")), - }, - ), - ), - - TC("negative PnL, negative margin ratio"). - Given( - CreateCustomMarket( - pair, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.5")), - ), - CreateCustomMarket( - pair2, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.9")), - ), - ). - When( - InsertPosition( - WithPair(pair), - WithTrader(alice), - WithMargin(sdk.OneDec()), - WithSize(sdk.NewDec(10)), - WithOpenNotional(sdk.NewDec(10)), - ), - InsertPosition( - WithPair(pair2), - WithTrader(alice), - WithMargin(sdk.OneDec()), - WithSize(sdk.NewDec(10)), - WithOpenNotional(sdk.NewDec(10)), - ), - ). - Then( - QueryPositions(alice, - []QueryPositionChecker{ - QueryPosition_PositionEquals(types.Position{ - Pair: pair, - TraderAddress: alice.String(), - Size_: sdk.NewDec(10), - Margin: sdk.OneDec(), - OpenNotional: sdk.NewDec(10), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - }), - QueryPosition_PositionNotionalEquals(sdk.MustNewDecFromStr("4.99999999995")), - QueryPosition_UnrealizedPnlEquals(sdk.MustNewDecFromStr("-5.00000000005")), - QueryPosition_MarginRatioEquals(sdk.MustNewDecFromStr("-0.800000000018")), - }, - []QueryPositionChecker{ - QueryPosition_PositionEquals(types.Position{ - Pair: pair2, - TraderAddress: alice.String(), - Size_: sdk.NewDec(10), - Margin: sdk.OneDec(), - OpenNotional: sdk.NewDec(10), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - }), - QueryPosition_PositionNotionalEquals(sdk.MustNewDecFromStr("8.99999999991")), - QueryPosition_UnrealizedPnlEquals(sdk.MustNewDecFromStr("-1.00000000009")), - QueryPosition_MarginRatioEquals(sdk.MustNewDecFromStr("-0.00000000001")), - }, - ), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} - -func TestQueryPosition(t *testing.T) { - alice := testutil.AccAddress() - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - - tc := TestCases{ - TC("positive PnL"). - Given( - CreateCustomMarket( - pair, - WithEnabled(true), - WithPricePeg(sdk.NewDec(2)), - ), - ). - When( - InsertPosition( - WithPair(pair), - WithTrader(alice), - WithMargin(sdk.OneDec()), - WithSize(sdk.NewDec(10)), - WithOpenNotional(sdk.NewDec(10)), - ), - ). - Then( - QueryPosition(pair, alice, - QueryPosition_PositionEquals(types.Position{ - Pair: pair, - TraderAddress: alice.String(), - Size_: sdk.NewDec(10), - Margin: sdk.OneDec(), - OpenNotional: sdk.NewDec(10), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - }), - QueryPosition_PositionNotionalEquals(sdk.MustNewDecFromStr("19.9999999998")), - QueryPosition_UnrealizedPnlEquals(sdk.MustNewDecFromStr("9.9999999998")), - QueryPosition_MarginRatioEquals(sdk.MustNewDecFromStr("0.5499999999955")), - ), - ), - - TC("negative PnL, positive margin ratio"). - Given( - CreateCustomMarket( - pair, - WithEnabled(true), - WithPricePeg(sdk.OneDec()), - ), - ). - When( - InsertPosition( - WithPair(pair), - WithTrader(alice), - WithMargin(sdk.OneDec()), - WithSize(sdk.NewDec(10)), - WithOpenNotional(sdk.NewDec(10)), - ), - ). - Then( - QueryPosition(pair, alice, - QueryPosition_PositionEquals(types.Position{ - Pair: pair, - TraderAddress: alice.String(), - Size_: sdk.NewDec(10), - Margin: sdk.OneDec(), - OpenNotional: sdk.NewDec(10), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - }), - QueryPosition_PositionNotionalEquals(sdk.MustNewDecFromStr("9.9999999999")), - QueryPosition_UnrealizedPnlEquals(sdk.MustNewDecFromStr("-0.0000000001")), - QueryPosition_MarginRatioEquals(sdk.MustNewDecFromStr("0.099999999991")), - ), - ), - - TC("negative PnL, negative margin ratio"). - Given( - CreateCustomMarket( - pair, - WithEnabled(true), - WithPricePeg(sdk.MustNewDecFromStr("0.5")), - ), - ). - When( - InsertPosition( - WithPair(pair), - WithTrader(alice), - WithMargin(sdk.OneDec()), - WithSize(sdk.NewDec(10)), - WithOpenNotional(sdk.NewDec(10)), - ), - ). - Then( - QueryPosition(pair, alice, - QueryPosition_PositionEquals(types.Position{ - Pair: pair, - TraderAddress: alice.String(), - Size_: sdk.NewDec(10), - Margin: sdk.OneDec(), - OpenNotional: sdk.NewDec(10), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - }), - QueryPosition_PositionNotionalEquals(sdk.MustNewDecFromStr("4.99999999995")), - QueryPosition_UnrealizedPnlEquals(sdk.MustNewDecFromStr("-5.00000000005")), - QueryPosition_MarginRatioEquals(sdk.MustNewDecFromStr("-0.800000000018")), - ), - ), - - TC("non existent position"). - Given( - CreateCustomMarket( - pair, - WithEnabled(true), - WithPricePeg(sdk.NewDec(2)), - ), - ). - When(). - Then( - QueryPositionNotFound(pair, alice), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} - -func TestQueryMarkets(t *testing.T) { - alice := testutil.AccAddress() - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - - tc := TestCases{ - TC("positive PnL"). - Given( - CreateCustomMarket( - pair, - WithEnabled(true), - WithPricePeg(sdk.NewDec(2)), - ), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(denoms.NUSD, sdk.NewInt(10)))), - ). - When( - InsertPosition( - WithPair(pair), - WithTrader(alice), - WithMargin(sdk.OneDec()), - WithSize(sdk.NewDec(10)), - WithOpenNotional(sdk.NewDec(10)), - ), - ). - Then( - QueryMarkets(false, QueryMarkets_MarketsShouldContain( - types.DefaultMarket(pair).WithEnabled(true)), - ), - QueryModuleAccounts(QueryModuleAccounts_ModulesBalanceShouldBe( - map[string]sdk.Coins{ - types.PerpFundModuleAccount: sdk.NewCoins( - sdk.NewCoin(denoms.BTC, sdk.ZeroInt()), - sdk.NewCoin(denoms.NUSD, sdk.NewInt(10)), - ), - }, - )), - ), - TC("versioned, all markets (active and inactive)").Given( - CreateCustomMarket("BTC:USD", WithVersion(1), WithEnabled(true)), - CreateCustomMarket("ETC:USD", WithVersion(1), WithEnabled(false)), - CreateCustomMarket("ETC:USD", WithVersion(2), WithEnabled(true)), - ).Then( - QueryMarkets(true, QueryMarkets_ShouldLength(3)), - ), - TC("not versioned, only active markets").Given( - CreateCustomMarket("BTC:USD", WithVersion(1), WithEnabled(true)), - CreateCustomMarket("ETC:USD", WithVersion(1), WithEnabled(false)), - CreateCustomMarket("ETC:USD", WithVersion(2), WithEnabled(true)), - ).Then( - QueryMarkets(true, QueryMarkets_ShouldLength(3)), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} - -func TestQueryPositionStore(t *testing.T) { - pairs := []asset.Pair{ - asset.Registry.Pair(denoms.BTC, denoms.NUSD), - asset.Registry.Pair(denoms.ETH, denoms.NUSD), - asset.Registry.Pair(denoms.NIBI, denoms.NUSD), - } - - insertManyPositions := func(num int, pair asset.Pair) []Action { - var actions []Action - for idx := 0; idx < num; idx++ { - insertAction := InsertPosition(WithPair(pair)) - actions = append(actions, insertAction) - } - - return actions - } - - tc := TestCases{ - TC("paginated positions in state"). - Given( - CreateCustomMarket(pairs[0], WithEnabled(true)), - CreateCustomMarket(pairs[1], WithEnabled(true)), - CreateCustomMarket(pairs[2], WithEnabled(true)), - ). - When( - InsertPosition(WithPair(pairs[2])), - InsertPosition(WithPair(pairs[1])), - InsertPosition(WithPair(pairs[2])), - ). - Then( - QueryPositionStore(&sdkquery.PageRequest{}, false, CheckPositionStore_NumPositions(3)), - ), - - TC("get default number of positions per page"). - Given( - CreateCustomMarket(pairs[2], WithEnabled(true)), - ). - When( - insertManyPositions(99, pairs[2])..., - ). - Then( - QueryPositionStore(&sdkquery.PageRequest{}, false, - CheckPositionStore_NumPositions(int(common.DefaultPageItemsLimit)), - ), - ), - - TC("invalid request (key and offset defined)"). - Given( - CreateCustomMarket(pairs[2], WithEnabled(true)), - ). - When( - insertManyPositions(2, pairs[2])..., - ). - Then( - QueryPositionStore(&sdkquery.PageRequest{ - Key: []byte{}, Offset: 25, - }, true, - ), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} - -func TestQueryCollateral(t *testing.T) { - tc := TestCases{ - TC("state starts as expected with the mock NUSD denomination"). - Given(). - When(). - Then( - QueryCollateral(types.TestingCollateralDenomNUSD), - ), - - TC("expected value returned after collateral denom changes"). - Given(). - When( - SetCollateral(denoms.BTC), - ). - Then( - QueryCollateral(denoms.BTC), - ), - - TC("sanity check: multiple changes"). - Given(). - When( - SetCollateral(denoms.BTC), - SetCollateral(denoms.ETH), - SetCollateral(denoms.SOL), - ). - Then( - QueryCollateral(denoms.SOL), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} diff --git a/x/perp/v2/keeper/hooks.go b/x/perp/v2/keeper/hooks.go deleted file mode 100644 index 25d953fd0..000000000 --- a/x/perp/v2/keeper/hooks.go +++ /dev/null @@ -1,90 +0,0 @@ -package keeper - -import ( - "time" - - "github.com/NibiruChain/collections" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/common/asset" - epochstypes "github.com/NibiruChain/nibiru/x/epochs/types" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func (k Keeper) BeforeEpochStart(_ sdk.Context, _ string, _ uint64) { -} - -func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, number uint64) { - k.maybeUpdateDnREpoch(ctx, epochIdentifier, number) - for _, market := range k.Markets.Iterate(ctx, collections.Range[collections.Pair[asset.Pair, uint64]]{}).Values() { - if !market.Enabled || epochIdentifier != market.FundingRateEpochId { - return - } - - indexTwap, err := k.OracleKeeper.GetExchangeRateTwap(ctx, market.OraclePair) - if err != nil { - ctx.Logger().Error("failed to fetch twap index price", "market.OraclePair", market.OraclePair, "market.Pair", market.Pair, "error", err) - continue - } - if indexTwap.IsZero() { - ctx.Logger().Error("index price is zero", "market.OraclePair", market.OraclePair, "market.Pair", market.Pair) - continue - } - - markTwap, err := k.CalcTwap(ctx, market.Pair, types.TwapCalcOption_SPOT, types.Direction_DIRECTION_UNSPECIFIED, sdk.ZeroDec(), market.TwapLookbackWindow) - if err != nil { - ctx.Logger().Error("failed to fetch twap mark price", "market.Pair", market.Pair, "error", err) - continue - } - if markTwap.IsZero() { - ctx.Logger().Error("mark price is zero", "market.Pair", market.Pair) - continue - } - - epochInfo, err := k.EpochKeeper.GetEpochInfo(ctx, epochIdentifier) - if err != nil { - ctx.Logger().Error("failed to fetch epoch info", "epochIdentifier", epochIdentifier, "error", err) - continue - } - intervalsPerDay := (24 * time.Hour) / epochInfo.Duration - // See https://www.notion.so/nibiru/Funding-Payments-5032d0f8ed164096808354296d43e1fa for an explanation of these terms. - clampedDivergence := common.Clamp(markTwap.Sub(indexTwap).Quo(indexTwap), market.MaxFundingRate) - premiumFraction := clampedDivergence.Mul(indexTwap).QuoInt64(int64(intervalsPerDay)) - - market.LatestCumulativePremiumFraction = market.LatestCumulativePremiumFraction.Add(premiumFraction) - k.SaveMarket(ctx, market) - - _ = ctx.EventManager().EmitTypedEvent(&types.FundingRateChangedEvent{ - Pair: market.Pair, - MarkPriceTwap: markTwap, - IndexPriceTwap: indexTwap, - PremiumFraction: premiumFraction, - CumulativePremiumFraction: market.LatestCumulativePremiumFraction, - }) - } -} - -// ___________________________________________________________________________________________________ - -// Hooks wrapper struct for perps keeper. -type Hooks struct { - k Keeper -} - -var _ epochstypes.EpochHooks = Hooks{} - -// Hooks Return the wrapper struct. -func (k Keeper) Hooks() Hooks { - return Hooks{k} -} - -// BeforeEpochStart epochs hooks. -func (h Hooks) BeforeEpochStart(ctx sdk.Context, epochIdentifier string, epochNumber uint64) { - h.k.BeforeEpochStart(ctx, epochIdentifier, epochNumber) -} - -func (h Hooks) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber uint64) { - h.k.AfterEpochEnd(ctx, epochIdentifier, epochNumber) -} diff --git a/x/perp/v2/keeper/hooks_test.go b/x/perp/v2/keeper/hooks_test.go deleted file mode 100644 index 6a7bcde5f..000000000 --- a/x/perp/v2/keeper/hooks_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/testutil" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - . "github.com/NibiruChain/nibiru/x/common/testutil/action" - . "github.com/NibiruChain/nibiru/x/epochs/integration/action" - epochtypes "github.com/NibiruChain/nibiru/x/epochs/types" - . "github.com/NibiruChain/nibiru/x/oracle/integration/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/assertion" -) - -func TestAfterEpochEnd(t *testing.T) { - pairBtcUsd := asset.Registry.Pair(denoms.BTC, denoms.USD) - pairBtcUsdc := asset.Registry.Pair(denoms.BTC, denoms.USDC) - startTime := time.Now() - - adminUser, err := sdk.AccAddressFromBech32(testutil.ADDR_SUDO_ROOT) - require.NoError(t, err) - - tc := TestCases{ - TC("index > mark"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - SetBlockTime(startTime), - InsertOraclePriceSnapshot(pairBtcUsd, startTime.Add(15*time.Minute), sdk.MustNewDecFromStr("5.8")), - StartEpoch(epochtypes.ThirtyMinuteEpochID), - ). - When( - MoveToNextBlockWithDuration(30 * time.Minute), - ). - Then( - MarketShouldBeEqual(pairBtcUsdc, Market_LatestCPFShouldBeEqualTo(sdk.MustNewDecFromStr("-0.099999999999999999"))), - ), - - TC("index < mark"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - SetBlockTime(startTime), - InsertOraclePriceSnapshot(pairBtcUsd, startTime.Add(15*time.Minute), sdk.MustNewDecFromStr("0.52")), - StartEpoch(epochtypes.ThirtyMinuteEpochID), - ). - When( - MoveToNextBlockWithDuration(30 * time.Minute), - ). - Then( - MarketShouldBeEqual(pairBtcUsdc, Market_LatestCPFShouldBeEqualTo(sdk.MustNewDecFromStr("0.01"))), - ), - - TC("index > mark - max funding rate"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true), WithMaxFundingRate(sdk.MustNewDecFromStr("0.001"))), - SetBlockTime(startTime), - InsertOraclePriceSnapshot(pairBtcUsd, startTime.Add(15*time.Minute), sdk.MustNewDecFromStr("5.8")), - StartEpoch(epochtypes.ThirtyMinuteEpochID), - ). - When( - MoveToNextBlockWithDuration(30 * time.Minute), - ). - Then( - MarketShouldBeEqual(pairBtcUsdc, Market_LatestCPFShouldBeEqualTo(sdk.MustNewDecFromStr("-0.000120833333333333"))), - ), - - TC("index < mark - max funding rate"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true), WithMaxFundingRate(sdk.MustNewDecFromStr("0.001"))), - SetBlockTime(startTime), - InsertOraclePriceSnapshot(pairBtcUsd, startTime.Add(15*time.Minute), sdk.MustNewDecFromStr("0.52")), - StartEpoch(epochtypes.ThirtyMinuteEpochID), - ). - When( - MoveToNextBlockWithDuration(30 * time.Minute), - ). - Then( - MarketShouldBeEqual(pairBtcUsdc, Market_LatestCPFShouldBeEqualTo(sdk.MustNewDecFromStr("0.000010833333333333"))), - ), - - TC("index == mark"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - SetBlockTime(startTime), - InsertOraclePriceSnapshot(pairBtcUsd, startTime.Add(15*time.Minute), sdk.OneDec()), - StartEpoch(epochtypes.ThirtyMinuteEpochID), - ). - When( - MoveToNextBlockWithDuration(30 * time.Minute), - ). - Then( - MarketShouldBeEqual(pairBtcUsdc, Market_LatestCPFShouldBeEqualTo(sdk.ZeroDec())), - ), - - TC("missing twap"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - SetBlockTime(startTime), - StartEpoch(epochtypes.ThirtyMinuteEpochID), - ). - When( - MoveToNextBlockWithDuration(30 * time.Minute), - ). - Then( - MarketShouldBeEqual(pairBtcUsdc, Market_LatestCPFShouldBeEqualTo(sdk.ZeroDec())), - ), - - TC("0 price mark"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - SetBlockTime(startTime), - StartEpoch(epochtypes.ThirtyMinuteEpochID), - InsertOraclePriceSnapshot(pairBtcUsd, startTime.Add(15*time.Minute), sdk.ZeroDec()), - ). - When( - MoveToNextBlockWithDuration(30 * time.Minute), - ). - Then( - MarketShouldBeEqual(pairBtcUsdc, Market_LatestCPFShouldBeEqualTo(sdk.ZeroDec())), - ), - - TC("market closed"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - CloseMarket(pairBtcUsdc, adminUser), - SetBlockTime(startTime), - StartEpoch(epochtypes.ThirtyMinuteEpochID), - InsertOraclePriceSnapshot(pairBtcUsd, startTime.Add(15*time.Minute), sdk.NewDec(2)), - ). - When( - MoveToNextBlockWithDuration(30 * time.Minute), - ). - Then( - MarketShouldBeEqual(pairBtcUsdc, Market_LatestCPFShouldBeEqualTo(sdk.ZeroDec())), - ), - - TC("not correct epoch id"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - CloseMarket(pairBtcUsdc, adminUser), - SetBlockTime(startTime), - StartEpoch(epochtypes.DayEpochID), - InsertOraclePriceSnapshot(pairBtcUsd, startTime.Add(15*time.Minute), sdk.NewDec(2)), - ). - When( - MoveToNextBlockWithDuration(30 * time.Minute), - ). - Then( - MarketShouldBeEqual(pairBtcUsdc, Market_LatestCPFShouldBeEqualTo(sdk.ZeroDec())), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} diff --git a/x/perp/v2/keeper/keeper.go b/x/perp/v2/keeper/keeper.go deleted file mode 100644 index 309e6e124..000000000 --- a/x/perp/v2/keeper/keeper.go +++ /dev/null @@ -1,154 +0,0 @@ -package keeper - -import ( - "fmt" - "time" - - "cosmossdk.io/math" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - - "github.com/NibiruChain/collections" - - "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/common/asset" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -type Keeper struct { - cdc codec.BinaryCodec - storeKey storetypes.StoreKey - - BankKeeper types.BankKeeper - AccountKeeper types.AccountKeeper - OracleKeeper types.OracleKeeper - EpochKeeper types.EpochKeeper - SudoKeeper types.SudoKeeper - - MarketLastVersion collections.Map[asset.Pair, types.MarketLastVersion] - Markets collections.Map[collections.Pair[asset.Pair, uint64], types.Market] - AMMs collections.Map[collections.Pair[asset.Pair, uint64], types.AMM] - Collateral collections.Item[string] - - Positions collections.Map[collections.Pair[collections.Pair[asset.Pair, uint64], sdk.AccAddress], types.Position] - ReserveSnapshots collections.Map[collections.Pair[asset.Pair, time.Time], types.ReserveSnapshot] - DnREpoch collections.Item[uint64] // Keeps track of the current DnR epoch. - DnREpochName collections.Item[string] // Keeps track of the current DnR epoch identifier, provided by x/epoch. - GlobalVolumes collections.Map[uint64, math.Int] // Keeps track of global volumes for each epoch. - TraderVolumes collections.Map[collections.Pair[sdk.AccAddress, uint64], math.Int] // Keeps track of user volumes for each epoch. - GlobalDiscounts collections.Map[math.Int, math.LegacyDec] // maps a volume level to a discount - TraderDiscounts collections.Map[collections.Pair[sdk.AccAddress, math.Int], math.LegacyDec] // maps a user and volume level to a discount, supersedes global discounts - EpochRebateAllocations collections.Map[uint64, types.DNRAllocation] // maps an epoch to a string representing the allocation of rebates for that epoch -} - -// NewKeeper Creates a new x/perp Keeper instance. -func NewKeeper( - cdc codec.BinaryCodec, - storeKey storetypes.StoreKey, - - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, - oracleKeeper types.OracleKeeper, - epochKeeper types.EpochKeeper, - sudoKeeper types.SudoKeeper, -) Keeper { - // Ensure that the module account is set. - if moduleAcc := accountKeeper.GetModuleAddress(types.ModuleName); moduleAcc == nil { - panic("The x/perp module account has not been set") - } - - return Keeper{ - cdc: cdc, - storeKey: storeKey, - BankKeeper: bankKeeper, - AccountKeeper: accountKeeper, - OracleKeeper: oracleKeeper, - EpochKeeper: epochKeeper, - SudoKeeper: sudoKeeper, - MarketLastVersion: collections.NewMap( - storeKey, NamespaceMarketLastVersion, - asset.PairKeyEncoder, - collections.ProtoValueEncoder[types.MarketLastVersion](cdc), - ), - Markets: collections.NewMap( - storeKey, NamespaceMarkets, - collections.PairKeyEncoder(asset.PairKeyEncoder, collections.Uint64KeyEncoder), - collections.ProtoValueEncoder[types.Market](cdc), - ), - AMMs: collections.NewMap( - storeKey, NamespaceAmms, - collections.PairKeyEncoder(asset.PairKeyEncoder, collections.Uint64KeyEncoder), - collections.ProtoValueEncoder[types.AMM](cdc), - ), - Positions: collections.NewMap( - storeKey, NamespacePositions, - collections.PairKeyEncoder(collections.PairKeyEncoder(asset.PairKeyEncoder, collections.Uint64KeyEncoder), collections.AccAddressKeyEncoder), - collections.ProtoValueEncoder[types.Position](cdc), - ), - ReserveSnapshots: collections.NewMap( - storeKey, NamespaceReserveSnapshots, - collections.PairKeyEncoder(asset.PairKeyEncoder, collections.TimeKeyEncoder), - collections.ProtoValueEncoder[types.ReserveSnapshot](cdc), - ), - DnREpoch: collections.NewItem( - storeKey, NamespaceDnrEpoch, - collections.Uint64ValueEncoder, - ), - GlobalVolumes: collections.NewMap( - storeKey, NamespaceGlobalVolumes, - collections.Uint64KeyEncoder, - collections.IntValueEncoder, - ), - TraderVolumes: collections.NewMap( - storeKey, NamespaceUserVolumes, - collections.PairKeyEncoder(collections.AccAddressKeyEncoder, collections.Uint64KeyEncoder), - collections.IntValueEncoder, - ), - GlobalDiscounts: collections.NewMap( - storeKey, NamespaceGlobalDiscounts, - collections.IntKeyEncoder, - collections.DecValueEncoder, - ), - TraderDiscounts: collections.NewMap( - storeKey, NamespaceUserDiscounts, - collections.PairKeyEncoder(collections.AccAddressKeyEncoder, collections.IntKeyEncoder), - collections.DecValueEncoder, - ), - EpochRebateAllocations: collections.NewMap( - storeKey, NamespaceRebatesAllocations, - collections.Uint64KeyEncoder, - collections.ProtoValueEncoder[types.DNRAllocation](cdc), - ), - Collateral: collections.NewItem( - storeKey, NamespaceCollateral, - common.StringValueEncoder, - ), - DnREpochName: collections.NewItem( - storeKey, NamespaceDnrEpochName, - common.StringValueEncoder, - ), - } -} - -const ( - NamespaceMarkets collections.Namespace = iota + 11 // == 11 because iota starts from 0 - NamespaceAmms - NamespacePositions - NamespaceReserveSnapshots - NamespaceDnrEpoch - NamespaceGlobalVolumes - NamespaceUserVolumes - NamespaceGlobalDiscounts - NamespaceUserDiscounts - NamespaceRebatesAllocations - NamespaceMarketLastVersion - NamespaceCollateral - NamespaceDnrEpochName -) - -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} diff --git a/x/perp/v2/keeper/liquidate.go b/x/perp/v2/keeper/liquidate.go deleted file mode 100644 index 3be649238..000000000 --- a/x/perp/v2/keeper/liquidate.go +++ /dev/null @@ -1,437 +0,0 @@ -package keeper - -import ( - "encoding/json" - "fmt" - "strings" - - sdkerrors "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func (k Keeper) MultiLiquidate( - ctx sdk.Context, liquidator sdk.AccAddress, liquidationRequests []*types.MsgMultiLiquidate_Liquidation, -) ([]*types.MsgMultiLiquidateResponse_LiquidationResponse, error) { - resps := make([]*types.MsgMultiLiquidateResponse_LiquidationResponse, len(liquidationRequests)) - - var allFailed bool = true - - for reqIdx, req := range liquidationRequests { - traderAddr, errAccAddress := sdk.AccAddressFromBech32(req.Trader) - liquidatorFee, perpEfFee, err := k.liquidate( - ctx, liquidator, req.Pair, traderAddr, - ) - - switch { - case errAccAddress != nil: - resps[reqIdx] = &types.MsgMultiLiquidateResponse_LiquidationResponse{ - Success: false, - Error: errAccAddress.Error(), - Trader: req.Trader, - Pair: req.Pair, - } - case err != nil: - resps[reqIdx] = &types.MsgMultiLiquidateResponse_LiquidationResponse{ - Success: false, - Error: err.Error(), - Trader: req.Trader, - Pair: req.Pair, - } - default: - // Success case - allFailed = false - resps[reqIdx] = &types.MsgMultiLiquidateResponse_LiquidationResponse{ - Success: true, - LiquidatorFee: &liquidatorFee, - PerpEfFee: &perpEfFee, - Trader: req.Trader, - Pair: req.Pair, - } - } - } - - if allFailed { - prettyResps, errPrettyResp := PrettyLiquidateResponse(resps) - - numLiquidations := len(liquidationRequests) - errDescription := strings.Join( - []string{ - fmt.Sprintf("%d liquidations failed", numLiquidations), - fmt.Sprintf("liquidate_responses: %s", prettyResps), - }, - "\n", - ) - if errPrettyResp != nil { - errDescription += fmt.Sprintf("\n%s", errPrettyResp.Error()) - } - return resps, types.ErrAllLiquidationsFailed.Wrap(errDescription) - } - - return resps, nil -} - -/* -PrettyLiquidateResponse converts a slice of liquidation responses into a -pretty formatted JSON array for each response. This helps with providing -descriptive error messages in the case of failed liquidations. - -Example outputs: - -```json -[ - - { - "success": false, - "error": "failed liquidation A", - "liquidator_fee": null, - "perp_ef_fee": null, - "trader": "dummytraderA" - }, - { - "success": true, - "error": "", - "liquidator_fee": { denom: "unibi", amount: "420"}, - "perp_ef_fee": null, - "trader": "dummytraderB" - } - -] -``` -*/ -func PrettyLiquidateResponse( - resps []*types.MsgMultiLiquidateResponse_LiquidationResponse, -) (pretty string, err error) { - protoCodec := codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) - var respJsons []json.RawMessage - var jsonErrs string = "" - for _, resp := range resps { - respJsonBz, jsonErr := protoCodec.MarshalJSON(resp) - if jsonErr != nil { - jsonErrs += jsonErr.Error() - } - respJsons = append(respJsons, respJsonBz) - } - - prettyBz, _ := json.MarshalIndent(respJsons, "", " ") - pretty = string(prettyBz) - if jsonErrs != "" { - return pretty, types.ErrParseLiquidateResponse.Wrap(jsonErrs) - } - return -} - -/* -liquidate allows to liquidate the trader position if the margin is below the -required margin maintenance ratio. - -args: - - liquidator: the liquidator who is executing the liquidation - - pair: the asset pair - - trader: the trader who owns the position being liquidated - -returns: - - liquidatorFee: the amount of coins given to the liquidator - - ecosystemFundFee: the amount of coins given to the ecosystem fund - - err: error - - event: pointer to a typed event (proto.Message). The 'event' value - exists when the liquidation fails and is nil when the liquidation succeeds. -*/ -func (k Keeper) liquidate( - ctx sdk.Context, - liquidator sdk.AccAddress, - pair asset.Pair, - trader sdk.AccAddress, -) (liquidatorFee sdk.Coin, ecosystemFundFee sdk.Coin, err error) { - // eventLiqFailed exists when the liquidation fails and is nil when the - // liquidation succeeds. - - market, err := k.GetMarket(ctx, pair) - if err != nil { - eventLiqFailed := &types.LiquidationFailedEvent{ - Pair: pair, - Trader: trader.String(), - Liquidator: liquidator.String(), - Reason: types.LiquidationFailedEvent_NONEXISTENT_PAIR, - } - _ = ctx.EventManager().EmitTypedEvent(eventLiqFailed) - err = sdkerrors.Wrapf(types.ErrPairNotFound, "pair: %s", pair) - return - } - - amm, err := k.GetAMM(ctx, pair) - if err != nil { - eventLiqFailed := &types.LiquidationFailedEvent{ - Pair: pair, - Trader: trader.String(), - Liquidator: liquidator.String(), - Reason: types.LiquidationFailedEvent_NONEXISTENT_PAIR, - } - _ = ctx.EventManager().EmitTypedEvent(eventLiqFailed) - err = sdkerrors.Wrapf(types.ErrPairNotFound, "pair: %s", pair) - return - } - - position, err := k.GetPosition(ctx, pair, market.Version, trader) - if err != nil { - eventLiqFailed := &types.LiquidationFailedEvent{ - Pair: pair, - Trader: trader.String(), - Liquidator: liquidator.String(), - Reason: types.LiquidationFailedEvent_NONEXISTENT_POSITION, - } - _ = ctx.EventManager().EmitTypedEvent(eventLiqFailed) - return - } - - spotNotional, err := PositionNotionalSpot(amm, position) - if err != nil { - return - } - twapNotional, err := k.PositionNotionalTWAP(ctx, position, market.TwapLookbackWindow) - if err != nil { - return - } - - // give the user the preferred position notional - var preferredPositionNotional sdk.Dec - if position.Size_.IsPositive() { - preferredPositionNotional = sdk.MaxDec(spotNotional, twapNotional) - } else { - preferredPositionNotional = sdk.MinDec(spotNotional, twapNotional) - } - - marginRatio := MarginRatio(position, preferredPositionNotional, market.LatestCumulativePremiumFraction) - if marginRatio.GTE(market.MaintenanceMarginRatio) { - eventLiqFailed := &types.LiquidationFailedEvent{ - Pair: pair, - Trader: trader.String(), - Liquidator: liquidator.String(), - Reason: types.LiquidationFailedEvent_POSITION_HEALTHY, - } - _ = ctx.EventManager().EmitTypedEvent(eventLiqFailed) - err = types.ErrPositionHealthy - return - } - - spotMarginRatio := MarginRatio(position, spotNotional, market.LatestCumulativePremiumFraction) - if spotMarginRatio.GTE(market.LiquidationFeeRatio) { - liquidatorFee, ecosystemFundFee, err = k.executePartialLiquidation(ctx, market, amm, liquidator, &position) - } else { - liquidatorFee, ecosystemFundFee, err = k.executeFullLiquidation(ctx, market, amm, liquidator, &position) - } - if err != nil { - return sdk.Coin{}, sdk.Coin{}, err - } - - return liquidatorFee, ecosystemFundFee, nil -} - -/* -executeFullLiquidation Fully liquidates a position. It is assumed that the margin ratio has already been -checked prior to calling this method. - -args: - - ctx: cosmos-sdk context - - liquidator: the liquidator's address - - position: the position to liquidate - -ret: - - liquidationResp: a response object containing the results of the liquidation - - err: error -*/ -func (k Keeper) executeFullLiquidation( - ctx sdk.Context, market types.Market, amm types.AMM, liquidator sdk.AccAddress, position *types.Position, -) (liquidatorfee sdk.Coin, ecosystemFundFee sdk.Coin, err error) { - _, positionResp, err := k.closePositionEntirely( - ctx, - market, - amm, - /* currentPosition */ *position, - /* quoteAssetAmountLimit */ sdk.ZeroDec(), - ) - if err != nil { - return sdk.Coin{}, sdk.Coin{}, err - } - - remainMargin := positionResp.MarginToVault.Abs() - - liquidatorFeeAmount := market.LiquidationFeeRatio. - Mul(positionResp.ExchangedNotionalValue). - QuoInt64(2) - totalBadDebt := positionResp.BadDebt - - if liquidatorFeeAmount.GT(remainMargin) { - // if the remainMargin is not enough for liquidationFee, count it as bad debt - totalBadDebt = totalBadDebt.Add(liquidatorFeeAmount.Sub(remainMargin)) - remainMargin = sdk.ZeroDec() - } else { - // Otherwise, the remaining margin will be transferred to ecosystemFund - remainMargin = remainMargin.Sub(liquidatorFeeAmount) - } - - // Realize bad debt - if totalBadDebt.IsPositive() { - if err = k.realizeBadDebt( - ctx, - market, - totalBadDebt.RoundInt(), - ); err != nil { - return sdk.Coin{}, sdk.Coin{}, err - } - } - - ecosystemFundFeeAmount := sdk.ZeroDec() - if remainMargin.IsPositive() { - ecosystemFundFeeAmount = remainMargin - } - - collateral, err := k.Collateral.Get(ctx) - if err != nil { - return sdk.Coin{}, sdk.Coin{}, err - } - - liquidatorfee = sdk.NewCoin(collateral, liquidatorFeeAmount.RoundInt()) - ecosystemFundFee = sdk.NewCoin(collateral, ecosystemFundFeeAmount.RoundInt()) - - err = k.distributeLiquidateRewards( - ctx, - market, - liquidator, - liquidatorfee, - ecosystemFundFee, - ) - if err != nil { - return sdk.Coin{}, sdk.Coin{}, err - } - - _ = ctx.EventManager().EmitTypedEvent(&types.PositionLiquidatedEvent{ - PositionChangedEvent: types.PositionChangedEvent{ - FinalPosition: positionResp.Position, - PositionNotional: positionResp.PositionNotional, - TransactionFee: sdk.NewCoin(collateral, sdk.ZeroInt()), // no transaction fee for liquidation - RealizedPnl: positionResp.RealizedPnl, - BadDebt: sdk.NewCoin(collateral, totalBadDebt.RoundInt()), - FundingPayment: positionResp.FundingPayment, - BlockHeight: ctx.BlockHeight(), - MarginToUser: sdk.ZeroInt(), // no margin to user for full liquidation - ChangeReason: types.ChangeReason_FullLiquidation, - }, - LiquidatorAddress: liquidator.String(), - FeeToLiquidator: sdk.NewCoin(collateral, liquidatorFeeAmount.RoundInt()), - FeeToEcosystemFund: sdk.NewCoin(collateral, ecosystemFundFeeAmount.RoundInt()), - }) - - return liquidatorfee, ecosystemFundFee, err -} - -// executePartialLiquidation partially liquidates a position -func (k Keeper) executePartialLiquidation( - ctx sdk.Context, market types.Market, amm types.AMM, liquidator sdk.AccAddress, position *types.Position, -) (liquidatorFee sdk.Coin, ecosystemFundFee sdk.Coin, err error) { - traderAddr, err := sdk.AccAddressFromBech32(position.TraderAddress) - if err != nil { - return sdk.Coin{}, sdk.Coin{}, err - } - - var dir types.Direction - if position.Size_.IsPositive() { - dir = types.Direction_SHORT - } else { - dir = types.Direction_LONG - } - - quoteReserveDelta, err := amm.GetQuoteReserveAmt(position.Size_.Mul(market.PartialLiquidationRatio), dir) - if err != nil { - return sdk.Coin{}, sdk.Coin{}, err - } - quoteAssetDelta := amm.QuoteReserveToAsset(quoteReserveDelta) - - _, positionResp, err := k.decreasePosition( - /* ctx */ ctx, - market, - amm, - /* currentPosition */ *position, - /* quoteAssetAmount */ quoteAssetDelta, - /* baseAmtLimit */ sdk.ZeroDec(), - ) - if err != nil { - return sdk.Coin{}, sdk.Coin{}, err - } - - // Remove the liquidation fee from the margin of the position - liquidationFeeAmount := quoteAssetDelta.Mul(market.LiquidationFeeRatio) - positionResp.Position.Margin = positionResp.Position.Margin.Sub(liquidationFeeAmount) - k.SavePosition(ctx, positionResp.Position.Pair, market.Version, traderAddr, positionResp.Position) - - // Compute splits for the liquidation fee - feeToLiquidator := liquidationFeeAmount.QuoInt64(2) - feeToPerpEcosystemFund := liquidationFeeAmount.Sub(feeToLiquidator) - - collateral, err := k.Collateral.Get(ctx) - if err != nil { - return sdk.Coin{}, sdk.Coin{}, err - } - - err = k.distributeLiquidateRewards(ctx, market, liquidator, - sdk.NewCoin(collateral, feeToPerpEcosystemFund.RoundInt()), - sdk.NewCoin(collateral, feeToLiquidator.RoundInt()), - ) - if err != nil { - return sdk.Coin{}, sdk.Coin{}, err - } - - _ = ctx.EventManager().EmitTypedEvent(&types.PositionLiquidatedEvent{ - PositionChangedEvent: types.PositionChangedEvent{ - FinalPosition: positionResp.Position, - PositionNotional: positionResp.PositionNotional, - TransactionFee: sdk.NewCoin(collateral, sdk.ZeroInt()), // no transaction fee for liquidation - RealizedPnl: positionResp.RealizedPnl, - BadDebt: sdk.NewCoin(collateral, sdk.ZeroInt()), // no bad debt for partial liquidation - FundingPayment: positionResp.FundingPayment, - BlockHeight: ctx.BlockHeight(), - MarginToUser: sdk.ZeroInt(), // no margin to user for partial liquidation - ChangeReason: types.ChangeReason_PartialLiquidation, - }, - LiquidatorAddress: liquidator.String(), - FeeToLiquidator: sdk.NewCoin(collateral, feeToLiquidator.RoundInt()), - FeeToEcosystemFund: sdk.NewCoin(collateral, feeToPerpEcosystemFund.RoundInt()), - }) - - return liquidatorFee, ecosystemFundFee, err -} - -func (k Keeper) distributeLiquidateRewards( - ctx sdk.Context, market types.Market, liquidator sdk.AccAddress, liquidatorFee sdk.Coin, ecosystemFundFee sdk.Coin, -) (err error) { - // -------------------------------------------------------------- - // Distribution of rewards - // -------------------------------------------------------------- - - // Transfer fee from vault to PerpEF - if ecosystemFundFee.IsPositive() { - if err = k.BankKeeper.SendCoinsFromModuleToModule( - ctx, - /* from */ types.VaultModuleAccount, - /* to */ types.PerpFundModuleAccount, - sdk.NewCoins(ecosystemFundFee), - ); err != nil { - return err - } - } - - // Transfer fee from vault to liquidator - if liquidatorFee.IsPositive() { - err = k.WithdrawFromVault(ctx, market, liquidator, liquidatorFee.Amount) - if err != nil { - return err - } - } - - return nil -} diff --git a/x/perp/v2/keeper/liquidate_test.go b/x/perp/v2/keeper/liquidate_test.go deleted file mode 100644 index 736dcd672..000000000 --- a/x/perp/v2/keeper/liquidate_test.go +++ /dev/null @@ -1,404 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - . "github.com/NibiruChain/nibiru/x/common/testutil/action" - . "github.com/NibiruChain/nibiru/x/common/testutil/assertion" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/assertion" - - "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func TestMultiLiquidate(t *testing.T) { - pairBtcUsdc := asset.Registry.Pair(denoms.BTC, denoms.USDC) - pairEthUsdc := asset.Registry.Pair(denoms.ETH, denoms.USDC) - pairAtomUsdc := asset.Registry.Pair(denoms.ATOM, denoms.USDC) - pairSolUsdc := asset.Registry.Pair(denoms.SOL, denoms.USDC) - - alice := testutil.AccAddress() - bob := testutil.AccAddress() - liquidator := testutil.AccAddress() - startTime := time.Now() - - tc := TestCases{ - TC("partial liquidation"). - Given( - SetBlockNumber(1), - SetBlockTime(startTime), - CreateCustomMarket(pairBtcUsdc), - InsertPosition(WithTrader(alice), WithPair(pairBtcUsdc), WithSize(sdk.NewDec(10000)), WithMargin(sdk.NewDec(1000)), WithOpenNotional(sdk.NewDec(10400))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1000))), - ). - When( - MoveToNextBlock(), - MultiLiquidate(liquidator, false, - PairTraderTuple{Pair: pairBtcUsdc, Trader: alice, Successful: true}, - ), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(750)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(125)), - BalanceEqual(liquidator, types.TestingCollateralDenomNUSD, sdk.NewInt(125)), - PositionShouldBeEqual(alice, pairBtcUsdc, - Position_PositionShouldBeEqualTo( - types.Position{ - Pair: pairBtcUsdc, - TraderAddress: alice.String(), - Size_: sdk.NewDec(5000), - Margin: sdk.MustNewDecFromStr("549.999951250000493750"), - OpenNotional: sdk.MustNewDecFromStr("5199.999975000000375000"), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - }, - ), - ), - ), - - TC("full liquidation"). - Given( - SetBlockNumber(1), - SetBlockTime(startTime), - CreateCustomMarket(pairBtcUsdc), - InsertPosition(WithTrader(alice), WithPair(pairBtcUsdc), WithSize(sdk.NewDec(10000)), WithMargin(sdk.NewDec(1000)), WithOpenNotional(sdk.NewDec(10600))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1000))), - ). - When( - MoveToNextBlock(), - MultiLiquidate(liquidator, false, - PairTraderTuple{Pair: pairBtcUsdc, Trader: alice, Successful: true}, - PairTraderTuple{Pair: pairAtomUsdc, Trader: alice, Successful: false}, - ), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(600)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(150)), - BalanceEqual(liquidator, types.TestingCollateralDenomNUSD, sdk.NewInt(250)), - PositionShouldNotExist(alice, pairBtcUsdc, 1), - ), - - TC("full liquidation"). - Given( - SetBlockNumber(1), - SetBlockTime(startTime), - CreateCustomMarket(pairBtcUsdc), - InsertPosition(WithTrader(alice), WithPair(pairBtcUsdc), WithSize(sdk.NewDec(10000)), WithMargin(sdk.NewDec(1000)), WithOpenNotional(sdk.NewDec(10600))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1000))), - ). - When( - MoveToNextBlock(), - MultiLiquidate(liquidator, false, - PairTraderTuple{Pair: pairBtcUsdc, Trader: alice, Successful: true}, - ), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(600)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(150)), - BalanceEqual(liquidator, types.TestingCollateralDenomNUSD, sdk.NewInt(250)), - PositionShouldNotExist(alice, pairBtcUsdc, 1), - ), - - TC("one fail liquidation - one correct"). - Given( - SetBlockNumber(1), - SetBlockTime(startTime), - CreateCustomMarket(pairBtcUsdc), - InsertPosition(WithTrader(alice), WithPair(pairBtcUsdc), WithSize(sdk.NewDec(10000)), WithMargin(sdk.NewDec(1000)), WithOpenNotional(sdk.NewDec(10600))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1000))), - ). - When( - MoveToNextBlock(), - MultiLiquidate(liquidator, false, - PairTraderTuple{Pair: pairBtcUsdc, Successful: false}, - PairTraderTuple{Pair: pairBtcUsdc, Trader: alice, Successful: true}, - ), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(600)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(150)), - BalanceEqual(liquidator, types.TestingCollateralDenomNUSD, sdk.NewInt(250)), - PositionShouldNotExist(alice, pairBtcUsdc, 1), - ), - - TC("one fail liquidation because market does not exists- one correct"). - Given( - SetBlockNumber(1), - SetBlockTime(startTime), - CreateCustomMarket(pairBtcUsdc), - InsertPosition(WithTrader(alice), WithPair(pairBtcUsdc), WithSize(sdk.NewDec(10000)), WithMargin(sdk.NewDec(1000)), WithOpenNotional(sdk.NewDec(10600))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1000))), - ). - When( - MoveToNextBlock(), - MultiLiquidate(liquidator, false, - PairTraderTuple{Pair: asset.MustNewPair("luna:usdt"), Successful: false}, - PairTraderTuple{Pair: pairBtcUsdc, Trader: alice, Successful: true}, - ), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(600)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(150)), - BalanceEqual(liquidator, types.TestingCollateralDenomNUSD, sdk.NewInt(250)), - PositionShouldNotExist(alice, pairBtcUsdc, 1), - ), - - TC("realizes bad debt"). - Given( - SetBlockNumber(1), - SetBlockTime(startTime), - CreateCustomMarket(pairBtcUsdc), - InsertPosition(WithTrader(alice), WithPair(pairBtcUsdc), WithSize(sdk.NewDec(10000)), WithMargin(sdk.NewDec(1000)), WithOpenNotional(sdk.NewDec(10800))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1000))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 50))), - ). - When( - MoveToNextBlock(), - MultiLiquidate(liquidator, false, - PairTraderTuple{Pair: pairBtcUsdc, Trader: alice, Successful: true}, - ), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(800)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - BalanceEqual(liquidator, types.TestingCollateralDenomNUSD, sdk.NewInt(250)), - PositionShouldNotExist(alice, pairBtcUsdc, 1), - ), - - TC("uses prepaid bad debt"). - Given( - SetBlockNumber(1), - SetBlockTime(startTime), - CreateCustomMarket(pairBtcUsdc, WithPrepaidBadDebt(sdk.NewInt(50), types.TestingCollateralDenomNUSD)), - InsertPosition(WithTrader(alice), WithPair(pairBtcUsdc), WithSize(sdk.NewDec(10000)), WithMargin(sdk.NewDec(1000)), WithOpenNotional(sdk.NewDec(10800))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1000))), - ). - When( - MoveToNextBlock(), - MultiLiquidate(liquidator, false, - PairTraderTuple{Pair: pairBtcUsdc, Trader: alice, Successful: true}, - ), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(750)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - BalanceEqual(liquidator, types.TestingCollateralDenomNUSD, sdk.NewInt(250)), - PositionShouldNotExist(alice, pairBtcUsdc, 1), - MarketShouldBeEqual(pairBtcUsdc, Market_PrepaidBadDebtShouldBeEqualTo(sdk.ZeroInt(), types.TestingCollateralDenomNUSD)), - ), - - TC("healthy position"). - Given( - SetBlockNumber(1), - SetBlockTime(startTime), - CreateCustomMarket(pairBtcUsdc), - InsertPosition(WithTrader(alice), WithPair(pairBtcUsdc), WithSize(sdk.NewDec(100)), WithMargin(sdk.NewDec(10)), WithOpenNotional(sdk.NewDec(100))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 10))), - ). - When( - MoveToNextBlock(), - MultiLiquidate(liquidator, true, - PairTraderTuple{Pair: pairBtcUsdc, Trader: alice, Successful: false}, - ), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(10)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - BalanceEqual(liquidator, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - PositionShouldBeEqual(alice, pairBtcUsdc, - Position_PositionShouldBeEqualTo( - types.Position{ - Pair: pairBtcUsdc, - TraderAddress: alice.String(), - Size_: sdk.NewDec(100), - Margin: sdk.NewDec(10), - OpenNotional: sdk.NewDec(100), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - }, - ), - ), - ContainsLiquidateEvent(&types.LiquidationFailedEvent{ - Pair: pairBtcUsdc, - Trader: alice.String(), - Liquidator: liquidator.String(), - Reason: types.LiquidationFailedEvent_POSITION_HEALTHY, - }), - ), - - TC("mixed bag"). - Given( - SetBlockNumber(1), - SetBlockTime(startTime), - CreateCustomMarket(pairBtcUsdc), - CreateCustomMarket(pairEthUsdc), - CreateCustomMarket(pairAtomUsdc), - InsertPosition(WithTrader(alice), WithPair(pairBtcUsdc), WithSize(sdk.NewDec(10000)), WithMargin(sdk.NewDec(1000)), WithOpenNotional(sdk.NewDec(10400))), // partial - InsertPosition(WithTrader(alice), WithPair(pairEthUsdc), WithSize(sdk.NewDec(10000)), WithMargin(sdk.NewDec(1000)), WithOpenNotional(sdk.NewDec(10600))), // full - InsertPosition(WithTrader(alice), WithPair(pairAtomUsdc), WithSize(sdk.NewDec(10000)), WithMargin(sdk.NewDec(1000)), WithOpenNotional(sdk.NewDec(10000))), // healthy - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 3000))), - ). - When( - MoveToNextBlock(), - MultiLiquidate(liquidator, false, - PairTraderTuple{Pair: pairBtcUsdc, Trader: alice, Successful: true}, - PairTraderTuple{Pair: pairEthUsdc, Trader: alice, Successful: true}, - PairTraderTuple{Pair: pairAtomUsdc, Trader: alice, Successful: false}, - PairTraderTuple{Pair: pairSolUsdc, Trader: alice, Successful: false}, // non-existent market - PairTraderTuple{Pair: pairBtcUsdc, Trader: bob, Successful: false}, // non-existent position - ), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(2350)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(275)), - BalanceEqual(liquidator, types.TestingCollateralDenomNUSD, sdk.NewInt(375)), - PositionShouldBeEqual(alice, pairBtcUsdc, - Position_PositionShouldBeEqualTo( - types.Position{ - Pair: pairBtcUsdc, - TraderAddress: alice.String(), - Size_: sdk.NewDec(5000), - Margin: sdk.MustNewDecFromStr("549.999951250000493750"), - OpenNotional: sdk.MustNewDecFromStr("5199.999975000000375000"), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - }, - ), - ), - PositionShouldNotExist(alice, pairEthUsdc, 1), - PositionShouldBeEqual(alice, pairAtomUsdc, - Position_PositionShouldBeEqualTo( - types.Position{ - Pair: pairAtomUsdc, - TraderAddress: alice.String(), - Size_: sdk.NewDec(10000), - Margin: sdk.NewDec(1000), - OpenNotional: sdk.NewDec(10000), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 0, - }, - ), - ), - - ContainsLiquidateEvent(&types.LiquidationFailedEvent{ - Pair: pairAtomUsdc, - Trader: alice.String(), - Liquidator: liquidator.String(), - Reason: types.LiquidationFailedEvent_POSITION_HEALTHY, - }), - ContainsLiquidateEvent(&types.LiquidationFailedEvent{ - Pair: pairSolUsdc, - Trader: alice.String(), - Liquidator: liquidator.String(), - Reason: types.LiquidationFailedEvent_NONEXISTENT_PAIR, - }), - ContainsLiquidateEvent(&types.LiquidationFailedEvent{ - Pair: pairBtcUsdc, - Trader: bob.String(), - Liquidator: liquidator.String(), - Reason: types.LiquidationFailedEvent_NONEXISTENT_POSITION, - }), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} - -func TestPrettyLiquidateResponse(t *testing.T) { - type TestCase struct { - name string - resps []*types.MsgMultiLiquidateResponse_LiquidationResponse - shouldError bool - // prettyContains: sections of JSON string expected to be contained in - // the pretty output. - prettyContains []string - } - - dummy := struct { - LiquidatorFee sdk.Coin - PerpEfFee sdk.Coin - Trader string - }{ - LiquidatorFee: sdk.NewInt64Coin("unibi", 420), - PerpEfFee: sdk.NewInt64Coin("unibi", 420), - Trader: "dummytrader", - } - - testCases := []TestCase{ - { - name: "empty", - resps: []*types.MsgMultiLiquidateResponse_LiquidationResponse{}, - shouldError: false, - }, - - { - name: "success only", - resps: []*types.MsgMultiLiquidateResponse_LiquidationResponse{ - { - Success: true, - LiquidatorFee: &dummy.LiquidatorFee, - PerpEfFee: &dummy.PerpEfFee, - Trader: dummy.Trader, - }, - }, - shouldError: false, - prettyContains: []string{ - `success": true`, - `liquidator_fee": {`, - `perp_ef_fee": {`, - `denom": "unibi`, - `amount": "420`, - `trader": "dummytrader"`, - }, - }, - - { - name: "errors only", - resps: []*types.MsgMultiLiquidateResponse_LiquidationResponse{ - { - Success: false, - Error: "failed liquidation A", - Trader: dummy.Trader, - }, - { - Success: false, - Error: "failed liquidation B", - Trader: dummy.Trader, - }, - }, - shouldError: false, - prettyContains: []string{ - `success": false`, - `liquidator_fee": null`, - `perp_ef_fee": null`, - `trader": "dummytrader"`, - `error": "failed liquidation A"`, - `error": "failed liquidation B"`, - }, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - pretty, err := keeper.PrettyLiquidateResponse(tc.resps) - - if tc.shouldError { - require.Errorf(t, err, "pretty: %s", pretty) - } else { - require.NoErrorf(t, err, "pretty: %s", pretty) - } - - for _, prettyContains := range tc.prettyContains { - require.Contains(t, pretty, prettyContains) - } - }) - } -} diff --git a/x/perp/v2/keeper/margin.go b/x/perp/v2/keeper/margin.go deleted file mode 100644 index 8f188d130..000000000 --- a/x/perp/v2/keeper/margin.go +++ /dev/null @@ -1,199 +0,0 @@ -package keeper - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// AddMargin adds margin to an existing position, effectively deleveraging it. -// Adding margin increases the margin ratio of the corresponding position. -// -// args: -// - ctx: the cosmos-sdk context -// - pair: the asset pair -// - traderAddr: the trader's address -// - marginToAdd: the amount of margin to add. Must be positive. -// -// ret: -// - res: the response -// - err: error if any -func (k Keeper) AddMargin( - ctx sdk.Context, pair asset.Pair, traderAddr sdk.AccAddress, marginToAdd sdk.Coin, -) (res *types.MsgAddMarginResponse, err error) { - collateral, err := k.Collateral.Get(ctx) - if err != nil { - return nil, err - } - - market, err := k.GetMarket(ctx, pair) - if err != nil { - return nil, fmt.Errorf("%w: %s", types.ErrPairNotFound, pair) - } - amm, err := k.GetAMM(ctx, pair) - if err != nil { - return nil, fmt.Errorf("%w: %s", types.ErrPairNotFound, pair) - } - - if marginToAdd.Denom != collateral { - return nil, fmt.Errorf("invalid margin denom: %s", marginToAdd.Denom) - } - - position, err := k.GetPosition(ctx, pair, market.Version, traderAddr) - if err != nil { - return nil, err - } - - fundingPayment := FundingPayment(position, market.LatestCumulativePremiumFraction) - remainingMargin := position.Margin.Add(sdk.NewDecFromInt(marginToAdd.Amount)).Sub(fundingPayment) - - if remainingMargin.IsNegative() { - return nil, types.ErrBadDebt.Wrapf("applying funding payment would result in negative remaining margin: %s", remainingMargin) - } - - if err = k.BankKeeper.SendCoinsFromAccountToModule( - ctx, - /* from */ traderAddr, - /* to */ types.VaultModuleAccount, - /* amount */ sdk.NewCoins(marginToAdd), - ); err != nil { - return nil, err - } - - // apply funding payment and add margin - position.Margin = remainingMargin - position.LatestCumulativePremiumFraction = market.LatestCumulativePremiumFraction - position.LastUpdatedBlockNumber = ctx.BlockHeight() - k.SavePosition(ctx, pair, market.Version, traderAddr, position) - - positionNotional, err := PositionNotionalSpot(amm, position) - if err != nil { - return nil, err - } - - return &types.MsgAddMarginResponse{ - FundingPayment: fundingPayment, - Position: &position, - }, ctx.EventManager().EmitTypedEvent( - &types.PositionChangedEvent{ - FinalPosition: position, - PositionNotional: positionNotional, - TransactionFee: sdk.NewCoin(collateral, sdk.ZeroInt()), // always zero when adding margin - RealizedPnl: sdk.ZeroDec(), // always zero when adding margin - BadDebt: sdk.NewCoin(collateral, sdk.ZeroInt()), // always zero when adding margin - FundingPayment: fundingPayment, - BlockHeight: ctx.BlockHeight(), - MarginToUser: marginToAdd.Amount.Neg(), - ChangeReason: types.ChangeReason_AddMargin, - }, - ) -} - -/* - RemoveMargin further leverages an existing position by directly removing - -the margin (collateral) that backs it from the vault. This also decreases the -margin ratio of the position. - -Fails if the position goes underwater. - -args: - - ctx: the cosmos-sdk context - - pair: the asset pair - - traderAddr: the trader's address - - margin: the amount of margin to withdraw. Must be positive. - -ret: - - marginOut: the amount of margin removed - - fundingPayment: the funding payment that was applied with this position interaction - - err: error if any -*/ -func (k Keeper) RemoveMargin( - ctx sdk.Context, pair asset.Pair, traderAddr sdk.AccAddress, marginToRemove sdk.Coin, -) (res *types.MsgRemoveMarginResponse, err error) { - collateral, err := k.Collateral.Get(ctx) - if err != nil { - return nil, err - } - - // fetch objects from state - market, err := k.GetMarket(ctx, pair) - if err != nil { - return nil, fmt.Errorf("%w: %s", types.ErrPairNotFound, pair) - } - - amm, err := k.GetAMM(ctx, pair) - if err != nil { - return nil, fmt.Errorf("%w: %s", types.ErrPairNotFound, pair) - } - if marginToRemove.Denom != collateral { - return nil, fmt.Errorf("invalid margin denom: %s", marginToRemove.Denom) - } - - position, err := k.GetPosition(ctx, pair, market.Version, traderAddr) - if err != nil { - return nil, err - } - - // ensure we have enough free collateral - spotNotional, err := PositionNotionalSpot(amm, position) - if err != nil { - return nil, err - } - twapNotional, err := k.PositionNotionalTWAP(ctx, position, market.TwapLookbackWindow) - if err != nil { - return nil, err - } - minPositionNotional := sdk.MinDec(spotNotional, twapNotional) - - // account for funding payment - fundingPayment := FundingPayment(position, market.LatestCumulativePremiumFraction) - remainingMargin := position.Margin.Sub(fundingPayment) - - // account for negative PnL - unrealizedPnl := UnrealizedPnl(position, minPositionNotional) - if unrealizedPnl.IsNegative() { - remainingMargin = remainingMargin.Add(unrealizedPnl) - } - - if remainingMargin.LT(sdk.NewDecFromInt(marginToRemove.Amount)) { - return nil, types.ErrBadDebt.Wrapf( - "not enough free collateral to remove margin; remainingMargin %s, marginToRemove %s", remainingMargin, marginToRemove, - ) - } - - // apply funding payment and remove margin - position.Margin = position.Margin.Sub(fundingPayment).Sub(sdk.NewDecFromInt(marginToRemove.Amount)) - position.LatestCumulativePremiumFraction = market.LatestCumulativePremiumFraction - position.LastUpdatedBlockNumber = ctx.BlockHeight() - - err = k.checkMarginRatio(ctx, market, amm, position) - if err != nil { - return nil, err - } - - if err = k.WithdrawFromVault(ctx, market, traderAddr, marginToRemove.Amount); err != nil { - return nil, err - } - k.SavePosition(ctx, pair, market.Version, traderAddr, position) - - return &types.MsgRemoveMarginResponse{ - FundingPayment: fundingPayment, - Position: &position, - }, ctx.EventManager().EmitTypedEvent( - &types.PositionChangedEvent{ - FinalPosition: position, - PositionNotional: spotNotional, - TransactionFee: sdk.NewCoin(collateral, sdk.ZeroInt()), // always zero when removing margin - RealizedPnl: sdk.ZeroDec(), // always zero when removing margin - BadDebt: sdk.NewCoin(collateral, sdk.ZeroInt()), // always zero when removing margin - FundingPayment: fundingPayment, - BlockHeight: ctx.BlockHeight(), - MarginToUser: marginToRemove.Amount, - ChangeReason: types.ChangeReason_RemoveMargin, - }, - ) -} diff --git a/x/perp/v2/keeper/margin_test.go b/x/perp/v2/keeper/margin_test.go deleted file mode 100644 index 45dbc7e02..000000000 --- a/x/perp/v2/keeper/margin_test.go +++ /dev/null @@ -1,312 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - . "github.com/NibiruChain/nibiru/x/common/testutil/action" - . "github.com/NibiruChain/nibiru/x/common/testutil/assertion" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/assertion" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func TestAddMargin(t *testing.T) { - alice := testutil.AccAddress() - pairBtcUsdc := asset.Registry.Pair(denoms.BTC, denoms.USDC) - pairEthUsdc := asset.Registry.Pair(denoms.ETH, denoms.USDC) - startBlockTime := time.Now() - - tc := TestCases{ - TC("existing long position, add margin"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(2000)))), - MarketOrder(alice, pairBtcUsdc, types.Direction_LONG, sdk.NewInt(1000), sdk.NewDec(10), sdk.ZeroDec()), - ). - When( - MoveToNextBlock(), - AddMargin(alice, pairBtcUsdc, sdk.NewInt(1000)), - ). - Then( - PositionShouldBeEqual(alice, pairBtcUsdc, Position_PositionShouldBeEqualTo( - types.Position{ - Pair: pairBtcUsdc, - TraderAddress: alice.String(), - Size_: sdk.MustNewDecFromStr("9799.999903960000941192"), - Margin: sdk.NewDec(1980), - OpenNotional: sdk.NewDec(9800), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - }, - )), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcUsdc, - TraderAddress: alice.String(), - Size_: sdk.MustNewDecFromStr("9799.999903960000941192"), - Margin: sdk.NewDec(1980), - OpenNotional: sdk.NewDec(9800), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - }, - PositionNotional: sdk.NewDec(9800), - RealizedPnl: sdk.ZeroDec(), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.ZeroDec(), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - BlockHeight: 2, - MarginToUser: sdk.NewInt(-1_000), - ChangeReason: types.ChangeReason_AddMargin, - ExchangedNotional: sdk.MustNewDecFromStr("0"), - ExchangedSize: sdk.MustNewDecFromStr("0"), - }), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(10)), - ModuleBalanceEqual(types.FeePoolModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(10)), - ), - - TC("existing short position, add margin"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(2000)))), - MarketOrder(alice, pairBtcUsdc, types.Direction_SHORT, sdk.NewInt(1000), sdk.NewDec(10), sdk.ZeroDec()), - ). - When( - MoveToNextBlock(), - AddMargin(alice, pairBtcUsdc, sdk.NewInt(1000)), - ). - Then( - PositionShouldBeEqual(alice, pairBtcUsdc, Position_PositionShouldBeEqualTo( - types.Position{ - Pair: pairBtcUsdc, - TraderAddress: alice.String(), - Size_: sdk.MustNewDecFromStr("-9800.000096040000941192"), - Margin: sdk.NewDec(1980), - OpenNotional: sdk.NewDec(9800), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - }, - )), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcUsdc, - TraderAddress: alice.String(), - Size_: sdk.MustNewDecFromStr("-9800.000096040000941192"), - Margin: sdk.NewDec(1980), - OpenNotional: sdk.NewDec(9800), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - }, - PositionNotional: sdk.NewDec(9800), - RealizedPnl: sdk.ZeroDec(), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.ZeroDec(), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - BlockHeight: 2, - MarginToUser: sdk.NewInt(-1000), - ChangeReason: types.ChangeReason_AddMargin, - ExchangedNotional: sdk.MustNewDecFromStr("0"), - ExchangedSize: sdk.MustNewDecFromStr("0"), - }), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(10)), - ModuleBalanceEqual(types.FeePoolModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(10)), - ), - - TC("Testing fails"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - CreateCustomMarket(pairEthUsdc, WithEnabled(true)), - - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1020)))), - MarketOrder(alice, pairBtcUsdc, types.Direction_LONG, sdk.NewInt(1000), sdk.NewDec(10), sdk.ZeroDec()), - ). - When( - MoveToNextBlock(), - AddMarginFail(alice, asset.MustNewPair("luna:usdt"), sdk.NewInt(1000), types.ErrPairNotFound), - AddMarginFail(alice, pairEthUsdc, sdk.NewInt(1000), types.ErrPositionNotFound), - AddMarginFail(alice, pairBtcUsdc, sdk.NewInt(1000), sdkerrors.ErrInsufficientFunds), - - RemoveMarginFail(alice, asset.MustNewPair("luna:usdt"), sdk.NewInt(1000), types.ErrPairNotFound), - RemoveMarginFail(alice, pairEthUsdc, sdk.NewInt(1000), types.ErrPositionNotFound), - RemoveMarginFail(alice, pairBtcUsdc, sdk.NewInt(2000), types.ErrBadDebt), - RemoveMarginFail(alice, pairBtcUsdc, sdk.NewInt(900), types.ErrMarginRatioTooLow), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} - -func TestRemoveMargin(t *testing.T) { - alice := testutil.AccAddress() - pairBtcUsdc := asset.Registry.Pair(denoms.BTC, denoms.USDC) - startBlockTime := time.Now() - - tc := TestCases{ - TC("existing long position, remove margin"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1000)))), - MarketOrder(alice, pairBtcUsdc, types.Direction_LONG, sdk.NewInt(1000), sdk.OneDec(), sdk.ZeroDec()), - ). - When( - MoveToNextBlock(), - RemoveMargin(alice, pairBtcUsdc, sdk.NewInt(500)), - ). - Then( - PositionShouldBeEqual(alice, pairBtcUsdc, Position_PositionShouldBeEqualTo(types.Position{ - Pair: pairBtcUsdc, - TraderAddress: alice.String(), - Size_: sdk.MustNewDecFromStr("997.999999003996000994"), - Margin: sdk.NewDec(498), - OpenNotional: sdk.NewDec(998), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - })), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcUsdc, - TraderAddress: alice.String(), - Size_: sdk.MustNewDecFromStr("997.999999003996000994"), - Margin: sdk.NewDec(498), - OpenNotional: sdk.NewDec(998), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - }, - PositionNotional: sdk.NewDec(998), - RealizedPnl: sdk.ZeroDec(), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.ZeroDec(), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - BlockHeight: 2, - MarginToUser: sdk.NewInt(500), - ChangeReason: types.ChangeReason_RemoveMargin, - ExchangedNotional: sdk.MustNewDecFromStr("0"), - ExchangedSize: sdk.MustNewDecFromStr("0"), - }), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(500)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.OneInt()), - ModuleBalanceEqual(types.FeePoolModuleAccount, types.TestingCollateralDenomNUSD, sdk.OneInt()), - ), - - TC("existing long position, remove almost all margin fails"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1000)))), - MarketOrder(alice, pairBtcUsdc, types.Direction_LONG, sdk.NewInt(1000), sdk.OneDec(), sdk.ZeroDec()), - MoveToNextBlock(), - ). - When( - RemoveMarginFail(alice, pairBtcUsdc, sdk.NewInt(997), types.ErrMarginRatioTooLow), - ). - Then( - PositionShouldBeEqual(alice, pairBtcUsdc, Position_PositionShouldBeEqualTo(types.Position{ - Pair: pairBtcUsdc, - TraderAddress: alice.String(), - Size_: sdk.MustNewDecFromStr("997.999999003996000994"), - Margin: sdk.NewDec(998), - OpenNotional: sdk.NewDec(998), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 1, - })), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.OneInt()), - ModuleBalanceEqual(types.FeePoolModuleAccount, types.TestingCollateralDenomNUSD, sdk.OneInt()), - ), - - TC("existing short position, remove margin"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1000)))), - MarketOrder(alice, pairBtcUsdc, types.Direction_SHORT, sdk.NewInt(1000), sdk.OneDec(), sdk.ZeroDec()), - ). - When( - MoveToNextBlock(), - RemoveMargin(alice, pairBtcUsdc, sdk.NewInt(500)), - ). - Then( - PositionShouldBeEqual(alice, pairBtcUsdc, Position_PositionShouldBeEqualTo(types.Position{ - Pair: pairBtcUsdc, - TraderAddress: alice.String(), - Size_: sdk.MustNewDecFromStr("-998.000000996004000994"), - Margin: sdk.NewDec(498), - OpenNotional: sdk.NewDec(998), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - })), - PositionChangedEventShouldBeEqual(&types.PositionChangedEvent{ - FinalPosition: types.Position{ - Pair: pairBtcUsdc, - TraderAddress: alice.String(), - Size_: sdk.MustNewDecFromStr("-998.000000996004000994"), - Margin: sdk.NewDec(498), - OpenNotional: sdk.NewDec(998), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - }, - PositionNotional: sdk.NewDec(998), - RealizedPnl: sdk.ZeroDec(), - BadDebt: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - FundingPayment: sdk.ZeroDec(), - TransactionFee: sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - BlockHeight: 2, - MarginToUser: sdk.NewInt(500), - ChangeReason: types.ChangeReason_RemoveMargin, - ExchangedNotional: sdk.MustNewDecFromStr("0"), - ExchangedSize: sdk.MustNewDecFromStr("0"), - }), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(500)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.OneInt()), - ModuleBalanceEqual(types.FeePoolModuleAccount, types.TestingCollateralDenomNUSD, sdk.OneInt()), - ), - - TC("existing short position, remove almost all margin fails"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - SetBlockNumber(1), - SetBlockTime(startBlockTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1000)))), - MarketOrder(alice, pairBtcUsdc, types.Direction_SHORT, sdk.NewInt(1000), sdk.OneDec(), sdk.ZeroDec()), - MoveToNextBlock(), - ). - When( - RemoveMarginFail(alice, pairBtcUsdc, sdk.NewInt(997), types.ErrMarginRatioTooLow), - ). - Then( - PositionShouldBeEqual(alice, pairBtcUsdc, Position_PositionShouldBeEqualTo(types.Position{ - Pair: pairBtcUsdc, - TraderAddress: alice.String(), - Size_: sdk.MustNewDecFromStr("-998.000000996004000994"), - Margin: sdk.NewDec(998), - OpenNotional: sdk.NewDec(998), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 1, - })), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.OneInt()), - ModuleBalanceEqual(types.FeePoolModuleAccount, types.TestingCollateralDenomNUSD, sdk.OneInt()), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} diff --git a/x/perp/v2/keeper/msg_server.go b/x/perp/v2/keeper/msg_server.go deleted file mode 100644 index 38586f68b..000000000 --- a/x/perp/v2/keeper/msg_server.go +++ /dev/null @@ -1,241 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -type msgServer struct { - k Keeper -} - -var _ types.MsgServer = msgServer{} - -// NewMsgServerImpl returns an implementation of the MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{k: keeper} -} - -func (m msgServer) RemoveMargin(ctx context.Context, msg *types.MsgRemoveMargin, -) (*types.MsgRemoveMarginResponse, error) { - // These fields should have already been validated by MsgRemoveMargin.ValidateBasic() prior to being sent to the msgServer. - traderAddr := sdk.MustAccAddressFromBech32(msg.Sender) - return m.k.RemoveMargin(sdk.UnwrapSDKContext(ctx), msg.Pair, traderAddr, msg.Margin) -} - -func (m msgServer) AddMargin(ctx context.Context, msg *types.MsgAddMargin, -) (*types.MsgAddMarginResponse, error) { - // These fields should have already been validated by MsgAddMargin.ValidateBasic() prior to being sent to the msgServer. - traderAddr := sdk.MustAccAddressFromBech32(msg.Sender) - return m.k.AddMargin(sdk.UnwrapSDKContext(ctx), msg.Pair, traderAddr, msg.Margin) -} - -func (m msgServer) MarketOrder(goCtx context.Context, req *types.MsgMarketOrder, -) (response *types.MsgMarketOrderResponse, err error) { - traderAddr := sdk.MustAccAddressFromBech32(req.Sender) - - positionResp, err := m.k.MarketOrder( - sdk.UnwrapSDKContext(goCtx), - req.Pair, - req.Side, - traderAddr, - req.QuoteAssetAmount, - req.Leverage, - sdk.NewDecFromInt(req.BaseAssetAmountLimit), - ) - if err != nil { - return nil, err - } - - return &types.MsgMarketOrderResponse{ - Position: &positionResp.Position, - ExchangedNotionalValue: positionResp.ExchangedNotionalValue, - ExchangedPositionSize: positionResp.ExchangedPositionSize, - FundingPayment: positionResp.FundingPayment, - RealizedPnl: positionResp.RealizedPnl, - UnrealizedPnlAfter: positionResp.UnrealizedPnlAfter, - MarginToVault: positionResp.MarginToVault, - PositionNotional: positionResp.PositionNotional, - }, nil -} - -func (m msgServer) ClosePosition(goCtx context.Context, req *types.MsgClosePosition) (*types.MsgClosePositionResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - traderAddr := sdk.MustAccAddressFromBech32(req.Sender) - - resp, err := m.k.ClosePosition(ctx, req.Pair, traderAddr) - if err != nil { - return nil, err - } - - return &types.MsgClosePositionResponse{ - ExchangedNotionalValue: resp.ExchangedNotionalValue, - ExchangedPositionSize: resp.ExchangedPositionSize, - FundingPayment: resp.FundingPayment, - RealizedPnl: resp.RealizedPnl, - MarginToTrader: resp.MarginToVault.Neg(), - }, nil -} - -func (m msgServer) PartialClose(goCtx context.Context, req *types.MsgPartialClose) (*types.MsgPartialCloseResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - traderAddr := sdk.MustAccAddressFromBech32(req.Sender) - - resp, err := m.k.PartialClose(ctx, req.Pair, traderAddr, req.Size_) - if err != nil { - return nil, err - } - - return &types.MsgPartialCloseResponse{ - ExchangedNotionalValue: resp.ExchangedNotionalValue, - ExchangedPositionSize: resp.ExchangedPositionSize, - FundingPayment: resp.FundingPayment, - RealizedPnl: resp.RealizedPnl, - MarginToTrader: resp.MarginToVault.Neg(), - }, nil -} - -func (m msgServer) MultiLiquidate(goCtx context.Context, req *types.MsgMultiLiquidate) (*types.MsgMultiLiquidateResponse, error) { - resp, err := m.k.MultiLiquidate(sdk.UnwrapSDKContext(goCtx), sdk.MustAccAddressFromBech32(req.Sender), req.Liquidations) - if err != nil { - return nil, err - } - - return &types.MsgMultiLiquidateResponse{Liquidations: resp}, nil -} - -func (m msgServer) SettlePosition(ctx context.Context, msg *types.MsgSettlePosition) (*types.MsgClosePositionResponse, error) { - // These fields should have already been validated by MsgSettlePosition.ValidateBasic() prior to being sent to the msgServer. - traderAddr := sdk.MustAccAddressFromBech32(msg.Sender) - resp, err := m.k.SettlePosition(sdk.UnwrapSDKContext(ctx), msg.Pair, msg.Version, traderAddr) - if err != nil { - return nil, err - } - - return &types.MsgClosePositionResponse{ - ExchangedNotionalValue: resp.ExchangedNotionalValue, - ExchangedPositionSize: resp.ExchangedPositionSize, - FundingPayment: resp.FundingPayment, - RealizedPnl: resp.RealizedPnl, - MarginToTrader: resp.MarginToVault.Neg(), - }, nil -} - -// DonateToEcosystemFund allows users to donate to the ecosystem fund. -func (m msgServer) DonateToEcosystemFund(ctx context.Context, msg *types.MsgDonateToEcosystemFund) (*types.MsgDonateToEcosystemFundResponse, error) { - if err := m.k.BankKeeper.SendCoinsFromAccountToModule( - sdk.UnwrapSDKContext(ctx), - sdk.MustAccAddressFromBech32(msg.Sender), - types.PerpFundModuleAccount, - sdk.NewCoins(msg.Donation), - ); err != nil { - return nil, err - } - - return &types.MsgDonateToEcosystemFundResponse{}, nil -} - -// ChangeCollateralDenom Updates the collateral denom. A denom is valid if it is -// possible to make an sdk.Coin using it. [SUDO] Only callable by sudoers. -func (m msgServer) ChangeCollateralDenom( - goCtx context.Context, txMsg *types.MsgChangeCollateralDenom, -) (resp *types.MsgChangeCollateralDenomResponse, err error) { - if txMsg == nil { - return resp, common.ErrNilMsg() - } - if err := txMsg.ValidateBasic(); err != nil { - return resp, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - err = m.k.Sudo().ChangeCollateralDenom(ctx, txMsg.NewDenom, txMsg.GetSigners()[0]) - - return &types.MsgChangeCollateralDenomResponse{}, err -} - -func (m msgServer) AllocateEpochRebates( - ctx context.Context, msg *types.MsgAllocateEpochRebates, -) (*types.MsgAllocateEpochRebatesResponse, error) { - if msg == nil { - return nil, common.ErrNilMsg() - } - - // Sender is checked in `msg.ValidateBasic` before reaching this fn call. - sender, _ := sdk.AccAddressFromBech32(msg.Sender) - total, err := m.k.AllocateEpochRebates(sdk.UnwrapSDKContext(ctx), sender, msg.Rebates) - if err != nil { - return nil, err - } - - return &types.MsgAllocateEpochRebatesResponse{TotalEpochRebates: total}, nil -} - -func (m msgServer) WithdrawEpochRebates(ctx context.Context, msg *types.MsgWithdrawEpochRebates) (*types.MsgWithdrawEpochRebatesResponse, error) { - if msg == nil { - return nil, common.ErrNilMsg() - } - // Sender is checked in `msg.ValidateBasic` before reaching this fn call. - sender, _ := sdk.AccAddressFromBech32(msg.Sender) - sdkCtx := sdk.UnwrapSDKContext(ctx) - totalWithdrawn := sdk.NewCoins() - for _, epoch := range msg.Epochs { - withdrawn, err := m.k.WithdrawEpochRebates(sdkCtx, epoch, sender) - if err != nil { - return nil, err - } - totalWithdrawn = totalWithdrawn.Add(withdrawn...) - } - return &types.MsgWithdrawEpochRebatesResponse{ - WithdrawnRebates: totalWithdrawn, - }, nil -} - -// ShiftPegMultiplier: gRPC tx msg for changing a market's peg multiplier. -// [SUDO] Only callable by sudoers. -func (m msgServer) ShiftPegMultiplier( - goCtx context.Context, msg *types.MsgShiftPegMultiplier, -) (*types.MsgShiftPegMultiplierResponse, error) { - // Sender is checked in `msg.ValidateBasic` before reaching this fn call. - sender, _ := sdk.AccAddressFromBech32(msg.Sender) - ctx := sdk.UnwrapSDKContext(goCtx) - err := m.k.Sudo().ShiftPegMultiplier(ctx, msg.Pair, msg.NewPegMult, sender) - return &types.MsgShiftPegMultiplierResponse{}, err -} - -// ShiftSwapInvariant: gRPC tx msg for changing a market's swap invariant. -// [SUDO] Only callable by sudoers. -func (m msgServer) ShiftSwapInvariant( - goCtx context.Context, msg *types.MsgShiftSwapInvariant, -) (*types.MsgShiftSwapInvariantResponse, error) { - // Sender is checked in `msg.ValidateBasic` before reaching this fn call. - sender, _ := sdk.AccAddressFromBech32(msg.Sender) - ctx := sdk.UnwrapSDKContext(goCtx) - err := m.k.Sudo().ShiftSwapInvariant(ctx, msg.Pair, msg.NewSwapInvariant, sender) - return &types.MsgShiftSwapInvariantResponse{}, err -} - -// WithdrawFromPerpFund: gRPC tx msg for changing a market's swap invariant. -// [SUDO] Only callable by sudoers. -func (m msgServer) WithdrawFromPerpFund( - goCtx context.Context, msg *types.MsgWithdrawFromPerpFund, -) (resp *types.MsgWithdrawFromPerpFundResponse, err error) { - // Sender is checked in `msg.ValidateBasic` before reaching this fn call. - sender, _ := sdk.AccAddressFromBech32(msg.Sender) - toAddr, _ := sdk.AccAddressFromBech32(msg.ToAddr) - ctx := sdk.UnwrapSDKContext(goCtx) - return resp, m.k.Sudo().WithdrawFromPerpFund( - ctx, msg.Amount, sender, toAddr, msg.Denom, - ) -} - -// CloseMarket closes a market. -func (m msgServer) CloseMarket(ctx context.Context, msg *types.MsgCloseMarket) (*types.MsgCloseMarketResponse, error) { - sender, _ := sdk.AccAddressFromBech32(msg.Sender) - err := m.k.Sudo().CloseMarket(sdk.UnwrapSDKContext(ctx), msg.Pair, sender) - return &types.MsgCloseMarketResponse{}, err -} diff --git a/x/perp/v2/keeper/msg_server_test.go b/x/perp/v2/keeper/msg_server_test.go deleted file mode 100644 index ea7269dd2..000000000 --- a/x/perp/v2/keeper/msg_server_test.go +++ /dev/null @@ -1,509 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - inflationtypes "github.com/NibiruChain/nibiru/x/inflation/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - . "github.com/NibiruChain/nibiru/x/common/testutil/action" - . "github.com/NibiruChain/nibiru/x/common/testutil/assertion" - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/assertion" - perpkeeper "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - "github.com/NibiruChain/nibiru/x/perp/v2/types" - sudoerTypes "github.com/NibiruChain/nibiru/x/sudo/types" -) - -func TestMsgServerMarketOrder(t *testing.T) { - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - alice := testutil.AccAddress() - - tests := TestCases{ - TC("open long position"). - Given( - CreateCustomMarket(pair, WithEnabled(true)), - FundAccount(alice, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 100))), - ). - When( - MsgServerMarketOrder(alice, pair, types.Direction_LONG, sdk.OneInt(), sdk.OneDec(), sdk.ZeroInt()), - ). - Then( - PositionShouldBeEqual(alice, pair, - Position_PositionShouldBeEqualTo(types.Position{ - TraderAddress: alice.String(), - Pair: pair, - Size_: sdk.MustNewDecFromStr("0.999999999999"), - Margin: sdk.OneDec(), - OpenNotional: sdk.OneDec(), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 1, - }), - ), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(99)), - ), - - TC("open short position"). - Given( - CreateCustomMarket(pair, WithEnabled(true)), - FundAccount(alice, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 100))), - ). - When( - MsgServerMarketOrder(alice, pair, types.Direction_SHORT, sdk.OneInt(), sdk.OneDec(), sdk.ZeroInt()), - ). - Then( - PositionShouldBeEqual(alice, pair, - Position_PositionShouldBeEqualTo(types.Position{ - TraderAddress: alice.String(), - Pair: pair, - Size_: sdk.MustNewDecFromStr("-1.000000000001"), - Margin: sdk.OneDec(), - OpenNotional: sdk.OneDec(), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 1, - }), - ), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(99)), - ), - } - - NewTestSuite(t).WithTestCases(tests...).Run() -} - -func TestMsgServerClosePosition(t *testing.T) { - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - alice := testutil.AccAddress() - - tests := TestCases{ - TC("close long position"). - Given( - CreateCustomMarket(pair, WithEnabled(true)), - FundAccount(alice, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 100))), - MarketOrder(alice, pair, types.Direction_LONG, sdk.OneInt(), sdk.OneDec(), sdk.ZeroDec()), - MoveToNextBlock(), - ). - When( - MsgServerClosePosition(alice, pair), - ). - Then( - PositionShouldNotExist(alice, pair, 1), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(100)), - ), - - TC("close short position"). - Given( - CreateCustomMarket(pair, WithEnabled(true)), - FundAccount(alice, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 100))), - MarketOrder(alice, pair, types.Direction_LONG, sdk.OneInt(), sdk.OneDec(), sdk.ZeroDec()), - MoveToNextBlock(), - ). - When( - MsgServerClosePosition(alice, pair), - ). - Then( - PositionShouldNotExist(alice, pair, 1), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(100)), - ), - } - - NewTestSuite(t).WithTestCases(tests...).Run() -} - -func TestMsgServerAddMargin(t *testing.T) { - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - alice := testutil.AccAddress() - - tests := TestCases{ - TC("add margin"). - Given( - CreateCustomMarket(pair, WithEnabled(true)), - FundAccount(alice, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 100))), - MarketOrder(alice, pair, types.Direction_LONG, sdk.OneInt(), sdk.OneDec(), sdk.ZeroDec()), - MoveToNextBlock(), - ). - When( - MsgServerAddMargin(alice, pair, sdk.OneInt()), - ). - Then( - PositionShouldBeEqual(alice, pair, - Position_PositionShouldBeEqualTo(types.Position{ - TraderAddress: alice.String(), - Pair: pair, - Size_: sdk.MustNewDecFromStr("0.999999999999"), - Margin: sdk.NewDec(2), - OpenNotional: sdk.OneDec(), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - }), - ), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(98)), - ), - TC("msg server close"). - Given( - CreateCustomMarket(pair, WithEnabled(true)), - FundAccount(alice, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 100))), - MarketOrder(alice, pair, types.Direction_LONG, sdk.OneInt(), sdk.OneDec(), sdk.ZeroDec()), - MoveToNextBlock(), - ). - When( - MsgServerAddMargin(alice, pair, sdk.OneInt()), - ). - Then( - PositionShouldBeEqual(alice, pair, - Position_PositionShouldBeEqualTo(types.Position{ - TraderAddress: alice.String(), - Pair: pair, - Size_: sdk.MustNewDecFromStr("0.999999999999"), - Margin: sdk.NewDec(2), - OpenNotional: sdk.OneDec(), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - }), - ), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(98)), - ), - TC("partial close"). - Given( - CreateCustomMarket(pair, WithEnabled(true)), - FundAccount(alice, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 100))), - MarketOrder(alice, pair, types.Direction_LONG, sdk.OneInt(), sdk.OneDec(), sdk.ZeroDec()), - MoveToNextBlock(), - ). - When( - MsgServerPartialClosePosition(alice, pair, sdk.MustNewDecFromStr("0.5")), - ). - Then( - PositionShouldBeEqual(alice, pair, - Position_PositionShouldBeEqualTo(types.Position{ - TraderAddress: alice.String(), - Pair: pair, - Size_: sdk.MustNewDecFromStr("0.499999999999"), - Margin: sdk.NewDec(1), - OpenNotional: sdk.MustNewDecFromStr("0.499999999999250000"), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - }), - ), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(99)), - ), - } - - NewTestSuite(t).WithTestCases(tests...).Run() -} - -func TestMsgServerRemoveMargin(t *testing.T) { - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - alice := testutil.AccAddress() - - tests := TestCases{ - TC("add margin"). - Given( - CreateCustomMarket(pair, WithEnabled(true)), - FundAccount(alice, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 100))), - MarketOrder(alice, pair, types.Direction_LONG, sdk.NewInt(2), sdk.OneDec(), sdk.ZeroDec()), - MoveToNextBlock(), - ). - When( - MsgServerRemoveMargin(alice, pair, sdk.OneInt()), - ). - Then( - PositionShouldBeEqual(alice, pair, - Position_PositionShouldBeEqualTo(types.Position{ - TraderAddress: alice.String(), - Pair: pair, - Size_: sdk.MustNewDecFromStr("1.999999999996"), - Margin: sdk.OneDec(), - OpenNotional: sdk.NewDec(2), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - }), - ), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(99)), - ), - } - - NewTestSuite(t).WithTestCases(tests...).Run() -} - -func TestMsgServerDonateToPerpEf(t *testing.T) { - alice := testutil.AccAddress() - - tests := TestCases{ - TC("success"). - Given( - SetCollateral(types.TestingCollateralDenomNUSD), - FundAccount(alice, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 100))), - ). - When( - MsgServerDonateToPerpEf(alice, sdk.NewInt(50)), - ). - Then( - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(50)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(50)), - ), - } - - NewTestSuite(t).WithTestCases(tests...).Run() -} - -func TestMsgServerMultiLiquidate(t *testing.T) { - pairBtcUsdc := asset.Registry.Pair(denoms.BTC, denoms.USDC) - alice := testutil.AccAddress() - liquidator := testutil.AccAddress() - startTime := time.Now() - - tests := TestCases{ - TC("partial liquidation"). - Given( - SetBlockNumber(1), - SetBlockTime(startTime), - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - InsertPosition(WithTrader(alice), WithPair(pairBtcUsdc), WithSize(sdk.NewDec(10000)), WithMargin(sdk.NewDec(1000)), WithOpenNotional(sdk.NewDec(10400))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1000))), - ). - When( - MoveToNextBlock(), - MsgServerMultiLiquidate(liquidator, false, - PairTraderTuple{Pair: pairBtcUsdc, Trader: alice, Successful: true}, - ), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(750)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(125)), - BalanceEqual(liquidator, types.TestingCollateralDenomNUSD, sdk.NewInt(125)), - PositionShouldBeEqual(alice, pairBtcUsdc, - Position_PositionShouldBeEqualTo( - types.Position{ - Pair: pairBtcUsdc, - TraderAddress: alice.String(), - Size_: sdk.NewDec(5000), - Margin: sdk.MustNewDecFromStr("549.999951250000493750"), - OpenNotional: sdk.MustNewDecFromStr("5199.999975000000375000"), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: 2, - }, - ), - ), - ), - - TC("full liquidation"). - Given( - SetBlockNumber(1), - SetBlockTime(startTime), - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - InsertPosition(WithTrader(alice), WithPair(pairBtcUsdc), WithSize(sdk.NewDec(10000)), WithMargin(sdk.NewDec(1000)), WithOpenNotional(sdk.NewDec(10600))), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 1000))), - ). - When( - MoveToNextBlock(), - MsgServerMultiLiquidate(liquidator, false, - PairTraderTuple{Pair: pairBtcUsdc, Trader: alice, Successful: true}, - ), - ). - Then( - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(600)), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.NewInt(150)), - BalanceEqual(liquidator, types.TestingCollateralDenomNUSD, sdk.NewInt(250)), - PositionShouldNotExist(alice, pairBtcUsdc, 1), - ), - } - - NewTestSuite(t).WithTestCases(tests...).Run() -} - -func TestFailMsgServer(t *testing.T) { - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - app, ctx := testapp.NewNibiruTestAppAndContext() - - sender := testutil.AccAddress().String() - - msgServer := perpkeeper.NewMsgServerImpl(app.PerpKeeperV2) - - _, err := msgServer.MarketOrder(ctx, &types.MsgMarketOrder{ - Sender: sender, - Pair: pair, - Side: types.Direction_LONG, - QuoteAssetAmount: sdk.OneInt(), - Leverage: sdk.OneDec(), - BaseAssetAmountLimit: sdk.ZeroInt(), - }) - require.ErrorContains(t, err, "pair ubtc:unusd not found") - - _, err = msgServer.ClosePosition(ctx, &types.MsgClosePosition{ - Sender: sender, - Pair: pair, - }) - require.ErrorContains(t, err, types.ErrPairNotFound.Error()) - - _, err = msgServer.PartialClose(ctx, &types.MsgPartialClose{ - Sender: sender, - Pair: pair, - Size_: sdk.OneDec(), - }) - require.ErrorContains(t, err, types.ErrPairNotFound.Error()) - - _, err = msgServer.MultiLiquidate(ctx, &types.MsgMultiLiquidate{ - Sender: sender, - Liquidations: []*types.MsgMultiLiquidate_Liquidation{ - { - Pair: pair, - Trader: sender, - }, - }, - }) - require.ErrorContains(t, err, types.ErrPairNotFound.Error()) - - _, err = msgServer.DonateToEcosystemFund(ctx, &types.MsgDonateToEcosystemFund{ - Sender: sender, - Donation: sdk.NewCoin("luna", sdk.OneInt()), - }) - require.ErrorContains(t, err, "spendable balance is smaller than 1luna") -} - -func TestMsgChangeCollateralDenom(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - sender := testutil.AccAddress().String() - - msgServer := perpkeeper.NewMsgServerImpl(app.PerpKeeperV2) - - _, err := msgServer.ChangeCollateralDenom(ctx, nil) - require.ErrorContains(t, err, "nil msg") - - _, err = msgServer.ChangeCollateralDenom(ctx, &types.MsgChangeCollateralDenom{ - Sender: sender, - NewDenom: "luna", - }) - require.ErrorContains(t, err, "insufficient permissions on smart contract") - - app.SudoKeeper.Sudoers.Set(ctx, sudoerTypes.Sudoers{Contracts: []string{sender}}) - _, err = msgServer.ChangeCollateralDenom(ctx, &types.MsgChangeCollateralDenom{ - Sender: sender, - NewDenom: "luna", - }) - require.NoError(t, err) - - app.SudoKeeper.Sudoers.Set(ctx, sudoerTypes.Sudoers{Contracts: []string{sender}}) - _, err = msgServer.ChangeCollateralDenom(ctx, &types.MsgChangeCollateralDenom{ - Sender: sender, - NewDenom: "", - }) - require.ErrorContains(t, err, "invalid denom") - - app.SudoKeeper.Sudoers.Set(ctx, sudoerTypes.Sudoers{Contracts: []string{sender}}) - _, err = msgServer.ChangeCollateralDenom(ctx, &types.MsgChangeCollateralDenom{ - NewDenom: "luna", - }) - require.ErrorContains(t, err, "invalid sender address") -} - -func TestMsgServerSettlePosition(t *testing.T) { - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - alice := testutil.AccAddress() - - adminUser, err := sdk.AccAddressFromBech32(testutil.ADDR_SUDO_ROOT) - require.NoError(t, err) - - tests := TestCases{ - TC("Settleposition"). - Given( - CreateCustomMarket(pair, WithEnabled(true)), - FundAccount(alice, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 100))), - MarketOrder(alice, pair, types.Direction_LONG, sdk.OneInt(), sdk.OneDec(), sdk.ZeroDec()), - MoveToNextBlock(), - CloseMarket(pair, adminUser), - ). - When( - MsgServerSettlePosition(alice, pair, 1), - ). - Then( - PositionShouldNotExist(alice, pair, 1), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(100)), - ), - TC("SettlepositionOpenedMarket"). - Given( - CreateCustomMarket(pair, WithEnabled(true)), - FundAccount(alice, sdk.NewCoins(sdk.NewInt64Coin(types.TestingCollateralDenomNUSD, 100))), - MarketOrder(alice, pair, types.Direction_LONG, sdk.OneInt(), sdk.OneDec(), sdk.ZeroDec()), - MoveToNextBlock(), - ). - When( - MsgServerSettlePositionShouldFail(alice, pair, 1), - ). - Then( - PositionShouldExist(alice, pair, 1), - ), - } - - NewTestSuite(t).WithTestCases(tests...).Run() -} - -func TestAllocateEpochRebates(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - sender := testutil.AccAddress().String() - - msgServer := perpkeeper.NewMsgServerImpl(app.PerpKeeperV2) - - _, err := msgServer.AllocateEpochRebates(ctx, nil) - require.ErrorContains(t, err, "nil msg") - - _, err = msgServer.AllocateEpochRebates(ctx, &types.MsgAllocateEpochRebates{}) - require.NoError(t, err) - - _, err = msgServer.AllocateEpochRebates(ctx, &types.MsgAllocateEpochRebates{ - Sender: sender, - Rebates: sdk.NewCoins(sdk.NewCoin("unibi", sdk.NewInt(100))), - }) - require.ErrorContains(t, err, "insufficient funds") - - require.NoError(t, - app.BankKeeper.MintCoins(ctx, - inflationtypes.ModuleName, - sdk.NewCoins(sdk.NewCoin("unibi", sdk.NewInt(100))), - ), - ) - require.NoError(t, - app.BankKeeper.SendCoinsFromModuleToAccount(ctx, - inflationtypes.ModuleName, sdk.MustAccAddressFromBech32(sender), - sdk.NewCoins(sdk.NewCoin("unibi", sdk.NewInt(100)))), - ) - - _, err = msgServer.AllocateEpochRebates(ctx, &types.MsgAllocateEpochRebates{ - Sender: sender, - Rebates: sdk.NewCoins(sdk.NewCoin("unibi", sdk.NewInt(100))), - }) - require.NoError(t, err) - - // Withdraw rebates - _, err = msgServer.WithdrawEpochRebates(ctx, nil) - require.ErrorContains(t, err, "nil msg") - - _, err = msgServer.WithdrawEpochRebates(ctx, &types.MsgWithdrawEpochRebates{}) - require.NoError(t, err) - - _, err = msgServer.WithdrawEpochRebates(ctx, &types.MsgWithdrawEpochRebates{ - Sender: sender, - Epochs: []uint64{1}, - }) - require.ErrorContains(t, err, "collections: not found") - - currentEpoch, err := app.PerpKeeperV2.DnREpoch.Get(ctx) - require.NoError(t, err) - - require.NoError(t, app.PerpKeeperV2.StartNewEpoch(ctx, currentEpoch+1)) - require.NoError(t, app.PerpKeeperV2.StartNewEpoch(ctx, currentEpoch+2)) - - _, err = msgServer.WithdrawEpochRebates(ctx, &types.MsgWithdrawEpochRebates{ - Sender: sender, - Epochs: []uint64{1}, - }) - require.NoError(t, err) -} diff --git a/x/perp/v2/keeper/position.go b/x/perp/v2/keeper/position.go deleted file mode 100644 index 52d5d9fe4..000000000 --- a/x/perp/v2/keeper/position.go +++ /dev/null @@ -1,33 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/collections" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// GetPosition returns the position or types.ErrPositionNotFound if it does not exist. -func (k Keeper) GetPosition(ctx sdk.Context, pair asset.Pair, version uint64, account sdk.AccAddress) (types.Position, error) { - position, err := k.Positions.Get(ctx, collections.Join(collections.Join(pair, version), account)) - if err != nil { - return types.Position{}, types.ErrPositionNotFound - } - - return position, nil -} - -func (k Keeper) DeletePosition(ctx sdk.Context, pair asset.Pair, version uint64, account sdk.AccAddress) error { - err := k.Positions.Delete(ctx, collections.Join(collections.Join(pair, version), account)) - if err != nil { - return types.ErrPositionNotFound - } - - return nil -} - -func (k Keeper) SavePosition(ctx sdk.Context, pair asset.Pair, version uint64, account sdk.AccAddress, position types.Position) { - k.Positions.Insert(ctx, collections.Join(collections.Join(position.Pair, version), account), position) -} diff --git a/x/perp/v2/keeper/position_test.go b/x/perp/v2/keeper/position_test.go deleted file mode 100644 index b55569d4a..000000000 --- a/x/perp/v2/keeper/position_test.go +++ /dev/null @@ -1 +0,0 @@ -package keeper diff --git a/x/perp/v2/keeper/settlement.go b/x/perp/v2/keeper/settlement.go deleted file mode 100644 index 5396be2b3..000000000 --- a/x/perp/v2/keeper/settlement.go +++ /dev/null @@ -1,118 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// SettlePosition settles a position and transfer the margin and funding payments to the trader. -func (k Keeper) SettlePosition(ctx sdk.Context, pair asset.Pair, version uint64, traderAddr sdk.AccAddress) (resp *types.PositionResp, err error) { - market, err := k.GetMarketByPairAndVersion(ctx, pair, version) - if err != nil { - return - } - if market.Enabled { - return nil, types.ErrSettlementPositionMarketEnabled - } - - amm, err := k.GetAMMByPairAndVersion(ctx, pair, version) - if err != nil { - return - } - - position, err := k.GetPosition(ctx, pair, version, traderAddr) - if err != nil { - return - } - - _, positionResp, err := k.settlePosition(ctx, market, amm, position) - if err != nil { - return - } - - if positionResp.BadDebt.IsPositive() { - if err = k.realizeBadDebt( - ctx, - market, - positionResp.BadDebt.RoundInt(), - ); err != nil { - return nil, err - } - } - - if err = k.afterPositionUpdate( - ctx, - market, - traderAddr, - *positionResp, - types.ChangeReason_Settlement, - sdk.ZeroInt(), - position, - ); err != nil { - return nil, err - } - - return positionResp, nil -} - -// Settles a position and realizes PnL and funding payments. -// Returns the updated AMM and the realized PnL and funding payments. -func (k Keeper) settlePosition(ctx sdk.Context, market types.Market, amm types.AMM, position types.Position) (updatedAMM *types.AMM, resp *types.PositionResp, err error) { - positionNotional := position.Size_.Abs().Mul(amm.SettlementPrice) - - resp = &types.PositionResp{ - ExchangedPositionSize: position.Size_.Neg(), - PositionNotional: sdk.ZeroDec(), - FundingPayment: FundingPayment(position, market.LatestCumulativePremiumFraction), - RealizedPnl: UnrealizedPnl(position, positionNotional), - UnrealizedPnlAfter: sdk.ZeroDec(), - } - - remainingMargin := position.Margin.Add(resp.RealizedPnl).Sub(resp.FundingPayment) - - if remainingMargin.IsPositive() { - resp.BadDebt = sdk.ZeroDec() - resp.MarginToVault = remainingMargin.Neg() - } else { - resp.BadDebt = remainingMargin.Abs() - resp.MarginToVault = sdk.ZeroDec() - } - - var dir types.Direction - // flipped since we are going against the current position - if position.Size_.IsPositive() { - dir = types.Direction_SHORT - } else { - dir = types.Direction_LONG - } - updatedAMM, exchangedNotionalValue, err := k.SwapBaseAsset( - ctx, - amm, - dir, - position.Size_.Abs(), - sdk.ZeroDec(), - ) - if err != nil { - return nil, nil, err - } - - resp.ExchangedNotionalValue = exchangedNotionalValue - resp.Position = types.Position{ - TraderAddress: position.TraderAddress, - Pair: position.Pair, - Size_: sdk.ZeroDec(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.ZeroDec(), - LatestCumulativePremiumFraction: market.LatestCumulativePremiumFraction, - LastUpdatedBlockNumber: ctx.BlockHeight(), - } - - err = k.DeletePosition(ctx, position.Pair, market.Version, sdk.MustAccAddressFromBech32(position.TraderAddress)) - if err != nil { - return nil, nil, err - } - - return updatedAMM, resp, nil -} diff --git a/x/perp/v2/keeper/settlement_test.go b/x/perp/v2/keeper/settlement_test.go deleted file mode 100644 index d80faaa0d..000000000 --- a/x/perp/v2/keeper/settlement_test.go +++ /dev/null @@ -1,242 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - . "github.com/NibiruChain/nibiru/x/common/testutil/action" - . "github.com/NibiruChain/nibiru/x/common/testutil/assertion" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/assertion" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func TestSettlePosition(t *testing.T) { - pairBtcUsdc := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - startTime := time.Now() - - alice := testutil.AccAddress() - bob := testutil.AccAddress() - - adminUser, err := sdk.AccAddressFromBech32(testutil.ADDR_SUDO_ROOT) - require.NoError(t, err) - - tc := TestCases{ - TC("Happy path").When( - CreateCustomMarket( - pairBtcUsdc, - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - WithEnabled(true), - ), - SetBlockNumber(1), - SetBlockTime(startTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200)))), - MarketOrder( - alice, - pairBtcUsdc, - types.Direction_LONG, - sdk.NewInt(10_000), - sdk.OneDec(), - sdk.ZeroDec(), - ), - ).When( - CloseMarket(pairBtcUsdc, adminUser), - SettlePosition(pairBtcUsdc, 1, alice), - ).Then( - PositionShouldNotExist(alice, pairBtcUsdc, 1), - ), - - TC("Happy path, but with bad debt").When( - CreateCustomMarket( - pairBtcUsdc, - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - WithEnabled(true), - ), - SetBlockNumber(1), - SetBlockTime(startTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(104)))), // need 4 because we need to pay for the close position fee - FundAccount(bob, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1_020)))), - MarketOrder( - alice, - pairBtcUsdc, - types.Direction_SHORT, - sdk.NewInt(100), - sdk.NewDec(10), - sdk.ZeroDec(), - ), - MarketOrder( - bob, - pairBtcUsdc, - types.Direction_LONG, - sdk.NewInt(1_000), - sdk.NewDec(10), - sdk.ZeroDec(), - ), - QueryPosition(pairBtcUsdc, alice, QueryPosition_MarginRatioEquals(sdk.MustNewDecFromStr("-0.090096188479034643"))), - ).When( - // Alice opened a short position (leverage x10) while bob a bigger long position - // Price jumped by 10%, with a settlement price of 1.09 - // That creates a bad debt for alice - // Her Realized Pnl is -101.01010101 and her margin is 100, so -1.01010101 is bad debt - // Bob's Realized Pnl is 1010, so he has 1010 more than his margin - - CloseMarket(pairBtcUsdc, adminUser), - SettlePosition( - pairBtcUsdc, - 1, - alice, - SettlePositionChecker_PositionEquals( - types.Position{ - TraderAddress: alice.String(), - Pair: "ubtc:unusd", - Size_: sdk.MustNewDecFromStr("0"), - Margin: sdk.MustNewDecFromStr("0"), - OpenNotional: sdk.MustNewDecFromStr("0"), - LatestCumulativePremiumFraction: sdk.MustNewDecFromStr("0"), - LastUpdatedBlockNumber: 1, - }, - ), - SettlePositionChecker_MarginToVault(sdk.MustNewDecFromStr("-1.009493031710765502")), - SettlePositionChecker_BadDebt(sdk.ZeroDec()), - ), - SettlePosition( - pairBtcUsdc, - 1, - bob, - SettlePositionChecker_MarginToVault(sdk.MustNewDecFromStr("-1076.990506968289234498")), - SettlePositionChecker_BadDebt(sdk.ZeroDec()), - ), - ).Then( - PositionShouldNotExist(alice, pairBtcUsdc, 1), - PositionShouldNotExist(bob, pairBtcUsdc, 1), - SetBlockNumber(2), - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(5)), - BalanceEqual(bob, types.TestingCollateralDenomNUSD, sdk.NewInt(1095)), - ), - - TC("Error: can't settle on enabled market").When( - CreateCustomMarket( - pairBtcUsdc, - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - WithEnabled(true), - ), - SetBlockNumber(1), - SetBlockTime(startTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(10_200)))), - MarketOrder( - alice, - pairBtcUsdc, - types.Direction_LONG, - sdk.NewInt(10_000), - sdk.OneDec(), - sdk.ZeroDec(), - ), - ).When( - SettlePositionShouldFail(pairBtcUsdc, 1, alice), - ), - - TC("Error: can't settle on enabled market (with a live market in another version)").When( - CreateCustomMarket( - pairBtcUsdc, - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - WithVersion(1), - WithEnabled(true), - ), - SetBlockNumber(1), - SetBlockTime(startTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(20_400)))), - MarketOrder( - alice, - pairBtcUsdc, - types.Direction_LONG, - sdk.NewInt(10_000), - sdk.OneDec(), - sdk.ZeroDec(), - ), - ).When( - CloseMarket(pairBtcUsdc, adminUser), - CreateCustomMarket( - pairBtcUsdc, - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - WithVersion(2), - WithEnabled(true), - ), - SetBlockNumber(2), - MarketOrder( - alice, - pairBtcUsdc, - types.Direction_LONG, - sdk.NewInt(10_000), - sdk.OneDec(), - sdk.ZeroDec(), - ), - ).Then( - SettlePositionShouldFail(pairBtcUsdc, 3, alice), // can't settle on non existing market - SettlePositionShouldFail(pairBtcUsdc, 2, alice), // can't settle on live market - SettlePosition(pairBtcUsdc, 1, alice), - - PositionShouldNotExist(alice, pairBtcUsdc, 1), - PositionShouldExist(alice, pairBtcUsdc, 2), - ), - - TC("Error: can't settle on non existing market").When( - CreateCustomMarket( - pairBtcUsdc, - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - WithVersion(1), - WithEnabled(true), - ), - SetBlockNumber(1), - SetBlockTime(startTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(20_400)))), - MarketOrder( - alice, - pairBtcUsdc, - types.Direction_LONG, - sdk.NewInt(10_000), - sdk.OneDec(), - sdk.ZeroDec(), - ), - ).When( - CloseMarket(pairBtcUsdc, adminUser), - CreateCustomMarket( - pairBtcUsdc, - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - WithVersion(2), - WithEnabled(true), - ), - SetBlockNumber(2), - MarketOrder( - alice, - pairBtcUsdc, - types.Direction_LONG, - sdk.NewInt(10_000), - sdk.OneDec(), - sdk.ZeroDec(), - ), - ).Then( - - SettlePositionShouldFail(pairBtcUsdc, 2, alice), - SettlePosition(pairBtcUsdc, 1, alice), - - PositionShouldNotExist(alice, pairBtcUsdc, 1), - PositionShouldExist(alice, pairBtcUsdc, 2), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} diff --git a/x/perp/v2/keeper/sudo.go b/x/perp/v2/keeper/sudo.go deleted file mode 100644 index bd3636fcf..000000000 --- a/x/perp/v2/keeper/sudo.go +++ /dev/null @@ -1,274 +0,0 @@ -package keeper - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// Sudo extends the Keeper with sudo functions. Sudo is syntactic sugar to separate -// sudoExtension calls off from the other Keeper methods. -// -// These Sudo functions should: -// 1. Not be called in other methods in the x/perp module. -// 2. Only be callable from the x/sudo root or sudo contracts. -// -// The intention behind "sudoExtension" is to make it more obvious to the -// developer that an unsafe function is being used when it's called from -// "PerpKeeper.Sudo()" -func (k Keeper) Sudo() sudoExtension { return sudoExtension{k} } - -type sudoExtension struct{ Keeper } - -// WithdrawFromPerpFund sends funds from the Perp Fund to the "to" address. -// -// Args: -// - ctx: Blockchain context holding the current state -// - amount: Amount of micro-NUSD to withdraw. -// - sender: Admin address registered in x/sudo -// - to: Recipient address -func (k sudoExtension) WithdrawFromPerpFund( - ctx sdk.Context, amount sdkmath.Int, sender, to sdk.AccAddress, denom string, -) (err error) { - if err := k.SudoKeeper.CheckPermissions(sender, ctx); err != nil { - return err - } - - var collateralDenom string = denom - if denom == "" { - denomFromState, err := k.Collateral.Get(ctx) - if err != nil { - return err - } - collateralDenom = denomFromState - } - - coinToSend := sdk.NewCoin(collateralDenom, amount) - if err = k.BankKeeper.SendCoinsFromModuleToAccount( - ctx, - /* from */ types.PerpFundModuleAccount, - /* to */ to, - /* amount */ sdk.NewCoins(coinToSend), - ); err != nil { - return err - } - ctx.EventManager().EmitEvent(sdk.NewEvent( - "withdraw_from_perp_fund", - sdk.NewAttribute("to", to.String()), - sdk.NewAttribute("funds", coinToSend.String()), - )) - return nil -} - -type ArgsCreateMarket struct { - Pair asset.Pair - PriceMultiplier sdk.Dec - SqrtDepth sdk.Dec - Market *types.Market // pointer makes it optional - // EnableMarket: Optionally enable the default market without explicitly passing - // in each field as an argument. If 'Market' is present, this field is ignored. - EnableMarket bool -} - -// CreateMarket creates a pool for a specific pair. -func (k sudoExtension) CreateMarket( - ctx sdk.Context, - args ArgsCreateMarket, -) error { - pair := args.Pair - market, err := k.GetMarket(ctx, pair) - if err == nil && market.Enabled { - return fmt.Errorf("market %s already exists and it is enabled", pair) - } - - // init market - sqrtDepth := args.SqrtDepth - quoteReserve := sqrtDepth - baseReserve := sqrtDepth - if args.Market == nil { - market = types.DefaultMarket(pair) - market.Enabled = args.EnableMarket - } else { - market = *args.Market - } - if err := market.Validate(); err != nil { - return err - } - - lastVersion := k.MarketLastVersion.GetOr(ctx, pair, types.MarketLastVersion{Version: 0}) - lastVersion.Version += 1 - market.Version = lastVersion.Version - - // init amm - amm := types.AMM{ - Pair: pair, - Version: lastVersion.Version, - BaseReserve: baseReserve, - QuoteReserve: quoteReserve, - SqrtDepth: sqrtDepth, - PriceMultiplier: args.PriceMultiplier, - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - } - if err := amm.Validate(); err != nil { - return err - } - - k.SaveMarket(ctx, market) - k.SaveAMM(ctx, amm) - k.MarketLastVersion.Insert(ctx, pair, lastVersion) - - return nil -} - -// CloseMarket closes the market. From now on, no new position can be opened on -// this market or closed. Only the open positions can be settled by calling -// SettlePosition. -func (k sudoExtension) CloseMarket(ctx sdk.Context, pair asset.Pair, sender sdk.AccAddress) (err error) { - if err := k.SudoKeeper.CheckPermissions(sender, ctx); err != nil { - return err - } - market, err := k.GetMarket(ctx, pair) - if err != nil { - return err - } - if !market.Enabled { - return types.ErrMarketNotEnabled - } - - amm, err := k.GetAMM(ctx, pair) - if err != nil { - return err - } - - settlementPrice, _, err := amm.ComputeSettlementPrice() - if err != nil { - return - } - - amm.SettlementPrice = settlementPrice - market.Enabled = false - - k.SaveAMM(ctx, amm) - k.SaveMarket(ctx, market) - - return nil -} - -// ChangeCollateralDenom Updates the collateral denom. A denom is valid if it is -// possible to make an sdk.Coin using it. [SUDO] Only callable by sudoers. -func (k sudoExtension) ChangeCollateralDenom( - ctx sdk.Context, - denom string, - sender sdk.AccAddress, -) error { - if err := k.SudoKeeper.CheckPermissions(sender, ctx); err != nil { - return err - } - return k.UnsafeChangeCollateralDenom(ctx, denom) -} - -// UnsafeChangeCollateralDenom Used in the genesis to set the collateral -// without requiring an explicit call from sudoers. -func (k sudoExtension) UnsafeChangeCollateralDenom( - ctx sdk.Context, - denom string, -) error { - if err := sdk.ValidateDenom(denom); err != nil { - return types.ErrInvalidCollateral.Wrap(err.Error()) - } - k.Collateral.Set(ctx, denom) - return nil -} - -// ShiftPegMultiplier Edit the peg multiplier of an amm pool after making sure -// there's enough money in the perp fund to pay for the repeg. These funds get -// send to the vault to pay for trader's new net margin. -func (k sudoExtension) ShiftPegMultiplier( - ctx sdk.Context, - pair asset.Pair, - newPriceMultiplier sdk.Dec, - sender sdk.AccAddress, -) error { - if err := k.SudoKeeper.CheckPermissions(sender, ctx); err != nil { - return err - } - - amm, err := k.GetAMM(ctx, pair) - if err != nil { - return err - } - oldPriceMult := amm.PriceMultiplier - - if newPriceMultiplier.Equal(oldPriceMult) { - // same price multiplier, no-op - return nil - } - - // Compute cost of re-pegging the pool - cost, err := amm.CalcRepegCost(newPriceMultiplier) - if err != nil { - return err - } - - costPaid, err := k.handleMarketUpdateCost(ctx, pair, cost) - if err != nil { - return err - } - - // Do the re-peg - amm.PriceMultiplier = newPriceMultiplier - k.SaveAMM(ctx, amm) - - return ctx.EventManager().EmitTypedEvent(&types.EventShiftPegMultiplier{ - OldPegMultiplier: oldPriceMult, - NewPegMultiplier: newPriceMultiplier, - CostPaid: costPaid, - }) -} - -// ShiftSwapInvariant Edit the swap invariant (liquidity depth) of an amm pool, -// ensuring that there's enough money in the perp fund to pay for the operation. -// These funds get send to the vault to pay for trader's new net margin. -func (k sudoExtension) ShiftSwapInvariant( - ctx sdk.Context, - pair asset.Pair, - newSwapInvariant sdkmath.Int, - sender sdk.AccAddress, -) error { - if err := k.SudoKeeper.CheckPermissions(sender, ctx); err != nil { - return err - } - amm, err := k.GetAMM(ctx, pair) - if err != nil { - return err - } - - cost, err := amm.CalcUpdateSwapInvariantCost(newSwapInvariant.ToLegacyDec()) - if err != nil { - return err - } - - costPaid, err := k.handleMarketUpdateCost(ctx, pair, cost) - if err != nil { - return err - } - - err = amm.UpdateSwapInvariant(newSwapInvariant.ToLegacyDec()) - if err != nil { - return err - } - - k.SaveAMM(ctx, amm) - - return ctx.EventManager().EmitTypedEvent(&types.EventShiftSwapInvariant{ - OldSwapInvariant: amm.BaseReserve.Mul(amm.QuoteReserve).RoundInt(), - NewSwapInvariant: newSwapInvariant, - CostPaid: costPaid, - }) -} diff --git a/x/perp/v2/keeper/sudo_test.go b/x/perp/v2/keeper/sudo_test.go deleted file mode 100644 index 6752e016c..000000000 --- a/x/perp/v2/keeper/sudo_test.go +++ /dev/null @@ -1,532 +0,0 @@ -package keeper_test - -import ( - "fmt" - "testing" - "time" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - "github.com/NibiruChain/nibiru/x/common/testutil/genesis" - "github.com/NibiruChain/nibiru/x/common/testutil/mock" - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - "github.com/NibiruChain/nibiru/x/perp/v2/types" - perptypes "github.com/NibiruChain/nibiru/x/perp/v2/types" - sudotypes "github.com/NibiruChain/nibiru/x/sudo/types" - tftypes "github.com/NibiruChain/nibiru/x/tokenfactory/types" - - . "github.com/NibiruChain/nibiru/x/common/testutil/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/assertion" -) - -func (s *TestSuiteAdmin) TestAdmin_WithdrawFromPerpFund() { - fundModule := func(amount sdkmath.Int, ctx sdk.Context, nibiru *app.NibiruApp) { - coins := sdk.NewCoins(sdk.NewCoin(perptypes.TestingCollateralDenomNUSD, amount)) - err := testapp.FundModuleAccount( - nibiru.BankKeeper, ctx, perptypes.PerpFundModuleAccount, - coins, - ) - s.NoError(err) - } - - testCases := []testutil.FunctionTestCase{ - { - Name: "withdraw all", - Test: func() { - s.SetupTest() - nibiru, ctx := s.nibiru, s.ctx - admin := s.addrAdmin - amountToFund := sdk.NewInt(420) - fundModule(amountToFund, ctx, nibiru) - - balBefore := nibiru.BankKeeper.GetBalance(ctx, admin, perptypes.TestingCollateralDenomNUSD).Amount - amountToWithdraw := amountToFund - err := nibiru.PerpKeeperV2.Sudo().WithdrawFromPerpFund( - ctx, amountToWithdraw, admin, admin, "") - s.Require().NoError(err) - - balAfter := nibiru.BankKeeper.GetBalance(ctx, admin, perptypes.TestingCollateralDenomNUSD).Amount - s.EqualValues( - amountToFund.String(), - balAfter.Sub(balBefore).String(), - ) - - perpFundAddr := nibiru.AccountKeeper.GetModuleAddress(perptypes.PerpFundModuleAccount) - got := nibiru.BankKeeper.GetAllBalances(ctx, perpFundAddr).AmountOf(perptypes.TestingCollateralDenomNUSD) - s.EqualValues(sdkmath.ZeroInt().String(), got.String()) - }, - }, - { - Name: "withdraw too much - err", - Test: func() { - s.SetupTest() - nibiru, ctx := s.nibiru, s.ctx - admin := s.addrAdmin - amountToFund := sdk.NewInt(420) - fundModule(amountToFund, ctx, nibiru) - - amountToWithdraw := amountToFund.MulRaw(5) - err := nibiru.PerpKeeperV2.Sudo().WithdrawFromPerpFund( - ctx, amountToWithdraw, admin, admin, "") - s.Require().Error(err) - }, - }, - } - - for _, tc := range testCases { - s.Run(tc.Name, tc.Test) - } -} - -func TestCreateMarket(t *testing.T) { - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - amm := *mock.TestAMMDefault() - app, ctx := testapp.NewNibiruTestAppAndContext() - admin := app.PerpKeeperV2.Sudo() - - adminUser, err := sdk.AccAddressFromBech32(testutil.ADDR_SUDO_ROOT) - require.NoError(t, err) - - // Error because of invalid market - market := perptypes.DefaultMarket(pair).WithMaintenanceMarginRatio(sdk.NewDec(2)) - err = admin.CreateMarket(ctx, keeper.ArgsCreateMarket{ - Pair: pair, - PriceMultiplier: amm.PriceMultiplier, - SqrtDepth: amm.SqrtDepth, - Market: &market, // Invalid maintenance ratio - }) - require.ErrorContains(t, err, "maintenance margin ratio ratio must be 0 <= ratio <= 1") - - // Error because of invalid oracle pair - market = perptypes.DefaultMarket(pair).WithOraclePair("random") - err = admin.CreateMarket(ctx, keeper.ArgsCreateMarket{ - Pair: pair, - PriceMultiplier: amm.PriceMultiplier, - SqrtDepth: amm.SqrtDepth, - Market: &market, // Invalid oracle pair - }) - require.ErrorContains(t, err, "err when validating oracle pair random: invalid token pair") - - // Error because of invalid amm - err = admin.CreateMarket(ctx, keeper.ArgsCreateMarket{ - Pair: pair, - PriceMultiplier: sdk.NewDec(-1), - SqrtDepth: amm.SqrtDepth, - }) - require.ErrorContains(t, err, types.ErrAmmNonPositivePegMult.Error()) - - // Set it correctly - err = admin.CreateMarket(ctx, keeper.ArgsCreateMarket{ - Pair: pair, - PriceMultiplier: amm.PriceMultiplier, - SqrtDepth: amm.SqrtDepth, - EnableMarket: true, - }) - require.NoError(t, err) - - lastVersion, err := app.PerpKeeperV2.MarketLastVersion.Get(ctx, pair) - require.NoError(t, err) - require.Equal(t, uint64(1), lastVersion.Version) - - // Check that amm and market have version 1 - amm, err = app.PerpKeeperV2.GetAMM(ctx, pair) - require.NoError(t, err) - require.Equal(t, uint64(1), amm.Version) - - market, err = app.PerpKeeperV2.GetMarket(ctx, pair) - require.NoError(t, err) - require.Equal(t, uint64(1), market.Version) - - // Fail since it already exists and it is not disabled - err = admin.CreateMarket(ctx, keeper.ArgsCreateMarket{ - Pair: pair, - PriceMultiplier: amm.PriceMultiplier, - SqrtDepth: amm.SqrtDepth, - }) - require.ErrorContains(t, err, "already exists") - - // Close the market to test that we can create it again but with an increased version - err = admin.CloseMarket(ctx, pair, adminUser) - require.NoError(t, err) - - err = admin.CreateMarket(ctx, keeper.ArgsCreateMarket{ - Pair: pair, - PriceMultiplier: amm.PriceMultiplier, - SqrtDepth: amm.SqrtDepth, - }) - require.NoError(t, err) - - lastVersion, err = app.PerpKeeperV2.MarketLastVersion.Get(ctx, pair) - require.NoError(t, err) - require.Equal(t, uint64(2), lastVersion.Version) - - // Check that amm and market have version 2 - amm, err = app.PerpKeeperV2.GetAMM(ctx, pair) - require.NoError(t, err) - require.Equal(t, uint64(2), amm.Version) - - market, err = app.PerpKeeperV2.GetMarket(ctx, pair) - require.NoError(t, err) - require.Equal(t, uint64(2), market.Version) -} - -func TestCloseMarket(t *testing.T) { - pairBtcUsdc := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - startTime := time.Now() - alice := testutil.AccAddress() - - adminAccount, err := sdk.AccAddressFromBech32(testutil.ADDR_SUDO_ROOT) - require.NoError(t, err) - - tc := TestCases{ - TC("market can be disabled"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - SetBlockTime(startTime), - MarketShouldBeEqual( - pairBtcUsdc, - Market_EnableShouldBeEqualTo(true), - ), - ). - When( - CloseMarket(pairBtcUsdc, adminAccount), - ). - Then( - MarketShouldBeEqual( - pairBtcUsdc, - Market_EnableShouldBeEqualTo(false), - ), - ), - TC("cannot open position on disabled market"). - Given( - CreateCustomMarket( - pairBtcUsdc, - WithEnabled(true), - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - ), - SetBlockNumber(1), - SetBlockTime(startTime), - - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(perptypes.TestingCollateralDenomNUSD, sdk.NewInt(1e6)))), - ). - When( - CloseMarket(pairBtcUsdc, adminAccount), - ). - Then( - MarketOrderFails( - alice, - pairBtcUsdc, - perptypes.Direction_LONG, - sdk.NewInt(10_000), - sdk.OneDec(), - sdk.ZeroDec(), - perptypes.ErrMarketNotEnabled, - ), - ), - TC("cannot close position on disabled market").When( - CreateCustomMarket( - pairBtcUsdc, - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - WithEnabled(true), - ), - SetBlockNumber(1), - SetBlockTime(startTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(perptypes.TestingCollateralDenomNUSD, sdk.NewInt(10_200)))), - MarketOrder( - alice, - pairBtcUsdc, - perptypes.Direction_LONG, - sdk.NewInt(10_000), - sdk.OneDec(), - sdk.ZeroDec(), - ), - ).When( - CloseMarket(pairBtcUsdc, adminAccount), - CloseMarketShouldFail(pairBtcUsdc, adminAccount), - CloseMarketShouldFail("random:pair", adminAccount), - ).Then( - ClosePositionFails(alice, pairBtcUsdc, perptypes.ErrMarketNotEnabled), - ), - TC("cannot partial close position on disabled market").When( - CreateCustomMarket( - pairBtcUsdc, - WithPricePeg(sdk.OneDec()), - WithSqrtDepth(sdk.NewDec(100_000)), - WithEnabled(true), - ), - SetBlockNumber(1), - SetBlockTime(startTime), - FundAccount(alice, sdk.NewCoins(sdk.NewCoin(perptypes.TestingCollateralDenomNUSD, sdk.NewInt(10_200)))), - MarketOrder( - alice, - pairBtcUsdc, - perptypes.Direction_LONG, - sdk.NewInt(10_000), - sdk.OneDec(), - sdk.ZeroDec(), - ), - ).When( - CloseMarket(pairBtcUsdc, adminAccount), - AMMShouldBeEqual(pairBtcUsdc, AMM_SettlementPriceShoulBeEqual(sdk.MustNewDecFromStr("1.099800000000000000"))), - ).Then( - PartialCloseFails(alice, pairBtcUsdc, sdk.NewDec(5_000), perptypes.ErrMarketNotEnabled), - ), - TC("it fails when a non-admin tries to close a market"). - Given( - CreateCustomMarket(pairBtcUsdc, WithEnabled(true)), - SetBlockTime(startTime), - ). - When( - CloseMarketShouldFail(pairBtcUsdc, alice), - ). - Then( - MarketShouldBeEqual( - pairBtcUsdc, - Market_EnableShouldBeEqualTo(true), - ), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} - -func TestAdmin_ChangeCollateralDenom(t *testing.T) { - adminSender := testutil.AccAddress() - nonAdminSender := testutil.AccAddress() - - setup := func() (nibiru *app.NibiruApp, ctx sdk.Context) { - nibiru, ctx = testapp.NewNibiruTestAppAndContext() - nibiru.SudoKeeper.Sudoers.Set(ctx, sudotypes.Sudoers{ - Root: "mock-root", // unused - Contracts: []string{adminSender.String()}, - }) - return nibiru, ctx - } - - for _, tc := range []struct { - newDenom string - sender sdk.AccAddress - wantErr string - name string - }{ - {name: "happy: normal denom", newDenom: "nusd", sender: adminSender, wantErr: ""}, - - { - name: "happy: token factory denom", - newDenom: tftypes.TFDenom{ - Creator: testutil.AccAddress().String(), - Subdenom: "nusd", - }.String(), sender: adminSender, wantErr: "", - }, - - { - name: "happy: token factory denom", - newDenom: tftypes.TFDenom{ - Creator: testutil.AccAddress().String(), - Subdenom: "nusd", - }.String(), sender: adminSender, wantErr: "", - }, - - { - name: "happy: IBC denom", - newDenom: "ibc/46B44899322F3CD854D2D46DEEF881958467CDD4B3B10086DA49296BBED94BED", // JUNO on Osmosis - sender: adminSender, wantErr: "", - }, - - { - name: "sad: invalid denom", - newDenom: "", sender: adminSender, wantErr: perptypes.ErrInvalidCollateral.Error(), - }, - { - name: "sad: sender not in sudoers", - newDenom: "nusd", sender: nonAdminSender, wantErr: "insufficient permissions on smart contract", - }, - } { - t.Run(tc.name, func(t *testing.T) { - bapp, ctx := setup() - err := bapp.PerpKeeperV2.Sudo().ChangeCollateralDenom( - ctx, tc.newDenom, tc.sender, - ) - - if tc.wantErr != "" { - require.ErrorContains(t, err, tc.wantErr) - return - } - require.NoError(t, err) - - newDenom, err := bapp.PerpKeeperV2.Collateral.Get(ctx) - require.NoError(t, err) - require.Equal(t, tc.newDenom, newDenom) - }) - } -} - -type TestSuiteAdmin struct { - suite.Suite - - nibiru *app.NibiruApp - ctx sdk.Context - addrAdmin sdk.AccAddress - perpKeeper keeper.Keeper - perpMsgServer perptypes.MsgServer -} - -var _ suite.SetupTestSuite = (*TestSuiteAdmin)(nil) - -func TestSuite_Admin_RunAll(t *testing.T) { - suite.Run(t, new(TestSuiteAdmin)) -} - -// SetupTest: Runs before every test in the suite. -func (s *TestSuiteAdmin) SetupTest() { - s.addrAdmin = testutil.AccAddress() - genesisState := genesis.NewTestGenesisState(app.MakeEncodingConfig()) - genesisState = genesis.AddPerpV2Genesis(genesisState) - nibiru := testapp.NewNibiruTestApp(genesisState) - ctx := testapp.NewContext(nibiru) - nibiru.SudoKeeper.Sudoers.Set(ctx, sudotypes.Sudoers{ - Root: "mock-root", // unused - Contracts: []string{s.addrAdmin.String()}, - }) - s.nibiru = nibiru - s.ctx = ctx - s.perpKeeper = s.nibiru.PerpKeeperV2 - s.perpMsgServer = keeper.NewMsgServerImpl(s.perpKeeper) - s.nibiru.PerpKeeperV2.Collateral.Set(s.ctx, perptypes.TestingCollateralDenomNUSD) - - sender := s.addrAdmin - coins := sdk.NewCoins( - sdk.NewCoin(denoms.NIBI, sdk.NewInt(1_000_000)), - sdk.NewCoin(perptypes.TestingCollateralDenomNUSD, sdk.NewInt(420_000*69)), - sdk.NewCoin(denoms.USDT, sdk.NewInt(420_000*69)), - ) - s.NoError(testapp.FundAccount(nibiru.BankKeeper, ctx, sender, coins)) -} - -// HandleMsg: Convenience Executes a tx msg from the MsgServer -func (s *TestSuiteAdmin) HandleMsg(txMsg sdk.Msg) (err error) { - ctx := s.ctx - switch msg := txMsg.(type) { - case *perptypes.MsgShiftPegMultiplier: - _, err = s.perpMsgServer.ShiftPegMultiplier(ctx, msg) - case *perptypes.MsgShiftSwapInvariant: - _, err = s.perpMsgServer.ShiftSwapInvariant(ctx, msg) - case *perptypes.MsgChangeCollateralDenom: - _, err = s.perpMsgServer.ChangeCollateralDenom(ctx, msg) - case *perptypes.MsgWithdrawFromPerpFund: - _, err = s.perpMsgServer.WithdrawFromPerpFund(ctx, msg) - default: - return fmt.Errorf("unexpected message of type %T encountered", msg) - } - return err -} - -// TestCheckPermissions: Verify that all of the expected admin functions fail -// when called without sudo permissions. -func (s *TestSuiteAdmin) TestCheckPermissions() { - // Sender should not be equal to the admin. - senderAddr := testutil.AccAddress() - if senderAddr.Equals(s.addrAdmin) { - senderAddr = testutil.AccAddress() - } - sender := senderAddr.String() - - for _, testCaseMsg := range []sdk.Msg{ - &perptypes.MsgShiftPegMultiplier{ - Sender: sender, Pair: asset.Pair("valid:pair"), NewPegMult: sdk.NewDec(420), - }, - &perptypes.MsgShiftSwapInvariant{ - Sender: sender, Pair: asset.Pair("valid:pair"), NewSwapInvariant: sdk.NewInt(420), - }, - &perptypes.MsgChangeCollateralDenom{ - Sender: sender, NewDenom: "newdenom", - }, - &perptypes.MsgWithdrawFromPerpFund{ - Sender: sender, - Amount: sdk.NewInt(420), - Denom: "", - ToAddr: sender, - }, - } { - s.Run(fmt.Sprintf("%T", testCaseMsg), func() { - err := s.HandleMsg(testCaseMsg) - s.ErrorContains(err, sudotypes.ErrUnauthorized.Error()) - }) - } -} - -func (s *TestSuiteAdmin) DoShiftPegTest(pair asset.Pair) error { - _, err := s.perpMsgServer.ShiftPegMultiplier( - sdk.WrapSDKContext(s.ctx), &perptypes.MsgShiftPegMultiplier{ - Sender: s.addrAdmin.String(), - Pair: pair, - NewPegMult: sdk.NewDec(420), - }, - ) - return err -} - -func (s *TestSuiteAdmin) DoShiftSwapInvariantTest(pair asset.Pair) error { - _, err := s.perpMsgServer.ShiftSwapInvariant( - sdk.WrapSDKContext(s.ctx), &perptypes.MsgShiftSwapInvariant{ - Sender: s.addrAdmin.String(), - Pair: pair, - NewSwapInvariant: sdk.NewInt(420), - }, - ) - return err -} - -func (s *TestSuiteAdmin) DoWithdrawFromPerpFundTest(toAddr string) error { - wantCoin := sdk.NewInt64Coin("perpfundtest", 25) - s.NoError( - testapp.FundModuleAccount( - s.nibiru.BankKeeper, s.ctx, types.PerpFundModuleAccount, - sdk.NewCoins(wantCoin)), - ) - _, err := s.perpMsgServer.WithdrawFromPerpFund( - sdk.WrapSDKContext(s.ctx), &perptypes.MsgWithdrawFromPerpFund{ - Sender: s.addrAdmin.String(), - Amount: wantCoin.Amount, - Denom: wantCoin.Denom, - ToAddr: toAddr, - }, - ) - return err -} - -// TestAdmin_DoHappy: Happy path test cases -func (s *TestSuiteAdmin) TestAdmin_DoHappy() { - pair := asset.Registry.Pair(denoms.ATOM, denoms.NUSD) - - for _, err := range []error{ - s.DoShiftPegTest(pair), - s.DoShiftSwapInvariantTest(pair), - s.DoWithdrawFromPerpFundTest(s.addrAdmin.String()), - } { - s.NoError(err) - } -} - -// TestAdmin_SadPathsInvalidPair: Test scenarios that fail due to the use of a -// market that doesn't exist. -func (s *TestSuiteAdmin) TestAdmin_SadPathsInvalidPair() { - pair := asset.Pair("ftt:ust:doge") - for _, err := range []error{ - s.DoShiftPegTest(pair), - s.DoShiftSwapInvariantTest(pair), - } { - s.Error(err) - } -} diff --git a/x/perp/v2/keeper/swap.go b/x/perp/v2/keeper/swap.go deleted file mode 100644 index 8751e8389..000000000 --- a/x/perp/v2/keeper/swap.go +++ /dev/null @@ -1,113 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// checkUserLimits checks if the limit is violated by the amount. -// returns error if it does -func checkUserLimits(limit, amount sdk.Dec, dir types.Direction) error { - if limit.IsZero() { - return nil - } - - if dir == types.Direction_LONG && amount.LT(limit) { - return types.ErrAssetFailsUserLimit.Wrapf( - "amount (%s) is less than selected limit (%s)", - amount.String(), - limit.String(), - ) - } - - if dir == types.Direction_SHORT && amount.GT(limit) { - return types.ErrAssetFailsUserLimit.Wrapf( - "amount (%s) is greater than selected limit (%s)", - amount.String(), - limit.String(), - ) - } - - return nil -} - -// SwapQuoteAsset trades quoteAssets in exchange for baseAssets. -// Updates the AMM reserves and persists it to state. -// -// args: -// - ctx: cosmos-sdk context -// - market: a market like BTC:NUSD -// - amm: the reserves of the AMM -// - dir: the direction the user takes -// - quoteAssetAmt: the amount of quote assets to swap, must be positive -// - baseAssetLimit: the limit of base assets to swap -// -// returns: -// - updatedAMM: the updated amm -// - baseAssetDelta: the amount of base assets swapped, unsigned -// - err: error if any -// -// NOTE: the baseAssetDelta is always positive -func (k Keeper) SwapQuoteAsset( - ctx sdk.Context, - amm types.AMM, - dir types.Direction, - quoteAssetAmt sdk.Dec, // unsigned - baseAssetLimit sdk.Dec, // unsigned -) (updatedAMM *types.AMM, baseAssetDelta sdk.Dec, err error) { - baseAssetDelta, err = amm.SwapQuoteAsset(quoteAssetAmt, dir) - if err != nil { - return nil, sdk.Dec{}, err - } - - if err := checkUserLimits(baseAssetLimit, baseAssetDelta, dir); err != nil { - return nil, sdk.Dec{}, err - } - - k.SaveAMM(ctx, amm) - - return &amm, baseAssetDelta, nil -} - -// SwapBaseAsset trades baseAssets in exchange for quoteAssets. -// Updates the AMM reserves and persists it to state. -// -// args: -// - ctx: cosmos-sdk context -// - market: a market like BTC:NUSD -// - amm: the reserves of the AMM -// - dir: the direction the user takes -// - baseAssetAmt: the amount of base assets to swap, must be positive -// - quoteAssetLimit: the limit of quote assets to swap -// -// returns: -// - updatedAMM: the updated amm -// - quoteAssetDelta: the amount of quote assets swapped -// - err: error if any -// -// NOTE: the quoteAssetDelta is always positive -func (k Keeper) SwapBaseAsset( - ctx sdk.Context, - amm types.AMM, - dir types.Direction, - baseAssetAmt sdk.Dec, - quoteAssetLimit sdk.Dec, -) (updatedAMM *types.AMM, quoteAssetDelta sdk.Dec, err error) { - if baseAssetAmt.IsZero() { - return &amm, sdk.ZeroDec(), nil - } - - quoteAssetDelta, err = amm.SwapBaseAsset(baseAssetAmt, dir) - if err != nil { - return nil, sdk.Dec{}, err - } - - if err := checkUserLimits(quoteAssetLimit, quoteAssetDelta, dir); err != nil { - return nil, sdk.Dec{}, err - } - - k.SaveAMM(ctx, amm) - - return &amm, quoteAssetDelta, err -} diff --git a/x/perp/v2/keeper/swap_test.go b/x/perp/v2/keeper/swap_test.go deleted file mode 100644 index 91686f33d..000000000 --- a/x/perp/v2/keeper/swap_test.go +++ /dev/null @@ -1,213 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/testutil/mock" - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func TestSwapQuoteAsset(t *testing.T) { - tests := []struct { - name string - direction types.Direction - quoteAssetAmt sdk.Dec - baseAssetLimit sdk.Dec - - expectedBaseAssetDelta sdk.Dec - expectedAMM *types.AMM - expectedErr error - }{ - { - name: "quote amount == 0", - direction: types.Direction_LONG, - quoteAssetAmt: sdk.ZeroDec(), - baseAssetLimit: sdk.ZeroDec(), - - expectedAMM: mock.TestAMMDefault(). - WithPriceMultiplier(sdk.NewDec(2)), - expectedBaseAssetDelta: sdk.ZeroDec(), - }, - { - name: "normal swap add", - direction: types.Direction_LONG, - quoteAssetAmt: sdk.NewDec(100_000), - baseAssetLimit: sdk.NewDec(49999), - - expectedAMM: mock.TestAMMDefault(). - WithQuoteReserve(sdk.NewDec(1_000_000_050_000)). - WithBaseReserve(sdk.MustNewDecFromStr("999999950000.002499999875000006")). - WithPriceMultiplier(sdk.NewDec(2)). - WithTotalLong(sdk.MustNewDecFromStr("49999.997500000124999994")), - expectedBaseAssetDelta: sdk.MustNewDecFromStr("49999.997500000124999994"), - }, - { - name: "normal swap remove", - direction: types.Direction_SHORT, - quoteAssetAmt: sdk.NewDec(100_000), - baseAssetLimit: sdk.NewDec(50_001), - - expectedAMM: mock.TestAMMDefault(). - WithQuoteReserve(sdk.NewDec(999_999_950_000)). - WithBaseReserve(sdk.MustNewDecFromStr("1000000050000.002500000125000006")). - WithPriceMultiplier(sdk.NewDec(2)). - WithTotalShort(sdk.MustNewDecFromStr("50000.002500000125000006")), - expectedBaseAssetDelta: sdk.MustNewDecFromStr("50000.002500000125000006"), - }, - { - name: "base amount less than base limit in Long", - direction: types.Direction_LONG, - quoteAssetAmt: sdk.NewDec(500_000), - baseAssetLimit: sdk.NewDec(454_500), - - expectedErr: types.ErrAssetFailsUserLimit, - }, - { - name: "base amount more than base limit in Short", - direction: types.Direction_SHORT, - quoteAssetAmt: sdk.NewDec(1e6), - baseAssetLimit: sdk.NewDec(454_500), - - expectedErr: types.ErrAssetFailsUserLimit, - }, - { - name: "over reserve amount when removing quote", - direction: types.Direction_SHORT, - quoteAssetAmt: sdk.NewDec(2e12 + 1), - baseAssetLimit: sdk.ZeroDec(), - - expectedErr: types.ErrAmmNonpositiveReserves, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - amm := mock.TestAMMDefault().WithPriceMultiplier(sdk.NewDec(2)) - - updatedAMM, baseAmt, err := app.PerpKeeperV2.SwapQuoteAsset( - ctx, - *amm, - tc.direction, - tc.quoteAssetAmt, - tc.baseAssetLimit, - ) - - if tc.expectedErr != nil { - require.ErrorIs(t, err, tc.expectedErr) - } else { - require.NoError(t, err) - assert.EqualValuesf(t, tc.expectedBaseAssetDelta, baseAmt, "base amount mismatch") - - require.NoError(t, err) - assert.Equal(t, *tc.expectedAMM, *updatedAMM) - } - }) - } -} - -func TestSwapBaseAsset(t *testing.T) { - tests := []struct { - name string - direction types.Direction - baseAssetAmt sdk.Dec - quoteAssetLimit sdk.Dec - - expectedAMM *types.AMM - expectedQuoteAssetDelta sdk.Dec - expectedErr error - }{ - { - name: "zero base asset swap", - direction: types.Direction_LONG, - baseAssetAmt: sdk.ZeroDec(), - quoteAssetLimit: sdk.ZeroDec(), - - expectedAMM: mock.TestAMMDefault(). - WithPriceMultiplier(sdk.NewDec(2)), - expectedQuoteAssetDelta: sdk.ZeroDec(), - }, - { - name: "go long", - direction: types.Direction_LONG, - baseAssetAmt: sdk.NewDec(100_000), - quoteAssetLimit: sdk.NewDec(200_000), - - expectedAMM: mock.TestAMMDefault(). - WithBaseReserve(sdk.NewDec(999999900000)). - WithQuoteReserve(sdk.MustNewDecFromStr("1000000100000.010000001000000100")). - WithPriceMultiplier(sdk.NewDec((2))). - WithTotalLong(sdk.NewDec(100_000)), - expectedQuoteAssetDelta: sdk.MustNewDecFromStr("200000.020000002000000200"), - }, - { - name: "go short", - direction: types.Direction_SHORT, - baseAssetAmt: sdk.NewDec(100_000), - quoteAssetLimit: sdk.NewDec(200_000), - - expectedQuoteAssetDelta: sdk.MustNewDecFromStr("199999.980000001999999800"), - expectedAMM: mock.TestAMMDefault(). - WithBaseReserve(sdk.NewDec(1000000100000)). - WithQuoteReserve(sdk.MustNewDecFromStr("999999900000.009999999000000100")). - WithPriceMultiplier(sdk.NewDec((2))). - WithTotalShort(sdk.NewDec(100_000)), - }, - { - name: "quote asset amt less than quote limit in Long", - direction: types.Direction_LONG, - baseAssetAmt: sdk.NewDec(100_000), - quoteAssetLimit: sdk.NewDec(200_001), - - expectedErr: types.ErrAssetFailsUserLimit, - }, - { - name: "quote amount more than quote limit in Short", - direction: types.Direction_SHORT, - baseAssetAmt: sdk.NewDec(100_000), - quoteAssetLimit: sdk.NewDec(199_999), - - expectedErr: types.ErrAssetFailsUserLimit, - }, - { - name: "over reserve amount when removing base", - direction: types.Direction_LONG, - baseAssetAmt: sdk.NewDec(1e12 + 1), - quoteAssetLimit: sdk.ZeroDec(), - - expectedErr: types.ErrAmmNonpositiveReserves, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - amm := mock.TestAMMDefault().WithPriceMultiplier(sdk.NewDec(2)) - - updatedAMM, quoteAssetAmount, err := app.PerpKeeperV2.SwapBaseAsset( - ctx, - *amm, - tc.direction, - tc.baseAssetAmt, - tc.quoteAssetLimit, - ) - - if tc.expectedErr != nil { - require.ErrorContains(t, err, tc.expectedErr.Error()) - } else { - require.NoError(t, err) - assert.EqualValuesf(t, tc.expectedQuoteAssetDelta, quoteAssetAmount, - "expected %s; got %s", tc.expectedQuoteAssetDelta.String(), quoteAssetAmount.String()) - - assert.Equal(t, *tc.expectedAMM, *updatedAMM) - } - }) - } -} diff --git a/x/perp/v2/keeper/twap.go b/x/perp/v2/keeper/twap.go deleted file mode 100644 index 473fdac9b..000000000 --- a/x/perp/v2/keeper/twap.go +++ /dev/null @@ -1,184 +0,0 @@ -package keeper - -import ( - "time" - - "github.com/NibiruChain/collections" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -/* -CalcTwap Gets the time-weighted average price from [ ctx.BlockTime() - interval, ctx.BlockTime() ) -Note the open-ended right bracket. - -args: - - ctx: cosmos-sdk context - - pair: the token pair - - twapCalcOption: one of SPOT, QUOTE_ASSET_SWAP, or BASE_ASSET_SWAP - - direction: add or remove, only required for QUOTE_ASSET_SWAP or BASE_ASSET_SWAP - - assetAmount: amount of asset to add or remove, only required for QUOTE_ASSET_SWAP or BASE_ASSET_SWAP - - lookbackInterval: how far back to calculate TWAP - -ret: - - price: TWAP as sdk.Dec - - err: error -*/ -func (k Keeper) CalcTwap( - ctx sdk.Context, - pair asset.Pair, - twapCalcOption types.TwapCalcOption, - direction types.Direction, - assetAmt sdk.Dec, - lookbackInterval time.Duration, -) (price sdk.Dec, err error) { - // earliest timestamp we'll look back until - lowerLimitTimestampMs := ctx.BlockTime().Add(-1 * lookbackInterval).UnixMilli() - - // fetch snapshots from state - var snapshots []types.ReserveSnapshot - iter := k.ReserveSnapshots.Iterate( - ctx, - collections.PairRange[asset.Pair, time.Time]{}. - Prefix(pair). - EndInclusive(ctx.BlockTime()). - Descending(), - ) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - s := iter.Value() - snapshots = append(snapshots, s) - if s.TimestampMs <= lowerLimitTimestampMs { - break - } - } - - if len(snapshots) == 0 { - return sdk.OneDec().Neg(), types.ErrNoValidTWAP - } - - // circuit-breaker when there's only one snapshot to process - if len(snapshots) == 1 { - return getPriceWithSnapshot( - snapshots[0], - snapshotPriceOps{ - twapCalcOption: twapCalcOption, - direction: direction, - assetAmt: assetAmt, - }, - ) - } - - // else, iterate over all snapshots and calculate TWAP - prevTimestampMs := ctx.BlockTime().UnixMilli() - cumulativePrice := sdk.ZeroDec() - cumulativePeriodMs := int64(0) - - for _, snapshot := range snapshots { - if snapshot.TimestampMs == prevTimestampMs { - // in some extreme cases, 2 reserves snapshots can have the same timestamp which would cause a divide by zero error - // in this case, we skip the second snapshot - continue - } - - price, err := getPriceWithSnapshot( - snapshot, - snapshotPriceOps{ - twapCalcOption: twapCalcOption, - direction: direction, - assetAmt: assetAmt, - }, - ) - if err != nil { - return sdk.Dec{}, err - } - - var timeElapsedMs int64 - if snapshot.TimestampMs <= lowerLimitTimestampMs { - // if we're at a snapshot below lowerLimitTimestamp, then consider that price as starting from the lower limit timestamp - timeElapsedMs = prevTimestampMs - lowerLimitTimestampMs - } else { - timeElapsedMs = prevTimestampMs - snapshot.TimestampMs - } - - cumulativePrice = cumulativePrice.Add(price.MulInt64(timeElapsedMs)) - cumulativePeriodMs += timeElapsedMs - - if snapshot.TimestampMs <= lowerLimitTimestampMs { - break - } - prevTimestampMs = snapshot.TimestampMs - } - - if cumulativePeriodMs == 0 { - // Should not be reachable - return getPriceWithSnapshot( - snapshots[0], - snapshotPriceOps{ - twapCalcOption: twapCalcOption, - direction: direction, - assetAmt: assetAmt, - }, - ) - } - - return cumulativePrice.QuoInt64(cumulativePeriodMs), nil -} - -/* -An object parameter for getPriceWithSnapshot(). - -Specifies how to read the price from a single snapshot. There are three ways: -SPOT: spot price -QUOTE_ASSET_SWAP: price when swapping y amount of quote assets -BASE_ASSET_SWAP: price when swapping x amount of base assets -*/ -type snapshotPriceOps struct { - twapCalcOption types.TwapCalcOption - direction types.Direction - assetAmt sdk.Dec -} - -/* -Pure function that returns a price from a snapshot. - -Can choose from three types of calc options: SPOT, QUOTE_ASSET_SWAP, and BASE_ASSET_SWAP. -QUOTE_ASSET_SWAP and BASE_ASSET_SWAP require the `direction“ and `assetAmount“ args. -SPOT does not require `direction` and `assetAmount`. - -args: - - pair: the token pair - - snapshot: a reserve snapshot - - twapCalcOption: SPOT, QUOTE_ASSET_SWAP, or BASE_ASSET_SWAP - - direction: add or remove; only required for QUOTE_ASSET_SWAP or BASE_ASSET_SWAP - - assetAmount: the amount of base or quote asset; only required for QUOTE_ASSET_SWAP or BASE_ASSET_SWAP - -ret: - - price: the price as sdk.Dec - - err: error -*/ -func getPriceWithSnapshot( - snapshot types.ReserveSnapshot, - opts snapshotPriceOps, -) (price sdk.Dec, err error) { - priceMult := snapshot.Amm.PriceMultiplier - switch opts.twapCalcOption { - case types.TwapCalcOption_SPOT: - return snapshot.Amm.QuoteReserve.Mul(priceMult).Quo(snapshot.Amm.BaseReserve), nil - - case types.TwapCalcOption_QUOTE_ASSET_SWAP: - quoteReserve := types.QuoteAssetToReserve(opts.assetAmt, priceMult) - return snapshot.Amm.GetBaseReserveAmt(quoteReserve, opts.direction) - - case types.TwapCalcOption_BASE_ASSET_SWAP: - quoteReserve, err := snapshot.Amm.GetQuoteReserveAmt(opts.assetAmt, opts.direction) - if err != nil { - return sdk.Dec{}, err - } - return types.QuoteReserveToAsset(quoteReserve, priceMult), nil - } - - return sdk.ZeroDec(), nil -} diff --git a/x/perp/v2/keeper/twap_test.go b/x/perp/v2/keeper/twap_test.go deleted file mode 100644 index c0b0f3a5c..000000000 --- a/x/perp/v2/keeper/twap_test.go +++ /dev/null @@ -1,404 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/collections" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - . "github.com/NibiruChain/nibiru/x/common/testutil/action" - "github.com/NibiruChain/nibiru/x/common/testutil/mock" - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/assertion" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" -) - -func TestCalcTwap(t *testing.T) { - pairBtcUsdc := asset.Registry.Pair(denoms.BTC, denoms.USDC) - startTime := time.Now() - - tc := TestCases{ - TC("spot twap"). - Given( - CreateCustomMarket(pairBtcUsdc), - SetBlockTime(startTime), - InsertReserveSnapshot(pairBtcUsdc, startTime, WithPriceMultiplier(sdk.NewDec(9))), - InsertReserveSnapshot(pairBtcUsdc, startTime.Add(10*time.Second), WithPriceMultiplier(sdk.NewDec(10))), - InsertReserveSnapshot(pairBtcUsdc, startTime.Add(20*time.Second), WithPriceMultiplier(sdk.NewDec(11))), - ). - When( - MoveToNextBlockWithDuration(30 * time.Second), - ). - Then( - TwapShouldBe(pairBtcUsdc, types.TwapCalcOption_SPOT, types.Direction_DIRECTION_UNSPECIFIED, sdk.ZeroDec(), 30*time.Second, sdk.NewDec(10)), - ), - - TC("base asset twap, long"). - Given( - CreateCustomMarket(pairBtcUsdc), - SetBlockTime(startTime), - InsertReserveSnapshot(pairBtcUsdc, startTime, WithPriceMultiplier(sdk.NewDec(9))), - InsertReserveSnapshot(pairBtcUsdc, startTime.Add(10*time.Second), WithPriceMultiplier(sdk.NewDec(10))), - InsertReserveSnapshot(pairBtcUsdc, startTime.Add(20*time.Second), WithPriceMultiplier(sdk.NewDec(11))), - ). - When( - MoveToNextBlockWithDuration(30 * time.Second), - ). - Then( - TwapShouldBe(pairBtcUsdc, types.TwapCalcOption_BASE_ASSET_SWAP, types.Direction_LONG, sdk.NewDec(5), 30*time.Second, sdk.MustNewDecFromStr("50.000000000250000000")), - ), - - TC("base asset twap, short"). - Given( - CreateCustomMarket(pairBtcUsdc), - SetBlockTime(startTime), - InsertReserveSnapshot(pairBtcUsdc, startTime, WithPriceMultiplier(sdk.NewDec(9))), - InsertReserveSnapshot(pairBtcUsdc, startTime.Add(10*time.Second), WithPriceMultiplier(sdk.NewDec(10))), - InsertReserveSnapshot(pairBtcUsdc, startTime.Add(20*time.Second), WithPriceMultiplier(sdk.NewDec(11))), - ). - When( - MoveToNextBlockWithDuration(30 * time.Second), - ). - Then( - TwapShouldBe(pairBtcUsdc, types.TwapCalcOption_BASE_ASSET_SWAP, types.Direction_SHORT, sdk.NewDec(5), 30*time.Second, sdk.MustNewDecFromStr("49.999999999750000000")), - ), - - TC("quote asset twap, long"). - Given( - CreateCustomMarket(pairBtcUsdc), - SetBlockTime(startTime), - InsertReserveSnapshot(pairBtcUsdc, startTime, WithPriceMultiplier(sdk.NewDec(9))), - InsertReserveSnapshot(pairBtcUsdc, startTime.Add(10*time.Second), WithPriceMultiplier(sdk.NewDec(10))), - InsertReserveSnapshot(pairBtcUsdc, startTime.Add(20*time.Second), WithPriceMultiplier(sdk.NewDec(11))), - ). - When( - MoveToNextBlockWithDuration(30 * time.Second), - ). - Then( - TwapShouldBe(pairBtcUsdc, types.TwapCalcOption_QUOTE_ASSET_SWAP, types.Direction_LONG, sdk.NewDec(5), 30*time.Second, sdk.MustNewDecFromStr("0.503367003366748282")), - ), - - TC("quote asset twap, short"). - Given( - CreateCustomMarket(pairBtcUsdc), - SetBlockTime(startTime), - InsertReserveSnapshot(pairBtcUsdc, startTime, WithPriceMultiplier(sdk.NewDec(9))), - InsertReserveSnapshot(pairBtcUsdc, startTime.Add(10*time.Second), WithPriceMultiplier(sdk.NewDec(10))), - InsertReserveSnapshot(pairBtcUsdc, startTime.Add(20*time.Second), WithPriceMultiplier(sdk.NewDec(11))), - ). - When( - MoveToNextBlockWithDuration(30 * time.Second), - ). - Then( - TwapShouldBe(pairBtcUsdc, types.TwapCalcOption_QUOTE_ASSET_SWAP, types.Direction_SHORT, sdk.NewDec(5), 30*time.Second, sdk.MustNewDecFromStr("0.503367003367258451")), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} - -func TestInvalidTwap(t *testing.T) { - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - app, _ := testapp.NewNibiruTestAppAndContext() - ctx := app.NewContext(false, tmproto.Header{ - Height: 1, - }) - startTime := time.UnixMilli(0) - - app.PerpKeeperV2.SaveMarket(ctx, *mock.TestMarket()) - app.PerpKeeperV2.SaveAMM(ctx, *mock.TestAMMDefault()) - app.PerpKeeperV2.ReserveSnapshots.Insert( - ctx, collections.Join(pair, startTime), types.ReserveSnapshot{ - Amm: *mock.TestAMMDefault(), - TimestampMs: 0, - }) - - tc := struct { - twapCalcOption types.TwapCalcOption - direction types.Direction - assetAmount sdk.Dec - lookbackInterval time.Duration - }{ - twapCalcOption: types.TwapCalcOption_SPOT, - direction: types.Direction_DIRECTION_UNSPECIFIED, - assetAmount: sdk.ZeroDec(), - lookbackInterval: 30 * time.Second, - } - _, err := app.PerpKeeperV2.CalcTwap(ctx, - pair, - tc.twapCalcOption, - tc.direction, - tc.assetAmount, - tc.lookbackInterval, - ) - require.ErrorIs(t, err, types.ErrNoValidTWAP) -} - -func TestCalcTwapExtended(t *testing.T) { - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - - tests := []struct { - name string - reserveSnapshots []types.ReserveSnapshot - currentBlockTime time.Time - currentBlockHeight int64 - lookbackInterval time.Duration - twapCalcOption types.TwapCalcOption - direction types.Direction - assetAmount sdk.Dec - expectedPrice sdk.Dec - expectedErr error - }{ - // Same price at 9 for 20 milliseconds - { - name: "spot price twap calc, t=[10,30]", - reserveSnapshots: []types.ReserveSnapshot{ - { - Amm: *mock.TestAMM(sdk.NewDec(100), sdk.NewDec(9)), - TimestampMs: 10, - }, - { - Amm: *mock.TestAMM(sdk.NewDec(100), sdk.NewDec(9)), - TimestampMs: 20, - }, - { - Amm: *mock.TestAMM(sdk.NewDec(100), sdk.NewDec(9)), - TimestampMs: 30, - }, - }, - currentBlockTime: time.UnixMilli(30), - currentBlockHeight: 3, - lookbackInterval: 20 * time.Millisecond, - twapCalcOption: types.TwapCalcOption_SPOT, - expectedPrice: sdk.MustNewDecFromStr("9"), - }, - // expected price: (9.5 * (30 - 30) + 8.5 * (30 - 20) + 9 * (20 - 10)) / (10 + 10) - { - name: "spot price twap calc, t=[10,30]", - reserveSnapshots: []types.ReserveSnapshot{ - { - Amm: *mock.TestAMM(sdk.NewDec(100), sdk.NewDec(9)), - TimestampMs: 10, - }, - { - Amm: *mock.TestAMM(sdk.NewDec(100), sdk.MustNewDecFromStr("8.5")), - TimestampMs: 20, - }, - { - Amm: *mock.TestAMM(sdk.NewDec(100), sdk.MustNewDecFromStr("9.5")), - TimestampMs: 30, - }, - }, - currentBlockTime: time.UnixMilli(30), - currentBlockHeight: 3, - lookbackInterval: 20 * time.Millisecond, - twapCalcOption: types.TwapCalcOption_SPOT, - expectedPrice: sdk.MustNewDecFromStr("8.75"), - }, - // expected price: (95/10 * (35 - 30) + 85/10 * (30 - 20) + 90/10 * (20 - 11)) / (5 + 10 + 9) - { - name: "spot price twap calc, t=[11,35]", - reserveSnapshots: []types.ReserveSnapshot{ - { - Amm: *mock.TestAMM(sdk.NewDec(100), sdk.NewDec(9)), - TimestampMs: 10, - }, - { - Amm: *mock.TestAMM(sdk.NewDec(100), sdk.MustNewDecFromStr("8.5")), - TimestampMs: 20, - }, - { - Amm: *mock.TestAMM(sdk.NewDec(100), sdk.MustNewDecFromStr("9.5")), - TimestampMs: 30, - }, - }, - currentBlockTime: time.UnixMilli(35), - currentBlockHeight: 4, - lookbackInterval: 24 * time.Millisecond, - twapCalcOption: types.TwapCalcOption_SPOT, - expectedPrice: sdk.MustNewDecFromStr("8.895833333333333333"), - }, - - // base asset reserve at t = 0: 100 - // quote asset reserve at t = 0: 100 - // expected price: 1 - { - name: "spot price twap calc, t=[0,0]", - reserveSnapshots: []types.ReserveSnapshot{}, - currentBlockTime: time.UnixMilli(0), - currentBlockHeight: 1, - lookbackInterval: 0 * time.Millisecond, - twapCalcOption: types.TwapCalcOption_SPOT, - expectedPrice: sdk.OneDec(), - }, - - // expected price: (95/10 * (35 - 30) + 85/10 * (30 - 20) + 90/10 * (20 - 11)) / (5 + 10 + 9) - { - name: "quote asset swap twap calc, add to pool, t=[10,30]", - reserveSnapshots: []types.ReserveSnapshot{ - { - Amm: *mock.TestAMM(sdk.NewDec(1000), sdk.NewDec(3)), - TimestampMs: 10, - }, - { - Amm: *mock.TestAMM(sdk.NewDec(1000), sdk.NewDec(5)), - TimestampMs: 20, - }, - }, - currentBlockTime: time.UnixMilli(30), - currentBlockHeight: 3, - lookbackInterval: 20 * time.Millisecond, - twapCalcOption: types.TwapCalcOption_QUOTE_ASSET_SWAP, - direction: types.Direction_LONG, - assetAmount: sdk.NewDec(5), - expectedPrice: sdk.MustNewDecFromStr("1.331447254908153411"), // ~ 5 base at a twap price of 4 - }, - - // expected price: (95/10 * (35 - 30) + 85/10 * (30 - 20) + 90/10 * (20 - 11)) / (5 + 10 + 9) - { - name: "quote asset swap twap calc, remove from pool, t=[10,30]", - reserveSnapshots: []types.ReserveSnapshot{ - { - Amm: *mock.TestAMM(sdk.NewDec(1000), sdk.NewDec(3)), - TimestampMs: 10, - }, - { - Amm: *mock.TestAMM(sdk.NewDec(1000), sdk.NewDec(5)), - TimestampMs: 20, - }, - }, - currentBlockTime: time.UnixMilli(30), - currentBlockHeight: 3, - lookbackInterval: 20 * time.Millisecond, - twapCalcOption: types.TwapCalcOption_QUOTE_ASSET_SWAP, - direction: types.Direction_SHORT, - assetAmount: sdk.NewDec(5), - expectedPrice: sdk.MustNewDecFromStr("1.335225041402003005"), // ~ 5 base at a twap price of 4 - }, - - { - name: "Error: quote asset reserve = asset amount", - reserveSnapshots: []types.ReserveSnapshot{ - { - Amm: *mock.TestAMM(sdk.NewDec(10), sdk.NewDec(2)), - TimestampMs: 20, - }, - }, - currentBlockTime: time.UnixMilli(30), - currentBlockHeight: 3, - lookbackInterval: 20 * time.Millisecond, - twapCalcOption: types.TwapCalcOption_QUOTE_ASSET_SWAP, - direction: types.Direction_SHORT, - assetAmount: sdk.NewDec(20), - expectedErr: types.ErrAmmNonpositiveReserves, - }, - - // k: 60 * 100 = 600 - // asset amount: 10 - // expected price: ((60 - 600/(10 + 10)) * (20 - 10) + (30 - 600/(20 + 10)) * (30 - 20)) / (10 + 10) - { - name: "base asset swap twap calc, add to pool, t=[10,30]", - reserveSnapshots: []types.ReserveSnapshot{ - { - Amm: *mock.TestAMM(sdk.NewDec(1000), sdk.NewDec(6)), - TimestampMs: 10, - }, - { - Amm: *mock.TestAMM(sdk.NewDec(1000), sdk.MustNewDecFromStr("1.5")), - TimestampMs: 20, - }, - }, - currentBlockTime: time.UnixMilli(30), - currentBlockHeight: 3, - lookbackInterval: 20 * time.Millisecond, - twapCalcOption: types.TwapCalcOption_BASE_ASSET_SWAP, - direction: types.Direction_SHORT, - assetAmount: sdk.NewDec(10), - expectedPrice: sdk.MustNewDecFromStr("37.128712871287128712"), - }, - - // k: 60 * 100 = 600 - // asset amount: 10 - // expected price: ((60 - 600/(10 - 2)) * (20 - 10) + (75 - 600/(8 - 2)) * (30 - 20)) / (10 + 10) - { - name: "base asset swap twap calc, remove from pool, t=[10,30]", - reserveSnapshots: []types.ReserveSnapshot{ - { - Amm: *mock.TestAMM(sdk.NewDec(1000), sdk.NewDec(6)), - TimestampMs: 10, - }, - { - Amm: *mock.TestAMM(sdk.NewDec(1000), sdk.MustNewDecFromStr("9.375")), - TimestampMs: 20, - }, - }, - currentBlockTime: time.UnixMilli(30), - currentBlockHeight: 3, - lookbackInterval: 20 * time.Millisecond, - twapCalcOption: types.TwapCalcOption_BASE_ASSET_SWAP, - direction: types.Direction_LONG, - assetAmount: sdk.NewDec(2), - expectedPrice: sdk.MustNewDecFromStr("15.405811623246492984"), - }, - { - name: "Error: base asset reserve = asset amount", - reserveSnapshots: []types.ReserveSnapshot{ - { - Amm: *mock.TestAMM(sdk.NewDec(10), sdk.NewDec(9)), - TimestampMs: 20, - }, - }, - currentBlockTime: time.UnixMilli(30), - currentBlockHeight: 3, - lookbackInterval: 20 * time.Millisecond, - twapCalcOption: types.TwapCalcOption_BASE_ASSET_SWAP, - direction: types.Direction_LONG, - assetAmount: sdk.NewDec(10), - expectedErr: types.ErrAmmNonpositiveReserves, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, _ := testapp.NewNibiruTestAppAndContext() - ctx := app.NewContext(false, tmproto.Header{ - Height: 1, - }) - startTime := time.UnixMilli(0) - - app.PerpKeeperV2.SaveMarket(ctx, *mock.TestMarket()) - app.PerpKeeperV2.SaveAMM(ctx, *mock.TestAMMDefault()) - app.PerpKeeperV2.ReserveSnapshots.Insert( - ctx, collections.Join(pair, startTime), types.ReserveSnapshot{ - Amm: *mock.TestAMMDefault(), - TimestampMs: 0, - }) - - for _, snapshot := range tc.reserveSnapshots { - ctx = ctx.WithBlockTime(time.UnixMilli(snapshot.TimestampMs)) - app.PerpKeeperV2.ReserveSnapshots.Insert(ctx, collections.Join(snapshot.Amm.Pair, time.UnixMilli(snapshot.TimestampMs)), snapshot) - } - ctx = ctx.WithBlockTime(tc.currentBlockTime).WithBlockHeight(tc.currentBlockHeight) - - price, err := app.PerpKeeperV2.CalcTwap(ctx, - pair, - tc.twapCalcOption, - tc.direction, - tc.assetAmount, - tc.lookbackInterval, - ) - require.ErrorIs(t, err, tc.expectedErr) - require.EqualValuesf(t, tc.expectedPrice, price, - "expected %s, got %s", tc.expectedPrice.String(), price.String()) - }) - } -} diff --git a/x/perp/v2/keeper/withdraw.go b/x/perp/v2/keeper/withdraw.go deleted file mode 100644 index 29c89ff23..000000000 --- a/x/perp/v2/keeper/withdraw.go +++ /dev/null @@ -1,140 +0,0 @@ -package keeper - -import ( - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// WithdrawFromVault coins from the vault to the receiver. -// If the total amount of coins to withdraw is greater than the vault's amount, then -// withdraw the shortage from the PerpEF and mark it as prepaid bad debt. -// -// Prepaid bad debt will count towards realized bad debt from negative PnL positions -// when those are closed/liquidated. -// -// An example of this happening is when a long position has really high PnL and -// closes their position, realizing their profits. -// There is a counter party short position with really negative PnL, but -// their position hasn't been closed/liquidated yet. -// We must pay the long trader first, which results in funds being taken from the EF. -// when the short position is closed, it also realizes some bad debt but because -// we have already withdrawn from the EF, we don't need to withdraw more from the EF. -// -// args: -// - ctx: context -// - market: the perp market -// - receiver: the receiver of the coins -// - amountToWithdraw: amount of coins to withdraw -// -// returns: -// - error: error -func (k Keeper) WithdrawFromVault( - ctx sdk.Context, - market types.Market, - receiver sdk.AccAddress, - amountToWithdraw sdkmath.Int, -) (err error) { - if !amountToWithdraw.IsPositive() { - return nil - } - - collateral, err := k.Collateral.Get(ctx) - if err != nil { - return err - } - - vaultQuoteBalance := k.BankKeeper.GetBalance( - ctx, - k.AccountKeeper.GetModuleAddress(types.VaultModuleAccount), - collateral, - ) - if vaultQuoteBalance.Amount.LT(amountToWithdraw) { - // if withdraw amount is larger than entire balance of vault - // means this trader's profit comes from other under collateral position's future loss - // and the balance of entire vault is not enough - // need money from PerpEF to pay first, and record this prepaidBadDebt - shortage := amountToWithdraw.Sub(vaultQuoteBalance.Amount) - k.IncrementPrepaidBadDebt(ctx, market, shortage) - - // TODO(k-yang): emit event for prepaid bad debt - - if err := k.BankKeeper.SendCoinsFromModuleToModule( - ctx, - types.PerpFundModuleAccount, - types.VaultModuleAccount, - sdk.NewCoins( - sdk.NewCoin(collateral, shortage), - ), - ); err != nil { - return err - } - } - - // Transfer from Vault to receiver - return k.BankKeeper.SendCoinsFromModuleToAccount( - ctx, - /* from */ types.VaultModuleAccount, - /* to */ receiver, - sdk.NewCoins( - sdk.NewCoin(collateral, amountToWithdraw), - ), - ) -} - -// IncrementPrepaidBadDebt increases the bad debt for the provided denom. -func (k Keeper) IncrementPrepaidBadDebt(ctx sdk.Context, market types.Market, amount sdkmath.Int) { - market.PrepaidBadDebt.Amount = market.PrepaidBadDebt.Amount.Add(amount) - k.SaveMarket(ctx, market) -} - -// ZeroPrepaidBadDebt out the prepaid bad debt -func (k Keeper) ZeroPrepaidBadDebt(ctx sdk.Context, market types.Market) { - market.PrepaidBadDebt.Amount = sdk.ZeroInt() - k.SaveMarket(ctx, market) -} - -// DecrementPrepaidBadDebt decrements the amount of bad debt prepaid by denom. -func (k Keeper) DecrementPrepaidBadDebt(ctx sdk.Context, market types.Market, amount sdkmath.Int) { - market.PrepaidBadDebt.Amount = market.PrepaidBadDebt.Amount.Sub(amount) - k.SaveMarket(ctx, market) -} - -/* -Realizes the bad debt by first decrementing it from the prepaid bad debt. -Prepaid bad debt accrues when more coins are withdrawn from the vault than the -vault contains, so we "credit" ourselves with prepaid bad debt. - -then, when bad debt is actually realized (by closing underwater positions), we -can consume the credit we have built before withdrawing more from the ecosystem fund. -*/ -func (k Keeper) realizeBadDebt(ctx sdk.Context, market types.Market, badDebtToRealize sdkmath.Int) ( - err error, -) { - if market.PrepaidBadDebt.Amount.GTE(badDebtToRealize) { - // prepaidBadDebtBalance > badDebtToRealize - k.DecrementPrepaidBadDebt(ctx, market, badDebtToRealize) - } else { - // badDebtToRealize > prepaidBadDebtBalance - k.ZeroPrepaidBadDebt(ctx, market) - - collateral, err := k.Collateral.Get(ctx) - if err != nil { - return err - } - - return k.BankKeeper.SendCoinsFromModuleToModule(ctx, - /*from=*/ types.PerpFundModuleAccount, - /*to=*/ types.VaultModuleAccount, - sdk.NewCoins( - sdk.NewCoin( - collateral, - badDebtToRealize.Sub(market.PrepaidBadDebt.Amount), - ), - ), - ) - } - - return nil -} diff --git a/x/perp/v2/keeper/withdraw_test.go b/x/perp/v2/keeper/withdraw_test.go deleted file mode 100644 index 040ff7e15..000000000 --- a/x/perp/v2/keeper/withdraw_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - . "github.com/NibiruChain/nibiru/x/common/testutil/action" - . "github.com/NibiruChain/nibiru/x/common/testutil/assertion" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/action" - . "github.com/NibiruChain/nibiru/x/perp/v2/integration/assertion" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func TestWithdrawFromVault(t *testing.T) { - alice := testutil.AccAddress() - pairBtcUsdc := asset.Registry.Pair(denoms.BTC, denoms.USDC) - startBlockTime := time.Now() - - tc := TestCases{ - TC("successful withdraw, no bad debt"). - Given( - SetBlockNumber(1), - SetBlockTime(startBlockTime), - CreateCustomMarket(pairBtcUsdc), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1000)))), - ). - When( - WithdrawFromVault(pairBtcUsdc, alice, sdk.NewInt(1000)), - ). - Then( - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(1000)), - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - MarketShouldBeEqual(pairBtcUsdc, Market_PrepaidBadDebtShouldBeEqualTo(sdk.ZeroInt(), types.TestingCollateralDenomNUSD)), - ), - - TC("successful withdraw, some bad debt"). - Given( - SetBlockNumber(1), - SetBlockTime(startBlockTime), - CreateCustomMarket(pairBtcUsdc), - FundModule(types.VaultModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(500)))), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(500)))), - ). - When( - WithdrawFromVault(pairBtcUsdc, alice, sdk.NewInt(1000)), - ). - Then( - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(1000)), - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - MarketShouldBeEqual(pairBtcUsdc, Market_PrepaidBadDebtShouldBeEqualTo(sdk.NewInt(500), types.TestingCollateralDenomNUSD)), - ), - - TC("successful withdraw, all bad debt"). - Given( - SetBlockNumber(1), - SetBlockTime(startBlockTime), - CreateCustomMarket(pairBtcUsdc), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1000)))), - ). - When( - WithdrawFromVault(pairBtcUsdc, alice, sdk.NewInt(1000)), - ). - Then( - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(1000)), - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - MarketShouldBeEqual(pairBtcUsdc, Market_PrepaidBadDebtShouldBeEqualTo(sdk.NewInt(1000), types.TestingCollateralDenomNUSD)), - ), - - TC("successful withdraw, existing bad debt"). - Given( - SetBlockNumber(1), - SetBlockTime(startBlockTime), - CreateCustomMarket(pairBtcUsdc, WithPrepaidBadDebt(sdk.NewInt(1000), types.TestingCollateralDenomNUSD)), - FundModule(types.PerpFundModuleAccount, sdk.NewCoins(sdk.NewCoin(types.TestingCollateralDenomNUSD, sdk.NewInt(1000)))), - ). - When( - WithdrawFromVault(pairBtcUsdc, alice, sdk.NewInt(1000)), - ). - Then( - BalanceEqual(alice, types.TestingCollateralDenomNUSD, sdk.NewInt(1000)), - ModuleBalanceEqual(types.VaultModuleAccount, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - ModuleBalanceEqual(types.PerpFundModuleAccount, types.TestingCollateralDenomNUSD, sdk.ZeroInt()), - MarketShouldBeEqual(pairBtcUsdc, Market_PrepaidBadDebtShouldBeEqualTo(sdk.NewInt(2000), types.TestingCollateralDenomNUSD)), - ), - } - - NewTestSuite(t).WithTestCases(tc...).Run() -} diff --git a/x/perp/v2/module/abci.go b/x/perp/v2/module/abci.go deleted file mode 100644 index 873ed7e83..000000000 --- a/x/perp/v2/module/abci.go +++ /dev/null @@ -1,69 +0,0 @@ -package perp - -import ( - abci "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/collections" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// EndBlocker Called every block to store a snapshot of the perpamm. -func EndBlocker(ctx sdk.Context, k keeper.Keeper) []abci.ValidatorUpdate { - for _, amm := range k.AMMs.Iterate(ctx, collections.Range[collections.Pair[asset.Pair, uint64]]{}).Values() { - market, err := k.GetMarket(ctx, amm.Pair) - if err != nil { - k.Logger(ctx).Error("failed to fetch market", "pair", amm.Pair, "error", err) - continue - } - - // only snapshot enabled markets - if !market.Enabled { - continue - } - - snapshot := types.ReserveSnapshot{ - Amm: amm, - TimestampMs: ctx.BlockTime().UnixMilli(), - } - k.ReserveSnapshots.Insert(ctx, collections.Join(amm.Pair, ctx.BlockTime()), snapshot) - - markTwap, err := k.CalcTwap(ctx, amm.Pair, types.TwapCalcOption_SPOT, types.Direction_DIRECTION_UNSPECIFIED, sdk.ZeroDec(), market.TwapLookbackWindow) - if err != nil { - k.Logger(ctx).Error("failed to fetch twap mark price", "market.Pair", market.Pair, "error", err) - continue - } - - if markTwap.IsNil() || markTwap.IsZero() { - k.Logger(ctx).Error("mark price is zero", "market.Pair", market.Pair) - continue - } - - var indexTwap sdk.Dec - indexTwap, err = k.OracleKeeper.GetExchangeRateTwap(ctx, market.OraclePair) - if err != nil { - k.Logger(ctx).Error("failed to fetch twap index price", "market.Pair", market.Pair, "market.OraclePair", market.OraclePair, "error", err) - indexTwap = sdk.OneDec().Neg() - } - - if indexTwap.IsNil() { - k.Logger(ctx).Error("index price is zero", "market.Pair", market.Pair, "market.OraclePair", market.OraclePair) - continue - } - - _ = ctx.EventManager().EmitTypedEvent(&types.AmmUpdatedEvent{ - FinalAmm: amm, - MarkPriceTwap: markTwap, - IndexPriceTwap: indexTwap, - }) - - _ = ctx.EventManager().EmitTypedEvent(&types.MarketUpdatedEvent{ - FinalMarket: market, - }) - } - - return []abci.ValidatorUpdate{} -} diff --git a/x/perp/v2/module/abci_test.go b/x/perp/v2/module/abci_test.go deleted file mode 100644 index 164262f80..000000000 --- a/x/perp/v2/module/abci_test.go +++ /dev/null @@ -1,146 +0,0 @@ -package perp_test - -import ( - "testing" - "time" - - "github.com/NibiruChain/collections" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - testutilevents "github.com/NibiruChain/nibiru/x/common/testutil" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil/mock" - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - perp "github.com/NibiruChain/nibiru/x/perp/v2/module" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func TestSnapshotUpdates(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - initialMarket := *mock.TestMarket() - initialAmm := *mock.TestAMMDefault() - - runBlock := func(duration time.Duration) { - perp.EndBlocker(ctx, app.PerpKeeperV2) - ctx = ctx. - WithBlockHeight(ctx.BlockHeight() + 1). - WithBlockTime(ctx.BlockTime().Add(duration)) - } - - ctx = ctx.WithBlockTime(time.Date(2015, 10, 21, 0, 0, 0, 0, time.UTC)).WithBlockHeight(1) - - require.NoError(t, app.PerpKeeperV2.Sudo().CreateMarket( - /* ctx */ ctx, keeper.ArgsCreateMarket{ - Pair: asset.Registry.Pair(denoms.BTC, denoms.NUSD), - PriceMultiplier: initialAmm.PriceMultiplier, - SqrtDepth: initialAmm.SqrtDepth, - Market: &initialMarket, - }, - )) - - expectedSnapshot := types.ReserveSnapshot{ - Amm: initialAmm, - TimestampMs: ctx.BlockTime().UnixMilli(), - } - - t.Log("run one block of 5 seconds") - runBlock(5 * time.Second) - snapshot, err := app.PerpKeeperV2.ReserveSnapshots.Get(ctx, - collections.Join( - asset.Registry.Pair(denoms.BTC, denoms.NUSD), - time.UnixMilli(expectedSnapshot.TimestampMs), - ), - ) - require.NoError(t, err) - assert.EqualValues(t, expectedSnapshot, snapshot) - - t.Log("affect mark price") - amm, err := app.PerpKeeperV2.GetAMM(ctx, asset.Registry.Pair(denoms.BTC, denoms.NUSD)) - require.NoError(t, err) - - _, baseAmtAbs, err := app.PerpKeeperV2.SwapQuoteAsset( - ctx, - amm, - types.Direction_LONG, - sdk.NewDec(250e9), - sdk.ZeroDec(), - ) - require.NoError(t, err) - // dxAmm := (k / (y + dyAmm)) - x = (1e24 / (1e12 + 250e9)) - 1e12 = -200e9 - assert.EqualValues(t, sdk.NewDec(200e9), baseAmtAbs) - - expectedSnapshot = types.ReserveSnapshot{ - Amm: types.AMM{ - Pair: asset.Registry.Pair(denoms.BTC, denoms.NUSD), - Version: 1, - BaseReserve: sdk.NewDec(800e9), - QuoteReserve: sdk.NewDec(1.25e12), - SqrtDepth: sdk.NewDec(1e12), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(200e9), - TotalShort: sdk.ZeroDec(), - SettlementPrice: sdk.ZeroDec(), - }, - TimestampMs: ctx.BlockTime().UnixMilli(), - } - - t.Log("run one block of 5 seconds") - runBlock(5 * time.Second) - - snapshot, err = app.PerpKeeperV2.ReserveSnapshots.Get(ctx, - collections.Join( - asset.Registry.Pair(denoms.BTC, denoms.NUSD), - time.UnixMilli(expectedSnapshot.TimestampMs), - ), - ) - require.NoError(t, err) - assert.EqualValues(t, expectedSnapshot, snapshot) -} - -func TestEndBlocker(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - initialMarket := *mock.TestMarket() - initialAmm := *mock.TestAMMDefault() - - runBlock := func(duration time.Duration) { - perp.EndBlocker(ctx, app.PerpKeeperV2) - ctx = ctx. - WithBlockHeight(ctx.BlockHeight() + 1). - WithBlockTime(ctx.BlockTime().Add(duration)) - } - - ctx = ctx.WithBlockTime(time.Date(2015, 10, 21, 0, 0, 0, 0, time.UTC)).WithBlockHeight(1) - - runBlock(5 * time.Second) - - require.NoError(t, app.PerpKeeperV2.Sudo().CreateMarket( - /* ctx */ ctx, keeper.ArgsCreateMarket{ - Pair: asset.Registry.Pair(denoms.BTC, denoms.NUSD), - PriceMultiplier: initialAmm.PriceMultiplier, - SqrtDepth: initialAmm.SqrtDepth, - Market: &initialMarket, - }, - )) - - t.Log("run one block of 5 seconds") - app.OracleKeeper.SetPrice(ctx, asset.Registry.Pair(denoms.BTC, denoms.NUSD), sdk.NewDec(100e6)) - - beforeEvents := ctx.EventManager().Events() - runBlock(5 * time.Second) - afterEvents := ctx.EventManager().Events() - - require.NoError(t, - testutilevents.AssertEventsPresent( - testutilevents.FilterNewEvents(beforeEvents, afterEvents), - []string{"nibiru.perp.v2.AmmUpdatedEvent", "nibiru.perp.v2.MarketUpdatedEvent"}, - ), - ) - - // add index price -} diff --git a/x/perp/v2/module/genesis.go b/x/perp/v2/module/genesis.go deleted file mode 100644 index 080bc5443..000000000 --- a/x/perp/v2/module/genesis.go +++ /dev/null @@ -1,187 +0,0 @@ -package perp - -import ( - "time" - - "cosmossdk.io/math" - "github.com/NibiruChain/collections" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// InitGenesis initializes the capability module's state from a provided genesis -// state. -func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) { - if err := genState.Validate(); err != nil { - panic(err) - } - - k.DnREpoch.Set(ctx, genState.DnrEpoch) - - k.DnREpochName.Set(ctx, genState.DnrEpochName) - - for _, m := range genState.Markets { - k.SaveMarket(ctx, m) - } - - for _, g := range genState.MarketLastVersions { - k.MarketLastVersion.Insert(ctx, g.Pair, types.MarketLastVersion{Version: g.Version}) - } - - for _, amm := range genState.Amms { - pair := amm.Pair - k.SaveAMM(ctx, amm) - timestampMs := ctx.BlockTime().UnixMilli() - k.ReserveSnapshots.Insert( - ctx, - collections.Join(pair, time.UnixMilli(timestampMs)), - types.ReserveSnapshot{ - Amm: amm, - TimestampMs: timestampMs, - }, - ) - } - - for _, p := range genState.Positions { - k.SavePosition(ctx, p.Pair, p.Version, sdk.MustAccAddressFromBech32(p.Position.TraderAddress), p.Position) - } - - for _, vol := range genState.TraderVolumes { - k.TraderVolumes.Insert( - ctx, - collections.Join(sdk.MustAccAddressFromBech32(vol.Trader), vol.Epoch), - vol.Volume, - ) - } - for _, globalDiscount := range genState.GlobalDiscount { - k.GlobalDiscounts.Insert( - ctx, - globalDiscount.Volume, - globalDiscount.Fee, - ) - } - - for _, customDiscount := range genState.CustomDiscounts { - k.TraderDiscounts.Insert( - ctx, - collections.Join(sdk.MustAccAddressFromBech32(customDiscount.Trader), customDiscount.Discount.Volume), - customDiscount.Discount.Fee, - ) - } - - if genState.CollateralDenom != "" { - err := k.Sudo().UnsafeChangeCollateralDenom(ctx, genState.CollateralDenom) - if err != nil { - panic(err) - } - } - - for _, globalVolume := range genState.GlobalVolumes { - k.GlobalVolumes.Insert( - ctx, - globalVolume.Epoch, - globalVolume.Volume, - ) - } - - for _, rebateAlloc := range genState.RebatesAllocations { - k.EpochRebateAllocations.Insert( - ctx, - rebateAlloc.Epoch, - types.DNRAllocation{ - Epoch: rebateAlloc.Epoch, - Amount: rebateAlloc.Amount, - }, - ) - } -} - -// ExportGenesis returns the capability module's exported genesis. -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { - genesis := new(types.GenesisState) - - genesis.Markets = k.Markets.Iterate(ctx, collections.Range[collections.Pair[asset.Pair, uint64]]{}).Values() - - kv := k.MarketLastVersion.Iterate(ctx, collections.Range[asset.Pair]{}).KeyValues() - for _, kv := range kv { - genesis.MarketLastVersions = append(genesis.MarketLastVersions, types.GenesisMarketLastVersion{ - Pair: kv.Key, - Version: kv.Value.Version, - }) - } - - genesis.Amms = k.AMMs.Iterate(ctx, collections.Range[collections.Pair[asset.Pair, uint64]]{}).Values() - pkv := k.Positions.Iterate(ctx, collections.PairRange[collections.Pair[asset.Pair, uint64], sdk.AccAddress]{}).KeyValues() - for _, kv := range pkv { - genesis.Positions = append(genesis.Positions, types.GenesisPosition{ - Pair: kv.Key.K1().K1(), - Version: kv.Key.K1().K2(), - Position: kv.Value, - }) - } - genesis.ReserveSnapshots = k.ReserveSnapshots.Iterate(ctx, collections.PairRange[asset.Pair, time.Time]{}).Values() - genesis.DnrEpoch = k.DnREpoch.GetOr(ctx, 0) - genesis.DnrEpochName = k.DnREpochName.GetOr(ctx, "") - - // export volumes - volumes := k.TraderVolumes.Iterate(ctx, collections.PairRange[sdk.AccAddress, uint64]{}) - defer volumes.Close() - for ; volumes.Valid(); volumes.Next() { - key := volumes.Key() - genesis.TraderVolumes = append(genesis.TraderVolumes, types.GenesisState_TraderVolume{ - Trader: key.K1().String(), - Epoch: key.K2(), - Volume: volumes.Value(), - }) - } - - // export global discounts - discounts := k.GlobalDiscounts.Iterate(ctx, collections.Range[math.Int]{}) - defer discounts.Close() - for ; discounts.Valid(); discounts.Next() { - genesis.GlobalDiscount = append(genesis.GlobalDiscount, types.GenesisState_Discount{ - Fee: discounts.Value(), - Volume: discounts.Key(), - }) - } - - // export custom discounts - customDiscounts := k.TraderDiscounts.Iterate(ctx, collections.PairRange[sdk.AccAddress, math.Int]{}) - defer customDiscounts.Close() - - for ; customDiscounts.Valid(); customDiscounts.Next() { - key := customDiscounts.Key() - genesis.CustomDiscounts = append(genesis.CustomDiscounts, types.GenesisState_CustomDiscount{ - Trader: key.K1().String(), - Discount: &types.GenesisState_Discount{ - Fee: sdk.Dec{}, - Volume: key.K2(), - }, - }) - } - - collateral, err := k.Collateral.Get(ctx) - if err != nil { - panic(err) - } - genesis.CollateralDenom = collateral - - // export global volumes - globalVolumes := k.GlobalVolumes.Iterate(ctx, collections.Range[uint64]{}) - defer globalVolumes.Close() - for ; globalVolumes.Valid(); globalVolumes.Next() { - genesis.GlobalVolumes = append(genesis.GlobalVolumes, types.GenesisState_GlobalVolume{ - Epoch: globalVolumes.Key(), - Volume: globalVolumes.Value(), - }) - } - - // export rebates allocations - genesis.RebatesAllocations = k.EpochRebateAllocations.Iterate(ctx, collections.Range[uint64]{}).Values() - - return genesis -} diff --git a/x/perp/v2/module/genesis_test.go b/x/perp/v2/module/genesis_test.go deleted file mode 100644 index f92dcbf45..000000000 --- a/x/perp/v2/module/genesis_test.go +++ /dev/null @@ -1,198 +0,0 @@ -package perp_test - -import ( - "encoding/json" - "testing" - - "cosmossdk.io/math" - "github.com/NibiruChain/collections" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - "github.com/NibiruChain/nibiru/x/common/testutil/mock" - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - perp "github.com/NibiruChain/nibiru/x/perp/v2/module" - types "github.com/NibiruChain/nibiru/x/perp/v2/types" - sudotypes "github.com/NibiruChain/nibiru/x/sudo/types" -) - -type TestCase struct { - name string - positions []types.Position -} - -func init() { - testapp.EnsureNibiruPrefix() -} - -func TestGenesis(t *testing.T) { - testapp.EnsureNibiruPrefix() - testCases := []TestCase{ - { - name: "empty positions genesis", - positions: []types.Position{}, - }, - } - - var positions []types.Position - // create some positions - for i := int64(1); i < 100; i++ { - trader := testutil.AccAddress() - position := types.Position{ - TraderAddress: trader.String(), - Pair: asset.Registry.Pair(denoms.NIBI, denoms.NUSD), - Size_: sdk.NewDec(i + 1), - Margin: sdk.NewDec(i * 2), - OpenNotional: sdk.NewDec(i * 100), - LatestCumulativePremiumFraction: sdk.NewDec(5 * 100), - LastUpdatedBlockNumber: i, - } - require.NoErrorf(t, position.Validate(), "position: %s", position) - positions = append(positions, position) - } - testCases = append(testCases, TestCase{ - name: "many valid positions", - positions: positions, - }) - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - RunTestGenesis(t, tc) - }) - } -} - -func PerpSudoers() sudotypes.Sudoers { - _, addrs := testutil.PrivKeyAddressPairs(2) - return sudotypes.Sudoers{ - Root: addrs[0].String(), - Contracts: []string{addrs[1].String()}, - } -} - -func RunTestGenesis(t *testing.T, tc TestCase) { - testapp.EnsureNibiruPrefix() - app, ctxUncached := testapp.NewNibiruTestAppAndContext() - ctx, _ := ctxUncached.CacheContext() - - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - - // Initialize sudo state - nibiruTeam := common.NIBIRU_TEAM - sudoers := PerpSudoers() - sudoersRoot := sdk.MustAccAddressFromBech32(nibiruTeam) - sudoers.Root = sudoersRoot.String() - app.SudoKeeper.Sudoers.Set(ctx, sudoers) - - // create some params - require.NoError(t, app.PerpKeeperV2.Sudo().ChangeCollateralDenom( - ctx, "unusd", sudoersRoot)) - app.PerpKeeperV2.SaveMarket(ctx, *mock.TestMarket()) - app.PerpKeeperV2.MarketLastVersion.Insert(ctx, pair, types.MarketLastVersion{Version: 1}) - app.PerpKeeperV2.SaveAMM(ctx, *mock.TestAMMDefault()) - app.PerpKeeperV2.TraderDiscounts.Insert(ctx, collections.Join(testutil.AccAddress(), math.NewInt(1_000_000)), sdk.MustNewDecFromStr("0.1")) - app.PerpKeeperV2.GlobalDiscounts.Insert(ctx, sdk.NewInt(1_000_000), sdk.MustNewDecFromStr("0.05")) - app.PerpKeeperV2.TraderVolumes.Insert(ctx, collections.Join(testutil.AccAddress(), uint64(0)), math.NewInt(1_000_000)) - app.PerpKeeperV2.GlobalVolumes.Insert(ctx, uint64(0), math.NewInt(1_000_000)) - app.PerpKeeperV2.EpochRebateAllocations.Insert(ctx, uint64(0), types.DNRAllocation{ - Epoch: 0, - Amount: sdk.NewCoins(sdk.NewCoin(denoms.NUSD, sdk.NewInt(1_000_000))), - }) - app.PerpKeeperV2.DnREpochName.Set(ctx, "weekly") - app.PerpKeeperV2.DnREpoch.Set(ctx, 1) - - // create some positions - for _, position := range tc.positions { - trader := sdk.MustAccAddressFromBech32(position.TraderAddress) - app.PerpKeeperV2.SavePosition(ctx, asset.Registry.Pair(denoms.NIBI, denoms.NUSD), 1, trader, position) - } - - // export genesis - genState := perp.ExportGenesis(ctx, app.PerpKeeperV2) - err := genState.Validate() - jsonBz, errMarshalJson := app.AppCodec().MarshalJSON(genState) - require.NoError(t, errMarshalJson) - require.NoErrorf(t, err, "genState: \n%s", jsonBz) - - // create new context and init genesis - ctx, _ = ctxUncached.CacheContext() - perp.InitGenesis(ctx, app.PerpKeeperV2, *genState) - - // export again to ensure they match - genStateAfterInit := perp.ExportGenesis(ctx, app.PerpKeeperV2) - - require.Len(t, genStateAfterInit.Markets, len(genState.Markets)) - for i, pm := range genState.Markets { - require.Equal(t, pm, genStateAfterInit.Markets[i]) - } - - require.Len(t, genStateAfterInit.MarketLastVersions, len(genState.MarketLastVersions)) - for i, mlv := range genState.MarketLastVersions { - require.Equal(t, mlv, genStateAfterInit.MarketLastVersions[i]) - } - - require.Len(t, genStateAfterInit.Amms, len(genState.Amms)) - for i, amm := range genState.Amms { - require.Equal(t, amm, genStateAfterInit.Amms[i]) - } - - require.Equal(t, len(genState.Positions), len(genStateAfterInit.Positions)) - for i, pos := range genState.Positions { - require.Equalf(t, pos, genStateAfterInit.Positions[i], "%s <-> %s", pos, genStateAfterInit.Positions[i]) - } - - require.Equal(t, genState.CustomDiscounts, genStateAfterInit.CustomDiscounts) - require.Equal(t, genState.GlobalDiscount, genStateAfterInit.GlobalDiscount) - require.Equal(t, genState.TraderVolumes, genStateAfterInit.TraderVolumes) - require.Equal(t, genState.CollateralDenom, genStateAfterInit.CollateralDenom) - require.Equal(t, genState.GlobalVolumes, genStateAfterInit.GlobalVolumes) - require.Equal(t, genState.RebatesAllocations, genStateAfterInit.RebatesAllocations) - require.Equal(t, genState.DnrEpochName, genStateAfterInit.DnrEpochName) - require.Equal(t, genState.DnrEpoch, genStateAfterInit.DnrEpoch) -} - -func TestNewAppModuleBasic(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - binaryCodec := codec.NewProtoCodec(nil) // Provide appropriate codec interface registry - appModuleBasic := perp.NewAppModuleBasic(binaryCodec) - - require.Equal(t, types.ModuleName, appModuleBasic.Name()) - cdc := codec.NewProtoCodec(nil) - - appModule := perp.NewAppModule(cdc, app.PerpKeeperV2, nil, nil, nil) - - require.Equal(t, types.ModuleName, appModule.Name()) - require.Equal(t, uint64(3), appModule.ConsensusVersion()) - - exportedGenesis := appModule.ExportGenesis(ctx, cdc) - err := appModule.ValidateGenesis(cdc, nil, exportedGenesis) - require.NoError(t, err) - - // Test genesis functionalities - genesisState := types.DefaultGenesis() - rawGS, err := cdc.MarshalJSON(genesisState) - require.NoError(t, err) - - // Test DefaultGenesis - require.Equal(t, json.RawMessage(rawGS), appModule.DefaultGenesis(cdc)) - - // Test ValidateGenesis - err = appModule.ValidateGenesis(cdc, nil, rawGS) - require.NoError(t, err) - - appModule.BeginBlock(ctx, abci.RequestBeginBlock{}) - appModule.EndBlock(ctx, abci.RequestEndBlock{}) - - cmds := appModule.GetTxCmd() - require.True(t, len(cmds.Commands()) > 0) - - cmds = appModule.GetQueryCmd() - require.True(t, len(cmds.Commands()) > 0) -} diff --git a/x/perp/v2/module/module.go b/x/perp/v2/module/module.go deleted file mode 100644 index 8770bb84a..000000000 --- a/x/perp/v2/module/module.go +++ /dev/null @@ -1,186 +0,0 @@ -package perp - -import ( - "context" - "encoding/json" - "fmt" - - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - "github.com/NibiruChain/nibiru/x/perp/v2/client/cli" - "github.com/NibiruChain/nibiru/x/perp/v2/keeper" - "github.com/NibiruChain/nibiru/x/perp/v2/simulation" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// type check to ensure the interface is properly implemented -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModule{} -) - -// ---------------------------------------------------------------------------- -// AppModuleBasic -// ---------------------------------------------------------------------------- - -type AppModuleBasic struct { - binaryCodec codec.BinaryCodec -} - -func NewAppModuleBasic(binaryCodec codec.BinaryCodec) AppModuleBasic { - return AppModuleBasic{binaryCodec: binaryCodec} -} - -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -// RegisterInterfaces registers interfaces and implementations of the perp module. -func (AppModuleBasic) RegisterInterfaces(interfaceRegistry codectypes.InterfaceRegistry) { - types.RegisterInterfaces(interfaceRegistry) -} - -func (AppModuleBasic) RegisterLegacyAminoCodec(aminoCodec *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(aminoCodec) -} - -// DefaultGenesis returns default genesis state as raw bytes for the erc20 -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesis()) -} - -// ValidateGenesis performs genesis state validation for the capability module. -func (AppModuleBasic) ValidateGenesis( - cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage, -) error { - var genState types.GenesisState - if err := cdc.UnmarshalJSON(bz, &genState); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - } - return genState.Validate() -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes( - clientCtx client.Context, mux *runtime.ServeMux, -) { - if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { - panic(err) - } -} - -// GetTxCmd returns the capability module's root tx command. -func (a AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.NewTxCmd() -} - -// GetQueryCmd returns the capability module's root query command. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.NewQueryCmd() -} - -// ---------------------------------------------------------------------------- -// AppModule -// ---------------------------------------------------------------------------- - -// AppModule implements the AppModule interface for the module. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - ak types.AccountKeeper - bk types.BankKeeper - ok types.OracleKeeper -} - -func NewAppModule( - cdc codec.Codec, - keeper keeper.Keeper, - ak types.AccountKeeper, - bk types.BankKeeper, - ok types.OracleKeeper, -) AppModule { - return AppModule{ - AppModuleBasic: NewAppModuleBasic(cdc), - keeper: keeper, - ak: ak, - bk: bk, - ok: ok, - } -} - -// Name returns the capability module's name. -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// RegisterServices registers a GRPC query service to respond to the -// module-specific GRPC queries. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQuerier(am.keeper)) - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) -} - -// RegisterInvariants registers the capability module's invariants. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// InitGenesis performs the capability module's genesis initialization It returns -// no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage, -) []abci.ValidatorUpdate { - var genState types.GenesisState - // Initialize global index to index in genesis state - cdc.MustUnmarshalJSON(gs, &genState) - - InitGenesis(ctx, am.keeper, genState) - - // See https://github.com/cosmos/cosmos-sdk/issues/5569 on why we do this. - am.ak.GetModuleAccount(ctx, types.PerpFundModuleAccount) - am.ak.GetModuleAccount(ctx, types.VaultModuleAccount) - am.ak.GetModuleAccount(ctx, types.FeePoolModuleAccount) - - return []abci.ValidatorUpdate{} -} - -// ExportGenesis returns the capability module's exported genesis state as raw JSON bytes. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - genState := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(genState) -} - -// ConsensusVersion implements ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return 3 } - -// BeginBlock executes all ABCI BeginBlock logic respective to the capability module. -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// EndBlock executes all ABCI EndBlock logic respective to the capability module. It -// returns no validator updates. -func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - EndBlocker(ctx, am.keeper) - return []abci.ValidatorUpdate{} -} - -// GenerateGenesisState implements module.AppModuleSimulation. -func (AppModule) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// RegisterStoreDecoder implements module.AppModuleSimulation. -func (AppModule) RegisterStoreDecoder(sdk.StoreDecoderRegistry) { -} - -// WeightedOperations implements module.AppModuleSimulation. -func (AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { - return []simtypes.WeightedOperation{} -} diff --git a/x/perp/v2/simulation/genesis.go b/x/perp/v2/simulation/genesis.go deleted file mode 100644 index 6f010bdef..000000000 --- a/x/perp/v2/simulation/genesis.go +++ /dev/null @@ -1,24 +0,0 @@ -package simulation - -// DONTCOVER - -import ( - "encoding/json" - "fmt" - - "github.com/cosmos/cosmos-sdk/types/module" - - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -// RandomizedGenState generates a random GenesisState for distribution -func RandomizedGenState(simState *module.SimulationState) { - perpGenesis := *types.DefaultGenesis() - - bz, err := json.MarshalIndent(&perpGenesis, "", " ") - if err != nil { - panic(err) - } - fmt.Printf("Selected randomly generated x/tokenfactory parameters:\n%s\n", bz) - simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&perpGenesis) -} diff --git a/x/perp/v2/types/amm.go b/x/perp/v2/types/amm.go deleted file mode 100644 index 27f052edd..000000000 --- a/x/perp/v2/types/amm.go +++ /dev/null @@ -1,452 +0,0 @@ -package types - -import ( - "math/big" - - sdkerrors "cosmossdk.io/errors" - sdkmath "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/common/asset" -) - -func (amm AMM) Validate() error { - if amm.BaseReserve.LTE(sdk.ZeroDec()) { - return ErrAmmBaseSupplyNonpositive - } - - if amm.QuoteReserve.LTE(sdk.ZeroDec()) { - return ErrAmmQuoteSupplyNonpositive - } - - if amm.PriceMultiplier.LTE(sdk.ZeroDec()) { - return ErrAmmNonPositivePegMult - } - - if amm.SqrtDepth.LTE(sdk.ZeroDec()) { - return ErrAmmNonPositiveSwapInvariant - } - - computedSqrtDepth, err := amm.ComputeSqrtDepth() - if err != nil { - return err - } - - if !amm.SqrtDepth.Sub(computedSqrtDepth).Abs().LTE(sdk.OneDec()) { - return ErrLiquidityDepth.Wrap( - "computed sqrt and current sqrt are mismatched. pool: " + amm.String()) - } - - // Short positions borrow base asset, so if the base reserve is below the - // quote reserve swapped to base, then the shorts can't close positions. - _, err = amm.SwapBaseAsset(amm.TotalShort, Direction_LONG) - if err != nil { - return sdkerrors.Wrapf(ErrAmmBaseBorrowedTooHigh, "Base amount error, short exceed total base supply: %s", err.Error()) - } - - return nil -} - -// ComputeSettlementPrice computes the uniform settlement price for the current AMM. -// -// Returns: -// - price: uniform settlement price from several batched trades. In this case, -// "price" is the result of closing all positions together and giving -// all traders the same price. -// - newAmm: The AMM that results from closing all positions together. Note that -// this should have a bias, or skew, of 0. -// - err: Errors if it's impossible to swap away the open interest bias. -func (amm AMM) ComputeSettlementPrice() (sdk.Dec, AMM, error) { - // bias: open interest (base) skew in the AMM. - bias := amm.Bias() - if bias.IsZero() { - return amm.InstMarkPrice(), amm, nil - } - - var dir Direction - if bias.IsPositive() { - dir = Direction_SHORT - } else { - dir = Direction_LONG - } - - quoteAssetDelta, err := amm.SwapBaseAsset(bias.Abs(), dir) - if err != nil { - return sdk.Dec{}, AMM{}, err - } - price := quoteAssetDelta.Abs().Quo(bias.Abs()) - - return price, amm, err -} - -// QuoteReserveToAsset converts quote reserves to assets\ -func (amm AMM) QuoteReserveToAsset(quoteReserve sdk.Dec) sdk.Dec { - return QuoteReserveToAsset(quoteReserve, amm.PriceMultiplier) -} - -// QuoteAssetToReserve converts quote assets to reserves -func (amm AMM) QuoteAssetToReserve(quoteAssets sdk.Dec) sdk.Dec { - return QuoteAssetToReserve(quoteAssets, amm.PriceMultiplier) -} - -// QuoteAssetToReserve converts "quote assets" to "quote reserves". In this -// convention, "assets" are liquid funds that change hands, whereas reserves -// are simply a number field on the DAMM. The reason for this distinction is to -// account for the AMM.PriceMultiplier. -func QuoteAssetToReserve(quoteAsset, priceMult sdk.Dec) sdk.Dec { - return quoteAsset.Quo(priceMult) -} - -// QuoteReserveToAsset converts "quote reserves" to "quote assets". In this -// convention, "assets" are liquid funds that change hands, whereas reserves -// are simply a number field on the DAMM. The reason for this distinction is to -// account for the AMM.PriceMultiplier. -func QuoteReserveToAsset(quoteReserve, priceMult sdk.Dec) sdk.Dec { - return quoteReserve.Mul(priceMult) -} - -// GetBaseReserveAmt Returns the amount of base reserve equivalent to the amount of quote reserve given -// -// args: -// - quoteReserveAmt: the amount of quote reserve before the trade, must be positive -// - dir: the direction of the trade -// -// returns: -// - baseReserveDelta: the amount of base reserve after the trade, unsigned -// - err: error -// -// NOTE: baseReserveDelta is always positive -// Throws an error if input quoteReserveAmt is negative, or if the final quote reserve is not positive -func (amm AMM) GetBaseReserveAmt( - quoteReserveAmt sdk.Dec, // unsigned - dir Direction, -) (baseReserveDelta sdk.Dec, err error) { - if quoteReserveAmt.IsNegative() { - return sdk.Dec{}, ErrInputQuoteAmtNegative - } - - invariant := amm.QuoteReserve.Mul(amm.BaseReserve) // x * y = k - - var quoteReservesAfter sdk.Dec - if dir == Direction_LONG { - quoteReservesAfter = amm.QuoteReserve.Add(quoteReserveAmt) - } else { - quoteReservesAfter = amm.QuoteReserve.Sub(quoteReserveAmt) - } - - if !quoteReservesAfter.IsPositive() { - return sdk.Dec{}, ErrAmmNonpositiveReserves - } - - baseReservesAfter := invariant.Quo(quoteReservesAfter) - baseReserveDelta = baseReservesAfter.Sub(amm.BaseReserve).Abs() - - return baseReserveDelta, nil -} - -// GetQuoteReserveAmt returns the amount of quote reserve equivalent to the amount of base asset given -// -// args: -// - baseReserveAmt: the amount of base reserves to trade, must be positive -// - dir: the direction of the trade -// -// returns: -// - quoteReserveDelta: the amount of quote reserve after the trade -// - err: error -// -// NOTE: quoteReserveDelta is always positive -func (amm AMM) GetQuoteReserveAmt( - baseReserveAmt sdk.Dec, - dir Direction, -) (quoteReserveDelta sdk.Dec, err error) { - if baseReserveAmt.IsNegative() { - return sdk.Dec{}, ErrInputBaseAmtNegative - } - if baseReserveAmt.IsZero() { - return sdk.ZeroDec(), nil - } - - invariant := amm.QuoteReserve.Mul(amm.BaseReserve) // x * y = k - - var baseReservesAfter sdk.Dec - if dir == Direction_LONG { - baseReservesAfter = amm.BaseReserve.Sub(baseReserveAmt) - } else { - baseReservesAfter = amm.BaseReserve.Add(baseReserveAmt) - } - - if !baseReservesAfter.IsPositive() { - return sdk.Dec{}, ErrAmmNonpositiveReserves.Wrapf( - "base assets below zero (%s) after trying to swap %s base assets", - baseReservesAfter.String(), - baseReserveAmt.String(), - ) - } - - quoteReservesAfter := invariant.Quo(baseReservesAfter) - quoteReserveDelta = quoteReservesAfter.Sub(amm.QuoteReserve).Abs() - - return quoteReserveDelta, nil -} - -// InstMarkPrice returns the instantaneous mark price of the trading pair. -// This is the price if the AMM has zero slippage, or equivalently, if there's -// infinite liquidity depth with the same ratio of reserves. -func (amm AMM) InstMarkPrice() sdk.Dec { - if amm.BaseReserve.IsNil() || amm.BaseReserve.IsZero() || - amm.QuoteReserve.IsNil() || amm.QuoteReserve.IsZero() { - return sdk.ZeroDec() - } - - return amm.QuoteReserve.Quo(amm.BaseReserve).Mul(amm.PriceMultiplier) -} - -// ComputeSqrtDepth returns the sqrt of the product of the reserves -func (amm AMM) ComputeSqrtDepth() (sqrtDepth sdk.Dec, err error) { - liqDepthBigInt := new(big.Int).Mul( - amm.QuoteReserve.BigInt(), amm.BaseReserve.BigInt(), - ) - chopped := common.ChopPrecisionAndRound(liqDepthBigInt) - if chopped.BitLen() > common.MaxDecBitLen { - return sdk.Dec{}, ErrAmmLiquidityDepthOverflow - } - liqDepth := amm.QuoteReserve.Mul(amm.BaseReserve) - return common.SqrtDec(liqDepth) -} - -func (amm *AMM) WithPair(pair asset.Pair) *AMM { - amm.Pair = pair - return amm -} - -func (amm *AMM) WithBaseReserve(baseReserve sdk.Dec) *AMM { - amm.BaseReserve = baseReserve - return amm -} - -func (amm *AMM) WithQuoteReserve(quoteReserve sdk.Dec) *AMM { - amm.QuoteReserve = quoteReserve - return amm -} - -func (amm *AMM) WithPriceMultiplier(priceMultiplier sdk.Dec) *AMM { - amm.PriceMultiplier = priceMultiplier - return amm -} - -func (amm *AMM) WithTotalLong(totalLong sdk.Dec) *AMM { - amm.TotalLong = totalLong - return amm -} - -func (amm *AMM) WithTotalShort(totalShort sdk.Dec) *AMM { - amm.TotalShort = totalShort - return amm -} - -func (amm *AMM) WithSqrtDepth(sqrtDepth sdk.Dec) *AMM { - amm.SqrtDepth = sqrtDepth - return amm -} - -// SwapQuoteAsset swaps base asset for quote asset -// -// args: -// - quoteAssetAmt: amount of base asset to swap, must be positive -// - dir: direction the user takes -// -// returns: -// - baseAssetDelta: amount of base asset received -// - err: error -// -// NOTE: baseAssetDelta is always positive -func (amm *AMM) SwapQuoteAsset( - quoteAssetAmt sdk.Dec, // unsigned - dir Direction, -) (baseAssetDelta sdk.Dec, err error) { - quoteReserveAmt := QuoteAssetToReserve(quoteAssetAmt, amm.PriceMultiplier) - baseReserveDelta, err := amm.GetBaseReserveAmt(quoteReserveAmt, dir) - if err != nil { - return sdk.Dec{}, err - } - - if dir == Direction_LONG { - amm.QuoteReserve = amm.QuoteReserve.Add(quoteReserveAmt) - amm.BaseReserve = amm.BaseReserve.Sub(baseReserveDelta) - amm.TotalLong = amm.TotalLong.Add(baseReserveDelta) - } else if dir == Direction_SHORT { - amm.QuoteReserve = amm.QuoteReserve.Sub(quoteReserveAmt) - amm.BaseReserve = amm.BaseReserve.Add(baseReserveDelta) - amm.TotalShort = amm.TotalShort.Add(baseReserveDelta) - } - - return baseReserveDelta, nil -} - -// SwapBaseAsset swaps base asset for quote asset -// -// args: -// - baseAssetAmt: amount of base asset to swap, must be positive -// - dir: direction of swap -// -// returns: -// - quoteAssetDelta: amount of quote asset received. Always positive -// - err: error if any -func (amm *AMM) SwapBaseAsset(baseAssetAmt sdk.Dec, dir Direction) (quoteAssetDelta sdk.Dec, err error) { - quoteReserveDelta, err := amm.GetQuoteReserveAmt(baseAssetAmt, dir) - if err != nil { - return sdk.Dec{}, err - } - - if dir == Direction_LONG { - amm.QuoteReserve = amm.QuoteReserve.Add(quoteReserveDelta) - amm.BaseReserve = amm.BaseReserve.Sub(baseAssetAmt) - amm.TotalLong = amm.TotalLong.Add(baseAssetAmt) - } else if dir == Direction_SHORT { - amm.QuoteReserve = amm.QuoteReserve.Sub(quoteReserveDelta) - amm.BaseReserve = amm.BaseReserve.Add(baseAssetAmt) - amm.TotalShort = amm.TotalShort.Add(baseAssetAmt) - } - - return amm.QuoteReserveToAsset(quoteReserveDelta), nil -} - -// Bias returns the bias, or open interest skew, of the market in the base -// units. Bias is the net amount of long perpetual contracts minus the net -// amount of shorts. -func (amm *AMM) Bias() (bias sdk.Dec) { - return amm.TotalLong.Sub(amm.TotalShort) -} - -/* -CalcRepegCost provides the cost of re-pegging the pool to a new candidate peg multiplier. -*/ -func (amm AMM) CalcRepegCost(newPriceMultiplier sdk.Dec) (cost sdkmath.Int, err error) { - if !newPriceMultiplier.IsPositive() { - return sdkmath.Int{}, ErrAmmNonPositivePegMult - } - - bias := amm.Bias() - - if bias.IsZero() { - return sdk.ZeroInt(), nil - } - - var dir Direction - if bias.IsPositive() { - dir = Direction_SHORT - } else { - dir = Direction_LONG - } - - biasInQuoteReserve, err := amm.GetQuoteReserveAmt(bias.Abs(), dir) - if err != nil { - return sdkmath.Int{}, err - } - - costDec := biasInQuoteReserve.Mul(newPriceMultiplier.Sub(amm.PriceMultiplier)) - - if bias.IsNegative() { - costDec = costDec.Neg() - } - - return costDec.Ceil().TruncateInt(), nil -} - -// GetMarketValue returns the amount of quote assets the amm has to pay out if all longs and shorts close out their positions -// positive value means the amm has to pay out quote assets -// negative value means the amm has to receive quote assets -func (amm AMM) GetMarketValue() (sdk.Dec, error) { - bias := amm.Bias() - - if bias.IsZero() { - return sdk.ZeroDec(), nil - } - - var dir Direction - if bias.IsPositive() { - dir = Direction_SHORT - } else { - dir = Direction_LONG - } - - marketValueInReserves, err := amm.GetQuoteReserveAmt(bias.Abs(), dir) - if err != nil { - return sdk.Dec{}, err - } - - if bias.IsNegative() { - marketValueInReserves = marketValueInReserves.Neg() - } - - return amm.QuoteReserveToAsset(marketValueInReserves), nil -} - -/* -CalcUpdateSwapInvariantCost returns the cost of updating the invariant of the pool -*/ -func (amm AMM) CalcUpdateSwapInvariantCost(newSwapInvariant sdk.Dec) (sdkmath.Int, error) { - if newSwapInvariant.IsNil() { - return sdkmath.Int{}, ErrNilSwapInvariant - } - - if !newSwapInvariant.IsPositive() { - return sdkmath.Int{}, ErrAmmNonPositiveSwapInvariant - } - - marketValueBefore, err := amm.GetMarketValue() - if err != nil { - return sdkmath.Int{}, err - } - - err = amm.UpdateSwapInvariant(newSwapInvariant) - if err != nil { - return sdkmath.Int{}, err - } - - marketValueAfter, err := amm.GetMarketValue() - if err != nil { - return sdkmath.Int{}, err - } - - cost := marketValueAfter.Sub(marketValueBefore) - - return cost.Ceil().TruncateInt(), nil -} - -// UpdateSwapInvariant updates the swap invariant of the amm -func (amm *AMM) UpdateSwapInvariant(newSwapInvariant sdk.Dec) (err error) { - // k = x * y - // newK = (cx) * (cy) = c^2 xy = c^2 k - // newPrice = (c y) / (c x) = y / x = price | unchanged price - newSqrtDepth, err := common.SqrtDec(newSwapInvariant) - if err != nil { - return err - } - - multiplier := newSqrtDepth.Quo(amm.SqrtDepth) - updatedBaseReserve := amm.BaseReserve.Mul(multiplier) - updatedQuoteReserve := amm.QuoteReserve.Mul(multiplier) - - newAmm := AMM{ - BaseReserve: updatedBaseReserve, - QuoteReserve: updatedQuoteReserve, - PriceMultiplier: amm.PriceMultiplier, - SqrtDepth: newSqrtDepth, - TotalLong: amm.TotalLong, - TotalShort: amm.TotalShort, - } - if err = newAmm.Validate(); err != nil { - return err - } - - // Change the swap invariant while holding price constant. - // Multiplying by the same factor to both of the reserves won't affect price. - amm.SqrtDepth = newSqrtDepth - amm.BaseReserve = updatedBaseReserve - amm.QuoteReserve = updatedQuoteReserve - - return nil -} diff --git a/x/perp/v2/types/amm_test.go b/x/perp/v2/types/amm_test.go deleted file mode 100644 index d3fc09ee9..000000000 --- a/x/perp/v2/types/amm_test.go +++ /dev/null @@ -1,836 +0,0 @@ -package types_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil/mock" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func TestSwapBaseAsset(t *testing.T) { - tests := []struct { - name string - baseAssetAmt sdk.Dec - dir types.Direction - expectedQuoteAssetDelta sdk.Dec - expectedBaseReserve sdk.Dec - expectedQuoteReserve sdk.Dec - expectedTotalLong sdk.Dec - expectedTotalShort sdk.Dec - expectedMarkPrice sdk.Dec - expectedErr error - }{ - { - name: "long base asset", - baseAssetAmt: sdk.NewDec(1e11), - dir: types.Direction_LONG, - expectedQuoteAssetDelta: sdk.MustNewDecFromStr("111111111111.111111111111111111"), - expectedBaseReserve: sdk.NewDec(900000000000), - expectedQuoteReserve: sdk.MustNewDecFromStr("1111111111111.111111111111111111"), - expectedTotalLong: sdk.NewDec(100000000000), - expectedTotalShort: sdk.ZeroDec(), - expectedMarkPrice: sdk.MustNewDecFromStr("1.234567901234567901"), - }, - { - name: "short base asset", - baseAssetAmt: sdk.NewDec(1e11), - dir: types.Direction_SHORT, - expectedQuoteAssetDelta: sdk.MustNewDecFromStr("90909090909.090909090909090909"), - expectedBaseReserve: sdk.NewDec(1100000000000), - expectedQuoteReserve: sdk.MustNewDecFromStr("909090909090.909090909090909091"), - expectedTotalLong: sdk.ZeroDec(), - expectedTotalShort: sdk.NewDec(100000000000), - expectedMarkPrice: sdk.MustNewDecFromStr("0.826446280991735537"), - }, - { - name: "long zero base asset", - baseAssetAmt: sdk.ZeroDec(), - dir: types.Direction_LONG, - expectedQuoteAssetDelta: sdk.ZeroDec(), - expectedBaseReserve: sdk.NewDec(1e12), - expectedQuoteReserve: sdk.NewDec(1e12), - expectedTotalLong: sdk.ZeroDec(), - expectedTotalShort: sdk.ZeroDec(), - expectedMarkPrice: sdk.OneDec(), - }, - { - name: "short zero base asset", - baseAssetAmt: sdk.ZeroDec(), - dir: types.Direction_SHORT, - expectedQuoteAssetDelta: sdk.ZeroDec(), - expectedBaseReserve: sdk.NewDec(1e12), - expectedQuoteReserve: sdk.NewDec(1e12), - expectedTotalLong: sdk.ZeroDec(), - expectedTotalShort: sdk.ZeroDec(), - expectedMarkPrice: sdk.OneDec(), - }, - { - name: "not enough base in reserves", - baseAssetAmt: sdk.NewDec(1e13), - dir: types.Direction_LONG, - expectedErr: types.ErrAmmNonpositiveReserves, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - amm := mock.TestAMM(sdk.NewDec(1e12), sdk.OneDec()) - - quoteAssetDelta, err := amm.SwapBaseAsset(tc.baseAssetAmt, tc.dir) - - if tc.expectedErr != nil { - require.ErrorIs(t, err, tc.expectedErr) - } else { - require.NoError(t, err) - assert.Equal(t, tc.expectedQuoteAssetDelta, quoteAssetDelta) - assert.Equal(t, types.AMM{ - Pair: amm.Pair, - BaseReserve: tc.expectedBaseReserve, - QuoteReserve: tc.expectedQuoteReserve, - SqrtDepth: amm.SqrtDepth, - PriceMultiplier: amm.PriceMultiplier, - TotalLong: tc.expectedTotalLong, - TotalShort: tc.expectedTotalShort, - }, *amm) - assert.Equal(t, tc.expectedMarkPrice, amm.InstMarkPrice()) - } - }) - } -} - -func TestSwapQuoteAsset(t *testing.T) { - tests := []struct { - name string - quoteAssetAmt sdk.Dec - dir types.Direction - expectedBaseAssetDelta sdk.Dec - expectedBaseReserve sdk.Dec - expectedQuoteReserve sdk.Dec - expectedTotalLong sdk.Dec - expectedTotalShort sdk.Dec - expectedMarkPrice sdk.Dec - expectedErr error - }{ - { - name: "long quote asset", - quoteAssetAmt: sdk.NewDec(1e11), - dir: types.Direction_LONG, - expectedBaseAssetDelta: sdk.MustNewDecFromStr("47619047619.047619047619047619"), - expectedBaseReserve: sdk.MustNewDecFromStr("952380952380.952380952380952381"), - expectedQuoteReserve: sdk.NewDec(1050000000000), - expectedTotalLong: sdk.MustNewDecFromStr("47619047619.047619047619047619"), - expectedTotalShort: sdk.ZeroDec(), - expectedMarkPrice: sdk.MustNewDecFromStr("2.205"), - }, - { - name: "short base asset", - quoteAssetAmt: sdk.NewDec(1e11), - dir: types.Direction_SHORT, - expectedBaseAssetDelta: sdk.MustNewDecFromStr("52631578947.368421052631578947"), - expectedBaseReserve: sdk.MustNewDecFromStr("1052631578947.368421052631578947"), - expectedQuoteReserve: sdk.NewDec(950000000000), - expectedTotalLong: sdk.ZeroDec(), - expectedTotalShort: sdk.MustNewDecFromStr("52631578947.368421052631578947"), - expectedMarkPrice: sdk.MustNewDecFromStr("1.805"), - }, - { - name: "long zero base asset", - quoteAssetAmt: sdk.ZeroDec(), - dir: types.Direction_LONG, - expectedBaseAssetDelta: sdk.ZeroDec(), - expectedBaseReserve: sdk.NewDec(1e12), - expectedQuoteReserve: sdk.NewDec(1e12), - expectedTotalLong: sdk.ZeroDec(), - expectedTotalShort: sdk.ZeroDec(), - expectedMarkPrice: sdk.NewDec(2), - }, - { - name: "short zero base asset", - quoteAssetAmt: sdk.ZeroDec(), - dir: types.Direction_SHORT, - expectedBaseAssetDelta: sdk.ZeroDec(), - expectedBaseReserve: sdk.NewDec(1e12), - expectedQuoteReserve: sdk.NewDec(1e12), - expectedTotalLong: sdk.ZeroDec(), - expectedTotalShort: sdk.ZeroDec(), - expectedMarkPrice: sdk.NewDec(2), - }, - { - name: "not enough base in reserves", - quoteAssetAmt: sdk.NewDec(1e13), - dir: types.Direction_SHORT, - expectedErr: types.ErrAmmNonpositiveReserves, - }, - { - name: "negative quote asset amt", - quoteAssetAmt: sdk.NewDec(-1), - dir: types.Direction_SHORT, - expectedErr: types.ErrInputQuoteAmtNegative, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - amm := mock.TestAMM(sdk.NewDec(1e12), sdk.NewDec(2)) - - quoteAssetDelta, err := amm.SwapQuoteAsset(tc.quoteAssetAmt, tc.dir) - - if tc.expectedErr != nil { - require.ErrorIs(t, err, tc.expectedErr) - } else { - require.NoError(t, err) - assert.Equal(t, tc.expectedBaseAssetDelta, quoteAssetDelta) - assert.Equal(t, types.AMM{ - Pair: amm.Pair, - BaseReserve: tc.expectedBaseReserve, - QuoteReserve: tc.expectedQuoteReserve, - SqrtDepth: amm.SqrtDepth, - PriceMultiplier: amm.PriceMultiplier, - TotalLong: tc.expectedTotalLong, - TotalShort: tc.expectedTotalShort, - }, *amm) - assert.Equal(t, tc.expectedMarkPrice, amm.InstMarkPrice()) - } - }) - } -} - -// baseReserves := base reserves if no one is trading -// bias := totalLong (bias) + totalShort (bias) := the net size of all positions together -// In the test cases you see, -// one is repegging bias of +25 with cost of 20, -// and the other has bias -20 with cost of -25 -// The reason for this is that swapping in different directions actually results in different amounts. -// Here's the case named "new peg -> simple math": -// Given: -// y = 100, x = 100, bias = 25, peg = 1 -// Do Repeg(peg=2) -// To get rid of the bias, we swap it away and see what that is in quote units: -// dy = k / (x + dx) - y, where dx = bias -// dy = 100^2 / (100 + 25) - 100 = -20 -// Here's the case named "new peg -> simple math but negative bias": -// Given: -// y = 100, x =100, bias = -20, peg=1 -// Do Repeg(peg=2) -// To get rid of the bias, we swap it away and see what that is in quote units: -// dy = k / (x + dx) - y, where dx = bias -// dy = 100^2 / (100 - 20) - 100 = +25 -func TestRepegCost(t *testing.T) { - pair := asset.Registry.Pair(denoms.BTC, denoms.NUSD) - tests := []struct { - name string - - amm types.AMM - newPriceMultiplier sdk.Dec - - expectedCost sdkmath.Int - shouldErr bool - }{ - { - name: "zero bias -> zero cost", - amm: types.AMM{ - Pair: pair, - BaseReserve: sdk.NewDec(100), - QuoteReserve: sdk.NewDec(100), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - newPriceMultiplier: sdk.NewDec(3), - expectedCost: sdk.ZeroInt(), - shouldErr: false, - }, - { - name: "same peg -> zero cost", - amm: types.AMM{ - Pair: pair, - BaseReserve: sdk.NewDec(100), - QuoteReserve: sdk.NewDec(100), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - newPriceMultiplier: sdk.OneDec(), - expectedCost: sdk.ZeroInt(), - shouldErr: false, - }, - { - name: "new peg -> net long and increase price multiplier", - amm: types.AMM{ - Pair: pair, - BaseReserve: sdk.NewDec(100), - QuoteReserve: sdk.NewDec(100), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(25), - TotalShort: sdk.ZeroDec(), - }, - newPriceMultiplier: sdk.NewDec(2), - expectedCost: sdk.NewInt(20), - shouldErr: false, - }, - { - name: "new peg -> net short and increase price multiplier", - amm: types.AMM{ - Pair: pair, - BaseReserve: sdk.NewDec(100), - QuoteReserve: sdk.NewDec(100), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.NewDec(20), - }, - newPriceMultiplier: sdk.NewDec(2), - expectedCost: sdk.NewInt(-25), - shouldErr: false, - }, - { - name: "new peg -> net long and decrease price multiplier", - amm: types.AMM{ - Pair: pair, - BaseReserve: sdk.NewDec(100), - QuoteReserve: sdk.NewDec(100), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(25), - TotalShort: sdk.ZeroDec(), - }, - newPriceMultiplier: sdk.MustNewDecFromStr("0.5"), - expectedCost: sdk.NewInt(-10), - shouldErr: false, - }, - { - name: "new peg -> net short and decrease price multiplier", - amm: types.AMM{ - Pair: pair, - BaseReserve: sdk.NewDec(100), - QuoteReserve: sdk.NewDec(100), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.NewDec(20), - }, - newPriceMultiplier: sdk.MustNewDecFromStr("0.5"), - expectedCost: sdk.NewInt(13), - shouldErr: false, - }, - { - name: "new peg -> negative bias big numbers", - amm: types.AMM{ - Pair: pair, - BaseReserve: sdk.NewDec(1e12), - QuoteReserve: sdk.NewDec(1e12), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(500), - TotalShort: sdk.NewDec(1000), - }, - newPriceMultiplier: sdk.NewDec(10), - expectedCost: sdk.NewInt(-4500), - shouldErr: false, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - cost, err := tc.amm.CalcRepegCost(tc.newPriceMultiplier) - if tc.shouldErr { - require.Error(t, err) - } else { - require.NoError(t, err) - assert.EqualValues(t, tc.expectedCost, cost) - } - }) - } -} - -func TestUpdateSwapInvariant(t *testing.T) { - tests := []struct { - name string - amm types.AMM - newSwapInvariant sdk.Dec - - expectedBaseReserve sdk.Dec - expectedQuoteReserve sdk.Dec - expectedSqrtDepth sdk.Dec - }{ - { - name: "same invariant", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - newSwapInvariant: sdk.NewDec(1e12), - expectedBaseReserve: sdk.NewDec(1e6), - expectedQuoteReserve: sdk.NewDec(1e6), - expectedSqrtDepth: sdk.NewDec(1e6), - }, - { - name: "higher invariant", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - newSwapInvariant: sdk.NewDec(1e14), - expectedBaseReserve: sdk.NewDec(1e7), - expectedQuoteReserve: sdk.NewDec(1e7), - expectedSqrtDepth: sdk.NewDec(1e7), - }, - { - name: "smaller invariant", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - newSwapInvariant: sdk.NewDec(1e10), - expectedBaseReserve: sdk.NewDec(1e5), - expectedQuoteReserve: sdk.NewDec(1e5), - expectedSqrtDepth: sdk.NewDec(1e5), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - err := tc.amm.UpdateSwapInvariant(tc.newSwapInvariant) - require.NoError(t, err) - assert.Equal(t, tc.expectedBaseReserve, tc.amm.BaseReserve) - assert.Equal(t, tc.expectedQuoteReserve, tc.amm.QuoteReserve) - assert.Equal(t, tc.expectedSqrtDepth, tc.amm.SqrtDepth) - }) - } -} - -// test cases shown at https://docs.google.com/spreadsheets/d/1kH7i0OGM4K2kwnovHc05E3f-VCdF7xDjSdYnnxRZxsM/edit?usp=sharing -func TestCalcUpdateSwapInvariantCost(t *testing.T) { - tests := []struct { - name string - amm types.AMM - newSwapInvariant sdk.Dec - - expectedCost sdkmath.Int - expectedErr error - }{ - { - name: "zero cost - same swap invariant", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(50), - TotalShort: sdk.NewDec(50), - }, - newSwapInvariant: sdk.NewDec(1e12), - expectedCost: sdk.ZeroInt(), - }, - - { - name: "zero cost - zero bias", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - newSwapInvariant: sdk.NewDec(1e18), - expectedCost: sdk.ZeroInt(), - }, - - { - name: "long bias, increase swap invariant", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(1e5), - TotalShort: sdk.ZeroDec(), - }, - newSwapInvariant: sdk.NewDec(1e14), - expectedCost: sdk.NewInt(8101), - }, - - { - name: "long bias, decrease swap invariant", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(1e2), - TotalShort: sdk.ZeroDec(), - }, - newSwapInvariant: sdk.NewDec(1e6), - expectedCost: sdk.NewInt(-9), - }, - - { - name: "short bias, increase swap invariant", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.NewDec(1e5), - }, - newSwapInvariant: sdk.NewDec(1e14), - expectedCost: sdk.NewInt(10102), - }, - - { - name: "short bias, decrease swap invariant", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.NewDec(1e2), - }, - newSwapInvariant: sdk.NewDec(1e6), - expectedCost: sdk.NewInt(-11), - }, - - { - name: "net long bias, increase swap invariant", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(2e5), - TotalShort: sdk.NewDec(1e5), - }, - newSwapInvariant: sdk.NewDec(1e14), - expectedCost: sdk.NewInt(8101), - }, - - { - name: "net long bias, decrease swap invariant", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(2e2), - TotalShort: sdk.NewDec(1e2), - }, - newSwapInvariant: sdk.NewDec(1e6), - expectedCost: sdk.NewInt(-9), - }, - - { - name: "net short bias, increase swap invariant", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(1e5), - TotalShort: sdk.NewDec(2e5), - }, - newSwapInvariant: sdk.NewDec(1e14), - expectedCost: sdk.NewInt(10102), - }, - - { - name: "net short bias, decrease swap invariant", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(1e2), - TotalShort: sdk.NewDec(2e2), - }, - newSwapInvariant: sdk.NewDec(1e6), - expectedCost: sdk.NewInt(-11), - }, - - { - name: "new swap invariant is nil", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - newSwapInvariant: sdk.Dec{}, - expectedErr: types.ErrNilSwapInvariant, - }, - - { - name: "new swap invariant is negative", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - newSwapInvariant: sdk.NewDec(-1), - expectedErr: types.ErrAmmNonPositiveSwapInvariant, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - cost, err := tc.amm.CalcUpdateSwapInvariantCost(tc.newSwapInvariant) - if tc.expectedErr != nil { - require.ErrorIs(t, err, tc.expectedErr) - } else { - require.NoError(t, err) - assert.Equal(t, tc.expectedCost, cost) - } - }) - } -} - -func TestGetMarketValue(t *testing.T) { - tests := []struct { - name string - amm types.AMM - expectedMarketValue sdk.Dec - }{ - { - name: "zero market value", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - }, - expectedMarketValue: sdk.ZeroDec(), - }, - { - name: "long only", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(1e5), - TotalShort: sdk.ZeroDec(), - }, - expectedMarketValue: sdk.MustNewDecFromStr("90909.090909090909090909"), - }, - { - name: "short only", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.NewDec(1e5), - }, - expectedMarketValue: sdk.MustNewDecFromStr("-111111.111111111111111111"), - }, - { - name: "long and short cancel each other out", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(1e5), - TotalShort: sdk.NewDec(1e5), - }, - expectedMarketValue: sdk.ZeroDec(), - }, - { - name: "net long", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(2e5), - TotalShort: sdk.NewDec(1e5), - }, - expectedMarketValue: sdk.MustNewDecFromStr("90909.090909090909090909"), - }, - { - name: "net short", - amm: types.AMM{ - BaseReserve: sdk.NewDec(1e6), - QuoteReserve: sdk.NewDec(1e6), - SqrtDepth: sdk.NewDec(1e6), - PriceMultiplier: sdk.OneDec(), - TotalLong: sdk.NewDec(1e5), - TotalShort: sdk.NewDec(2e5), - }, - expectedMarketValue: sdk.MustNewDecFromStr("-111111.111111111111111111"), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - marketValue, err := tc.amm.GetMarketValue() - require.NoError(t, err) - - assert.Equal(t, tc.expectedMarketValue, marketValue) - }) - } -} - -func TestValidateAMM(t *testing.T) { - tests := []struct { - name string - amm types.AMM - expectedErr error - }{ - { - name: "Invalid base reserve", - amm: types.AMM{ - BaseReserve: sdk.ZeroDec(), - QuoteReserve: sdk.OneDec(), - PriceMultiplier: sdk.OneDec(), - SqrtDepth: sdk.OneDec(), - }, - expectedErr: types.ErrAmmBaseSupplyNonpositive, - }, - { - name: "Invalid quote reserve", - amm: types.AMM{ - BaseReserve: sdk.OneDec(), - QuoteReserve: sdk.ZeroDec(), - PriceMultiplier: sdk.OneDec(), - SqrtDepth: sdk.OneDec(), - }, - expectedErr: types.ErrAmmQuoteSupplyNonpositive, - }, - { - name: "Invalid price multiplier", - amm: types.AMM{ - BaseReserve: sdk.OneDec(), - QuoteReserve: sdk.OneDec(), - PriceMultiplier: sdk.ZeroDec(), - SqrtDepth: sdk.OneDec(), - }, - expectedErr: types.ErrAmmNonPositivePegMult, - }, - { - name: "Invalid sqrt depth", - amm: types.AMM{ - BaseReserve: sdk.OneDec(), - QuoteReserve: sdk.OneDec(), - PriceMultiplier: sdk.OneDec(), - SqrtDepth: sdk.ZeroDec(), - }, - expectedErr: types.ErrAmmNonPositiveSwapInvariant, - }, - { - name: "Invalid sqrt depth value", - amm: types.AMM{ - BaseReserve: sdk.OneDec(), - QuoteReserve: sdk.OneDec(), - PriceMultiplier: sdk.OneDec(), - SqrtDepth: sdk.NewDec(3), - }, - expectedErr: types.ErrLiquidityDepth, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - err := tc.amm.Validate() - if tc.expectedErr == nil { - require.NoError(t, err) - } else { - require.Error(t, err) - assert.Contains(t, err.Error(), tc.expectedErr.Error()) - } - }) - } -} - -func TestValidateAMMShortVsQuote(t *testing.T) { - amm := types.AMM{ - BaseReserve: sdk.OneDec(), - QuoteReserve: sdk.OneDec(), - PriceMultiplier: sdk.OneDec(), - SqrtDepth: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - } - - err := amm.Validate() - require.NoError(t, err) - - quoteAssetDelta, err := amm.SwapBaseAsset(sdk.NewDec(2), types.Direction_SHORT) - require.NoError(t, err) - assert.Equal(t, sdk.MustNewDecFromStr("0.666666666666666667"), quoteAssetDelta) - - previousAmm := amm - - err = amm.UpdateSwapInvariant(sdk.MustNewDecFromStr("0.01")) - require.ErrorContains(t, err, "Base amount error, short exceed total base supply") - - err = amm.UpdateSwapInvariant(sdk.MustNewDecFromStr("-1")) - require.ErrorContains(t, err, "square root of negative number") - - require.Equal(t, amm, previousAmm) -} - -func TestPositionNotionalFail(t *testing.T) { - amm := mock.TestAMM(sdk.NewDec(-1), sdk.NewDec(2)) - _, err := amm.GetQuoteReserveAmt(sdk.NewDec(-1), types.Direction_LONG) - require.ErrorIs(t, err, types.ErrInputBaseAmtNegative) -} - -func TestAMM_WithMethods(t *testing.T) { - pair := asset.MustNewPair("ubtc:unusd") - baseReserve := sdk.NewDec(100) - quoteReserve := sdk.NewDec(200) - priceMultiplier := sdk.NewDec(1) - totalLong := sdk.NewDec(50) - totalShort := sdk.NewDec(50) - sqrtDepth := sdk.NewDec(10) - - amm := new(types.AMM). - WithPair(pair). - WithBaseReserve(baseReserve). - WithQuoteReserve(quoteReserve). - WithPriceMultiplier(priceMultiplier). - WithTotalLong(totalLong). - WithTotalShort(totalShort). - WithSqrtDepth(sqrtDepth) - - require.Equal(t, pair, amm.Pair) - require.Equal(t, baseReserve, amm.BaseReserve) - require.Equal(t, quoteReserve, amm.QuoteReserve) - require.Equal(t, priceMultiplier, amm.PriceMultiplier) - require.Equal(t, totalLong, amm.TotalLong) - require.Equal(t, totalShort, amm.TotalShort) - require.Equal(t, sqrtDepth, amm.SqrtDepth) -} diff --git a/x/perp/v2/types/change_reason.go b/x/perp/v2/types/change_reason.go deleted file mode 100644 index a984900d0..000000000 --- a/x/perp/v2/types/change_reason.go +++ /dev/null @@ -1,61 +0,0 @@ -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_MarketOrder ChangeReason = "market_order" - ChangeReason_ClosePosition ChangeReason = "close_position" - ChangeReason_PartialClose ChangeReason = "partial_close" - ChangeReason_AddMargin ChangeReason = "add_margin" - ChangeReason_RemoveMargin ChangeReason = "remove_margin" - ChangeReason_PartialLiquidation ChangeReason = "partial_liquidation" - ChangeReason_FullLiquidation ChangeReason = "full_liquidation" - ChangeReason_Settlement ChangeReason = "settlement" -) - -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 -} diff --git a/x/perp/v2/types/change_reason_test.go b/x/perp/v2/types/change_reason_test.go deleted file mode 100644 index 62fa3a95f..000000000 --- a/x/perp/v2/types/change_reason_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package types - -import ( - "bytes" - "testing" -) - -func TestChangeReason(t *testing.T) { - testCases := []struct { - name string - reason ChangeReason - data []byte - }{ - {"MarketOrder", ChangeReason_MarketOrder, []byte("market_order")}, - {"ClosePosition", ChangeReason_ClosePosition, []byte("close_position")}, - // add other cases here... - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - // Test Marshal - result, err := tc.reason.Marshal() - if err != nil { - t.Errorf("unexpected error on Marshal: %v", err) - } - - if !bytes.Equal(result, tc.data) { - t.Errorf("expected %s, got %s on Marshal", tc.data, result) - } - - // Test Unmarshal - var reason ChangeReason - err = reason.Unmarshal(tc.data) - if err != nil { - t.Errorf("unexpected error on Unmarshal: %v", err) - } - - if reason != tc.reason { - t.Errorf("expected %s, got %s on Unmarshal", tc.reason, reason) - } - - // Test MarshalJSON and UnmarshalJSON - jsonData, err := tc.reason.MarshalJSON() - if err != nil { - t.Errorf("unexpected error on MarshalJSON: %v", err) - } - - var jsonResult ChangeReason - err = jsonResult.UnmarshalJSON(jsonData) - if err != nil { - t.Errorf("unexpected error on UnmarshalJSON: %v", err) - } - - if jsonResult != tc.reason { - t.Errorf("expected %s, got %s on UnmarshalJSON", tc.reason, jsonResult) - } - }) - } -} diff --git a/x/perp/v2/types/codec.go b/x/perp/v2/types/codec.go deleted file mode 100644 index 739ef814e..000000000 --- a/x/perp/v2/types/codec.go +++ /dev/null @@ -1,41 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" -) - -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgAddMargin{}, "perpv2/add_margin", nil) - cdc.RegisterConcrete(&MsgRemoveMargin{}, "perpv2/remove_margin", nil) - cdc.RegisterConcrete(&MsgMarketOrder{}, "perpv2/market_order", nil) - cdc.RegisterConcrete(&MsgClosePosition{}, "perpv2/close_position", nil) - cdc.RegisterConcrete(&MsgPartialClose{}, "perpv2/partial_close", nil) - cdc.RegisterConcrete(&MsgDonateToEcosystemFund{}, "perpv2/donate_to_ef", nil) - cdc.RegisterConcrete(&MsgMultiLiquidate{}, "perpv2/multi_liquidate", nil) - cdc.RegisterConcrete(&MsgChangeCollateralDenom{}, "perpv2/change_collateral_denom", nil) - cdc.RegisterConcrete(&MsgShiftPegMultiplier{}, "perpv2/shift_peg_multiplier", nil) - cdc.RegisterConcrete(&MsgShiftSwapInvariant{}, "perpv2/shift_swap_invariant", nil) -} - -func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { - registry.RegisterImplementations( - /* interface */ (*sdk.Msg)(nil), - /* implementations */ - &MsgRemoveMargin{}, - &MsgAddMargin{}, - &MsgMarketOrder{}, - &MsgClosePosition{}, - &MsgPartialClose{}, - &MsgMultiLiquidate{}, - &MsgChangeCollateralDenom{}, - &MsgShiftPegMultiplier{}, - &MsgShiftSwapInvariant{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) diff --git a/x/perp/v2/types/codec_test.go b/x/perp/v2/types/codec_test.go deleted file mode 100644 index afae79b86..000000000 --- a/x/perp/v2/types/codec_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package types - -import ( - "testing" - - "github.com/cosmos/cosmos-sdk/codec" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - proto "github.com/cosmos/gogoproto/proto" - "github.com/stretchr/testify/require" -) - -func TestCodec(t *testing.T) { - cdc := codec.NewLegacyAmino() - RegisterLegacyAminoCodec(cdc) - - interfaceRegistry := cdctypes.NewInterfaceRegistry() - RegisterInterfaces(interfaceRegistry) - - msgs := []sdk.Msg{ - &MsgAddMargin{}, - &MsgRemoveMargin{}, - &MsgMarketOrder{}, - &MsgClosePosition{}, - &MsgPartialClose{}, - &MsgDonateToEcosystemFund{}, - &MsgMultiLiquidate{}, - &MsgShiftPegMultiplier{}, - &MsgShiftSwapInvariant{}, - } - - for _, msg := range msgs { - bz, err := cdc.Amino.MarshalBinaryBare(msg) - require.NoError(t, err) - - decodedMsg, ok := msg.(proto.Message) - require.True(t, ok) - - err = cdc.Amino.UnmarshalBinaryBare(bz, decodedMsg) - require.NoError(t, err) - - require.Equal(t, msg, decodedMsg) - } -} diff --git a/x/perp/v2/types/collateral.go b/x/perp/v2/types/collateral.go deleted file mode 100644 index 8b6eb3296..000000000 --- a/x/perp/v2/types/collateral.go +++ /dev/null @@ -1,11 +0,0 @@ -package types - -import ( - tftypes "github.com/NibiruChain/nibiru/x/tokenfactory/types" -) - -// TestingCollateralDenomNUSD: For testing only -var TestingCollateralDenomNUSD string = tftypes.TFDenom{ - Creator: "nibi14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9ssa9gcs", - Subdenom: "unusd", -}.String() diff --git a/x/perp/v2/types/errors.go b/x/perp/v2/types/errors.go deleted file mode 100644 index c4c4fc111..000000000 --- a/x/perp/v2/types/errors.go +++ /dev/null @@ -1,64 +0,0 @@ -package types - -import ( - "sync/atomic" - - sdkerrors "cosmossdk.io/errors" -) - -var moduleErrorCodeIdx uint32 = 1 - -// registerError: Cleaner way of using 'sdkerrors.Register' without as much time -// manually writing integers. -func registerError(msg string) *sdkerrors.Error { - // Atomic for thread safety on concurrent calls - atomic.AddUint32(&moduleErrorCodeIdx, 1) - return sdkerrors.Register(ModuleName, moduleErrorCodeIdx, msg) -} - -var ( - ErrPairNotSupported = registerError("pair not supported") - ErrAssetFailsUserLimit = registerError("amount of assets traded does not meet user-defined limit") - - ErrNoValidTWAP = registerError("TWAP price not found") - - ErrAmmNonpositiveReserves = errorAmm("base and quote reserves must always be positive") - ErrLiquidityDepth = errorAmm("liquidity depth must be positive and equal to the square of the reserves") - ErrAmmBaseSupplyNonpositive = errorAmm("base supply must be > 0") - ErrAmmBaseBorrowedTooHigh = errorAmm("short supply exceeds existing supply") - ErrAmmQuoteSupplyNonpositive = errorAmm("quote supply must be > 0") - ErrAmmLiquidityDepthOverflow = errorAmm("liquidty depth overflow") - ErrAmmNonPositivePegMult = errorAmm("peg multiplier must be > 0") - ErrAmmNonPositiveSwapInvariant = errorAmm("swap invariant (and sqrt depth) must be > 0") - ErrNilSwapInvariant = errorAmm("swap invariant (and sqrt depth) must not be nil") - - ErrPairNotFound = registerError("pair doesn't have live market") - ErrPositionNotFound = registerError("position not found") - ErrBadDebt = registerError("position is underwater") - ErrInputBaseAmtNegative = registerError("base amount cannot be zero") - - ErrInputQuoteAmtNegative = errorMarketOrder("quote amount cannot be zero") - ErrUserLeverageNegative = errorMarketOrder("leverage cannot be zero") - ErrLeverageIsTooHigh = errorMarketOrder("leverage cannot be higher than market parameter") - - ErrMarginRatioTooLow = registerError("margin ratio did not meet maintenance margin ratio") - ErrAllLiquidationsFailed = registerError("all liquidations failed") - ErrParseLiquidateResponse = registerError("failed to JSON parse liquidate responses") - ErrPositionHealthy = registerError("position is healthy") - ErrMarketNotEnabled = registerError("market is not enabled, you can only fully close your position") - ErrNotEnoughFundToPayAction = registerError("not enough fund in perp EF to pay for action") - - ErrSettlementPositionMarketEnabled = registerError("market is enabled, you can only settle position on disabled market") - ErrCollateralDenomNotSet = registerError("ErrorCollateral: no collateral denom set for the perp keeper") - ErrInvalidCollateral = registerError("ErrorCollateral: invalid collateral denom") - ErrGeneric = registerError("perp GenericError") -) - -// Register error instance for "ErrorMarketOrder" -func errorMarketOrder(msg string) *sdkerrors.Error { - return registerError("ErrorMarketOrder: " + msg) -} - -func errorAmm(msg string) *sdkerrors.Error { - return registerError("ErrorAMM: " + msg) -} diff --git a/x/perp/v2/types/event.pb.go b/x/perp/v2/types/event.pb.go deleted file mode 100644 index 4db1fe795..000000000 --- a/x/perp/v2/types/event.pb.go +++ /dev/null @@ -1,3204 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: nibiru/perp/v2/event.proto - -package types - -import ( - fmt "fmt" - github_com_NibiruChain_nibiru_x_common_asset "github.com/NibiruChain/nibiru/x/common/asset" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - _ "google.golang.org/protobuf/types/known/timestamppb" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type LiquidationFailedEvent_LiquidationFailedReason int32 - -const ( - LiquidationFailedEvent_UNSPECIFIED LiquidationFailedEvent_LiquidationFailedReason = 0 - // the position is healthy and does not need to be liquidated. - LiquidationFailedEvent_POSITION_HEALTHY LiquidationFailedEvent_LiquidationFailedReason = 1 - // the pair does not exist. - LiquidationFailedEvent_NONEXISTENT_PAIR LiquidationFailedEvent_LiquidationFailedReason = 2 - // the position does not exist. - LiquidationFailedEvent_NONEXISTENT_POSITION LiquidationFailedEvent_LiquidationFailedReason = 3 -) - -var LiquidationFailedEvent_LiquidationFailedReason_name = map[int32]string{ - 0: "UNSPECIFIED", - 1: "POSITION_HEALTHY", - 2: "NONEXISTENT_PAIR", - 3: "NONEXISTENT_POSITION", -} - -var LiquidationFailedEvent_LiquidationFailedReason_value = map[string]int32{ - "UNSPECIFIED": 0, - "POSITION_HEALTHY": 1, - "NONEXISTENT_PAIR": 2, - "NONEXISTENT_POSITION": 3, -} - -func (x LiquidationFailedEvent_LiquidationFailedReason) String() string { - return proto.EnumName(LiquidationFailedEvent_LiquidationFailedReason_name, int32(x)) -} - -func (LiquidationFailedEvent_LiquidationFailedReason) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_a5313bbc89fa31dd, []int{4, 0} -} - -// Emitted when a position changes. -type PositionChangedEvent struct { - FinalPosition Position `protobuf:"bytes,1,opt,name=final_position,json=finalPosition,proto3" json:"final_position"` - // Position notional (in quote units) after the change. In general, - // 'notional = baseAmount * priceQuotePerBase', where size is the baseAmount. - PositionNotional github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=position_notional,json=positionNotional,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"position_notional"` - // Transaction fee paid. A "taker" fee. - TransactionFee types.Coin `protobuf:"bytes,3,opt,name=transaction_fee,json=transactionFee,proto3" json:"transaction_fee" yaml:"transaction_fee"` - // realize profits and losses after the change - RealizedPnl github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=realized_pnl,json=realizedPnl,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"realized_pnl"` - // Amount of bad debt cleared by the PerpEF during the change. - // Bad debt is negative net margin past the liquidation point of a position. - BadDebt types.Coin `protobuf:"bytes,5,opt,name=bad_debt,json=badDebt,proto3" json:"bad_debt"` - // A funding payment made or received by the trader on the current position. - //'fundingPayment' 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 exchanges). - FundingPayment github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=funding_payment,json=fundingPayment,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"funding_payment"` - // The block number at which this position was changed. - BlockHeight int64 `protobuf:"varint,7,opt,name=block_height,json=blockHeight,proto3" json:"block_height,omitempty"` - // 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. - MarginToUser github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,8,opt,name=margin_to_user,json=marginToUser,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"margin_to_user"` - // change_reason describes the reason for why the position resulted in a - // change. Change type can take the following values: - // - // - 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. - ChangeReason ChangeReason `protobuf:"bytes,9,opt,name=change_reason,json=changeReason,proto3,customtype=ChangeReason" json:"change_reason"` - // exchanged_size represent the change in size for an existing position - // after the change. A positive value indicates that the position size - // increased, while a negative value indicates that the position size - // decreased. - ExchangedSize github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,10,opt,name=exchanged_size,json=exchangedSize,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"exchanged_size"` - // exchanged_notional represent the change in notional for an existing - // position after the change. A positive value indicates that the position - // notional increased, while a negative value indicates that the position - // notional decreased. - ExchangedNotional github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,11,opt,name=exchanged_notional,json=exchangedNotional,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"exchanged_notional"` -} - -func (m *PositionChangedEvent) Reset() { *m = PositionChangedEvent{} } -func (m *PositionChangedEvent) String() string { return proto.CompactTextString(m) } -func (*PositionChangedEvent) ProtoMessage() {} -func (*PositionChangedEvent) Descriptor() ([]byte, []int) { - return fileDescriptor_a5313bbc89fa31dd, []int{0} -} -func (m *PositionChangedEvent) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PositionChangedEvent) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PositionChangedEvent.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *PositionChangedEvent) XXX_Merge(src proto.Message) { - xxx_messageInfo_PositionChangedEvent.Merge(m, src) -} -func (m *PositionChangedEvent) XXX_Size() int { - return m.Size() -} -func (m *PositionChangedEvent) XXX_DiscardUnknown() { - xxx_messageInfo_PositionChangedEvent.DiscardUnknown(m) -} - -var xxx_messageInfo_PositionChangedEvent proto.InternalMessageInfo - -func (m *PositionChangedEvent) GetFinalPosition() Position { - if m != nil { - return m.FinalPosition - } - return Position{} -} - -func (m *PositionChangedEvent) GetTransactionFee() types.Coin { - if m != nil { - return m.TransactionFee - } - return types.Coin{} -} - -func (m *PositionChangedEvent) GetBadDebt() types.Coin { - if m != nil { - return m.BadDebt - } - return types.Coin{} -} - -func (m *PositionChangedEvent) GetBlockHeight() int64 { - if m != nil { - return m.BlockHeight - } - return 0 -} - -// Emitted when a position is liquidated. Wraps a PositionChanged event since a -// liquidation causes position changes. -type PositionLiquidatedEvent struct { - PositionChangedEvent PositionChangedEvent `protobuf:"bytes,1,opt,name=position_changed_event,json=positionChangedEvent,proto3" json:"position_changed_event"` - // Address of the account that executed the tx. - LiquidatorAddress string `protobuf:"bytes,2,opt,name=liquidator_address,json=liquidatorAddress,proto3" json:"liquidator_address,omitempty"` - // Commission (in margin units) received by 'liquidator'. - FeeToLiquidator types.Coin `protobuf:"bytes,3,opt,name=fee_to_liquidator,json=feeToLiquidator,proto3" json:"fee_to_liquidator" yaml:"fee_to_liquidator"` - // Commission (in margin units) given to the ecosystem fund. - FeeToEcosystemFund types.Coin `protobuf:"bytes,4,opt,name=fee_to_ecosystem_fund,json=feeToEcosystemFund,proto3" json:"fee_to_ecosystem_fund" yaml:"fee_to_ecosystem_fund"` -} - -func (m *PositionLiquidatedEvent) Reset() { *m = PositionLiquidatedEvent{} } -func (m *PositionLiquidatedEvent) String() string { return proto.CompactTextString(m) } -func (*PositionLiquidatedEvent) ProtoMessage() {} -func (*PositionLiquidatedEvent) Descriptor() ([]byte, []int) { - return fileDescriptor_a5313bbc89fa31dd, []int{1} -} -func (m *PositionLiquidatedEvent) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PositionLiquidatedEvent) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PositionLiquidatedEvent.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *PositionLiquidatedEvent) XXX_Merge(src proto.Message) { - xxx_messageInfo_PositionLiquidatedEvent.Merge(m, src) -} -func (m *PositionLiquidatedEvent) XXX_Size() int { - return m.Size() -} -func (m *PositionLiquidatedEvent) XXX_DiscardUnknown() { - xxx_messageInfo_PositionLiquidatedEvent.DiscardUnknown(m) -} - -var xxx_messageInfo_PositionLiquidatedEvent proto.InternalMessageInfo - -func (m *PositionLiquidatedEvent) GetPositionChangedEvent() PositionChangedEvent { - if m != nil { - return m.PositionChangedEvent - } - return PositionChangedEvent{} -} - -func (m *PositionLiquidatedEvent) GetLiquidatorAddress() string { - if m != nil { - return m.LiquidatorAddress - } - return "" -} - -func (m *PositionLiquidatedEvent) GetFeeToLiquidator() types.Coin { - if m != nil { - return m.FeeToLiquidator - } - return types.Coin{} -} - -func (m *PositionLiquidatedEvent) GetFeeToEcosystemFund() types.Coin { - if m != nil { - return m.FeeToEcosystemFund - } - return types.Coin{} -} - -// Emitted when a position is settled. -type PositionSettledEvent struct { - // Identifier for the virtual pool of the position. - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,1,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - // Owner of the position. - TraderAddress string `protobuf:"bytes,2,opt,name=trader_address,json=traderAddress,proto3" json:"trader_address,omitempty"` - // Settled coin as dictated by the settlement price of the perp.amm. - SettledCoins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=settled_coins,json=settledCoins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"settled_coins" yaml:"settled_coins"` -} - -func (m *PositionSettledEvent) Reset() { *m = PositionSettledEvent{} } -func (m *PositionSettledEvent) String() string { return proto.CompactTextString(m) } -func (*PositionSettledEvent) ProtoMessage() {} -func (*PositionSettledEvent) Descriptor() ([]byte, []int) { - return fileDescriptor_a5313bbc89fa31dd, []int{2} -} -func (m *PositionSettledEvent) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PositionSettledEvent) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PositionSettledEvent.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *PositionSettledEvent) XXX_Merge(src proto.Message) { - xxx_messageInfo_PositionSettledEvent.Merge(m, src) -} -func (m *PositionSettledEvent) XXX_Size() int { - return m.Size() -} -func (m *PositionSettledEvent) XXX_DiscardUnknown() { - xxx_messageInfo_PositionSettledEvent.DiscardUnknown(m) -} - -var xxx_messageInfo_PositionSettledEvent proto.InternalMessageInfo - -func (m *PositionSettledEvent) GetTraderAddress() string { - if m != nil { - return m.TraderAddress - } - return "" -} - -func (m *PositionSettledEvent) GetSettledCoins() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.SettledCoins - } - return nil -} - -// Emitted when the funding rate changes for a market. -type FundingRateChangedEvent struct { - // The pair for which the funding rate was calculated. - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,1,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - // The mark price of the pair. - MarkPriceTwap github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=mark_price_twap,json=markPriceTwap,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"mark_price_twap"` - // The oracle index price of the pair. - IndexPriceTwap github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=index_price_twap,json=indexPriceTwap,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"index_price_twap"` - // The latest premium fraction just calculated. - PremiumFraction github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=premium_fraction,json=premiumFraction,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"premium_fraction"` - // The market's latest cumulative premium fraction. - // The funding payment a position will pay is the difference between this - // value and the latest cumulative premium fraction on the position, - // multiplied by the position size. - CumulativePremiumFraction github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=cumulative_premium_fraction,json=cumulativePremiumFraction,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"cumulative_premium_fraction"` -} - -func (m *FundingRateChangedEvent) Reset() { *m = FundingRateChangedEvent{} } -func (m *FundingRateChangedEvent) String() string { return proto.CompactTextString(m) } -func (*FundingRateChangedEvent) ProtoMessage() {} -func (*FundingRateChangedEvent) Descriptor() ([]byte, []int) { - return fileDescriptor_a5313bbc89fa31dd, []int{3} -} -func (m *FundingRateChangedEvent) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *FundingRateChangedEvent) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_FundingRateChangedEvent.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *FundingRateChangedEvent) XXX_Merge(src proto.Message) { - xxx_messageInfo_FundingRateChangedEvent.Merge(m, src) -} -func (m *FundingRateChangedEvent) XXX_Size() int { - return m.Size() -} -func (m *FundingRateChangedEvent) XXX_DiscardUnknown() { - xxx_messageInfo_FundingRateChangedEvent.DiscardUnknown(m) -} - -var xxx_messageInfo_FundingRateChangedEvent proto.InternalMessageInfo - -// Emitted when liquidation fails. -type LiquidationFailedEvent struct { - // The pair for which we are trying to liquidate. - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,1,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - // owner of the position. - Trader string `protobuf:"bytes,2,opt,name=trader,proto3" json:"trader,omitempty"` - // Address of the account that executed the tx. - Liquidator string `protobuf:"bytes,3,opt,name=liquidator,proto3" json:"liquidator,omitempty"` - // Reason for the liquidation failure. - Reason LiquidationFailedEvent_LiquidationFailedReason `protobuf:"varint,4,opt,name=reason,proto3,enum=nibiru.perp.v2.LiquidationFailedEvent_LiquidationFailedReason" json:"reason,omitempty"` -} - -func (m *LiquidationFailedEvent) Reset() { *m = LiquidationFailedEvent{} } -func (m *LiquidationFailedEvent) String() string { return proto.CompactTextString(m) } -func (*LiquidationFailedEvent) ProtoMessage() {} -func (*LiquidationFailedEvent) Descriptor() ([]byte, []int) { - return fileDescriptor_a5313bbc89fa31dd, []int{4} -} -func (m *LiquidationFailedEvent) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *LiquidationFailedEvent) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_LiquidationFailedEvent.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *LiquidationFailedEvent) XXX_Merge(src proto.Message) { - xxx_messageInfo_LiquidationFailedEvent.Merge(m, src) -} -func (m *LiquidationFailedEvent) XXX_Size() int { - return m.Size() -} -func (m *LiquidationFailedEvent) XXX_DiscardUnknown() { - xxx_messageInfo_LiquidationFailedEvent.DiscardUnknown(m) -} - -var xxx_messageInfo_LiquidationFailedEvent proto.InternalMessageInfo - -func (m *LiquidationFailedEvent) GetTrader() string { - if m != nil { - return m.Trader - } - return "" -} - -func (m *LiquidationFailedEvent) GetLiquidator() string { - if m != nil { - return m.Liquidator - } - return "" -} - -func (m *LiquidationFailedEvent) GetReason() LiquidationFailedEvent_LiquidationFailedReason { - if m != nil { - return m.Reason - } - return LiquidationFailedEvent_UNSPECIFIED -} - -// This event is emitted when the amm is updated, which can be triggered by -// the following events: -// -// - swap -// - edit price multiplier -// - edit depth -type AmmUpdatedEvent struct { - // the final state of the AMM - FinalAmm AMM `protobuf:"bytes,1,opt,name=final_amm,json=finalAmm,proto3" json:"final_amm"` - // The mark price of the pair. - MarkPriceTwap github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=mark_price_twap,json=markPriceTwap,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"mark_price_twap"` - // The oracle index price of the pair. - IndexPriceTwap github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=index_price_twap,json=indexPriceTwap,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"index_price_twap"` -} - -func (m *AmmUpdatedEvent) Reset() { *m = AmmUpdatedEvent{} } -func (m *AmmUpdatedEvent) String() string { return proto.CompactTextString(m) } -func (*AmmUpdatedEvent) ProtoMessage() {} -func (*AmmUpdatedEvent) Descriptor() ([]byte, []int) { - return fileDescriptor_a5313bbc89fa31dd, []int{5} -} -func (m *AmmUpdatedEvent) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AmmUpdatedEvent) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AmmUpdatedEvent.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *AmmUpdatedEvent) XXX_Merge(src proto.Message) { - xxx_messageInfo_AmmUpdatedEvent.Merge(m, src) -} -func (m *AmmUpdatedEvent) XXX_Size() int { - return m.Size() -} -func (m *AmmUpdatedEvent) XXX_DiscardUnknown() { - xxx_messageInfo_AmmUpdatedEvent.DiscardUnknown(m) -} - -var xxx_messageInfo_AmmUpdatedEvent proto.InternalMessageInfo - -func (m *AmmUpdatedEvent) GetFinalAmm() AMM { - if m != nil { - return m.FinalAmm - } - return AMM{} -} - -// This event is emitted at the end of every block for persisting market changes -// off-chain -// -// Market changes are triggered by the following actions: -// -// - disabling market -// - changing market fees -// - bad debt is prepaid by the ecosystem fund -type MarketUpdatedEvent struct { - // the final state of the market - FinalMarket Market `protobuf:"bytes,1,opt,name=final_market,json=finalMarket,proto3" json:"final_market"` -} - -func (m *MarketUpdatedEvent) Reset() { *m = MarketUpdatedEvent{} } -func (m *MarketUpdatedEvent) String() string { return proto.CompactTextString(m) } -func (*MarketUpdatedEvent) ProtoMessage() {} -func (*MarketUpdatedEvent) Descriptor() ([]byte, []int) { - return fileDescriptor_a5313bbc89fa31dd, []int{6} -} -func (m *MarketUpdatedEvent) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MarketUpdatedEvent) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MarketUpdatedEvent.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MarketUpdatedEvent) XXX_Merge(src proto.Message) { - xxx_messageInfo_MarketUpdatedEvent.Merge(m, src) -} -func (m *MarketUpdatedEvent) XXX_Size() int { - return m.Size() -} -func (m *MarketUpdatedEvent) XXX_DiscardUnknown() { - xxx_messageInfo_MarketUpdatedEvent.DiscardUnknown(m) -} - -var xxx_messageInfo_MarketUpdatedEvent proto.InternalMessageInfo - -func (m *MarketUpdatedEvent) GetFinalMarket() Market { - if m != nil { - return m.FinalMarket - } - return Market{} -} - -// EventShiftPegMultiplier: ABCI event emitted from MsgShiftPegMultiplier -type EventShiftPegMultiplier struct { - OldPegMultiplier github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=old_peg_multiplier,json=oldPegMultiplier,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"old_peg_multiplier"` - NewPegMultiplier github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=new_peg_multiplier,json=newPegMultiplier,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"new_peg_multiplier"` - CostPaid types.Coin `protobuf:"bytes,3,opt,name=cost_paid,json=costPaid,proto3" json:"cost_paid"` -} - -func (m *EventShiftPegMultiplier) Reset() { *m = EventShiftPegMultiplier{} } -func (m *EventShiftPegMultiplier) String() string { return proto.CompactTextString(m) } -func (*EventShiftPegMultiplier) ProtoMessage() {} -func (*EventShiftPegMultiplier) Descriptor() ([]byte, []int) { - return fileDescriptor_a5313bbc89fa31dd, []int{7} -} -func (m *EventShiftPegMultiplier) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *EventShiftPegMultiplier) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_EventShiftPegMultiplier.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *EventShiftPegMultiplier) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventShiftPegMultiplier.Merge(m, src) -} -func (m *EventShiftPegMultiplier) XXX_Size() int { - return m.Size() -} -func (m *EventShiftPegMultiplier) XXX_DiscardUnknown() { - xxx_messageInfo_EventShiftPegMultiplier.DiscardUnknown(m) -} - -var xxx_messageInfo_EventShiftPegMultiplier proto.InternalMessageInfo - -func (m *EventShiftPegMultiplier) GetCostPaid() types.Coin { - if m != nil { - return m.CostPaid - } - return types.Coin{} -} - -// EventShiftSwapInvariant: ABCI event emitted from MsgShiftSwapInvariant -type EventShiftSwapInvariant struct { - OldSwapInvariant github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,1,opt,name=old_swap_invariant,json=oldSwapInvariant,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"old_swap_invariant"` - NewSwapInvariant github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=new_swap_invariant,json=newSwapInvariant,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"new_swap_invariant"` - CostPaid types.Coin `protobuf:"bytes,3,opt,name=cost_paid,json=costPaid,proto3" json:"cost_paid"` -} - -func (m *EventShiftSwapInvariant) Reset() { *m = EventShiftSwapInvariant{} } -func (m *EventShiftSwapInvariant) String() string { return proto.CompactTextString(m) } -func (*EventShiftSwapInvariant) ProtoMessage() {} -func (*EventShiftSwapInvariant) Descriptor() ([]byte, []int) { - return fileDescriptor_a5313bbc89fa31dd, []int{8} -} -func (m *EventShiftSwapInvariant) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *EventShiftSwapInvariant) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_EventShiftSwapInvariant.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *EventShiftSwapInvariant) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventShiftSwapInvariant.Merge(m, src) -} -func (m *EventShiftSwapInvariant) XXX_Size() int { - return m.Size() -} -func (m *EventShiftSwapInvariant) XXX_DiscardUnknown() { - xxx_messageInfo_EventShiftSwapInvariant.DiscardUnknown(m) -} - -var xxx_messageInfo_EventShiftSwapInvariant proto.InternalMessageInfo - -func (m *EventShiftSwapInvariant) GetCostPaid() types.Coin { - if m != nil { - return m.CostPaid - } - return types.Coin{} -} - -func init() { - proto.RegisterEnum("nibiru.perp.v2.LiquidationFailedEvent_LiquidationFailedReason", LiquidationFailedEvent_LiquidationFailedReason_name, LiquidationFailedEvent_LiquidationFailedReason_value) - proto.RegisterType((*PositionChangedEvent)(nil), "nibiru.perp.v2.PositionChangedEvent") - proto.RegisterType((*PositionLiquidatedEvent)(nil), "nibiru.perp.v2.PositionLiquidatedEvent") - proto.RegisterType((*PositionSettledEvent)(nil), "nibiru.perp.v2.PositionSettledEvent") - proto.RegisterType((*FundingRateChangedEvent)(nil), "nibiru.perp.v2.FundingRateChangedEvent") - proto.RegisterType((*LiquidationFailedEvent)(nil), "nibiru.perp.v2.LiquidationFailedEvent") - proto.RegisterType((*AmmUpdatedEvent)(nil), "nibiru.perp.v2.AmmUpdatedEvent") - proto.RegisterType((*MarketUpdatedEvent)(nil), "nibiru.perp.v2.MarketUpdatedEvent") - proto.RegisterType((*EventShiftPegMultiplier)(nil), "nibiru.perp.v2.EventShiftPegMultiplier") - proto.RegisterType((*EventShiftSwapInvariant)(nil), "nibiru.perp.v2.EventShiftSwapInvariant") -} - -func init() { proto.RegisterFile("nibiru/perp/v2/event.proto", fileDescriptor_a5313bbc89fa31dd) } - -var fileDescriptor_a5313bbc89fa31dd = []byte{ - // 1230 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x97, 0xcf, 0x6f, 0x1b, 0x45, - 0x14, 0xc7, 0xe3, 0xb8, 0xa4, 0xcd, 0xc4, 0xb1, 0x9d, 0xc1, 0x24, 0xdb, 0x52, 0x39, 0x61, 0x55, - 0x50, 0x2e, 0xdd, 0x55, 0x83, 0x84, 0xd4, 0x0a, 0x81, 0x92, 0xd4, 0x21, 0x96, 0x1a, 0xd7, 0xac, - 0x9d, 0xd2, 0xf2, 0x43, 0xcb, 0x78, 0xf7, 0xd9, 0x19, 0x65, 0x77, 0x66, 0xd9, 0x19, 0xc7, 0x4d, - 0xff, 0x01, 0x38, 0x22, 0x71, 0xe0, 0x7f, 0xe0, 0x2f, 0xe9, 0xb1, 0x47, 0xc4, 0xa1, 0xa0, 0x56, - 0x1c, 0xb8, 0x21, 0xae, 0x5c, 0xd0, 0xce, 0xce, 0xc6, 0x3f, 0xd2, 0x36, 0xc4, 0xc0, 0x81, 0x53, - 0xb2, 0xef, 0xcd, 0x7c, 0xde, 0x9b, 0xef, 0xbe, 0xf7, 0x66, 0x8d, 0xae, 0x30, 0xda, 0xa1, 0x71, - 0xdf, 0x8e, 0x20, 0x8e, 0xec, 0xa3, 0x0d, 0x1b, 0x8e, 0x80, 0x49, 0x2b, 0x8a, 0xb9, 0xe4, 0xb8, - 0x98, 0xfa, 0xac, 0xc4, 0x67, 0x1d, 0x6d, 0x5c, 0xa9, 0xf4, 0x78, 0x8f, 0x2b, 0x97, 0x9d, 0xfc, - 0x97, 0xae, 0xba, 0x72, 0xb5, 0xc7, 0x79, 0x2f, 0x00, 0x9b, 0x44, 0xd4, 0x26, 0x8c, 0x71, 0x49, - 0x24, 0xe5, 0x4c, 0x68, 0x6f, 0xd5, 0xe3, 0x22, 0xe4, 0xc2, 0xee, 0x10, 0x01, 0xf6, 0xd1, 0x8d, - 0x0e, 0x48, 0x72, 0xc3, 0xf6, 0x38, 0x65, 0xda, 0x3f, 0x19, 0x5f, 0x48, 0x22, 0x41, 0xfb, 0x56, - 0x35, 0x59, 0x3d, 0x75, 0xfa, 0x5d, 0x5b, 0xd2, 0x10, 0x84, 0x24, 0x61, 0x94, 0x2e, 0x30, 0x7f, - 0x9f, 0x43, 0x95, 0x26, 0x17, 0x34, 0x09, 0xb8, 0x7d, 0x40, 0x58, 0x0f, 0xfc, 0x5a, 0x92, 0x3f, - 0xae, 0xa1, 0x62, 0x97, 0x32, 0x12, 0xb8, 0x91, 0xf6, 0x1a, 0xb9, 0xb5, 0xdc, 0xfa, 0xc2, 0x86, - 0x61, 0x8d, 0x1f, 0xc9, 0xca, 0x76, 0x6f, 0x5d, 0x78, 0xfc, 0x74, 0x75, 0xc6, 0x59, 0x54, 0xbb, - 0x32, 0x23, 0xfe, 0x0c, 0x2d, 0x65, 0x00, 0x97, 0xf1, 0xe4, 0x0f, 0x09, 0x8c, 0xd9, 0xb5, 0xdc, - 0xfa, 0xfc, 0x96, 0x95, 0xac, 0xff, 0xe9, 0xe9, 0xea, 0x3b, 0x3d, 0x2a, 0x0f, 0xfa, 0x1d, 0xcb, - 0xe3, 0xa1, 0xad, 0x8f, 0x9a, 0xfe, 0xb9, 0x2e, 0xfc, 0x43, 0x5b, 0x1e, 0x47, 0x20, 0xac, 0xdb, - 0xe0, 0x39, 0xe5, 0x0c, 0xd4, 0xd0, 0x1c, 0xdc, 0x41, 0x25, 0x19, 0x13, 0x26, 0x88, 0xa7, 0xf8, - 0x5d, 0x00, 0x23, 0xaf, 0x92, 0xbc, 0x6c, 0xa5, 0x04, 0x2b, 0xd1, 0xcc, 0xd2, 0x9a, 0x59, 0xdb, - 0x9c, 0xb2, 0xad, 0x6a, 0x12, 0xf5, 0x8f, 0xa7, 0xab, 0xcb, 0xc7, 0x24, 0x0c, 0x6e, 0x99, 0x13, - 0xfb, 0x4d, 0xa7, 0x38, 0x62, 0xd9, 0x01, 0xc0, 0x1f, 0xa3, 0x42, 0x0c, 0x24, 0xa0, 0x8f, 0xc0, - 0x77, 0x23, 0x16, 0x18, 0x17, 0xa6, 0xca, 0x7d, 0x21, 0x63, 0x34, 0x59, 0x80, 0x6f, 0xa1, 0x4b, - 0x1d, 0xe2, 0xbb, 0x3e, 0x74, 0xa4, 0xf1, 0xda, 0x59, 0xf9, 0xa6, 0xaa, 0x5e, 0xec, 0x10, 0xff, - 0x36, 0x74, 0x24, 0xfe, 0x04, 0x95, 0xba, 0x7d, 0xe6, 0x53, 0xd6, 0x73, 0x23, 0x72, 0x1c, 0x02, - 0x93, 0xc6, 0xdc, 0x54, 0x19, 0x15, 0x35, 0xa6, 0x99, 0x52, 0xf0, 0x5b, 0xa8, 0xd0, 0x09, 0xb8, - 0x77, 0xe8, 0x1e, 0x00, 0xed, 0x1d, 0x48, 0xe3, 0xe2, 0x5a, 0x6e, 0x3d, 0xef, 0x2c, 0x28, 0xdb, - 0xae, 0x32, 0xe1, 0x36, 0x2a, 0x86, 0x24, 0xee, 0x51, 0xe6, 0x4a, 0xee, 0xf6, 0x05, 0xc4, 0xc6, - 0xa5, 0x73, 0x87, 0xae, 0x33, 0xe9, 0x14, 0x52, 0x4a, 0x9b, 0xef, 0x0b, 0x88, 0xf1, 0x4d, 0xb4, - 0xe8, 0xa9, 0xc2, 0x73, 0x63, 0x20, 0x82, 0x33, 0x63, 0x5e, 0x41, 0x2b, 0x1a, 0x5a, 0x48, 0xab, - 0xd2, 0x51, 0x3e, 0xa7, 0xe0, 0x8d, 0x3c, 0xe1, 0x7d, 0x54, 0x84, 0x87, 0xa9, 0xc5, 0x77, 0x05, - 0x7d, 0x04, 0x06, 0x9a, 0x4a, 0x8b, 0xc5, 0x13, 0x4a, 0x8b, 0x3e, 0x02, 0xfc, 0x05, 0xc2, 0x43, - 0xec, 0x49, 0xd1, 0x2e, 0x4c, 0x85, 0x5e, 0x3a, 0x21, 0x65, 0x55, 0x6b, 0x7e, 0x9d, 0x47, 0x2b, - 0x59, 0x7f, 0xdc, 0xa1, 0x5f, 0xf5, 0xa9, 0x4f, 0x64, 0xd6, 0x75, 0x5f, 0xa2, 0xe5, 0x93, 0x76, - 0xc9, 0x32, 0x50, 0xf3, 0x44, 0x77, 0xdf, 0xb5, 0x97, 0x75, 0xdf, 0x68, 0xef, 0xea, 0x9a, 0xa9, - 0x44, 0x2f, 0xea, 0xeb, 0xeb, 0x08, 0x07, 0x3a, 0x28, 0x8f, 0x5d, 0xe2, 0xfb, 0x31, 0x08, 0x91, - 0x76, 0xa4, 0xb3, 0x34, 0xf4, 0x6c, 0xa6, 0x0e, 0xdc, 0x43, 0x4b, 0x5d, 0x80, 0xe4, 0x85, 0x0f, - 0x7d, 0x67, 0x37, 0xd9, 0x9a, 0x6e, 0x32, 0x23, 0x6d, 0xb2, 0x53, 0x04, 0xd3, 0x29, 0x75, 0x01, - 0xda, 0xfc, 0xce, 0x89, 0x05, 0xc7, 0xe8, 0x0d, 0xbd, 0x0c, 0x3c, 0x2e, 0x8e, 0x85, 0x84, 0xd0, - 0x4d, 0x4a, 0x54, 0x35, 0xdc, 0x2b, 0x83, 0x5d, 0xd3, 0xc1, 0xae, 0x8e, 0x05, 0x1b, 0xa7, 0x98, - 0x0e, 0x56, 0x01, 0x6b, 0x99, 0x75, 0x27, 0x31, 0x7e, 0x3f, 0x3b, 0x1c, 0x7e, 0x2d, 0x90, 0x32, - 0xc8, 0x44, 0xda, 0x43, 0x17, 0x22, 0x42, 0x63, 0x25, 0xfa, 0xfc, 0xd6, 0x4d, 0xfd, 0xce, 0x6f, - 0x8c, 0xbc, 0xf3, 0x86, 0x7a, 0x0d, 0xdb, 0x07, 0x84, 0x32, 0x5b, 0xcf, 0xdf, 0x87, 0xb6, 0xc7, - 0xc3, 0x90, 0x33, 0x9b, 0x08, 0x01, 0xd2, 0x6a, 0x12, 0x1a, 0x3b, 0x0a, 0x83, 0xdf, 0x46, 0xc9, - 0x54, 0xf1, 0x61, 0x52, 0xef, 0xc5, 0xd4, 0x9a, 0x69, 0xfd, 0x4d, 0x0e, 0x2d, 0x8a, 0x34, 0x0d, - 0x37, 0x99, 0xef, 0xc2, 0xc8, 0xaf, 0xe5, 0x5f, 0x7d, 0xf6, 0x5d, 0x7d, 0xf6, 0x4a, 0x7a, 0xf6, - 0xb1, 0xdd, 0xe6, 0x0f, 0x3f, 0xaf, 0xae, 0xff, 0x8d, 0x32, 0x4d, 0x40, 0xc2, 0x29, 0xe8, 0xbd, - 0xea, 0xc9, 0xfc, 0x35, 0x8f, 0x56, 0x76, 0xd2, 0x01, 0xe1, 0x10, 0x09, 0x63, 0x15, 0xf4, 0x2f, - 0x8b, 0x73, 0x0f, 0x95, 0x42, 0x12, 0x1f, 0xba, 0x51, 0x4c, 0x3d, 0x70, 0xe5, 0x80, 0x44, 0x53, - 0xde, 0x0f, 0x8b, 0x09, 0xa6, 0x99, 0x50, 0xda, 0x03, 0x12, 0xe1, 0xfb, 0xa8, 0x4c, 0x99, 0x0f, - 0x0f, 0x47, 0xc1, 0xf9, 0xe9, 0x46, 0xa5, 0xe2, 0x0c, 0xc9, 0x0f, 0x50, 0x39, 0x8a, 0x21, 0xa4, - 0xfd, 0xd0, 0xed, 0xc6, 0xe9, 0x4d, 0xa1, 0xe6, 0xf8, 0xf9, 0xc9, 0x25, 0xcd, 0xd9, 0xd1, 0x18, - 0xcc, 0xd0, 0x9b, 0x5e, 0x3f, 0xec, 0x07, 0x44, 0xd2, 0x23, 0x70, 0x4f, 0x45, 0x99, 0x6e, 0xd4, - 0x5f, 0x1e, 0x22, 0x9b, 0xe3, 0xf1, 0xcc, 0xdf, 0x66, 0xd1, 0x72, 0xd6, 0x84, 0xc9, 0x85, 0x47, - 0xe8, 0x7f, 0xd5, 0x03, 0xcb, 0x68, 0x2e, 0xad, 0x76, 0x5d, 0xfb, 0xfa, 0x09, 0x57, 0x11, 0x9a, - 0x98, 0x2c, 0xf3, 0xce, 0x88, 0x05, 0xdf, 0x43, 0x73, 0xfa, 0x5e, 0x48, 0x06, 0x41, 0x71, 0xe3, - 0x83, 0xc9, 0x09, 0xf8, 0xe2, 0xf4, 0x4f, 0x9b, 0xf5, 0x0d, 0xa2, 0x69, 0x66, 0x84, 0x56, 0x5e, - 0xb2, 0x04, 0x97, 0xd0, 0xc2, 0x7e, 0xa3, 0xd5, 0xac, 0x6d, 0xd7, 0x77, 0xea, 0xb5, 0xdb, 0xe5, - 0x19, 0x5c, 0x41, 0xe5, 0xe6, 0xdd, 0x56, 0xbd, 0x5d, 0xbf, 0xdb, 0x70, 0x77, 0x6b, 0x9b, 0x77, - 0xda, 0xbb, 0x0f, 0xca, 0xb9, 0xc4, 0xda, 0xb8, 0xdb, 0xa8, 0xdd, 0xaf, 0xb7, 0xda, 0xb5, 0x46, - 0xdb, 0x6d, 0x6e, 0xd6, 0x9d, 0xf2, 0x2c, 0x36, 0x50, 0x65, 0xcc, 0xaa, 0xf7, 0x95, 0xf3, 0xe6, - 0x9f, 0x39, 0x54, 0xda, 0x0c, 0xc3, 0xfd, 0x68, 0x64, 0xde, 0xbf, 0x87, 0xe6, 0xd3, 0xaf, 0x2c, - 0x12, 0x86, 0x7a, 0xc4, 0xbf, 0x3e, 0x79, 0xc0, 0xcd, 0xbd, 0x3d, 0x3d, 0xd1, 0x2f, 0xa9, 0xb5, - 0x9b, 0x61, 0xf8, 0xff, 0x6b, 0x1a, 0x73, 0x1f, 0xe1, 0x3d, 0x12, 0x1f, 0x82, 0x1c, 0x3b, 0xff, - 0x87, 0xa8, 0x90, 0x9e, 0x3f, 0x54, 0x3e, 0x2d, 0xc1, 0xf2, 0xa4, 0x04, 0xe9, 0x4e, 0xad, 0xc2, - 0x82, 0xda, 0x91, 0x9a, 0xcc, 0xef, 0x66, 0xd1, 0x8a, 0x42, 0xb5, 0x0e, 0x68, 0x57, 0x36, 0xa1, - 0xb7, 0xd7, 0x0f, 0x24, 0x8d, 0x02, 0x0a, 0x31, 0xfe, 0x1c, 0x61, 0x1e, 0xf8, 0x6e, 0x04, 0x3d, - 0x37, 0x3c, 0xb1, 0xea, 0x7a, 0x3e, 0xf7, 0xc7, 0x27, 0x0f, 0xfc, 0x53, 0x74, 0x06, 0x83, 0x49, - 0xfa, 0x94, 0x9f, 0xb6, 0x0c, 0x06, 0xe3, 0xf4, 0xf7, 0xd1, 0xbc, 0xc7, 0x85, 0x74, 0x23, 0x42, - 0xfd, 0xb3, 0xef, 0x5b, 0x5d, 0x1e, 0xc9, 0x8e, 0x26, 0xa1, 0xfe, 0x84, 0x2a, 0xad, 0x01, 0x89, - 0xea, 0xec, 0x88, 0xc4, 0x94, 0x30, 0x99, 0xa9, 0x22, 0x06, 0x24, 0x72, 0x69, 0x66, 0x9d, 0x42, - 0x95, 0xe4, 0x4b, 0x2e, 0x51, 0xe5, 0x14, 0x3d, 0x51, 0x65, 0x82, 0x3e, 0x3b, 0x1d, 0x9d, 0xc1, - 0x60, 0x9c, 0xfe, 0x8f, 0x54, 0xd9, 0xfa, 0xe8, 0xf1, 0xb3, 0x6a, 0xee, 0xc9, 0xb3, 0x6a, 0xee, - 0x97, 0x67, 0xd5, 0xdc, 0xb7, 0xcf, 0xab, 0x33, 0x4f, 0x9e, 0x57, 0x67, 0x7e, 0x7c, 0x5e, 0x9d, - 0xf9, 0xf4, 0xfa, 0x59, 0x53, 0x2d, 0xfb, 0x6d, 0xa5, 0x92, 0xeb, 0xcc, 0xa9, 0xdf, 0x4e, 0xef, - 0xfe, 0x15, 0x00, 0x00, 0xff, 0xff, 0x50, 0x37, 0x90, 0x96, 0xfa, 0x0d, 0x00, 0x00, -} - -func (m *PositionChangedEvent) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PositionChangedEvent) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PositionChangedEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.ExchangedNotional.Size() - i -= size - if _, err := m.ExchangedNotional.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x5a - { - size := m.ExchangedSize.Size() - i -= size - if _, err := m.ExchangedSize.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 - { - size := m.ChangeReason.Size() - i -= size - if _, err := m.ChangeReason.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - { - size := m.MarginToUser.Size() - i -= size - if _, err := m.MarginToUser.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - if m.BlockHeight != 0 { - i = encodeVarintEvent(dAtA, i, uint64(m.BlockHeight)) - i-- - dAtA[i] = 0x38 - } - { - size := m.FundingPayment.Size() - i -= size - if _, err := m.FundingPayment.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.BadDebt.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.RealizedPnl.Size() - i -= size - if _, err := m.RealizedPnl.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.TransactionFee.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.PositionNotional.Size() - i -= size - if _, err := m.PositionNotional.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.FinalPosition.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *PositionLiquidatedEvent) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PositionLiquidatedEvent) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PositionLiquidatedEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.FeeToEcosystemFund.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.FeeToLiquidator.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.LiquidatorAddress) > 0 { - i -= len(m.LiquidatorAddress) - copy(dAtA[i:], m.LiquidatorAddress) - i = encodeVarintEvent(dAtA, i, uint64(len(m.LiquidatorAddress))) - i-- - dAtA[i] = 0x12 - } - { - size, err := m.PositionChangedEvent.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *PositionSettledEvent) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PositionSettledEvent) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PositionSettledEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.SettledCoins) > 0 { - for iNdEx := len(m.SettledCoins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SettledCoins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.TraderAddress) > 0 { - i -= len(m.TraderAddress) - copy(dAtA[i:], m.TraderAddress) - i = encodeVarintEvent(dAtA, i, uint64(len(m.TraderAddress))) - i-- - dAtA[i] = 0x12 - } - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *FundingRateChangedEvent) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *FundingRateChangedEvent) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *FundingRateChangedEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.CumulativePremiumFraction.Size() - i -= size - if _, err := m.CumulativePremiumFraction.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size := m.PremiumFraction.Size() - i -= size - if _, err := m.PremiumFraction.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.IndexPriceTwap.Size() - i -= size - if _, err := m.IndexPriceTwap.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.MarkPriceTwap.Size() - i -= size - if _, err := m.MarkPriceTwap.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *LiquidationFailedEvent) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *LiquidationFailedEvent) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *LiquidationFailedEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Reason != 0 { - i = encodeVarintEvent(dAtA, i, uint64(m.Reason)) - i-- - dAtA[i] = 0x20 - } - if len(m.Liquidator) > 0 { - i -= len(m.Liquidator) - copy(dAtA[i:], m.Liquidator) - i = encodeVarintEvent(dAtA, i, uint64(len(m.Liquidator))) - i-- - dAtA[i] = 0x1a - } - if len(m.Trader) > 0 { - i -= len(m.Trader) - copy(dAtA[i:], m.Trader) - i = encodeVarintEvent(dAtA, i, uint64(len(m.Trader))) - i-- - dAtA[i] = 0x12 - } - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *AmmUpdatedEvent) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AmmUpdatedEvent) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AmmUpdatedEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.IndexPriceTwap.Size() - i -= size - if _, err := m.IndexPriceTwap.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.MarkPriceTwap.Size() - i -= size - if _, err := m.MarkPriceTwap.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.FinalAmm.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *MarketUpdatedEvent) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MarketUpdatedEvent) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MarketUpdatedEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.FinalMarket.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *EventShiftPegMultiplier) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *EventShiftPegMultiplier) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *EventShiftPegMultiplier) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.CostPaid.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.NewPegMultiplier.Size() - i -= size - if _, err := m.NewPegMultiplier.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.OldPegMultiplier.Size() - i -= size - if _, err := m.OldPegMultiplier.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *EventShiftSwapInvariant) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *EventShiftSwapInvariant) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *EventShiftSwapInvariant) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.CostPaid.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.NewSwapInvariant.Size() - i -= size - if _, err := m.NewSwapInvariant.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.OldSwapInvariant.Size() - i -= size - if _, err := m.OldSwapInvariant.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintEvent(dAtA []byte, offset int, v uint64) int { - offset -= sovEvent(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *PositionChangedEvent) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.FinalPosition.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.PositionNotional.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.TransactionFee.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.RealizedPnl.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.BadDebt.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.FundingPayment.Size() - n += 1 + l + sovEvent(uint64(l)) - if m.BlockHeight != 0 { - n += 1 + sovEvent(uint64(m.BlockHeight)) - } - l = m.MarginToUser.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.ChangeReason.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.ExchangedSize.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.ExchangedNotional.Size() - n += 1 + l + sovEvent(uint64(l)) - return n -} - -func (m *PositionLiquidatedEvent) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.PositionChangedEvent.Size() - n += 1 + l + sovEvent(uint64(l)) - l = len(m.LiquidatorAddress) - if l > 0 { - n += 1 + l + sovEvent(uint64(l)) - } - l = m.FeeToLiquidator.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.FeeToEcosystemFund.Size() - n += 1 + l + sovEvent(uint64(l)) - return n -} - -func (m *PositionSettledEvent) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Pair.Size() - n += 1 + l + sovEvent(uint64(l)) - l = len(m.TraderAddress) - if l > 0 { - n += 1 + l + sovEvent(uint64(l)) - } - if len(m.SettledCoins) > 0 { - for _, e := range m.SettledCoins { - l = e.Size() - n += 1 + l + sovEvent(uint64(l)) - } - } - return n -} - -func (m *FundingRateChangedEvent) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Pair.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.MarkPriceTwap.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.IndexPriceTwap.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.PremiumFraction.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.CumulativePremiumFraction.Size() - n += 1 + l + sovEvent(uint64(l)) - return n -} - -func (m *LiquidationFailedEvent) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Pair.Size() - n += 1 + l + sovEvent(uint64(l)) - l = len(m.Trader) - if l > 0 { - n += 1 + l + sovEvent(uint64(l)) - } - l = len(m.Liquidator) - if l > 0 { - n += 1 + l + sovEvent(uint64(l)) - } - if m.Reason != 0 { - n += 1 + sovEvent(uint64(m.Reason)) - } - return n -} - -func (m *AmmUpdatedEvent) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.FinalAmm.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.MarkPriceTwap.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.IndexPriceTwap.Size() - n += 1 + l + sovEvent(uint64(l)) - return n -} - -func (m *MarketUpdatedEvent) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.FinalMarket.Size() - n += 1 + l + sovEvent(uint64(l)) - return n -} - -func (m *EventShiftPegMultiplier) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.OldPegMultiplier.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.NewPegMultiplier.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.CostPaid.Size() - n += 1 + l + sovEvent(uint64(l)) - return n -} - -func (m *EventShiftSwapInvariant) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.OldSwapInvariant.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.NewSwapInvariant.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.CostPaid.Size() - n += 1 + l + sovEvent(uint64(l)) - return n -} - -func sovEvent(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozEvent(x uint64) (n int) { - return sovEvent(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *PositionChangedEvent) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PositionChangedEvent: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PositionChangedEvent: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FinalPosition", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FinalPosition.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PositionNotional", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.PositionNotional.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TransactionFee", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TransactionFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RealizedPnl", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.RealizedPnl.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BadDebt", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BadDebt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FundingPayment", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FundingPayment.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field BlockHeight", wireType) - } - m.BlockHeight = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.BlockHeight |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarginToUser", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MarginToUser.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ChangeReason", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ChangeReason.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExchangedSize", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExchangedSize.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExchangedNotional", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExchangedNotional.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipEvent(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthEvent - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PositionLiquidatedEvent) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PositionLiquidatedEvent: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PositionLiquidatedEvent: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PositionChangedEvent", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.PositionChangedEvent.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LiquidatorAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.LiquidatorAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FeeToLiquidator", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FeeToLiquidator.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FeeToEcosystemFund", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FeeToEcosystemFund.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipEvent(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthEvent - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PositionSettledEvent) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PositionSettledEvent: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PositionSettledEvent: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TraderAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TraderAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SettledCoins", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SettledCoins = append(m.SettledCoins, types.Coin{}) - if err := m.SettledCoins[len(m.SettledCoins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipEvent(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthEvent - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *FundingRateChangedEvent) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: FundingRateChangedEvent: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: FundingRateChangedEvent: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarkPriceTwap", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MarkPriceTwap.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IndexPriceTwap", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IndexPriceTwap.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PremiumFraction", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.PremiumFraction.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CumulativePremiumFraction", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CumulativePremiumFraction.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipEvent(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthEvent - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *LiquidationFailedEvent) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: LiquidationFailedEvent: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: LiquidationFailedEvent: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Trader", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Trader = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Liquidator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Liquidator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Reason", wireType) - } - m.Reason = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Reason |= LiquidationFailedEvent_LiquidationFailedReason(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipEvent(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthEvent - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *AmmUpdatedEvent) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AmmUpdatedEvent: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AmmUpdatedEvent: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FinalAmm", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FinalAmm.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarkPriceTwap", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MarkPriceTwap.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IndexPriceTwap", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IndexPriceTwap.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipEvent(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthEvent - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MarketUpdatedEvent) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MarketUpdatedEvent: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MarketUpdatedEvent: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FinalMarket", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FinalMarket.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipEvent(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthEvent - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *EventShiftPegMultiplier) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: EventShiftPegMultiplier: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: EventShiftPegMultiplier: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OldPegMultiplier", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OldPegMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NewPegMultiplier", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.NewPegMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CostPaid", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CostPaid.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipEvent(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthEvent - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *EventShiftSwapInvariant) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: EventShiftSwapInvariant: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: EventShiftSwapInvariant: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OldSwapInvariant", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OldSwapInvariant.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NewSwapInvariant", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.NewSwapInvariant.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CostPaid", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowEvent - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthEvent - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthEvent - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CostPaid.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipEvent(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthEvent - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipEvent(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowEvent - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowEvent - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowEvent - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthEvent - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupEvent - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthEvent - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthEvent = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowEvent = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupEvent = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/perp/v2/types/expected_keepers.go b/x/perp/v2/types/expected_keepers.go deleted file mode 100644 index 38df68b35..000000000 --- a/x/perp/v2/types/expected_keepers.go +++ /dev/null @@ -1,57 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/epochs/types" - - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// ---------------------------------------------------------- -// Keeper Interfaces -// ---------------------------------------------------------- - -// AccountKeeper defines the expected account keeper used for simulations (noalias) -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, moduleName string) authtypes.ModuleAccountI -} - -// BankKeeper defines the expected interface needed to retrieve account balances. -type BankKeeper interface { - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - SendCoinsFromAccountToModule( - ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, - amt sdk.Coins, - ) error - SendCoinsFromModuleToModule( - ctx sdk.Context, senderModule string, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToAccount( - ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, - amt sdk.Coins, - ) error - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins -} - -type OracleKeeper interface { - GetExchangeRate(ctx sdk.Context, pair asset.Pair) (sdk.Dec, error) - GetExchangeRateTwap(ctx sdk.Context, pair asset.Pair) (sdk.Dec, error) - SetPrice(ctx sdk.Context, pair asset.Pair, price sdk.Dec) -} - -type EpochKeeper interface { - // GetEpochInfo returns epoch info by identifier. - GetEpochInfo(ctx sdk.Context, identifier string) (types.EpochInfo, error) -} - -type SudoKeeper interface { - // CheckPermissions Checks if a contract is contained within the set of sudo - // contracts defined in the x/sudo module. These smart contracts are able to - // execute certain permissioned functions. - CheckPermissions(contract sdk.AccAddress, ctx sdk.Context) error -} diff --git a/x/perp/v2/types/export.go b/x/perp/v2/types/export.go deleted file mode 100644 index fb4b6e3b6..000000000 --- a/x/perp/v2/types/export.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -import ( - grpc "google.golang.org/grpc" -) - -// GrpcQueryServiceDesc represents the query server's RPC service specification. -// This gives access to the service name and method names needed for stargate -// queries. -func GrpcQueryServiceDesc() grpc.ServiceDesc { - return _Query_serviceDesc -} diff --git a/x/perp/v2/types/genesis.go b/x/perp/v2/types/genesis.go deleted file mode 100644 index 28a8f6e43..000000000 --- a/x/perp/v2/types/genesis.go +++ /dev/null @@ -1,80 +0,0 @@ -package types - -import ( - "encoding/json" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - epochstypes "github.com/NibiruChain/nibiru/x/epochs/types" - - "github.com/cosmos/cosmos-sdk/codec" -) - -// DefaultGenesis returns the default Capability genesis state -func DefaultGenesis() *GenesisState { - return &GenesisState{ - Markets: []Market{}, - Amms: []AMM{}, - Positions: []GenesisPosition{}, - ReserveSnapshots: []ReserveSnapshot{}, - CollateralDenom: TestingCollateralDenomNUSD, - } -} - -// Validate performs basic genesis state validation returning an error upon any -// failure. -func (gs GenesisState) Validate() error { - for _, m := range gs.Markets { - if err := m.Validate(); err != nil { - return err - } - } - - for _, m := range gs.Amms { - if err := m.Validate(); err != nil { - return err - } - } - - // TODO: validate positions - //for _, pos := range gs.Positions { - // if err := pos.Validate(); err != nil { - // return err - // } - //} - - return nil -} - -func DefaultMarket(pair asset.Pair) Market { - return Market{ - Pair: pair, - Enabled: false, - Version: 1, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - ExchangeFeeRatio: sdk.MustNewDecFromStr("0.0010"), - EcosystemFundFeeRatio: sdk.MustNewDecFromStr("0.0010"), - LiquidationFeeRatio: sdk.MustNewDecFromStr("0.0500"), - PartialLiquidationRatio: sdk.MustNewDecFromStr("0.5000"), - FundingRateEpochId: epochstypes.ThirtyMinuteEpochID, - MaxFundingRate: sdk.NewDec(1), - TwapLookbackWindow: time.Minute * 30, - PrepaidBadDebt: sdk.NewCoin(TestingCollateralDenomNUSD, sdk.ZeroInt()), - MaintenanceMarginRatio: sdk.MustNewDecFromStr("0.0625"), - MaxLeverage: sdk.NewDec(10), - OraclePair: asset.NewPair(pair.BaseDenom(), denoms.USD), - } -} - -func GetGenesisStateFromAppState(cdc codec.JSONCodec, appState map[string]json.RawMessage) *GenesisState { - var genesisState GenesisState - - if appState[ModuleName] != nil { - cdc.MustUnmarshalJSON(appState[ModuleName], &genesisState) - } - - return &genesisState -} diff --git a/x/perp/v2/types/genesis.pb.go b/x/perp/v2/types/genesis.pb.go deleted file mode 100644 index d56739798..000000000 --- a/x/perp/v2/types/genesis.pb.go +++ /dev/null @@ -1,2422 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: nibiru/perp/v2/genesis.proto - -package types - -import ( - fmt "fmt" - github_com_NibiruChain_nibiru_x_common_asset "github.com/NibiruChain/nibiru/x/common/asset" - _ "github.com/cosmos/cosmos-sdk/types" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// GenesisState defines the perp module's genesis state. -// Thge genesis state is used not only to start the network but also useful for -// exporting and importing state during network upgrades. -type GenesisState struct { - Markets []Market `protobuf:"bytes,2,rep,name=markets,proto3" json:"markets"` - Amms []AMM `protobuf:"bytes,3,rep,name=amms,proto3" json:"amms"` - Positions []GenesisPosition `protobuf:"bytes,4,rep,name=positions,proto3" json:"positions"` - ReserveSnapshots []ReserveSnapshot `protobuf:"bytes,5,rep,name=reserve_snapshots,json=reserveSnapshots,proto3" json:"reserve_snapshots"` - DnrEpoch uint64 `protobuf:"varint,6,opt,name=dnr_epoch,json=dnrEpoch,proto3" json:"dnr_epoch,omitempty"` - // For testing purposes, we allow the collateral to be set at genesis - CollateralDenom string `protobuf:"bytes,11,opt,name=collateral_denom,json=collateralDenom,proto3" json:"collateral_denom,omitempty"` - TraderVolumes []GenesisState_TraderVolume `protobuf:"bytes,7,rep,name=trader_volumes,json=traderVolumes,proto3" json:"trader_volumes"` - GlobalDiscount []GenesisState_Discount `protobuf:"bytes,8,rep,name=global_discount,json=globalDiscount,proto3" json:"global_discount"` - CustomDiscounts []GenesisState_CustomDiscount `protobuf:"bytes,9,rep,name=custom_discounts,json=customDiscounts,proto3" json:"custom_discounts"` - MarketLastVersions []GenesisMarketLastVersion `protobuf:"bytes,10,rep,name=market_last_versions,json=marketLastVersions,proto3" json:"market_last_versions"` - GlobalVolumes []GenesisState_GlobalVolume `protobuf:"bytes,13,rep,name=global_volumes,json=globalVolumes,proto3" json:"global_volumes"` - RebatesAllocations []DNRAllocation `protobuf:"bytes,12,rep,name=rebates_allocations,json=rebatesAllocations,proto3" json:"rebates_allocations"` - DnrEpochName string `protobuf:"bytes,14,opt,name=dnr_epoch_name,json=dnrEpochName,proto3" json:"dnr_epoch_name,omitempty"` -} - -func (m *GenesisState) Reset() { *m = GenesisState{} } -func (m *GenesisState) String() string { return proto.CompactTextString(m) } -func (*GenesisState) ProtoMessage() {} -func (*GenesisState) Descriptor() ([]byte, []int) { - return fileDescriptor_c2c7acfef3993fde, []int{0} -} -func (m *GenesisState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState.Merge(m, src) -} -func (m *GenesisState) XXX_Size() int { - return m.Size() -} -func (m *GenesisState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState proto.InternalMessageInfo - -func (m *GenesisState) GetMarkets() []Market { - if m != nil { - return m.Markets - } - return nil -} - -func (m *GenesisState) GetAmms() []AMM { - if m != nil { - return m.Amms - } - return nil -} - -func (m *GenesisState) GetPositions() []GenesisPosition { - if m != nil { - return m.Positions - } - return nil -} - -func (m *GenesisState) GetReserveSnapshots() []ReserveSnapshot { - if m != nil { - return m.ReserveSnapshots - } - return nil -} - -func (m *GenesisState) GetDnrEpoch() uint64 { - if m != nil { - return m.DnrEpoch - } - return 0 -} - -func (m *GenesisState) GetCollateralDenom() string { - if m != nil { - return m.CollateralDenom - } - return "" -} - -func (m *GenesisState) GetTraderVolumes() []GenesisState_TraderVolume { - if m != nil { - return m.TraderVolumes - } - return nil -} - -func (m *GenesisState) GetGlobalDiscount() []GenesisState_Discount { - if m != nil { - return m.GlobalDiscount - } - return nil -} - -func (m *GenesisState) GetCustomDiscounts() []GenesisState_CustomDiscount { - if m != nil { - return m.CustomDiscounts - } - return nil -} - -func (m *GenesisState) GetMarketLastVersions() []GenesisMarketLastVersion { - if m != nil { - return m.MarketLastVersions - } - return nil -} - -func (m *GenesisState) GetGlobalVolumes() []GenesisState_GlobalVolume { - if m != nil { - return m.GlobalVolumes - } - return nil -} - -func (m *GenesisState) GetRebatesAllocations() []DNRAllocation { - if m != nil { - return m.RebatesAllocations - } - return nil -} - -func (m *GenesisState) GetDnrEpochName() string { - if m != nil { - return m.DnrEpochName - } - return "" -} - -type GenesisState_TraderVolume struct { - Trader string `protobuf:"bytes,1,opt,name=trader,proto3" json:"trader,omitempty"` - Epoch uint64 `protobuf:"varint,2,opt,name=epoch,proto3" json:"epoch,omitempty"` - Volume github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=volume,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"volume"` -} - -func (m *GenesisState_TraderVolume) Reset() { *m = GenesisState_TraderVolume{} } -func (m *GenesisState_TraderVolume) String() string { return proto.CompactTextString(m) } -func (*GenesisState_TraderVolume) ProtoMessage() {} -func (*GenesisState_TraderVolume) Descriptor() ([]byte, []int) { - return fileDescriptor_c2c7acfef3993fde, []int{0, 0} -} -func (m *GenesisState_TraderVolume) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState_TraderVolume) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState_TraderVolume.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState_TraderVolume) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState_TraderVolume.Merge(m, src) -} -func (m *GenesisState_TraderVolume) XXX_Size() int { - return m.Size() -} -func (m *GenesisState_TraderVolume) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState_TraderVolume.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState_TraderVolume proto.InternalMessageInfo - -func (m *GenesisState_TraderVolume) GetTrader() string { - if m != nil { - return m.Trader - } - return "" -} - -func (m *GenesisState_TraderVolume) GetEpoch() uint64 { - if m != nil { - return m.Epoch - } - return 0 -} - -type GenesisState_Discount struct { - Fee github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=fee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"fee"` - Volume github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=volume,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"volume"` -} - -func (m *GenesisState_Discount) Reset() { *m = GenesisState_Discount{} } -func (m *GenesisState_Discount) String() string { return proto.CompactTextString(m) } -func (*GenesisState_Discount) ProtoMessage() {} -func (*GenesisState_Discount) Descriptor() ([]byte, []int) { - return fileDescriptor_c2c7acfef3993fde, []int{0, 1} -} -func (m *GenesisState_Discount) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState_Discount) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState_Discount.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState_Discount) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState_Discount.Merge(m, src) -} -func (m *GenesisState_Discount) XXX_Size() int { - return m.Size() -} -func (m *GenesisState_Discount) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState_Discount.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState_Discount proto.InternalMessageInfo - -type GenesisState_CustomDiscount struct { - Trader string `protobuf:"bytes,1,opt,name=trader,proto3" json:"trader,omitempty"` - Discount *GenesisState_Discount `protobuf:"bytes,2,opt,name=discount,proto3" json:"discount,omitempty"` -} - -func (m *GenesisState_CustomDiscount) Reset() { *m = GenesisState_CustomDiscount{} } -func (m *GenesisState_CustomDiscount) String() string { return proto.CompactTextString(m) } -func (*GenesisState_CustomDiscount) ProtoMessage() {} -func (*GenesisState_CustomDiscount) Descriptor() ([]byte, []int) { - return fileDescriptor_c2c7acfef3993fde, []int{0, 2} -} -func (m *GenesisState_CustomDiscount) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState_CustomDiscount) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState_CustomDiscount.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState_CustomDiscount) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState_CustomDiscount.Merge(m, src) -} -func (m *GenesisState_CustomDiscount) XXX_Size() int { - return m.Size() -} -func (m *GenesisState_CustomDiscount) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState_CustomDiscount.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState_CustomDiscount proto.InternalMessageInfo - -func (m *GenesisState_CustomDiscount) GetTrader() string { - if m != nil { - return m.Trader - } - return "" -} - -func (m *GenesisState_CustomDiscount) GetDiscount() *GenesisState_Discount { - if m != nil { - return m.Discount - } - return nil -} - -type GenesisState_GlobalVolume struct { - Epoch uint64 `protobuf:"varint,1,opt,name=epoch,proto3" json:"epoch,omitempty"` - Volume github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=volume,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"volume"` -} - -func (m *GenesisState_GlobalVolume) Reset() { *m = GenesisState_GlobalVolume{} } -func (m *GenesisState_GlobalVolume) String() string { return proto.CompactTextString(m) } -func (*GenesisState_GlobalVolume) ProtoMessage() {} -func (*GenesisState_GlobalVolume) Descriptor() ([]byte, []int) { - return fileDescriptor_c2c7acfef3993fde, []int{0, 3} -} -func (m *GenesisState_GlobalVolume) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisState_GlobalVolume) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState_GlobalVolume.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisState_GlobalVolume) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState_GlobalVolume.Merge(m, src) -} -func (m *GenesisState_GlobalVolume) XXX_Size() int { - return m.Size() -} -func (m *GenesisState_GlobalVolume) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState_GlobalVolume.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState_GlobalVolume proto.InternalMessageInfo - -func (m *GenesisState_GlobalVolume) GetEpoch() uint64 { - if m != nil { - return m.Epoch - } - return 0 -} - -// GenesisMarketLastVersion is the last version including pair only used for -// genesis -type GenesisMarketLastVersion struct { - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,1,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - Version uint64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"` -} - -func (m *GenesisMarketLastVersion) Reset() { *m = GenesisMarketLastVersion{} } -func (m *GenesisMarketLastVersion) String() string { return proto.CompactTextString(m) } -func (*GenesisMarketLastVersion) ProtoMessage() {} -func (*GenesisMarketLastVersion) Descriptor() ([]byte, []int) { - return fileDescriptor_c2c7acfef3993fde, []int{1} -} -func (m *GenesisMarketLastVersion) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisMarketLastVersion) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisMarketLastVersion.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisMarketLastVersion) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisMarketLastVersion.Merge(m, src) -} -func (m *GenesisMarketLastVersion) XXX_Size() int { - return m.Size() -} -func (m *GenesisMarketLastVersion) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisMarketLastVersion.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisMarketLastVersion proto.InternalMessageInfo - -func (m *GenesisMarketLastVersion) GetVersion() uint64 { - if m != nil { - return m.Version - } - return 0 -} - -type GenesisPosition struct { - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,1,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - Version uint64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"` - Position Position `protobuf:"bytes,3,opt,name=position,proto3" json:"position"` -} - -func (m *GenesisPosition) Reset() { *m = GenesisPosition{} } -func (m *GenesisPosition) String() string { return proto.CompactTextString(m) } -func (*GenesisPosition) ProtoMessage() {} -func (*GenesisPosition) Descriptor() ([]byte, []int) { - return fileDescriptor_c2c7acfef3993fde, []int{2} -} -func (m *GenesisPosition) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *GenesisPosition) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisPosition.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *GenesisPosition) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisPosition.Merge(m, src) -} -func (m *GenesisPosition) XXX_Size() int { - return m.Size() -} -func (m *GenesisPosition) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisPosition.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisPosition proto.InternalMessageInfo - -func (m *GenesisPosition) GetVersion() uint64 { - if m != nil { - return m.Version - } - return 0 -} - -func (m *GenesisPosition) GetPosition() Position { - if m != nil { - return m.Position - } - return Position{} -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "nibiru.perp.v2.GenesisState") - proto.RegisterType((*GenesisState_TraderVolume)(nil), "nibiru.perp.v2.GenesisState.TraderVolume") - proto.RegisterType((*GenesisState_Discount)(nil), "nibiru.perp.v2.GenesisState.Discount") - proto.RegisterType((*GenesisState_CustomDiscount)(nil), "nibiru.perp.v2.GenesisState.CustomDiscount") - proto.RegisterType((*GenesisState_GlobalVolume)(nil), "nibiru.perp.v2.GenesisState.GlobalVolume") - proto.RegisterType((*GenesisMarketLastVersion)(nil), "nibiru.perp.v2.GenesisMarketLastVersion") - proto.RegisterType((*GenesisPosition)(nil), "nibiru.perp.v2.GenesisPosition") -} - -func init() { proto.RegisterFile("nibiru/perp/v2/genesis.proto", fileDescriptor_c2c7acfef3993fde) } - -var fileDescriptor_c2c7acfef3993fde = []byte{ - // 788 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x55, 0xdf, 0x6a, 0x13, 0x4f, - 0x14, 0xce, 0x36, 0x69, 0x9a, 0x4c, 0xd2, 0xa4, 0xbf, 0x69, 0x29, 0x43, 0x7e, 0x35, 0x2d, 0x45, - 0x25, 0x45, 0xba, 0x4b, 0x23, 0x08, 0x7a, 0x65, 0xd3, 0x68, 0x11, 0x4c, 0x29, 0xdb, 0xd2, 0x0b, - 0x11, 0xd6, 0xc9, 0x66, 0xdc, 0x2c, 0xdd, 0xdd, 0x59, 0x76, 0x26, 0x41, 0xaf, 0xf5, 0x01, 0x14, - 0x7c, 0x16, 0x9f, 0xa1, 0x97, 0xbd, 0x14, 0x2f, 0x8a, 0xb4, 0x2f, 0x22, 0x3b, 0x33, 0x9b, 0x3f, - 0x4b, 0x53, 0x2b, 0x05, 0xaf, 0x92, 0x39, 0xe7, 0x7c, 0xdf, 0xf9, 0xe6, 0xec, 0x37, 0x33, 0x60, - 0x2d, 0x70, 0xbb, 0x6e, 0x34, 0x30, 0x42, 0x12, 0x85, 0xc6, 0xb0, 0x69, 0x38, 0x24, 0x20, 0xcc, - 0x65, 0x7a, 0x18, 0x51, 0x4e, 0x61, 0x45, 0x66, 0xf5, 0x38, 0xab, 0x0f, 0x9b, 0xb5, 0xba, 0x4d, - 0x99, 0x4f, 0x99, 0xd1, 0xc5, 0x8c, 0x18, 0xc3, 0x9d, 0x2e, 0xe1, 0x78, 0xc7, 0xb0, 0xa9, 0x1b, - 0xc8, 0xfa, 0xda, 0x9a, 0x43, 0xa9, 0xe3, 0x11, 0x03, 0x87, 0xae, 0x81, 0x83, 0x80, 0x72, 0xcc, - 0x5d, 0x1a, 0x28, 0xb6, 0xda, 0x8a, 0x43, 0x1d, 0x2a, 0xfe, 0x1a, 0xf1, 0x3f, 0x15, 0xad, 0xa5, - 0x14, 0x30, 0x8e, 0x39, 0x91, 0xb9, 0xcd, 0xaf, 0x25, 0x50, 0xde, 0x97, 0x8a, 0x8e, 0xe2, 0x30, - 0x7c, 0x02, 0x16, 0x7c, 0x1c, 0x9d, 0x12, 0xce, 0xd0, 0xdc, 0x46, 0xb6, 0x51, 0x6a, 0xae, 0xea, - 0xd3, 0x12, 0xf5, 0x8e, 0x48, 0xb7, 0x72, 0x67, 0x17, 0xeb, 0x19, 0x33, 0x29, 0x86, 0xdb, 0x20, - 0x87, 0x7d, 0x9f, 0xa1, 0xac, 0x00, 0x2d, 0xa7, 0x41, 0xbb, 0x9d, 0x8e, 0x42, 0x88, 0x32, 0xb8, - 0x07, 0x8a, 0x21, 0x65, 0xae, 0x10, 0x8f, 0x72, 0x02, 0xb3, 0x9e, 0xc6, 0x28, 0x5d, 0x87, 0xaa, - 0x4e, 0xe1, 0xc7, 0x38, 0x68, 0x82, 0xff, 0x22, 0xc2, 0x48, 0x34, 0x24, 0x16, 0x0b, 0x70, 0xc8, - 0xfa, 0x94, 0x33, 0x34, 0x7f, 0x3d, 0x99, 0x29, 0x0b, 0x8f, 0x54, 0x9d, 0x22, 0x5b, 0x8a, 0xa6, - 0xc3, 0x0c, 0xfe, 0x0f, 0x8a, 0xbd, 0x20, 0xb2, 0x48, 0x48, 0xed, 0x3e, 0xca, 0x6f, 0x68, 0x8d, - 0x9c, 0x59, 0xe8, 0x05, 0xd1, 0x8b, 0x78, 0x0d, 0xb7, 0xc0, 0x92, 0x4d, 0x3d, 0x0f, 0x73, 0x12, - 0x61, 0xcf, 0xea, 0x91, 0x80, 0xfa, 0xa8, 0xb4, 0xa1, 0x35, 0x8a, 0x66, 0x75, 0x1c, 0x6f, 0xc7, - 0x61, 0x78, 0x02, 0x2a, 0x3c, 0xc2, 0x3d, 0x12, 0x59, 0x43, 0xea, 0x0d, 0x7c, 0xc2, 0xd0, 0x82, - 0x10, 0xb6, 0x35, 0x63, 0x97, 0x62, 0xfa, 0xfa, 0xb1, 0x80, 0x9c, 0x08, 0x84, 0x92, 0xb8, 0xc8, - 0x27, 0x62, 0x0c, 0x1e, 0x83, 0xaa, 0xe3, 0xd1, 0x6e, 0xdc, 0xde, 0x65, 0x36, 0x1d, 0x04, 0x1c, - 0x15, 0x04, 0xf1, 0x83, 0x1b, 0x89, 0xdb, 0xaa, 0x58, 0x91, 0x56, 0x24, 0x47, 0x12, 0x85, 0x6f, - 0xc1, 0x92, 0x3d, 0x60, 0x9c, 0xfa, 0x23, 0x56, 0x86, 0x8a, 0x82, 0xf6, 0xd1, 0x8d, 0xb4, 0x7b, - 0x02, 0x94, 0x22, 0xaf, 0xda, 0x53, 0x51, 0x06, 0xdf, 0x81, 0x15, 0x69, 0x13, 0xcb, 0xc3, 0x8c, - 0x5b, 0x43, 0x12, 0x31, 0xf1, 0xdd, 0x81, 0xe8, 0xd0, 0x98, 0xd1, 0x41, 0xfa, 0xec, 0x35, 0x66, - 0xfc, 0x44, 0x02, 0x14, 0x3d, 0xf4, 0xd3, 0x09, 0x16, 0x4f, 0x5b, 0x4d, 0x25, 0x99, 0xf6, 0xe2, - 0x2d, 0xa6, 0xbd, 0x2f, 0x20, 0xd3, 0xd3, 0x76, 0x26, 0x62, 0xf1, 0xb4, 0x97, 0x23, 0xd2, 0xc5, - 0x9c, 0x30, 0x0b, 0x7b, 0x1e, 0xb5, 0xe5, 0x69, 0x43, 0x65, 0x41, 0x7e, 0x2f, 0x4d, 0xde, 0x3e, - 0x30, 0x77, 0x47, 0x55, 0x89, 0x5a, 0x85, 0x1f, 0x27, 0x18, 0xbc, 0x0f, 0x2a, 0x23, 0x8f, 0x59, - 0x01, 0xf6, 0x09, 0xaa, 0x08, 0x13, 0x95, 0x13, 0xa3, 0x1d, 0x60, 0x9f, 0xd4, 0x3e, 0x6b, 0xa0, - 0x3c, 0xe9, 0x07, 0xb8, 0x0a, 0xf2, 0xd2, 0x0b, 0x48, 0x13, 0xe5, 0x6a, 0x05, 0x57, 0xc0, 0xbc, - 0xb4, 0xeb, 0x9c, 0xb0, 0xab, 0x5c, 0xc0, 0x97, 0x20, 0x2f, 0x67, 0x81, 0xb2, 0x71, 0x75, 0x4b, - 0x8f, 0xe5, 0xfc, 0xbc, 0x58, 0x7f, 0xe8, 0xb8, 0xbc, 0x3f, 0xe8, 0xea, 0x36, 0xf5, 0x0d, 0x75, - 0xd9, 0xc8, 0x9f, 0x6d, 0xd6, 0x3b, 0x35, 0xf8, 0xc7, 0x90, 0x30, 0xfd, 0x55, 0xc0, 0x4d, 0x85, - 0xae, 0x7d, 0xd3, 0x40, 0x61, 0xe4, 0x93, 0xe7, 0x20, 0xfb, 0x9e, 0x10, 0xd9, 0xff, 0xaf, 0x18, - 0xdb, 0xc4, 0x36, 0x63, 0xe8, 0x84, 0xac, 0xb9, 0x3b, 0xc9, 0x3a, 0x05, 0x95, 0x69, 0xf3, 0xcd, - 0x1c, 0xcf, 0x2e, 0x28, 0x8c, 0x8e, 0x4a, 0xdc, 0xf3, 0xb6, 0x47, 0xc5, 0x1c, 0xc1, 0x6a, 0x1e, - 0x28, 0x4f, 0x7a, 0x65, 0x3c, 0x71, 0xed, 0xfa, 0x89, 0xdf, 0x69, 0x6b, 0x9b, 0x9f, 0x34, 0x80, - 0x66, 0x9d, 0x01, 0xd8, 0x01, 0xb9, 0x10, 0xbb, 0x6a, 0x8f, 0xad, 0xa7, 0xaa, 0xc5, 0xce, 0x44, - 0x8b, 0x03, 0xb1, 0xb7, 0xbd, 0x3e, 0x76, 0x03, 0x43, 0xdd, 0xfc, 0x1f, 0x0c, 0x9b, 0xfa, 0x3e, - 0x0d, 0x0c, 0xcc, 0x18, 0xe1, 0xfa, 0x21, 0x76, 0x23, 0x53, 0xd0, 0x40, 0x04, 0x16, 0xd4, 0x71, - 0x54, 0xee, 0x49, 0x96, 0x9b, 0xdf, 0x35, 0x50, 0x4d, 0xdd, 0xc0, 0xff, 0xac, 0x39, 0x7c, 0x06, - 0x0a, 0xc9, 0x35, 0x2f, 0xec, 0x5b, 0x6a, 0xa2, 0xf4, 0x37, 0x4b, 0x3d, 0x0b, 0xa3, 0xfa, 0xd6, - 0xfe, 0xd9, 0x65, 0x5d, 0x3b, 0xbf, 0xac, 0x6b, 0xbf, 0x2e, 0xeb, 0xda, 0x97, 0xab, 0x7a, 0xe6, - 0xfc, 0xaa, 0x9e, 0xf9, 0x71, 0x55, 0xcf, 0xbc, 0xd9, 0xfe, 0x93, 0xd0, 0xe4, 0x85, 0x14, 0xdf, - 0xa4, 0x9b, 0x17, 0x4f, 0xe4, 0xe3, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xf5, 0x5d, 0xaf, 0x6c, - 0xc2, 0x07, 0x00, 0x00, -} - -func (m *GenesisState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.DnrEpochName) > 0 { - i -= len(m.DnrEpochName) - copy(dAtA[i:], m.DnrEpochName) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.DnrEpochName))) - i-- - dAtA[i] = 0x72 - } - if len(m.GlobalVolumes) > 0 { - for iNdEx := len(m.GlobalVolumes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.GlobalVolumes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x6a - } - } - if len(m.RebatesAllocations) > 0 { - for iNdEx := len(m.RebatesAllocations) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RebatesAllocations[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x62 - } - } - if len(m.CollateralDenom) > 0 { - i -= len(m.CollateralDenom) - copy(dAtA[i:], m.CollateralDenom) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.CollateralDenom))) - i-- - dAtA[i] = 0x5a - } - if len(m.MarketLastVersions) > 0 { - for iNdEx := len(m.MarketLastVersions) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MarketLastVersions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 - } - } - if len(m.CustomDiscounts) > 0 { - for iNdEx := len(m.CustomDiscounts) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.CustomDiscounts[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - } - } - if len(m.GlobalDiscount) > 0 { - for iNdEx := len(m.GlobalDiscount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.GlobalDiscount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - } - if len(m.TraderVolumes) > 0 { - for iNdEx := len(m.TraderVolumes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TraderVolumes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - } - if m.DnrEpoch != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.DnrEpoch)) - i-- - dAtA[i] = 0x30 - } - if len(m.ReserveSnapshots) > 0 { - for iNdEx := len(m.ReserveSnapshots) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ReserveSnapshots[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - if len(m.Positions) > 0 { - for iNdEx := len(m.Positions) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Positions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.Amms) > 0 { - for iNdEx := len(m.Amms) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amms[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Markets) > 0 { - for iNdEx := len(m.Markets) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Markets[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - return len(dAtA) - i, nil -} - -func (m *GenesisState_TraderVolume) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState_TraderVolume) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState_TraderVolume) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Volume.Size() - i -= size - if _, err := m.Volume.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if m.Epoch != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.Epoch)) - i-- - dAtA[i] = 0x10 - } - if len(m.Trader) > 0 { - i -= len(m.Trader) - copy(dAtA[i:], m.Trader) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.Trader))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *GenesisState_Discount) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState_Discount) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState_Discount) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Volume.Size() - i -= size - if _, err := m.Volume.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.Fee.Size() - i -= size - if _, err := m.Fee.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *GenesisState_CustomDiscount) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState_CustomDiscount) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState_CustomDiscount) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Discount != nil { - { - size, err := m.Discount.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Trader) > 0 { - i -= len(m.Trader) - copy(dAtA[i:], m.Trader) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.Trader))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *GenesisState_GlobalVolume) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState_GlobalVolume) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState_GlobalVolume) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Volume.Size() - i -= size - if _, err := m.Volume.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.Epoch != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.Epoch)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *GenesisMarketLastVersion) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisMarketLastVersion) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisMarketLastVersion) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Version != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.Version)) - i-- - dAtA[i] = 0x10 - } - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *GenesisPosition) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisPosition) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisPosition) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Position.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if m.Version != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.Version)) - i-- - dAtA[i] = 0x10 - } - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Markets) > 0 { - for _, e := range m.Markets { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Amms) > 0 { - for _, e := range m.Amms { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Positions) > 0 { - for _, e := range m.Positions { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ReserveSnapshots) > 0 { - for _, e := range m.ReserveSnapshots { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if m.DnrEpoch != 0 { - n += 1 + sovGenesis(uint64(m.DnrEpoch)) - } - if len(m.TraderVolumes) > 0 { - for _, e := range m.TraderVolumes { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.GlobalDiscount) > 0 { - for _, e := range m.GlobalDiscount { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.CustomDiscounts) > 0 { - for _, e := range m.CustomDiscounts { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.MarketLastVersions) > 0 { - for _, e := range m.MarketLastVersions { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - l = len(m.CollateralDenom) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if len(m.RebatesAllocations) > 0 { - for _, e := range m.RebatesAllocations { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.GlobalVolumes) > 0 { - for _, e := range m.GlobalVolumes { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - l = len(m.DnrEpochName) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - return n -} - -func (m *GenesisState_TraderVolume) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Trader) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if m.Epoch != 0 { - n += 1 + sovGenesis(uint64(m.Epoch)) - } - l = m.Volume.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *GenesisState_Discount) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Fee.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = m.Volume.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *GenesisState_CustomDiscount) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Trader) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if m.Discount != nil { - l = m.Discount.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - return n -} - -func (m *GenesisState_GlobalVolume) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Epoch != 0 { - n += 1 + sovGenesis(uint64(m.Epoch)) - } - l = m.Volume.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func (m *GenesisMarketLastVersion) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Pair.Size() - n += 1 + l + sovGenesis(uint64(l)) - if m.Version != 0 { - n += 1 + sovGenesis(uint64(m.Version)) - } - return n -} - -func (m *GenesisPosition) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Pair.Size() - n += 1 + l + sovGenesis(uint64(l)) - if m.Version != 0 { - n += 1 + sovGenesis(uint64(m.Version)) - } - l = m.Position.Size() - n += 1 + l + sovGenesis(uint64(l)) - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *GenesisState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Markets", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Markets = append(m.Markets, Market{}) - if err := m.Markets[len(m.Markets)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amms", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amms = append(m.Amms, AMM{}) - if err := m.Amms[len(m.Amms)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Positions", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Positions = append(m.Positions, GenesisPosition{}) - if err := m.Positions[len(m.Positions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ReserveSnapshots", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ReserveSnapshots = append(m.ReserveSnapshots, ReserveSnapshot{}) - if err := m.ReserveSnapshots[len(m.ReserveSnapshots)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field DnrEpoch", wireType) - } - m.DnrEpoch = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.DnrEpoch |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TraderVolumes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TraderVolumes = append(m.TraderVolumes, GenesisState_TraderVolume{}) - if err := m.TraderVolumes[len(m.TraderVolumes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field GlobalDiscount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.GlobalDiscount = append(m.GlobalDiscount, GenesisState_Discount{}) - if err := m.GlobalDiscount[len(m.GlobalDiscount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CustomDiscounts", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CustomDiscounts = append(m.CustomDiscounts, GenesisState_CustomDiscount{}) - if err := m.CustomDiscounts[len(m.CustomDiscounts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarketLastVersions", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MarketLastVersions = append(m.MarketLastVersions, GenesisMarketLastVersion{}) - if err := m.MarketLastVersions[len(m.MarketLastVersions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralDenom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralDenom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 12: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RebatesAllocations", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RebatesAllocations = append(m.RebatesAllocations, DNRAllocation{}) - if err := m.RebatesAllocations[len(m.RebatesAllocations)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 13: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field GlobalVolumes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.GlobalVolumes = append(m.GlobalVolumes, GenesisState_GlobalVolume{}) - if err := m.GlobalVolumes[len(m.GlobalVolumes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 14: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DnrEpochName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DnrEpochName = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *GenesisState_TraderVolume) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TraderVolume: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TraderVolume: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Trader", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Trader = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Epoch", wireType) - } - m.Epoch = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Epoch |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Volume", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Volume.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *GenesisState_Discount) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Discount: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Discount: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Fee", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Fee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Volume", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Volume.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *GenesisState_CustomDiscount) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CustomDiscount: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CustomDiscount: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Trader", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Trader = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Discount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Discount == nil { - m.Discount = &GenesisState_Discount{} - } - if err := m.Discount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *GenesisState_GlobalVolume) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GlobalVolume: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GlobalVolume: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Epoch", wireType) - } - m.Epoch = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Epoch |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Volume", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Volume.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *GenesisMarketLastVersion) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisMarketLastVersion: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisMarketLastVersion: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) - } - m.Version = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Version |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *GenesisPosition) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisPosition: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisPosition: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) - } - m.Version = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Version |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Position", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Position.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/perp/v2/types/genesis_test.go b/x/perp/v2/types/genesis_test.go deleted file mode 100644 index 5d825f669..000000000 --- a/x/perp/v2/types/genesis_test.go +++ /dev/null @@ -1,192 +0,0 @@ -package types_test - -import ( - "encoding/json" - "testing" - "time" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" - epochstypes "github.com/NibiruChain/nibiru/x/epochs/types" - "github.com/NibiruChain/nibiru/x/perp/v2/types" -) - -func TestDefaultGenesis(t *testing.T) { - // Initialization - genesis := types.DefaultGenesis() - - // Test the conditions - require.NotNil(t, genesis) - require.Empty(t, genesis.Markets) - require.Empty(t, genesis.Amms) - require.Empty(t, genesis.Positions) - require.Empty(t, genesis.ReserveSnapshots) - require.NotNil(t, genesis.CollateralDenom) -} - -func TestGenesisValidate(t *testing.T) { - pair := asset.MustNewPair("ubtc:unusd") - validMarket := types.DefaultMarket(pair) - validAmms := types.AMM{ - BaseReserve: sdk.OneDec(), - QuoteReserve: sdk.OneDec(), - PriceMultiplier: sdk.OneDec(), - SqrtDepth: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - } - validPositions := types.GenesisPosition{ - Pair: pair, - Version: 1, - Position: types.Position{ - TraderAddress: "cosmos1zaavvzxez0elundtn32qnk9lkm8kmcszzsv80v", - Pair: pair, - Size_: sdk.OneDec(), - Margin: sdk.OneDec(), - OpenNotional: sdk.OneDec(), - LatestCumulativePremiumFraction: sdk.OneDec(), - LastUpdatedBlockNumber: 0, - }, - } - invalidMarket := &types.Market{ - Pair: pair, - Enabled: true, - LatestCumulativePremiumFraction: sdk.ZeroDec(), - ExchangeFeeRatio: sdk.MustNewDecFromStr("-0.0010"), - EcosystemFundFeeRatio: sdk.MustNewDecFromStr("0.0010"), - LiquidationFeeRatio: sdk.MustNewDecFromStr("0.0500"), - PartialLiquidationRatio: sdk.MustNewDecFromStr("0.5000"), - FundingRateEpochId: epochstypes.ThirtyMinuteEpochID, - MaxFundingRate: sdk.NewDec(1), - TwapLookbackWindow: time.Minute * 30, - PrepaidBadDebt: sdk.NewCoin(denoms.USDC, sdk.ZeroInt()), - MaintenanceMarginRatio: sdk.MustNewDecFromStr("0.0625"), - MaxLeverage: sdk.NewDec(10), - } - invalidAmms := types.AMM{ - BaseReserve: sdk.ZeroDec(), - QuoteReserve: sdk.OneDec(), - PriceMultiplier: sdk.OneDec(), - SqrtDepth: sdk.OneDec(), - TotalLong: sdk.ZeroDec(), - TotalShort: sdk.ZeroDec(), - } - invalidPositions := types.GenesisPosition{ - Pair: pair, - Version: 1, - Position: types.Position{ - TraderAddress: "cosmos1zaavvzxez0elundtn32qnk9lkm8kmcszzsv80v", - Pair: pair, - Size_: sdk.ZeroDec(), - Margin: sdk.OneDec(), - OpenNotional: sdk.OneDec(), - LatestCumulativePremiumFraction: sdk.OneDec(), - LastUpdatedBlockNumber: 0, - }, - } - - tests := []struct { - name string - setupGenesis func() *types.GenesisState - shouldFail bool - }{ - { - name: "valid genesis", - setupGenesis: func() *types.GenesisState { - genesis := types.GenesisState{ - Markets: []types.Market{validMarket}, - Amms: []types.AMM{validAmms}, - Positions: []types.GenesisPosition{validPositions}, - ReserveSnapshots: []types.ReserveSnapshot{}, - } - - return &genesis - }, - shouldFail: false, - }, - { - name: "invalid market", - setupGenesis: func() *types.GenesisState { - genesis := types.GenesisState{ - Markets: []types.Market{*invalidMarket}, - Amms: []types.AMM{validAmms}, - Positions: []types.GenesisPosition{validPositions}, - ReserveSnapshots: []types.ReserveSnapshot{}, - } - - return &genesis - }, - shouldFail: true, - }, - { - name: "invalid amm", - setupGenesis: func() *types.GenesisState { - genesis := types.GenesisState{ - Markets: []types.Market{*invalidMarket}, - Amms: []types.AMM{invalidAmms}, - Positions: []types.GenesisPosition{validPositions}, - ReserveSnapshots: []types.ReserveSnapshot{}, - } - - return &genesis - }, - shouldFail: true, - }, - { - name: "invalid position", - setupGenesis: func() *types.GenesisState { - genesis := types.GenesisState{ - Markets: []types.Market{*invalidMarket}, - Amms: []types.AMM{validAmms}, - Positions: []types.GenesisPosition{invalidPositions}, - ReserveSnapshots: []types.ReserveSnapshot{}, - } - - return &genesis - }, - shouldFail: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := tt.setupGenesis().Validate() - if tt.shouldFail { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestDefaultMarket(t *testing.T) { - // Initialize asset pair - pair := asset.NewPair("ubtc", "unusd") - - // Initialize the market with default values - market := types.DefaultMarket(pair) - - // Test the conditions - require.NotNil(t, market) - // Continue testing individual attributes of market as required -} - -func TestGetGenesisStateFromAppState(t *testing.T) { - // Initialize codec and AppState - var cdc codec.JSONCodec - appState := make(map[string]json.RawMessage) - - // Insert valid ModuleName data into AppState - // insert valid ModuleName data - - // Get the GenesisState - genesis := types.GetGenesisStateFromAppState(cdc, appState) - - // Test the conditions - require.NotNil(t, genesis) -} diff --git a/x/perp/v2/types/keys.go b/x/perp/v2/types/keys.go deleted file mode 100644 index 00e36f632..000000000 --- a/x/perp/v2/types/keys.go +++ /dev/null @@ -1,33 +0,0 @@ -package types - -import "github.com/NibiruChain/nibiru/x/common" - -const ( - ModuleName = "perp" - VaultModuleAccount = "vault" - PerpFundModuleAccount = "perp_fund" - FeePoolModuleAccount = "fee_pool" - DNRAllocationModuleAccount = "dnr_allocation" - DNREscrowModuleAccount = "dnr_escrow" -) - -var ( - // StoreKey defines the primary module store key. - StoreKey = ModuleName - - MemStoreKey = "mem_" + ModuleName - - // RouterKey is the message route for perp. - RouterKey = ModuleName - - // QuerierRoute defines the module's query routing key. - QuerierRoute = ModuleName -) - -var ModuleAccounts = []string{ - ModuleName, - PerpFundModuleAccount, - VaultModuleAccount, - FeePoolModuleAccount, - common.TreasuryPoolModuleAccount, -} diff --git a/x/perp/v2/types/market.go b/x/perp/v2/types/market.go deleted file mode 100644 index 1b36cdfb2..000000000 --- a/x/perp/v2/types/market.go +++ /dev/null @@ -1,203 +0,0 @@ -package types - -import ( - fmt "fmt" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" -) - -func isPercent(v sdk.Dec) bool { - return v.GTE(sdk.ZeroDec()) && v.LTE(sdk.OneDec()) -} - -func (market Market) Validate() error { - if !isPercent(market.MaintenanceMarginRatio) { - return fmt.Errorf("maintenance margin ratio ratio must be 0 <= ratio <= 1") - } - - if !isPercent(market.EcosystemFundFeeRatio) { - return fmt.Errorf("ecosystem fund fee ratio must be 0 <= ratio <= 1") - } - - if !isPercent(market.ExchangeFeeRatio) { - return fmt.Errorf("exchange fee ratio must be 0 <= ratio <= 1") - } - - if !isPercent(market.LiquidationFeeRatio) { - return fmt.Errorf("liquidation fee ratio must be 0 <= ratio <= 1") - } - - if !isPercent(market.PartialLiquidationRatio) { - return fmt.Errorf("partial liquidation ratio must be 0 <= ratio <= 1") - } - - if market.MaxLeverage.LTE(sdk.ZeroDec()) { - return fmt.Errorf("max leverage must be > 0") - } - - if market.MaxFundingRate.LT(sdk.ZeroDec()) { - return fmt.Errorf("max funding rate must be >= 0") - } - - if sdk.OneDec().Quo(market.MaxLeverage).LT(market.MaintenanceMarginRatio) { - return fmt.Errorf("margin ratio opened with max leverage position will be lower than Maintenance margin ratio") - } - - if err := market.OraclePair.Validate(); err != nil { - return fmt.Errorf("err when validating oracle pair %w", err) - } - - return nil -} - -func (market Market) WithMaintenanceMarginRatio(value sdk.Dec) Market { - market.MaintenanceMarginRatio = value - return market -} - -func (market Market) WithMaxLeverage(value sdk.Dec) Market { - market.MaxLeverage = value - return market -} - -func (market Market) WithEcosystemFee(value sdk.Dec) Market { - market.EcosystemFundFeeRatio = value - return market -} - -func (market Market) WithExchangeFee(value sdk.Dec) Market { - market.ExchangeFeeRatio = value - return market -} - -func (market Market) WithLiquidationFee(value sdk.Dec) Market { - market.LiquidationFeeRatio = value - return market -} - -func (market Market) WithPartialLiquidationRatio(value sdk.Dec) Market { - market.PartialLiquidationRatio = value - return market -} - -func (market Market) WithFundingRateEpochId(value string) Market { - market.FundingRateEpochId = value - return market -} - -func (market Market) WithMaxFundingRate(value sdk.Dec) Market { - market.MaxFundingRate = value - return market -} - -func (market Market) WithPair(value asset.Pair) Market { - market.Pair = value - return market -} - -func (market Market) WithOraclePair(value asset.Pair) Market { - market.OraclePair = value - return market -} - -func (market Market) WithLatestCumulativePremiumFraction(value sdk.Dec) Market { - market.LatestCumulativePremiumFraction = value - return market -} - -func (market Market) WithEcosystemFundFeeRatio(value sdk.Dec) Market { - market.EcosystemFundFeeRatio = value - return market -} - -func (market Market) WithExchangeFeeRatio(value sdk.Dec) Market { - market.ExchangeFeeRatio = value - return market -} - -func (market Market) WithLiquidationFeeRatio(value sdk.Dec) Market { - market.LiquidationFeeRatio = value - return market -} - -func (market Market) WithPrepaidBadDebt(value sdk.Coin) Market { - market.PrepaidBadDebt = value - return market -} - -func (market Market) WithEnabled(value bool) Market { - market.Enabled = value - return market -} - -func (market Market) WithTwapLookbackWindow(value time.Duration) Market { - market.TwapLookbackWindow = value - return market -} - -func MarketsAreEqual(expected, actual Market) error { - if expected.Pair != actual.Pair { - return fmt.Errorf("expected market pair %s, got %s", expected.Pair, actual.Pair) - } - - if !expected.MaintenanceMarginRatio.Equal(actual.MaintenanceMarginRatio) { - return fmt.Errorf("expected market maintenance margin ratio %s, got %s", expected.MaintenanceMarginRatio, actual.MaintenanceMarginRatio) - } - - if !expected.MaxLeverage.Equal(actual.MaxLeverage) { - return fmt.Errorf("expected market max leverage %s, got %s", expected.MaxLeverage, actual.MaxLeverage) - } - - if !expected.EcosystemFundFeeRatio.Equal(actual.EcosystemFundFeeRatio) { - return fmt.Errorf("expected market ecosystem fund fee ratio %s, got %s", expected.EcosystemFundFeeRatio, actual.EcosystemFundFeeRatio) - } - - if !expected.ExchangeFeeRatio.Equal(actual.ExchangeFeeRatio) { - return fmt.Errorf("expected market exchange fee ratio %s, got %s", expected.ExchangeFeeRatio, actual.ExchangeFeeRatio) - } - - if !expected.LiquidationFeeRatio.Equal(actual.LiquidationFeeRatio) { - return fmt.Errorf("expected market liquidation fee ratio %s, got %s", expected.LiquidationFeeRatio, actual.LiquidationFeeRatio) - } - - if !expected.PartialLiquidationRatio.Equal(actual.PartialLiquidationRatio) { - return fmt.Errorf("expected market partial liquidation ratio %s, got %s", expected.PartialLiquidationRatio, actual.PartialLiquidationRatio) - } - - if expected.FundingRateEpochId != actual.FundingRateEpochId { - return fmt.Errorf("expected market funding rate epoch id %s, got %s", expected.FundingRateEpochId, actual.FundingRateEpochId) - } - - if !expected.MaxFundingRate.Equal(actual.MaxFundingRate) { - return fmt.Errorf("expected market max funding rate %s, got %s", expected.MaxFundingRate, actual.MaxFundingRate) - } - - if !expected.PrepaidBadDebt.Equal(actual.PrepaidBadDebt) { - return fmt.Errorf("expected market prepaid bad debt %s, got %s", expected.PrepaidBadDebt, actual.PrepaidBadDebt) - } - - if expected.Enabled != actual.Enabled { - return fmt.Errorf("expected market enabled %t, got %t", expected.Enabled, actual.Enabled) - } - - if expected.TwapLookbackWindow != actual.TwapLookbackWindow { - return fmt.Errorf("expected market twap lookback window %s, got %s", expected.TwapLookbackWindow, actual.TwapLookbackWindow) - } - - if expected.OraclePair != actual.OraclePair { - return fmt.Errorf("expected oracle pair %s, got %s", expected.OraclePair, actual.OraclePair) - } - - if !expected.LatestCumulativePremiumFraction.Equal(actual.LatestCumulativePremiumFraction) { - return fmt.Errorf( - "expected market latest cumulative premium fraction %s, got %s", - expected.LatestCumulativePremiumFraction, - actual.LatestCumulativePremiumFraction, - ) - } - - return nil -} diff --git a/x/perp/v2/types/market_test.go b/x/perp/v2/types/market_test.go deleted file mode 100644 index 23e80458a..000000000 --- a/x/perp/v2/types/market_test.go +++ /dev/null @@ -1,192 +0,0 @@ -package types - -import ( - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/asset" - "github.com/NibiruChain/nibiru/x/common/denoms" -) - -func TestIsPercent(t *testing.T) { - require.True(t, isPercent(sdk.ZeroDec())) - require.True(t, isPercent(sdk.NewDec(1))) - require.True(t, isPercent(sdk.NewDecWithPrec(5, 1))) // 0.5 - require.False(t, isPercent(sdk.NewDec(-1))) - require.False(t, isPercent(sdk.NewDec(2))) -} - -func TestValidate(t *testing.T) { - // Test when all values are within expected ranges - market := Market{}. - WithMaintenanceMarginRatio(sdk.NewDecWithPrec(1, 1)). - WithEcosystemFee(sdk.NewDecWithPrec(3, 1)). - WithExchangeFee(sdk.NewDecWithPrec(4, 1)). - WithLiquidationFee(sdk.NewDecWithPrec(2, 1)). - WithPartialLiquidationRatio(sdk.NewDecWithPrec(1, 1)). - WithMaxLeverage(sdk.NewDec(10)). - WithMaxFundingRate(sdk.NewDec(1)). - WithOraclePair(asset.Registry.Pair(denoms.BTC, denoms.USD)) - require.NoError(t, market.Validate()) - - testCases := []struct { - modifier func(Market) Market - requiredError string - }{ - { - modifier: func(m Market) Market { return m.WithMaintenanceMarginRatio(sdk.NewDec(-1)) }, - requiredError: "maintenance margin ratio ratio must be 0 <= ratio <= 1", - }, - { - modifier: func(m Market) Market { return m.WithEcosystemFee(sdk.NewDec(2)) }, - requiredError: "ecosystem fund fee ratio must be 0 <= ratio <= 1", - }, - { - modifier: func(m Market) Market { return m.WithExchangeFee(sdk.NewDec(-1)) }, - requiredError: "exchange fee ratio must be 0 <= ratio <= 1", - }, - { - modifier: func(m Market) Market { return m.WithLiquidationFee(sdk.NewDec(2)) }, - requiredError: "liquidation fee ratio must be 0 <= ratio <= 1", - }, - { - modifier: func(m Market) Market { return m.WithPartialLiquidationRatio(sdk.NewDec(-1)) }, - requiredError: "partial liquidation ratio must be 0 <= ratio <= 1", - }, - { - modifier: func(m Market) Market { return m.WithMaxLeverage(sdk.ZeroDec()) }, - requiredError: "max leverage must be > 0", - }, - { - modifier: func(m Market) Market { return m.WithMaxFundingRate(sdk.NewDec(-1)) }, - requiredError: "max funding rate must be >= 0", - }, - { - modifier: func(m Market) Market { return m.WithOraclePair("abc") }, - requiredError: "err when validating oracle pair abc: invalid token pair", - }, - { - modifier: func(m Market) Market { - return m.WithMaxLeverage(sdk.NewDec(20)).WithMaintenanceMarginRatio(sdk.NewDec(1)) - }, - requiredError: "margin ratio opened with max leverage position will be lower than Maintenance margin ratio", - }, - } - for _, tc := range testCases { - tc := tc - t.Run(tc.requiredError, func(t *testing.T) { - newMarket := tc.modifier(market) - - err := newMarket.Validate() - require.Error(t, err) - require.Contains(t, err.Error(), tc.requiredError) - }) - } -} - -func TestMarketEqual(t *testing.T) { - market := Market{}. - WithMaintenanceMarginRatio(sdk.NewDecWithPrec(1, 1)). - WithEcosystemFee(sdk.NewDecWithPrec(3, 1)). - WithExchangeFee(sdk.NewDecWithPrec(4, 1)). - WithLiquidationFee(sdk.NewDecWithPrec(2, 1)). - WithPartialLiquidationRatio(sdk.NewDecWithPrec(1, 1)). - WithMaxLeverage(sdk.NewDec(10)). - WithLatestCumulativePremiumFraction(sdk.OneDec()). - WithMaxFundingRate(sdk.OneDec()). - WithOraclePair(asset.Registry.Pair(denoms.BTC, denoms.USD)) - - // Test when all values are within expected ranges - require.NoError(t, market.Validate()) - - testCases := []struct { - modifier func(Market) Market - requiredError string - }{ - { - modifier: func(m Market) Market { return m.WithPair("ueth:unusd") }, - requiredError: "expected market pair", - }, - { - modifier: func(m Market) Market { return m.WithMaintenanceMarginRatio(sdk.NewDec(42)) }, - requiredError: "expected market maintenance margin ratio", - }, - { - modifier: func(m Market) Market { return m.WithMaxLeverage(sdk.NewDec(42)) }, - requiredError: "expected market max leverage", - }, - { - modifier: func(m Market) Market { return m.WithPartialLiquidationRatio(sdk.NewDec(42)) }, - requiredError: "expected market partial liquidation ratio", - }, - { - modifier: func(m Market) Market { return m.WithFundingRateEpochId("hi") }, - requiredError: "expected market funding rate epoch id", - }, - { - modifier: func(m Market) Market { return m.WithMaxFundingRate(sdk.NewDec(42)) }, - requiredError: "expected market max funding rate", - }, - { - modifier: func(m Market) Market { return m.WithLatestCumulativePremiumFraction(sdk.NewDec(42)) }, - requiredError: "expected market latest cumulative premium fraction", - }, - { - modifier: func(m Market) Market { return m.WithEcosystemFundFeeRatio(sdk.NewDec(42)) }, - requiredError: "expected market ecosystem fund fee ratio", - }, - { - modifier: func(m Market) Market { return m.WithExchangeFeeRatio(sdk.NewDec(42)) }, - requiredError: "expected market exchange fee ratio", - }, - { - modifier: func(m Market) Market { return m.WithLiquidationFeeRatio(sdk.NewDec(42)) }, - requiredError: "expected market liquidation fee ratio", - }, - { - modifier: func(m Market) Market { - return m.WithPrepaidBadDebt(sdk.NewCoin(TestingCollateralDenomNUSD, sdk.OneInt())) - }, - requiredError: "expected market prepaid bad debt", - }, - { - modifier: func(m Market) Market { return m.WithEnabled(true) }, - requiredError: "expected market enabled", - }, - { - modifier: func(m Market) Market { return m.WithTwapLookbackWindow(time.Minute) }, - requiredError: "expected market twap lookback window", - }, - { - modifier: func(m Market) Market { return m.WithOraclePair("abc") }, - requiredError: "expected oracle pair ubtc:uusd, got abc", - }, - } - for _, tc := range testCases { - tc := tc - t.Run(tc.requiredError, func(t *testing.T) { - newMarket := tc.modifier(market) - - err := MarketsAreEqual(market, newMarket) - require.Error(t, err) - require.Contains(t, err.Error(), tc.requiredError) - }) - } -} - -func TestMarketsAreEqual(t *testing.T) { - market1 := new(Market).WithMaintenanceMarginRatio(sdk.NewDecWithPrec(5, 1)) - market2 := new(Market).WithMaintenanceMarginRatio(sdk.NewDecWithPrec(5, 1)) - - // Test when markets are equal - require.NoError(t, MarketsAreEqual(market1, market2)) - - // Test when markets are not equal - market2 = market2.WithMaintenanceMarginRatio(sdk.NewDecWithPrec(3, 1)) - require.Error(t, MarketsAreEqual(market1, market2)) - - require.NoError(t, MarketsAreEqual(market1, market1)) -} diff --git a/x/perp/v2/types/msgs.go b/x/perp/v2/types/msgs.go deleted file mode 100644 index c58d88218..000000000 --- a/x/perp/v2/types/msgs.go +++ /dev/null @@ -1,464 +0,0 @@ -package types - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/types/errors" - - sdkerrors "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var ( - _ sdk.Msg = &MsgRemoveMargin{} - _ sdk.Msg = &MsgAddMargin{} - _ sdk.Msg = &MsgMarketOrder{} - _ sdk.Msg = &MsgMultiLiquidate{} - _ sdk.Msg = &MsgClosePosition{} - _ sdk.Msg = &MsgDonateToEcosystemFund{} - _ sdk.Msg = &MsgPartialClose{} - _ sdk.Msg = &MsgAllocateEpochRebates{} - _ sdk.Msg = &MsgWithdrawEpochRebates{} - _ sdk.Msg = &MsgShiftPegMultiplier{} - _ sdk.Msg = &MsgShiftSwapInvariant{} - _ sdk.Msg = &MsgWithdrawFromPerpFund{} -) - -// ------------------------ MsgRemoveMargin ------------------------ - -func (m MsgRemoveMargin) Route() string { return "perp" } -func (m MsgRemoveMargin) Type() string { return "remove_margin_msg" } - -func (m MsgRemoveMargin) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return err - } - - err := m.Pair.Validate() - if err != nil { - return err - } - - if !m.Margin.Amount.IsPositive() { - return fmt.Errorf("margin must be positive, not: %v", m.Margin.Amount.String()) - } - - return nil -} - -func (m MsgRemoveMargin) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -func (m MsgRemoveMargin) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{signer} -} - -// ------------------------ MsgAddMargin ------------------------ - -func (m MsgAddMargin) Route() string { return "perp" } -func (m MsgAddMargin) Type() string { return "add_margin_msg" } - -func (m MsgAddMargin) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return err - } - - err := m.Pair.Validate() - if err != nil { - return err - } - - if !m.Margin.Amount.IsPositive() { - return fmt.Errorf("margin must be positive, not: %v", m.Margin.Amount.String()) - } - - return nil -} - -func (m MsgAddMargin) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -func (m MsgAddMargin) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{signer} -} - -// ------------------------ MsgMarketOrder ------------------------ - -func (m MsgMarketOrder) Route() string { return "perp" } -func (m MsgMarketOrder) Type() string { return "market_order_msg" } - -func (m *MsgMarketOrder) ValidateBasic() error { - if m.Side != Direction_SHORT && m.Side != Direction_LONG { - return fmt.Errorf("invalid side") - } - if err := m.Pair.Validate(); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return err - } - if !m.Leverage.IsPositive() { - return fmt.Errorf("leverage must always be greater than zero") - } - if m.BaseAssetAmountLimit.IsNegative() { - return fmt.Errorf("base asset amount limit must not be negative") - } - if !m.QuoteAssetAmount.IsPositive() { - return fmt.Errorf("quote asset amount must be always greater than zero") - } - - return nil -} - -func (m MsgMarketOrder) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -func (m *MsgMarketOrder) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{signer} -} - -// ------------------------ MsgMultiLiquidate ------------------------ - -func (m MsgMultiLiquidate) Route() string { return "perp" } -func (m MsgMultiLiquidate) Type() string { return "multi_liquidate_msg" } - -func (m *MsgMultiLiquidate) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return err - } - - for i, liquidation := range m.Liquidations { - if _, err := sdk.AccAddressFromBech32(liquidation.Trader); err != nil { - return fmt.Errorf("invalid liquidation at index %d: %w", i, err) - } - - if err := liquidation.Pair.Validate(); err != nil { - return fmt.Errorf("invalid liquidation at index %d: %w", i, err) - } - } - - return nil -} - -func (m MsgMultiLiquidate) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -func (m *MsgMultiLiquidate) GetSigners() []sdk.AccAddress { - addr, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - - return []sdk.AccAddress{addr} -} - -// ------------------------ MsgClosePosition ------------------------ - -func (m MsgClosePosition) Route() string { return "perp" } -func (m MsgClosePosition) Type() string { return "close_position_msg" } - -func (m MsgClosePosition) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return sdkerrors.Wrapf(errors.ErrInvalidAddress, "invalid sender address (%s)", err) - } - if err := m.Pair.Validate(); err != nil { - return err - } - return nil -} - -func (m MsgClosePosition) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -func (m MsgClosePosition) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{signer} -} - -// ------------------------ MsgSettlePosition ------------------------ - -func (m MsgSettlePosition) Route() string { return "perp" } -func (m MsgSettlePosition) Type() string { return "settle_position_msg" } - -func (m MsgSettlePosition) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return sdkerrors.Wrapf(errors.ErrInvalidAddress, "invalid sender address (%s)", err) - } - if err := m.Pair.Validate(); err != nil { - return err - } - - return nil -} - -func (m MsgSettlePosition) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -func (m MsgSettlePosition) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{signer} -} - -// ------------------------ MsgDonateToEcosystemFund ------------------------ - -func (m MsgDonateToEcosystemFund) Route() string { return "perp" } -func (m MsgDonateToEcosystemFund) Type() string { return "donate_to_ef_msg" } - -func (m MsgDonateToEcosystemFund) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return sdkerrors.Wrapf(errors.ErrInvalidAddress, "invalid sender address (%s)", err) - } - if m.Donation.IsNil() || m.Donation.IsNegative() { - return fmt.Errorf("invalid donation amount: %s", m.Donation.String()) - } - return nil -} - -func (m MsgDonateToEcosystemFund) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -func (m MsgDonateToEcosystemFund) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{signer} -} - -// ------------------------ MsgPartialClose ------------------------ - -func (m MsgPartialClose) Route() string { return "perp" } -func (m MsgPartialClose) Type() string { return "partial_close_msg" } - -func (m MsgPartialClose) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return sdkerrors.Wrapf(errors.ErrInvalidAddress, "invalid sender address (%s)", err) - } - if err := m.Pair.Validate(); err != nil { - return err - } - if !m.Size_.IsPositive() { - return fmt.Errorf("invalid size amount: %s", m.Size_.String()) - } - return nil -} - -func (m MsgPartialClose) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -func (m MsgPartialClose) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{signer} -} - -// ------------------------ MsgChangeCollateralDenom ------------------------ - -func (m MsgChangeCollateralDenom) Route() string { return "perp" } -func (m MsgChangeCollateralDenom) Type() string { return "change_collateral_denom_msg" } - -func (m MsgChangeCollateralDenom) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return sdkerrors.Wrapf(errors.ErrInvalidAddress, "invalid sender address (%s)", err) - } - if err := sdk.ValidateDenom(m.NewDenom); err != nil { - return err - } - return nil -} - -func (m MsgChangeCollateralDenom) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -func (m MsgChangeCollateralDenom) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{signer} -} - -// ------------------------ MsgAllocateEpochRebates ------------------------ - -func (m MsgAllocateEpochRebates) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return sdkerrors.Wrapf(errors.ErrInvalidAddress, "invalid sender address (%s)", err) - } - if err := m.Rebates.Validate(); err != nil { - return err - } - return nil -} - -func (m MsgAllocateEpochRebates) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{signer} -} - -func (m MsgAllocateEpochRebates) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -// ------------------------ MsgWithdrawEpochRebates ------------------------ - -func (m MsgWithdrawEpochRebates) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return sdkerrors.Wrapf(errors.ErrInvalidAddress, "invalid sender address (%s)", err) - } - if len(m.Epochs) == 0 { - return fmt.Errorf("epochs cannot be empty") - } - return nil -} - -func (m MsgWithdrawEpochRebates) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{signer} -} - -func (m MsgWithdrawEpochRebates) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -// ------------------------ MsgShiftPegMultiplier ------------------------ - -func (m MsgShiftPegMultiplier) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return sdkerrors.Wrapf(errors.ErrInvalidAddress, "invalid sender address (%s)", err) - } - if err := m.Pair.Validate(); err != nil { - return err - } - if !m.NewPegMult.IsPositive() { - return fmt.Errorf("%w: got value %s", ErrAmmNonPositivePegMult, m.NewPegMult) - } - return nil -} - -func (m MsgShiftPegMultiplier) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{signer} -} - -func (m MsgShiftPegMultiplier) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -// ------------------------ MsgShiftSwapInvariant ------------------------ - -func (m MsgShiftSwapInvariant) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return sdkerrors.Wrapf(errors.ErrInvalidAddress, "invalid sender address (%s)", err) - } - if err := m.Pair.Validate(); err != nil { - return err - } - if !m.NewSwapInvariant.IsPositive() { - return fmt.Errorf("%w: got value %s", ErrAmmNonPositiveSwapInvariant, m.NewSwapInvariant) - } - return nil -} - -func (m MsgShiftSwapInvariant) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{signer} -} - -func (m MsgShiftSwapInvariant) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} - -// ------------------------ MsgCloseMarket ------------------------ - -func (m MsgCloseMarket) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return sdkerrors.Wrapf(errors.ErrInvalidAddress, "invalid sender address (%s)", err) - } - - if err := m.Pair.Validate(); err != nil { - return err - } - return nil -} - -func (m MsgCloseMarket) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - - return []sdk.AccAddress{signer} -} - -// ------------------------ MsgWithdrawFromPerpFund ------------------------ - -func (m MsgWithdrawFromPerpFund) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Sender); err != nil { - return fmt.Errorf("%w: invalid sender address (%s): %s", - errors.ErrInvalidAddress, m.Sender, err, - ) - } - if !m.Amount.IsPositive() { - return fmt.Errorf( - "%w: msg \"amount\" must be positive, got %s", ErrGeneric, m.Amount) - } - if _, err := sdk.AccAddressFromBech32(m.ToAddr); err != nil { - return fmt.Errorf("%w: invalid \"to_addr\" (%s): %s", - errors.ErrInvalidAddress, m.ToAddr, err, - ) - } - return nil -} - -func (m MsgWithdrawFromPerpFund) GetSigners() []sdk.AccAddress { - signer, err := sdk.AccAddressFromBech32(m.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{signer} -} - -func (m MsgWithdrawFromPerpFund) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -} diff --git a/x/perp/v2/types/msgs_test.go b/x/perp/v2/types/msgs_test.go deleted file mode 100644 index fcc13e75c..000000000 --- a/x/perp/v2/types/msgs_test.go +++ /dev/null @@ -1,667 +0,0 @@ -package types - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/asset" -) - -func TestMsgValidateBasic(t *testing.T) { - validSender := "cosmos1zaavvzxez0elundtn32qnk9lkm8kmcszzsv80v" - validPair := asset.MustNewPair("ubtc:unusd") - invalidPair := asset.NewPair("//ubtc", "unusd") - - testCases := []struct { - name string - msg sdk.Msg - expectErr bool - expectedError string - }{ - // MsgRemoveMargin test cases - { - "Test MsgRemoveMargin: Valid input", - &MsgRemoveMargin{ - Sender: validSender, - Pair: validPair, - Margin: sdk.NewCoin("unusd", sdk.NewInt(10)), - }, - false, - "", - }, - { - "Test MsgRemoveMargin: Invalid pair", - &MsgRemoveMargin{ - Sender: validSender, - Pair: invalidPair, - Margin: sdk.NewCoin("denom", sdk.NewInt(10)), - }, - true, - "invalid base asset", - }, - { - "Test MsgRemoveMargin: Invalid sender", - &MsgRemoveMargin{ - Sender: "invalid", - Pair: validPair, - Margin: sdk.NewCoin("denom", sdk.NewInt(10)), - }, - true, - "decoding bech32 failed", - }, - { - "Test MsgRemoveMargin: Negative margin", - &MsgRemoveMargin{ - Sender: validSender, - Pair: validPair, - Margin: sdk.NewCoin("denom", sdk.ZeroInt()), - }, - true, - "margin must be positive", - }, - - // MsgAddMargin test cases - { - "Test MsgAddMargin: Valid input", - &MsgAddMargin{ - Sender: validSender, - Pair: validPair, - Margin: sdk.NewCoin("unusd", sdk.NewInt(10)), - }, - false, - "", - }, - { - "Test MsgAddMargin: Invalid sender", - &MsgAddMargin{ - Sender: "invalid", - Pair: validPair, - Margin: sdk.NewCoin("denom", sdk.NewInt(10)), - }, - true, - "decoding bech32 failed", - }, - { - "Test MsgAddMargin: Invalid pair", - &MsgAddMargin{ - Sender: validSender, - Pair: invalidPair, - Margin: sdk.NewCoin("denom", sdk.NewInt(10)), - }, - true, - "invalid base asset", - }, - { - "Test MsgAddMargin: Negative margin", - &MsgAddMargin{ - Sender: validSender, - Pair: validPair, - Margin: sdk.NewCoin("denom", sdk.ZeroInt()), - }, - true, - "margin must be positive", - }, - // MsgMarketOrder test cases - { - "Test MsgMarketOrder: Valid input", - &MsgMarketOrder{ - Sender: validSender, - Pair: validPair, - Side: Direction_SHORT, - Leverage: sdk.NewDec(10), - BaseAssetAmountLimit: sdk.NewInt(10), - QuoteAssetAmount: sdk.NewInt(10), - }, - false, - "", - }, - { - "Test MsgMarketOrder: Invalid Side", - &MsgMarketOrder{ - Sender: validSender, - Pair: validPair, - Side: Direction_DIRECTION_UNSPECIFIED, - Leverage: sdk.NewDec(10), - BaseAssetAmountLimit: sdk.NewInt(10), - QuoteAssetAmount: sdk.NewInt(10), - }, - true, - "invalid side", - }, - { - "Test MsgMarketOrder: Invalid Pair", - &MsgMarketOrder{ - Sender: validSender, - Pair: invalidPair, - Side: Direction_SHORT, - Leverage: sdk.NewDec(10), - BaseAssetAmountLimit: sdk.NewInt(10), - QuoteAssetAmount: sdk.NewInt(10), - }, - true, - "invalid base asset", - }, - { - "Test MsgMarketOrder: Invalid Sender", - &MsgMarketOrder{ - Sender: "invalid", - Pair: validPair, - Side: Direction_SHORT, - Leverage: sdk.NewDec(10), - BaseAssetAmountLimit: sdk.NewInt(10), - QuoteAssetAmount: sdk.NewInt(10), - }, - true, - "decoding bech32 failed", - }, - { - "Test MsgMarketOrder: Negative Leverage", - &MsgMarketOrder{ - Sender: validSender, - Pair: validPair, - Side: Direction_SHORT, - Leverage: sdk.NewDec(-10), - BaseAssetAmountLimit: sdk.NewInt(10), - QuoteAssetAmount: sdk.NewInt(10), - }, - true, - "leverage must always be greater than zero", - }, - { - "Test MsgMarketOrder: Negative BaseAssetAmountLimit", - &MsgMarketOrder{ - Sender: validSender, - Pair: validPair, - Side: Direction_SHORT, - Leverage: sdk.NewDec(10), - BaseAssetAmountLimit: sdk.NewInt(-10), - QuoteAssetAmount: sdk.NewInt(10), - }, - true, - "base asset amount limit must not be negative", - }, - { - "Test MsgMarketOrder: Negative QuoteAssetAmount", - &MsgMarketOrder{ - Sender: validSender, - Pair: validPair, - Side: Direction_SHORT, - Leverage: sdk.NewDec(10), - BaseAssetAmountLimit: sdk.NewInt(10), - QuoteAssetAmount: sdk.NewInt(-10), - }, - true, - "quote asset amount must be always greater than zero", - }, - // MsgClosePosition test cases - { - "Test MsgClosePosition: Valid input", - &MsgClosePosition{ - Sender: validSender, - Pair: validPair, - }, - false, - "", - }, - { - "Test MsgClosePosition: Invalid pair", - &MsgClosePosition{ - Sender: validSender, - Pair: invalidPair, - }, - true, - "invalid base asset", - }, - { - "Test MsgClosePosition: Invalid sender", - &MsgClosePosition{ - Sender: "invalid", - Pair: validPair, - }, - true, - "decoding bech32 failed", - }, - // MsgSettlePosition test cases - { - "Test MsgSettlePosition: Valid input", - &MsgSettlePosition{ - Sender: validSender, - Pair: validPair, - Version: 1, - }, - false, - "", - }, - { - "Test MsgSettlePosition: Invalid pair", - &MsgSettlePosition{ - Sender: validSender, - Pair: invalidPair, - Version: 1, - }, - true, - "invalid base asset", - }, - { - "Test MsgSettlePosition: Invalid sender", - &MsgSettlePosition{ - Sender: "invalid", - Pair: validPair, - }, - true, - "decoding bech32 failed", - }, - // MsgPartialClose test cases - { - "Test MsgPartialClose: Valid input", - &MsgPartialClose{ - Sender: validSender, - Pair: validPair, - Size_: sdk.NewDec(10), - }, - false, - "", - }, - { - "Test MsgPartialClose: Invalid pair", - &MsgPartialClose{ - Sender: validSender, - Pair: invalidPair, - Size_: sdk.NewDec(10), - }, - true, - "invalid base asset", - }, - { - "Test MsgPartialClose: Invalid sender", - &MsgPartialClose{ - Sender: "invalid", - Pair: validPair, - Size_: sdk.NewDec(10), - }, - true, - "decoding bech32 failed", - }, - { - "Test MsgPartialClose: Invalid size", - &MsgPartialClose{ - Sender: validSender, - Pair: validPair, - Size_: sdk.NewDec(0), - }, - true, - "invalid size amount", - }, - - // MsgDonateToEcosystemFund test cases - { - "Test MsgDonateToEcosystemFund: Valid input", - &MsgDonateToEcosystemFund{ - Sender: validSender, - Donation: sdk.NewCoin("unusd", sdk.NewInt(10)), - }, - false, - "", - }, - { - "Test MsgDonateToEcosystemFund: Invalid sender", - &MsgDonateToEcosystemFund{ - Sender: "invalid", - Donation: sdk.NewCoin("unusd", sdk.NewInt(10)), - }, - true, - "decoding bech32 failed", - }, - { - "Test MsgDonateToEcosystemFund: Invalid donation amount", - &MsgDonateToEcosystemFund{ - Sender: validSender, - }, - true, - "invalid donation amount", - }, - // MsgMultiLiquidate - { - "Test MsgMultiLiquidate: Valid input", - &MsgMultiLiquidate{ - Sender: validSender, - Liquidations: []*MsgMultiLiquidate_Liquidation{ - {Trader: validSender, Pair: validPair}, - {Trader: validSender, Pair: validPair}, - }, - }, - false, - "", - }, - { - "Test MsgMultiLiquidate: Invalid Sender", - &MsgMultiLiquidate{ - Sender: "invalid", - Liquidations: []*MsgMultiLiquidate_Liquidation{ - {Trader: validSender, Pair: validPair}, - {Trader: validSender, Pair: validPair}, - }, - }, - true, - "decoding bech32 failed", - }, - { - "Test MsgMultiLiquidate: Invalid Trader", - &MsgMultiLiquidate{ - Sender: validSender, - Liquidations: []*MsgMultiLiquidate_Liquidation{ - {Trader: "invalid", Pair: validPair}, - {Trader: validSender, Pair: validPair}, - }, - }, - true, - "invalid liquidation at index 0: decoding bech32 failed", - }, - { - "Test MsgMultiLiquidate: Invalid Pair", - &MsgMultiLiquidate{ - Sender: validSender, - Liquidations: []*MsgMultiLiquidate_Liquidation{ - {Trader: validSender, Pair: invalidPair}, - {Trader: validSender, Pair: validPair}, - }, - }, - true, - "invalid liquidation at index 0: invalid base asset", - }, - // MsgShiftPegMultiplier - { - name: "MsgShiftPegMultiplier: Invalid pair", - msg: &MsgShiftPegMultiplier{ - Sender: validSender, - Pair: asset.Pair("not_a_pair"), - NewPegMult: sdk.NewDec(420), // valid positive value, unused - }, - expectErr: true, - expectedError: asset.ErrInvalidTokenPair.Error(), - }, - { - name: "MsgShiftPegMultiplier: nonpositive peg multiplier", - msg: &MsgShiftPegMultiplier{ - Sender: validSender, - Pair: asset.Pair("valid:pair"), - NewPegMult: sdk.NewDec(-420), // invalid nonpositive - }, - expectErr: true, - expectedError: ErrAmmNonPositivePegMult.Error(), - }, - - // MsgShiftSwapInvariant test cases - { - name: "MsgShiftSwapInvariant: Invalid pair", - msg: &MsgShiftSwapInvariant{ - Sender: validSender, - Pair: asset.Pair("not_a_pair"), - NewSwapInvariant: sdk.NewInt(420), // valid positive - }, - expectErr: true, - expectedError: asset.ErrInvalidTokenPair.Error(), - }, - { - name: "MsgShiftSwapInvariant: nonpositive swap invariant", - msg: &MsgShiftSwapInvariant{ - Sender: validSender, - Pair: asset.Pair("valid:pair"), - NewSwapInvariant: sdk.NewInt(-420), // invalid nonpositive - }, - expectErr: true, - expectedError: ErrAmmNonPositiveSwapInvariant.Error(), - }, - { - name: "MsgShiftSwapInvariant: nonpositive swap invariant", - msg: &MsgShiftSwapInvariant{ - Sender: validSender, - Pair: asset.Pair("valid:pair"), - NewSwapInvariant: sdk.ZeroInt(), // invalid nonpositive - }, - expectErr: true, - expectedError: ErrAmmNonPositiveSwapInvariant.Error(), - }, - - // MsgWithdrawFromPerpFund test cases - { - name: "MsgWithdrawFromPerpFund: invalid to addr", - msg: &MsgWithdrawFromPerpFund{ - Sender: validSender, - Amount: sdk.NewInt(420), // valid positive - Denom: "", - ToAddr: "invalidaddr", - }, - expectErr: true, - expectedError: sdkerrors.ErrInvalidAddress.Error(), - }, - { - name: "MsgWithdrawFromPerpFund: invalid sender", - msg: &MsgWithdrawFromPerpFund{ - Sender: "invalidaddr", - Amount: sdk.NewInt(420), // valid positive - Denom: "", - ToAddr: validSender, - }, - expectErr: true, - expectedError: sdkerrors.ErrInvalidAddress.Error(), - }, - { - name: "MsgWithdrawFromPerpFund: invalid amount", - msg: &MsgWithdrawFromPerpFund{ - Sender: validSender, - Amount: sdk.NewInt(-420), - Denom: "", - ToAddr: validSender, - }, - expectErr: true, - expectedError: ErrGeneric.Error(), - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.expectErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expectedError) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestMsg_GetSigners(t *testing.T) { - validSender := "cosmos1zaavvzxez0elundtn32qnk9lkm8kmcszzsv80v" - invalidSender := "invalid_address" - - msgValidSenderList := []sdk.Msg{ - &MsgAddMargin{Sender: validSender}, - &MsgRemoveMargin{Sender: validSender}, - &MsgMarketOrder{Sender: validSender}, - &MsgClosePosition{Sender: validSender}, - &MsgSettlePosition{Sender: validSender}, - &MsgPartialClose{Sender: validSender}, - &MsgDonateToEcosystemFund{Sender: validSender}, - &MsgMultiLiquidate{Sender: validSender}, - &MsgShiftPegMultiplier{Sender: validSender}, - &MsgShiftSwapInvariant{Sender: validSender}, - &MsgWithdrawFromPerpFund{Sender: validSender}, - } - msgInvalidSenderList := []sdk.Msg{ - &MsgAddMargin{Sender: invalidSender}, - &MsgRemoveMargin{Sender: invalidSender}, - &MsgMarketOrder{Sender: invalidSender}, - &MsgClosePosition{Sender: invalidSender}, - &MsgSettlePosition{Sender: invalidSender}, - &MsgPartialClose{Sender: invalidSender}, - &MsgDonateToEcosystemFund{Sender: invalidSender}, - &MsgMultiLiquidate{Sender: invalidSender}, - &MsgShiftPegMultiplier{Sender: invalidSender}, - &MsgShiftSwapInvariant{Sender: invalidSender}, - &MsgWithdrawFromPerpFund{Sender: invalidSender}, - } - - for _, msg := range msgValidSenderList { - defer func() { - r := recover() - if (r != nil) != false { - t.Errorf("GetSigners() recover = %v, expectPanic = %v", r, false) - } - }() - signerAddr, _ := sdk.AccAddressFromBech32(validSender) - require.Equal(t, []sdk.AccAddress{signerAddr}, msg.GetSigners()) - } - for _, msg := range msgInvalidSenderList { - defer func() { - r := recover() - if (r != nil) != true { - t.Errorf("GetSigners() recover = %v, expectPanic = %v", r, true) - } - }() - msg.GetSigners() - } -} - -type RouteTyper interface { - sdk.Msg - Route() string - Type() string -} - -func TestMsg_RouteAndType(t *testing.T) { - testCases := []struct { - name string - msg RouteTyper - expectedRoute string - expectedType string - }{ - { - name: "MsgAddMargin", - msg: &MsgAddMargin{}, - expectedRoute: "perp", - expectedType: "add_margin_msg", - }, - { - name: "MsgRemoveMargin", - msg: &MsgRemoveMargin{}, - expectedRoute: "perp", - expectedType: "remove_margin_msg", - }, - { - name: "MsgMarketOrder", - msg: &MsgMarketOrder{}, - expectedRoute: "perp", - expectedType: "market_order_msg", - }, - { - name: "MsgClosePosition", - msg: &MsgClosePosition{}, - expectedRoute: "perp", - expectedType: "close_position_msg", - }, - { - name: "MsgSettlePosition", - msg: &MsgSettlePosition{}, - expectedRoute: "perp", - expectedType: "settle_position_msg", - }, - { - name: "MsgPartialClose", - msg: &MsgPartialClose{}, - expectedRoute: "perp", - expectedType: "partial_close_msg", - }, - { - name: "MsgDonateToEcosystemFund", - msg: &MsgDonateToEcosystemFund{}, - expectedRoute: "perp", - expectedType: "donate_to_ef_msg", - }, - { - name: "MsgMultiLiquidate", - msg: &MsgMultiLiquidate{}, - expectedRoute: "perp", - expectedType: "multi_liquidate_msg", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - require.Equal(t, tc.expectedRoute, tc.msg.Route()) - require.Equal(t, tc.expectedType, tc.msg.Type()) - }) - } -} - -type SignBytesGetter interface { - sdk.Msg - GetSignBytes() []byte -} - -func TestMsg_GetSignBytes(t *testing.T) { - testCases := []struct { - name string - msg SignBytesGetter - }{ - { - name: "MsgAddMargin", - msg: &MsgAddMargin{}, - }, - { - name: "MsgRemoveMargin", - msg: &MsgRemoveMargin{}, - }, - { - name: "MsgMarketOrder", - msg: &MsgMarketOrder{}, - }, - { - name: "MsgClosePosition", - msg: &MsgClosePosition{}, - }, - { - name: "MsgSettlePosition", - msg: &MsgSettlePosition{}, - }, - { - name: "MsgPartialClose", - msg: &MsgPartialClose{}, - }, - { - name: "MsgDonateToEcosystemFund", - msg: &MsgDonateToEcosystemFund{}, - }, - { - name: "MsgMultiLiquidate", - msg: &MsgMultiLiquidate{}, - }, - { - name: "MsgShiftPegMultiplier", - msg: &MsgShiftPegMultiplier{}, - }, - { - name: "MsgShiftSwapInvariant", - msg: &MsgShiftSwapInvariant{}, - }, - { - name: "MsgWithdrawFromPerpFund", - msg: &MsgWithdrawFromPerpFund{}, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - bytes := tc.msg.GetSignBytes() - require.NotNil(t, bytes) - require.NotEmpty(t, bytes) - - // The same message should always return the same bytes - require.Equal(t, bytes, tc.msg.GetSignBytes()) - }) - } -} diff --git a/x/perp/v2/types/position.go b/x/perp/v2/types/position.go deleted file mode 100644 index 141fe3f76..000000000 --- a/x/perp/v2/types/position.go +++ /dev/null @@ -1,156 +0,0 @@ -package types - -import ( - fmt "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common/asset" -) - -func ZeroPosition(ctx sdk.Context, tokenPair asset.Pair, traderAddr sdk.AccAddress) Position { - return Position{ - TraderAddress: traderAddr.String(), - Pair: tokenPair, - Size_: sdk.ZeroDec(), - Margin: sdk.ZeroDec(), - OpenNotional: sdk.ZeroDec(), - LatestCumulativePremiumFraction: sdk.ZeroDec(), - LastUpdatedBlockNumber: ctx.BlockHeight(), - } -} - -func PositionsAreEqual(expected, actual *Position) error { - if expected.Pair != actual.Pair { - return fmt.Errorf("expected position pair %s, got %s", expected.Pair, actual.Pair) - } - - if expected.TraderAddress != actual.TraderAddress { - return fmt.Errorf("expected position trader address %s, got %s", expected.TraderAddress, actual.TraderAddress) - } - - if !expected.Margin.Equal(actual.Margin) { - return fmt.Errorf("expected position margin %s, got %s", expected.Margin, actual.Margin) - } - - if !expected.OpenNotional.Equal(actual.OpenNotional) { - return fmt.Errorf("expected position open notional %s, got %s", expected.OpenNotional, actual.OpenNotional) - } - - if !expected.Size_.Equal(actual.Size_) { - return fmt.Errorf("expected position size %s, got %s", expected.Size_, actual.Size_) - } - - if expected.LastUpdatedBlockNumber != actual.LastUpdatedBlockNumber { - return fmt.Errorf("expected position block number %d, got %d", expected.LastUpdatedBlockNumber, actual.LastUpdatedBlockNumber) - } - - if !expected.LatestCumulativePremiumFraction.Equal(actual.LatestCumulativePremiumFraction) { - return fmt.Errorf( - "expected position latest cumulative premium fraction %s, got %s", - expected.LatestCumulativePremiumFraction, - actual.LatestCumulativePremiumFraction, - ) - } - return nil -} - -type PositionResp struct { - Position Position - // The amount of quote assets exchanged. - ExchangedNotionalValue sdk.Dec - // The amount of base assets exchanged. Signed, positive represents long and negative represents short from the user's perspective. - ExchangedPositionSize sdk.Dec - // The amount of bad debt accrued during this position change. - // Measured in absolute value of quote units. - // If greater than zero, then the position change event will likely fail. - BadDebt sdk.Dec - // The funding payment applied on this position change. - FundingPayment sdk.Dec - // The amount of PnL realized on this position changed, measured in quote - // units. - RealizedPnl sdk.Dec - // The unrealized PnL in the position after the position change. - UnrealizedPnlAfter sdk.Dec - // The amount of margin the trader has to give to the vault. - // A negative value means the vault pays the trader. - MarginToVault sdk.Dec - // The position's notional value after the position change, measured in quote - // units. - PositionNotional sdk.Dec -} - -func (m *Position) Validate() error { - if _, err := sdk.AccAddressFromBech32(m.TraderAddress); err != nil { - return err - } - - if err := m.Pair.Validate(); err != nil { - return err - } - - if m.Size_.IsZero() { - return fmt.Errorf("zero size") - } - - if m.Margin.IsNegative() || m.Margin.IsZero() { - return fmt.Errorf("margin <= 0") - } - - if m.OpenNotional.IsNegative() || m.OpenNotional.IsZero() { - return fmt.Errorf("open notional <= 0") - } - - if m.LastUpdatedBlockNumber < 0 { - return fmt.Errorf("invalid block number") - } - - return nil -} - -func (position *Position) WithTraderAddress(value string) *Position { - position.TraderAddress = value - return position -} - -func (position *Position) WithPair(value asset.Pair) *Position { - position.Pair = value - return position -} - -func (position *Position) WithSize_(value sdk.Dec) *Position { - position.Size_ = value - return position -} - -func (position *Position) WithMargin(value sdk.Dec) *Position { - position.Margin = value - return position -} - -func (position *Position) WithOpenNotional(value sdk.Dec) *Position { - position.OpenNotional = value - return position -} - -func (position *Position) WithLatestCumulativePremiumFraction(value sdk.Dec) *Position { - position.LatestCumulativePremiumFraction = value - return position -} - -func (position *Position) WithLastUpdatedBlockNumber(value int64) *Position { - position.LastUpdatedBlockNumber = value - return position -} - -func (p *Position) copy() *Position { - return &Position{ - TraderAddress: p.TraderAddress, - Pair: p.Pair, - Size_: p.Size_, - Margin: p.Margin, - OpenNotional: p.OpenNotional, - LatestCumulativePremiumFraction: p.LatestCumulativePremiumFraction, - LastUpdatedBlockNumber: p.LastUpdatedBlockNumber, - } -} diff --git a/x/perp/v2/types/position_test.go b/x/perp/v2/types/position_test.go deleted file mode 100644 index 98c67ac4f..000000000 --- a/x/perp/v2/types/position_test.go +++ /dev/null @@ -1,143 +0,0 @@ -package types - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/asset" -) - -func TestZeroPosition(t *testing.T) { - // Initialization - ctx := sdk.Context{} - tokenPair := asset.NewPair("ubtc", "unusd") - traderAddr := sdk.AccAddress{} - - position := ZeroPosition(ctx, tokenPair, traderAddr) - - // Test the conditions - require.NotNil(t, position) - // Continue testing individual attributes of position as required -} - -func TestPositionsAreEqual(t *testing.T) { - accAddress := "cosmos1zaavvzxez0elundtn32qnk9lkm8kmcszzsv80v" - accOtherAddress := "cosmos1g7vzqfthhf4l4vs6skyjj27vqhe97m5gp33hxy" - - expected := Position{ - TraderAddress: accAddress, - Pair: "ubtc:unusd", - Size_: sdk.OneDec(), - Margin: sdk.OneDec(), - OpenNotional: sdk.OneDec(), - LatestCumulativePremiumFraction: sdk.OneDec(), - LastUpdatedBlockNumber: 0, - } - - err := PositionsAreEqual(&expected, expected.copy()) - require.NoError(t, err) - - testCases := []struct { - modifier func(*Position) - requiredError string - }{ - { - modifier: func(p *Position) { p.WithPair(asset.NewPair("ueth", "unusd")) }, - requiredError: "expected position pair", - }, - { - modifier: func(p *Position) { p.WithTraderAddress(accOtherAddress) }, - requiredError: "expected position trader address", - }, - { - modifier: func(p *Position) { p.WithMargin(sdk.NewDec(42)) }, - requiredError: "expected position margin", - }, - { - modifier: func(p *Position) { p.WithOpenNotional(sdk.NewDec(42)) }, - requiredError: "expected position open notional", - }, - { - modifier: func(p *Position) { p.WithSize_(sdk.NewDec(42)) }, - requiredError: "expected position size", - }, - { - modifier: func(p *Position) { p.WithLastUpdatedBlockNumber(42) }, - requiredError: "expected position block number", - }, - { - modifier: func(p *Position) { p.WithLatestCumulativePremiumFraction(sdk.NewDec(42)) }, - requiredError: "expected position latest cumulative premium fraction", - }, - } - for _, tc := range testCases { - tc := tc - t.Run(tc.requiredError, func(t *testing.T) { - newPosition := expected.copy() - - tc.modifier(newPosition) - - err := PositionsAreEqual(&expected, newPosition) - require.Error(t, err) - require.Contains(t, err.Error(), tc.requiredError) - }) - } -} - -func TestPositionValidate(t *testing.T) { - accAddress := "cosmos1zaavvzxez0elundtn32qnk9lkm8kmcszzsv80v" - - validPosition := Position{ - TraderAddress: accAddress, - Pair: "ubtc:unusd", - Size_: sdk.OneDec(), - Margin: sdk.OneDec(), - OpenNotional: sdk.OneDec(), - LatestCumulativePremiumFraction: sdk.OneDec(), - LastUpdatedBlockNumber: 0, - } - - testCases := []struct { - modifier func(*Position) - requiredError string - }{ - { - modifier: func(p *Position) { p.WithTraderAddress("invalid") }, - requiredError: "decoding bech32 failed", - }, - { - modifier: func(p *Position) { p.WithPair("invalid") }, - requiredError: "invalid: invalid token pair", - }, - { - modifier: func(p *Position) { p.WithSize_(sdk.ZeroDec()) }, - requiredError: "zero size", - }, - { - modifier: func(p *Position) { p.WithMargin(sdk.ZeroDec()) }, - requiredError: "margin <= 0", - }, - { - modifier: func(p *Position) { p.WithOpenNotional(sdk.ZeroDec()) }, - requiredError: "open notional <= 0", - }, - { - modifier: func(p *Position) { p.WithLastUpdatedBlockNumber(-1) }, - requiredError: "invalid block number", - }, - } - for _, tc := range testCases { - tc := tc - t.Run(tc.requiredError, func(t *testing.T) { - newPosition := validPosition.copy() - - tc.modifier(newPosition) - - err := newPosition.Validate() - require.Error(t, err) - require.Contains(t, err.Error(), tc.requiredError) - }) - } -} diff --git a/x/perp/v2/types/query.pb.go b/x/perp/v2/types/query.pb.go deleted file mode 100644 index a6b75f9b4..000000000 --- a/x/perp/v2/types/query.pb.go +++ /dev/null @@ -1,3245 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: nibiru/perp/v2/query.proto - -package types - -import ( - context "context" - fmt "fmt" - github_com_NibiruChain_nibiru_x_common_asset "github.com/NibiruChain/nibiru/x/common/asset" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - query "github.com/cosmos/cosmos-sdk/types/query" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// QueryPositionsRequest: Request type for the -// "nibiru.perp.v2.Query/Positions" gRPC service method -type QueryPositionsRequest struct { - Trader string `protobuf:"bytes,1,opt,name=trader,proto3" json:"trader,omitempty"` -} - -func (m *QueryPositionsRequest) Reset() { *m = QueryPositionsRequest{} } -func (m *QueryPositionsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryPositionsRequest) ProtoMessage() {} -func (*QueryPositionsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fc8f0be94fac333f, []int{0} -} -func (m *QueryPositionsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPositionsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPositionsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryPositionsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPositionsRequest.Merge(m, src) -} -func (m *QueryPositionsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryPositionsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPositionsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPositionsRequest proto.InternalMessageInfo - -func (m *QueryPositionsRequest) GetTrader() string { - if m != nil { - return m.Trader - } - return "" -} - -// QueryPositionsResponse: Response type for the -// "nibiru.perp.v2.Query/Positions" gRPC service method -type QueryPositionsResponse struct { - Positions []QueryPositionResponse `protobuf:"bytes,1,rep,name=positions,proto3" json:"positions"` -} - -func (m *QueryPositionsResponse) Reset() { *m = QueryPositionsResponse{} } -func (m *QueryPositionsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryPositionsResponse) ProtoMessage() {} -func (*QueryPositionsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fc8f0be94fac333f, []int{1} -} -func (m *QueryPositionsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPositionsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPositionsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryPositionsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPositionsResponse.Merge(m, src) -} -func (m *QueryPositionsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryPositionsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPositionsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPositionsResponse proto.InternalMessageInfo - -func (m *QueryPositionsResponse) GetPositions() []QueryPositionResponse { - if m != nil { - return m.Positions - } - return nil -} - -// QueryPositionStoreRequest: Request type for the -// "nibiru.perp.v2.Query/PositionStore" gRPC service method -type QueryPositionStoreRequest struct { - // pagination defines a paginated request - Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryPositionStoreRequest) Reset() { *m = QueryPositionStoreRequest{} } -func (m *QueryPositionStoreRequest) String() string { return proto.CompactTextString(m) } -func (*QueryPositionStoreRequest) ProtoMessage() {} -func (*QueryPositionStoreRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fc8f0be94fac333f, []int{2} -} -func (m *QueryPositionStoreRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPositionStoreRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPositionStoreRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryPositionStoreRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPositionStoreRequest.Merge(m, src) -} -func (m *QueryPositionStoreRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryPositionStoreRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPositionStoreRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPositionStoreRequest proto.InternalMessageInfo - -func (m *QueryPositionStoreRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryPositionStoreResponse: Response type for the -// "nibiru.perp.v2.Query/PositionStore" gRPC service method -type QueryPositionStoreResponse struct { - // Position responses: collection of all stored positions (with pagination) - Positions []Position `protobuf:"bytes,1,rep,name=positions,proto3" json:"positions"` - // pagination defines a paginated response - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryPositionStoreResponse) Reset() { *m = QueryPositionStoreResponse{} } -func (m *QueryPositionStoreResponse) String() string { return proto.CompactTextString(m) } -func (*QueryPositionStoreResponse) ProtoMessage() {} -func (*QueryPositionStoreResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fc8f0be94fac333f, []int{3} -} -func (m *QueryPositionStoreResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPositionStoreResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPositionStoreResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryPositionStoreResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPositionStoreResponse.Merge(m, src) -} -func (m *QueryPositionStoreResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryPositionStoreResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPositionStoreResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPositionStoreResponse proto.InternalMessageInfo - -func (m *QueryPositionStoreResponse) GetPositions() []Position { - if m != nil { - return m.Positions - } - return nil -} - -func (m *QueryPositionStoreResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -// QueryPositionRequest: Request type for the -// "nibiru.perp.v2.Query/Position" gRPC service method -type QueryPositionRequest struct { - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,1,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - Trader string `protobuf:"bytes,2,opt,name=trader,proto3" json:"trader,omitempty"` -} - -func (m *QueryPositionRequest) Reset() { *m = QueryPositionRequest{} } -func (m *QueryPositionRequest) String() string { return proto.CompactTextString(m) } -func (*QueryPositionRequest) ProtoMessage() {} -func (*QueryPositionRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fc8f0be94fac333f, []int{4} -} -func (m *QueryPositionRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPositionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPositionRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryPositionRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPositionRequest.Merge(m, src) -} -func (m *QueryPositionRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryPositionRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPositionRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPositionRequest proto.InternalMessageInfo - -func (m *QueryPositionRequest) GetTrader() string { - if m != nil { - return m.Trader - } - return "" -} - -// QueryPositionResponse: Response type for the -// "nibiru.perp.v2.Query/Position" gRPC service method -type QueryPositionResponse struct { - // The position as it exists in the blockchain state - Position Position `protobuf:"bytes,1,opt,name=position,proto3" json:"position"` - // The position's current notional value, if it were to be entirely closed (in - // margin units). - PositionNotional github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=position_notional,json=positionNotional,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"position_notional"` - // The position's unrealized PnL. - UnrealizedPnl github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=unrealized_pnl,json=unrealizedPnl,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"unrealized_pnl"` - // margin ratio of the position based on the spot price - MarginRatio github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=margin_ratio,json=marginRatio,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"margin_ratio"` -} - -func (m *QueryPositionResponse) Reset() { *m = QueryPositionResponse{} } -func (m *QueryPositionResponse) String() string { return proto.CompactTextString(m) } -func (*QueryPositionResponse) ProtoMessage() {} -func (*QueryPositionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fc8f0be94fac333f, []int{5} -} -func (m *QueryPositionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPositionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPositionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryPositionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPositionResponse.Merge(m, src) -} -func (m *QueryPositionResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryPositionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPositionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPositionResponse proto.InternalMessageInfo - -func (m *QueryPositionResponse) GetPosition() Position { - if m != nil { - return m.Position - } - return Position{} -} - -// QueryModuleAccountsRequest: Request type for the -// "nibiru.perp.v2.Query/ModuleAccounts" gRPC service method -type QueryModuleAccountsRequest struct { -} - -func (m *QueryModuleAccountsRequest) Reset() { *m = QueryModuleAccountsRequest{} } -func (m *QueryModuleAccountsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryModuleAccountsRequest) ProtoMessage() {} -func (*QueryModuleAccountsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fc8f0be94fac333f, []int{6} -} -func (m *QueryModuleAccountsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryModuleAccountsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryModuleAccountsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryModuleAccountsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryModuleAccountsRequest.Merge(m, src) -} -func (m *QueryModuleAccountsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryModuleAccountsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryModuleAccountsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryModuleAccountsRequest proto.InternalMessageInfo - -// QueryModuleAccountsResponse: Response type for the -// "nibiru.perp.v2.Query/ModuleAccounts" gRPC service method -type QueryModuleAccountsResponse struct { - Accounts []AccountWithBalance `protobuf:"bytes,1,rep,name=accounts,proto3" json:"accounts"` -} - -func (m *QueryModuleAccountsResponse) Reset() { *m = QueryModuleAccountsResponse{} } -func (m *QueryModuleAccountsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryModuleAccountsResponse) ProtoMessage() {} -func (*QueryModuleAccountsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fc8f0be94fac333f, []int{7} -} -func (m *QueryModuleAccountsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryModuleAccountsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryModuleAccountsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryModuleAccountsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryModuleAccountsResponse.Merge(m, src) -} -func (m *QueryModuleAccountsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryModuleAccountsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryModuleAccountsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryModuleAccountsResponse proto.InternalMessageInfo - -func (m *QueryModuleAccountsResponse) GetAccounts() []AccountWithBalance { - if m != nil { - return m.Accounts - } - return nil -} - -type AccountWithBalance struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` - Balance github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=balance,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"balance"` -} - -func (m *AccountWithBalance) Reset() { *m = AccountWithBalance{} } -func (m *AccountWithBalance) String() string { return proto.CompactTextString(m) } -func (*AccountWithBalance) ProtoMessage() {} -func (*AccountWithBalance) Descriptor() ([]byte, []int) { - return fileDescriptor_fc8f0be94fac333f, []int{8} -} -func (m *AccountWithBalance) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AccountWithBalance) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AccountWithBalance.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *AccountWithBalance) XXX_Merge(src proto.Message) { - xxx_messageInfo_AccountWithBalance.Merge(m, src) -} -func (m *AccountWithBalance) XXX_Size() int { - return m.Size() -} -func (m *AccountWithBalance) XXX_DiscardUnknown() { - xxx_messageInfo_AccountWithBalance.DiscardUnknown(m) -} - -var xxx_messageInfo_AccountWithBalance proto.InternalMessageInfo - -func (m *AccountWithBalance) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *AccountWithBalance) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func (m *AccountWithBalance) GetBalance() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Balance - } - return nil -} - -type AmmMarket struct { - Market Market `protobuf:"bytes,1,opt,name=market,proto3" json:"market"` - Amm AMM `protobuf:"bytes,2,opt,name=amm,proto3" json:"amm"` -} - -func (m *AmmMarket) Reset() { *m = AmmMarket{} } -func (m *AmmMarket) String() string { return proto.CompactTextString(m) } -func (*AmmMarket) ProtoMessage() {} -func (*AmmMarket) Descriptor() ([]byte, []int) { - return fileDescriptor_fc8f0be94fac333f, []int{9} -} -func (m *AmmMarket) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AmmMarket) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AmmMarket.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *AmmMarket) XXX_Merge(src proto.Message) { - xxx_messageInfo_AmmMarket.Merge(m, src) -} -func (m *AmmMarket) XXX_Size() int { - return m.Size() -} -func (m *AmmMarket) XXX_DiscardUnknown() { - xxx_messageInfo_AmmMarket.DiscardUnknown(m) -} - -var xxx_messageInfo_AmmMarket proto.InternalMessageInfo - -func (m *AmmMarket) GetMarket() Market { - if m != nil { - return m.Market - } - return Market{} -} - -func (m *AmmMarket) GetAmm() AMM { - if m != nil { - return m.Amm - } - return AMM{} -} - -type QueryMarketsRequest struct { - Versioned bool `protobuf:"varint,1,opt,name=versioned,proto3" json:"versioned,omitempty"` -} - -func (m *QueryMarketsRequest) Reset() { *m = QueryMarketsRequest{} } -func (m *QueryMarketsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryMarketsRequest) ProtoMessage() {} -func (*QueryMarketsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fc8f0be94fac333f, []int{10} -} -func (m *QueryMarketsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryMarketsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryMarketsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryMarketsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryMarketsRequest.Merge(m, src) -} -func (m *QueryMarketsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryMarketsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryMarketsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryMarketsRequest proto.InternalMessageInfo - -func (m *QueryMarketsRequest) GetVersioned() bool { - if m != nil { - return m.Versioned - } - return false -} - -type QueryMarketsResponse struct { - AmmMarkets []AmmMarket `protobuf:"bytes,1,rep,name=amm_markets,json=ammMarkets,proto3" json:"amm_markets"` -} - -func (m *QueryMarketsResponse) Reset() { *m = QueryMarketsResponse{} } -func (m *QueryMarketsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryMarketsResponse) ProtoMessage() {} -func (*QueryMarketsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fc8f0be94fac333f, []int{11} -} -func (m *QueryMarketsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryMarketsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryMarketsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryMarketsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryMarketsResponse.Merge(m, src) -} -func (m *QueryMarketsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryMarketsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryMarketsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryMarketsResponse proto.InternalMessageInfo - -func (m *QueryMarketsResponse) GetAmmMarkets() []AmmMarket { - if m != nil { - return m.AmmMarkets - } - return nil -} - -// QueryCollateralRequest: Request type for the -// "nibiru.perp.v2.Query/Collateral" gRPC service method -type QueryCollateralRequest struct { -} - -func (m *QueryCollateralRequest) Reset() { *m = QueryCollateralRequest{} } -func (m *QueryCollateralRequest) String() string { return proto.CompactTextString(m) } -func (*QueryCollateralRequest) ProtoMessage() {} -func (*QueryCollateralRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_fc8f0be94fac333f, []int{12} -} -func (m *QueryCollateralRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCollateralRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCollateralRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryCollateralRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCollateralRequest.Merge(m, src) -} -func (m *QueryCollateralRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryCollateralRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCollateralRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCollateralRequest proto.InternalMessageInfo - -// QueryCollateralRequest: Response type for the -// "nibiru.perp.v2.Query/Collateral" gRPC service method -type QueryCollateralResponse struct { - CollateralDenom string `protobuf:"bytes,1,opt,name=collateral_denom,json=collateralDenom,proto3" json:"collateral_denom,omitempty"` -} - -func (m *QueryCollateralResponse) Reset() { *m = QueryCollateralResponse{} } -func (m *QueryCollateralResponse) String() string { return proto.CompactTextString(m) } -func (*QueryCollateralResponse) ProtoMessage() {} -func (*QueryCollateralResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_fc8f0be94fac333f, []int{13} -} -func (m *QueryCollateralResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryCollateralResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCollateralResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryCollateralResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCollateralResponse.Merge(m, src) -} -func (m *QueryCollateralResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryCollateralResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCollateralResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCollateralResponse proto.InternalMessageInfo - -func (m *QueryCollateralResponse) GetCollateralDenom() string { - if m != nil { - return m.CollateralDenom - } - return "" -} - -func init() { - proto.RegisterType((*QueryPositionsRequest)(nil), "nibiru.perp.v2.QueryPositionsRequest") - proto.RegisterType((*QueryPositionsResponse)(nil), "nibiru.perp.v2.QueryPositionsResponse") - proto.RegisterType((*QueryPositionStoreRequest)(nil), "nibiru.perp.v2.QueryPositionStoreRequest") - proto.RegisterType((*QueryPositionStoreResponse)(nil), "nibiru.perp.v2.QueryPositionStoreResponse") - proto.RegisterType((*QueryPositionRequest)(nil), "nibiru.perp.v2.QueryPositionRequest") - proto.RegisterType((*QueryPositionResponse)(nil), "nibiru.perp.v2.QueryPositionResponse") - proto.RegisterType((*QueryModuleAccountsRequest)(nil), "nibiru.perp.v2.QueryModuleAccountsRequest") - proto.RegisterType((*QueryModuleAccountsResponse)(nil), "nibiru.perp.v2.QueryModuleAccountsResponse") - proto.RegisterType((*AccountWithBalance)(nil), "nibiru.perp.v2.AccountWithBalance") - proto.RegisterType((*AmmMarket)(nil), "nibiru.perp.v2.AmmMarket") - proto.RegisterType((*QueryMarketsRequest)(nil), "nibiru.perp.v2.QueryMarketsRequest") - proto.RegisterType((*QueryMarketsResponse)(nil), "nibiru.perp.v2.QueryMarketsResponse") - proto.RegisterType((*QueryCollateralRequest)(nil), "nibiru.perp.v2.QueryCollateralRequest") - proto.RegisterType((*QueryCollateralResponse)(nil), "nibiru.perp.v2.QueryCollateralResponse") -} - -func init() { proto.RegisterFile("nibiru/perp/v2/query.proto", fileDescriptor_fc8f0be94fac333f) } - -var fileDescriptor_fc8f0be94fac333f = []byte{ - // 968 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x56, 0x4f, 0x6f, 0xdc, 0x44, - 0x14, 0x8f, 0x93, 0x90, 0x26, 0x2f, 0x6d, 0x5a, 0xa6, 0x25, 0xf5, 0xba, 0xd1, 0x6e, 0x6a, 0x4a, - 0x92, 0xb6, 0xaa, 0x4d, 0xb6, 0x5c, 0x40, 0x1c, 0xe8, 0x26, 0xa2, 0xe2, 0xb0, 0x55, 0x6a, 0x84, - 0x40, 0x70, 0x58, 0xcd, 0x7a, 0x47, 0x1b, 0xab, 0xf6, 0x8c, 0xeb, 0xf1, 0x46, 0xb4, 0x12, 0x1c, - 0x7a, 0xe0, 0x8c, 0xe8, 0x47, 0xe0, 0x04, 0x9f, 0x81, 0x0f, 0xd0, 0x63, 0x25, 0x2e, 0xa8, 0x87, - 0x82, 0x12, 0x3e, 0x48, 0xe5, 0xf1, 0x1b, 0xef, 0xda, 0xde, 0x66, 0xa3, 0x9e, 0x76, 0x3c, 0xef, - 0xf7, 0xde, 0xfb, 0xbd, 0xbf, 0xb3, 0x60, 0xf1, 0xa0, 0x1f, 0x24, 0x23, 0x37, 0x66, 0x49, 0xec, - 0x1e, 0xb5, 0xdd, 0xc7, 0x23, 0x96, 0x3c, 0x71, 0xe2, 0x44, 0xa4, 0x82, 0xac, 0xe5, 0x32, 0x27, - 0x93, 0x39, 0x47, 0x6d, 0xeb, 0xca, 0x50, 0x0c, 0x85, 0x12, 0xb9, 0xd9, 0x29, 0x47, 0x59, 0x1b, - 0x43, 0x21, 0x86, 0x21, 0x73, 0x69, 0x1c, 0xb8, 0x94, 0x73, 0x91, 0xd2, 0x34, 0x10, 0x5c, 0xa2, - 0xb4, 0x6a, 0x5f, 0xa6, 0x34, 0x65, 0x28, 0x6b, 0xfa, 0x42, 0x46, 0x42, 0xba, 0x7d, 0x2a, 0x99, - 0x7b, 0xb4, 0xdb, 0x67, 0x29, 0xdd, 0x75, 0x7d, 0x11, 0x70, 0x94, 0xdf, 0x9a, 0x94, 0x2b, 0x62, - 0x05, 0x2a, 0xa6, 0xc3, 0x80, 0x2b, 0x47, 0x39, 0xd6, 0x76, 0xe1, 0x83, 0x87, 0x19, 0xe2, 0x40, - 0xc8, 0x40, 0xf9, 0xf7, 0xd8, 0xe3, 0x11, 0x93, 0x29, 0x59, 0x87, 0xa5, 0x34, 0xa1, 0x03, 0x96, - 0x98, 0xc6, 0xa6, 0xb1, 0xb3, 0xe2, 0xe1, 0x97, 0xed, 0xc3, 0x7a, 0x55, 0x41, 0xc6, 0x82, 0x4b, - 0x46, 0xbe, 0x82, 0x95, 0x58, 0x5f, 0x9a, 0xc6, 0xe6, 0xc2, 0xce, 0x6a, 0xfb, 0x23, 0xa7, 0x9c, - 0x0a, 0xa7, 0xa4, 0xaa, 0x35, 0x3b, 0x8b, 0x2f, 0x5e, 0xb7, 0xe6, 0xbc, 0xb1, 0xb6, 0xed, 0x43, - 0xa3, 0x84, 0xfc, 0x3a, 0x15, 0x09, 0xd3, 0xcc, 0xbe, 0x04, 0x18, 0x87, 0xa1, 0xd8, 0xad, 0xb6, - 0xb7, 0x9c, 0x3c, 0x66, 0x27, 0x8b, 0xd9, 0xc9, 0x8b, 0x81, 0x31, 0x3b, 0x07, 0x74, 0xa8, 0x75, - 0xbd, 0x09, 0x4d, 0xfb, 0x77, 0x03, 0xac, 0x69, 0x5e, 0x30, 0x9c, 0xcf, 0xeb, 0xe1, 0x98, 0xd5, - 0x70, 0xb4, 0x66, 0x2d, 0x02, 0x72, 0xbf, 0x44, 0x72, 0x5e, 0x91, 0xdc, 0x9e, 0x49, 0x32, 0x77, - 0x5d, 0x62, 0xf9, 0x13, 0x5c, 0xa9, 0x24, 0x2d, 0xcf, 0x42, 0x17, 0x16, 0x63, 0x1a, 0x60, 0x75, - 0x3a, 0x9f, 0x66, 0xfe, 0x5f, 0xbd, 0x6e, 0xed, 0x0e, 0x83, 0xf4, 0x70, 0xd4, 0x77, 0x7c, 0x11, - 0xb9, 0x0f, 0x14, 0xd7, 0xbd, 0x43, 0x1a, 0x70, 0x17, 0xbb, 0xe9, 0x47, 0xd7, 0x17, 0x51, 0x24, - 0xb8, 0x4b, 0xa5, 0x64, 0xa9, 0x73, 0x40, 0x83, 0xc4, 0x53, 0x66, 0x26, 0xca, 0x3d, 0x5f, 0x2a, - 0xf7, 0xab, 0xf9, 0x4a, 0x83, 0x14, 0xf9, 0xf9, 0x0c, 0x96, 0x75, 0xb8, 0x58, 0x84, 0x59, 0xe9, - 0x29, 0xf0, 0xe4, 0x07, 0x78, 0x5f, 0x9f, 0x7b, 0x5c, 0x64, 0x3f, 0x34, 0xcc, 0x1d, 0x77, 0x1c, - 0x8c, 0x64, 0x6b, 0x22, 0x12, 0xec, 0xe7, 0xfc, 0xe7, 0x8e, 0x1c, 0x3c, 0x72, 0xd3, 0x27, 0x31, - 0x93, 0xce, 0x3e, 0xf3, 0xbd, 0x4b, 0xda, 0xd0, 0x03, 0xb4, 0x43, 0xbe, 0x81, 0xb5, 0x11, 0x4f, - 0x18, 0x0d, 0x83, 0xa7, 0x6c, 0xd0, 0x8b, 0x79, 0x68, 0x2e, 0xbc, 0x93, 0xe5, 0x0b, 0x63, 0x2b, - 0x07, 0x3c, 0x24, 0x0f, 0xe1, 0x7c, 0x44, 0x93, 0x61, 0xc0, 0x7b, 0x49, 0x56, 0x19, 0x73, 0xf1, - 0x9d, 0x8c, 0xae, 0xe6, 0x36, 0xbc, 0xcc, 0x84, 0xbd, 0x81, 0x0d, 0xd8, 0x15, 0x83, 0x51, 0xc8, - 0xee, 0xf9, 0xbe, 0x18, 0xf1, 0x54, 0x4f, 0xa0, 0xed, 0xc3, 0xb5, 0xa9, 0x52, 0xcc, 0xff, 0x3e, - 0x2c, 0x53, 0xbc, 0xc3, 0xf6, 0xb4, 0xab, 0xf9, 0x47, 0x9d, 0x6f, 0x83, 0xf4, 0xb0, 0x43, 0x43, - 0xca, 0x7d, 0x3d, 0x6a, 0x85, 0xa6, 0xfd, 0x87, 0x01, 0xa4, 0x0e, 0x23, 0x04, 0x16, 0x39, 0x8d, - 0x18, 0xce, 0xbe, 0x3a, 0x13, 0x13, 0xce, 0xd1, 0xc1, 0x20, 0x61, 0x52, 0x62, 0x8f, 0xe8, 0x4f, - 0xc2, 0xe0, 0x5c, 0x3f, 0x57, 0x34, 0x17, 0x14, 0x93, 0x46, 0xa9, 0xd3, 0x75, 0x8f, 0xef, 0x89, - 0x80, 0x77, 0x3e, 0xce, 0x08, 0xfc, 0xf9, 0x6f, 0x6b, 0xe7, 0x0c, 0x09, 0xcb, 0x14, 0xa4, 0xa7, - 0x6d, 0xdb, 0x1c, 0x56, 0xee, 0x45, 0x51, 0x97, 0x26, 0x8f, 0x58, 0x4a, 0x3e, 0x81, 0xa5, 0x48, - 0x9d, 0xb0, 0xf9, 0xd6, 0xab, 0xc1, 0xe7, 0x38, 0x0c, 0x18, 0xb1, 0xe4, 0x36, 0x2c, 0xd0, 0x28, - 0xc2, 0x79, 0xbc, 0x5c, 0xcb, 0x57, 0xb7, 0x8b, 0xf8, 0x0c, 0x65, 0xdf, 0x85, 0xcb, 0x79, 0x01, - 0x94, 0x6e, 0xb1, 0x19, 0x37, 0x60, 0xe5, 0x88, 0x25, 0x32, 0x10, 0x9c, 0x0d, 0x94, 0xf3, 0x65, - 0x6f, 0x7c, 0x61, 0x7f, 0x87, 0xf3, 0x5a, 0x28, 0x61, 0xb9, 0xbe, 0x80, 0x55, 0x1a, 0x45, 0xbd, - 0x9c, 0x87, 0xae, 0x58, 0xa3, 0xc6, 0x40, 0xc7, 0x87, 0x3c, 0x80, 0xea, 0x0b, 0x69, 0x9b, 0xb8, - 0x79, 0xf7, 0x44, 0x18, 0xd2, 0x94, 0x25, 0x34, 0xd4, 0x9d, 0xb2, 0x0f, 0x57, 0x6b, 0x12, 0x74, - 0x7b, 0x13, 0x2e, 0xf9, 0xc5, 0x6d, 0x6f, 0xc0, 0xb8, 0x88, 0xb0, 0xa8, 0x17, 0xc7, 0xf7, 0xfb, - 0xd9, 0x75, 0xfb, 0xaf, 0x25, 0x78, 0x4f, 0x99, 0x21, 0x3f, 0xc3, 0x85, 0xd2, 0xcc, 0x93, 0x1b, - 0x33, 0xf6, 0xb8, 0xa2, 0x61, 0x9d, 0x6d, 0xdb, 0xdb, 0x9b, 0xcf, 0xfe, 0xfe, 0xff, 0xf9, 0xbc, - 0x45, 0x4c, 0xb7, 0xf2, 0xc6, 0x15, 0xeb, 0xe1, 0x99, 0x01, 0x6b, 0xe5, 0x47, 0x86, 0x9c, 0x6e, - 0x5b, 0xd7, 0xc6, 0xda, 0x9a, 0x05, 0x43, 0x0e, 0xd7, 0x15, 0x87, 0x6b, 0xa4, 0xf1, 0x36, 0x0e, - 0x92, 0x3c, 0x37, 0x80, 0xd4, 0x9f, 0x07, 0x72, 0xf3, 0x54, 0x0f, 0x93, 0x0f, 0x95, 0x75, 0xeb, - 0x2c, 0x50, 0x24, 0xb4, 0xa5, 0x08, 0x6d, 0x92, 0xe6, 0xdb, 0x08, 0xf5, 0xa4, 0x72, 0xff, 0x9b, - 0x01, 0x6b, 0xe5, 0x85, 0x40, 0xa6, 0xbb, 0x99, 0xba, 0x53, 0xac, 0xdb, 0x67, 0xc2, 0x22, 0xa7, - 0x6d, 0xc5, 0xe9, 0x3a, 0x69, 0x55, 0x39, 0x45, 0x0a, 0xdf, 0xd3, 0x4b, 0x84, 0x3c, 0x85, 0xf3, - 0x93, 0x3d, 0x4f, 0x3e, 0x9c, 0xee, 0xa5, 0x34, 0x46, 0xd6, 0x8d, 0xd3, 0x41, 0xc8, 0xa1, 0xa5, - 0x38, 0x34, 0xc8, 0xd5, 0x1a, 0x07, 0xf4, 0xf5, 0x8b, 0x01, 0x17, 0x2b, 0xcd, 0x4f, 0xa6, 0x77, - 0x41, 0x6d, 0x6e, 0xac, 0xed, 0x99, 0x38, 0x64, 0x61, 0x2b, 0x16, 0x1b, 0xc4, 0xaa, 0xb2, 0x18, - 0xcf, 0x50, 0xe7, 0xfe, 0x8b, 0xe3, 0xa6, 0xf1, 0xf2, 0xb8, 0x69, 0xfc, 0x77, 0xdc, 0x34, 0x7e, - 0x3d, 0x69, 0xce, 0xbd, 0x3c, 0x69, 0xce, 0xfd, 0x73, 0xd2, 0x9c, 0xfb, 0xfe, 0xce, 0xac, 0x47, - 0x59, 0x5b, 0x53, 0x5b, 0xaf, 0xbf, 0xa4, 0xfe, 0x99, 0xdd, 0x7d, 0x13, 0x00, 0x00, 0xff, 0xff, - 0x87, 0x56, 0xd6, 0x1b, 0x63, 0x0a, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // QueryPosition: Query one position on the given market for a user - QueryPosition(ctx context.Context, in *QueryPositionRequest, opts ...grpc.CallOption) (*QueryPositionResponse, error) - // QueryPositions: Query all positions for a user - QueryPositions(ctx context.Context, in *QueryPositionsRequest, opts ...grpc.CallOption) (*QueryPositionsResponse, error) - // QueryPositionStore queries all of the positions in the KV store. - QueryPositionStore(ctx context.Context, in *QueryPositionStoreRequest, opts ...grpc.CallOption) (*QueryPositionStoreResponse, error) - // Queries the module accounts for x/perp - ModuleAccounts(ctx context.Context, in *QueryModuleAccountsRequest, opts ...grpc.CallOption) (*QueryModuleAccountsResponse, error) - // QueryMarkets: Query all markets - QueryMarkets(ctx context.Context, in *QueryMarketsRequest, opts ...grpc.CallOption) (*QueryMarketsResponse, error) - // QueryCollateral: Queries info about the collateral - QueryCollateral(ctx context.Context, in *QueryCollateralRequest, opts ...grpc.CallOption) (*QueryCollateralResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) QueryPosition(ctx context.Context, in *QueryPositionRequest, opts ...grpc.CallOption) (*QueryPositionResponse, error) { - out := new(QueryPositionResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Query/QueryPosition", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) QueryPositions(ctx context.Context, in *QueryPositionsRequest, opts ...grpc.CallOption) (*QueryPositionsResponse, error) { - out := new(QueryPositionsResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Query/QueryPositions", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) QueryPositionStore(ctx context.Context, in *QueryPositionStoreRequest, opts ...grpc.CallOption) (*QueryPositionStoreResponse, error) { - out := new(QueryPositionStoreResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Query/QueryPositionStore", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) ModuleAccounts(ctx context.Context, in *QueryModuleAccountsRequest, opts ...grpc.CallOption) (*QueryModuleAccountsResponse, error) { - out := new(QueryModuleAccountsResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Query/ModuleAccounts", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) QueryMarkets(ctx context.Context, in *QueryMarketsRequest, opts ...grpc.CallOption) (*QueryMarketsResponse, error) { - out := new(QueryMarketsResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Query/QueryMarkets", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) QueryCollateral(ctx context.Context, in *QueryCollateralRequest, opts ...grpc.CallOption) (*QueryCollateralResponse, error) { - out := new(QueryCollateralResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Query/QueryCollateral", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // QueryPosition: Query one position on the given market for a user - QueryPosition(context.Context, *QueryPositionRequest) (*QueryPositionResponse, error) - // QueryPositions: Query all positions for a user - QueryPositions(context.Context, *QueryPositionsRequest) (*QueryPositionsResponse, error) - // QueryPositionStore queries all of the positions in the KV store. - QueryPositionStore(context.Context, *QueryPositionStoreRequest) (*QueryPositionStoreResponse, error) - // Queries the module accounts for x/perp - ModuleAccounts(context.Context, *QueryModuleAccountsRequest) (*QueryModuleAccountsResponse, error) - // QueryMarkets: Query all markets - QueryMarkets(context.Context, *QueryMarketsRequest) (*QueryMarketsResponse, error) - // QueryCollateral: Queries info about the collateral - QueryCollateral(context.Context, *QueryCollateralRequest) (*QueryCollateralResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) QueryPosition(ctx context.Context, req *QueryPositionRequest) (*QueryPositionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method QueryPosition not implemented") -} -func (*UnimplementedQueryServer) QueryPositions(ctx context.Context, req *QueryPositionsRequest) (*QueryPositionsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method QueryPositions not implemented") -} -func (*UnimplementedQueryServer) QueryPositionStore(ctx context.Context, req *QueryPositionStoreRequest) (*QueryPositionStoreResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method QueryPositionStore not implemented") -} -func (*UnimplementedQueryServer) ModuleAccounts(ctx context.Context, req *QueryModuleAccountsRequest) (*QueryModuleAccountsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ModuleAccounts not implemented") -} -func (*UnimplementedQueryServer) QueryMarkets(ctx context.Context, req *QueryMarketsRequest) (*QueryMarketsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method QueryMarkets not implemented") -} -func (*UnimplementedQueryServer) QueryCollateral(ctx context.Context, req *QueryCollateralRequest) (*QueryCollateralResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method QueryCollateral not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_QueryPosition_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryPositionRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).QueryPosition(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Query/QueryPosition", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).QueryPosition(ctx, req.(*QueryPositionRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_QueryPositions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryPositionsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).QueryPositions(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Query/QueryPositions", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).QueryPositions(ctx, req.(*QueryPositionsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_QueryPositionStore_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryPositionStoreRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).QueryPositionStore(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Query/QueryPositionStore", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).QueryPositionStore(ctx, req.(*QueryPositionStoreRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_ModuleAccounts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryModuleAccountsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).ModuleAccounts(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Query/ModuleAccounts", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).ModuleAccounts(ctx, req.(*QueryModuleAccountsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_QueryMarkets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryMarketsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).QueryMarkets(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Query/QueryMarkets", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).QueryMarkets(ctx, req.(*QueryMarketsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_QueryCollateral_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryCollateralRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).QueryCollateral(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Query/QueryCollateral", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).QueryCollateral(ctx, req.(*QueryCollateralRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "nibiru.perp.v2.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "QueryPosition", - Handler: _Query_QueryPosition_Handler, - }, - { - MethodName: "QueryPositions", - Handler: _Query_QueryPositions_Handler, - }, - { - MethodName: "QueryPositionStore", - Handler: _Query_QueryPositionStore_Handler, - }, - { - MethodName: "ModuleAccounts", - Handler: _Query_ModuleAccounts_Handler, - }, - { - MethodName: "QueryMarkets", - Handler: _Query_QueryMarkets_Handler, - }, - { - MethodName: "QueryCollateral", - Handler: _Query_QueryCollateral_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "nibiru/perp/v2/query.proto", -} - -func (m *QueryPositionsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryPositionsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPositionsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Trader) > 0 { - i -= len(m.Trader) - copy(dAtA[i:], m.Trader) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Trader))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryPositionsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryPositionsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPositionsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Positions) > 0 { - for iNdEx := len(m.Positions) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Positions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryPositionStoreRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryPositionStoreRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPositionStoreRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryPositionStoreResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryPositionStoreResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPositionStoreResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Positions) > 0 { - for iNdEx := len(m.Positions) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Positions[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryPositionRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryPositionRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPositionRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Trader) > 0 { - i -= len(m.Trader) - copy(dAtA[i:], m.Trader) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Trader))) - i-- - dAtA[i] = 0x12 - } - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryPositionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryPositionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPositionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.MarginRatio.Size() - i -= size - if _, err := m.MarginRatio.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.UnrealizedPnl.Size() - i -= size - if _, err := m.UnrealizedPnl.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.PositionNotional.Size() - i -= size - if _, err := m.PositionNotional.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.Position.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryModuleAccountsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryModuleAccountsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryModuleAccountsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryModuleAccountsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryModuleAccountsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryModuleAccountsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Accounts) > 0 { - for iNdEx := len(m.Accounts) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Accounts[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *AccountWithBalance) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AccountWithBalance) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AccountWithBalance) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Balance) > 0 { - for iNdEx := len(m.Balance) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Balance[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0x12 - } - if len(m.Name) > 0 { - i -= len(m.Name) - copy(dAtA[i:], m.Name) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Name))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *AmmMarket) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AmmMarket) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AmmMarket) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Amm.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.Market.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryMarketsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryMarketsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryMarketsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Versioned { - i-- - if m.Versioned { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryMarketsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryMarketsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryMarketsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.AmmMarkets) > 0 { - for iNdEx := len(m.AmmMarkets) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AmmMarkets[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryCollateralRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryCollateralRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCollateralRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryCollateralResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryCollateralResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCollateralResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CollateralDenom) > 0 { - i -= len(m.CollateralDenom) - copy(dAtA[i:], m.CollateralDenom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CollateralDenom))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryPositionsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Trader) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryPositionsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Positions) > 0 { - for _, e := range m.Positions { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryPositionStoreRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryPositionStoreResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Positions) > 0 { - for _, e := range m.Positions { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryPositionRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Pair.Size() - n += 1 + l + sovQuery(uint64(l)) - l = len(m.Trader) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryPositionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Position.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.PositionNotional.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.UnrealizedPnl.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.MarginRatio.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryModuleAccountsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryModuleAccountsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Accounts) > 0 { - for _, e := range m.Accounts { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *AccountWithBalance) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Name) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.Balance) > 0 { - for _, e := range m.Balance { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *AmmMarket) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Market.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.Amm.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryMarketsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Versioned { - n += 2 - } - return n -} - -func (m *QueryMarketsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.AmmMarkets) > 0 { - for _, e := range m.AmmMarkets { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryCollateralRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryCollateralResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CollateralDenom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryPositionsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryPositionsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPositionsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Trader", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Trader = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryPositionsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryPositionsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPositionsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Positions", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Positions = append(m.Positions, QueryPositionResponse{}) - if err := m.Positions[len(m.Positions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryPositionStoreRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryPositionStoreRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPositionStoreRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryPositionStoreResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryPositionStoreResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPositionStoreResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Positions", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Positions = append(m.Positions, Position{}) - if err := m.Positions[len(m.Positions)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryPositionRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryPositionRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPositionRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Trader", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Trader = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryPositionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryPositionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPositionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Position", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Position.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PositionNotional", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.PositionNotional.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UnrealizedPnl", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.UnrealizedPnl.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarginRatio", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MarginRatio.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryModuleAccountsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryModuleAccountsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryModuleAccountsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryModuleAccountsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryModuleAccountsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryModuleAccountsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Accounts", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Accounts = append(m.Accounts, AccountWithBalance{}) - if err := m.Accounts[len(m.Accounts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *AccountWithBalance) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AccountWithBalance: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AccountWithBalance: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Balance", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Balance = append(m.Balance, types.Coin{}) - if err := m.Balance[len(m.Balance)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *AmmMarket) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AmmMarket: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AmmMarket: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Market", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Market.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amm", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amm.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryMarketsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryMarketsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryMarketsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Versioned", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Versioned = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryMarketsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryMarketsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryMarketsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AmmMarkets", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AmmMarkets = append(m.AmmMarkets, AmmMarket{}) - if err := m.AmmMarkets[len(m.AmmMarkets)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryCollateralRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryCollateralRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCollateralRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryCollateralResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryCollateralResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCollateralResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CollateralDenom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CollateralDenom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/perp/v2/types/query.pb.gw.go b/x/perp/v2/types/query.pb.gw.go deleted file mode 100644 index d4ffdef8e..000000000 --- a/x/perp/v2/types/query.pb.gw.go +++ /dev/null @@ -1,550 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: nibiru/perp/v2/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -var ( - filter_Query_QueryPosition_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_QueryPosition_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPositionRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_QueryPosition_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.QueryPosition(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_QueryPosition_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPositionRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_QueryPosition_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.QueryPosition(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_QueryPositions_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_QueryPositions_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPositionsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_QueryPositions_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.QueryPositions(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_QueryPositions_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPositionsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_QueryPositions_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.QueryPositions(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_QueryPositionStore_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_QueryPositionStore_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPositionStoreRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_QueryPositionStore_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.QueryPositionStore(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_QueryPositionStore_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPositionStoreRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_QueryPositionStore_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.QueryPositionStore(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_ModuleAccounts_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryModuleAccountsRequest - var metadata runtime.ServerMetadata - - msg, err := client.ModuleAccounts(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_ModuleAccounts_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryModuleAccountsRequest - var metadata runtime.ServerMetadata - - msg, err := server.ModuleAccounts(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_QueryMarkets_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_QueryMarkets_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryMarketsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_QueryMarkets_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.QueryMarkets(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_QueryMarkets_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryMarketsRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_QueryMarkets_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.QueryMarkets(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_QueryCollateral_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCollateralRequest - var metadata runtime.ServerMetadata - - msg, err := client.QueryCollateral(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_QueryCollateral_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCollateralRequest - var metadata runtime.ServerMetadata - - msg, err := server.QueryCollateral(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_QueryPosition_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_QueryPosition_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_QueryPosition_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_QueryPositions_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_QueryPositions_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_QueryPositions_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_QueryPositionStore_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_QueryPositionStore_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_QueryPositionStore_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_ModuleAccounts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_ModuleAccounts_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ModuleAccounts_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_QueryMarkets_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_QueryMarkets_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_QueryMarkets_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_QueryCollateral_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_QueryCollateral_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_QueryCollateral_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_QueryPosition_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_QueryPosition_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_QueryPosition_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_QueryPositions_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_QueryPositions_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_QueryPositions_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_QueryPositionStore_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_QueryPositionStore_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_QueryPositionStore_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_ModuleAccounts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_ModuleAccounts_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_ModuleAccounts_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_QueryMarkets_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_QueryMarkets_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_QueryMarkets_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_QueryCollateral_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_QueryCollateral_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_QueryCollateral_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_QueryPosition_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"nibiru", "perp", "v2", "position"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_QueryPositions_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"nibiru", "perp", "v2", "positions"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_QueryPositionStore_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"nibiru", "perp", "v2", "position_store"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_ModuleAccounts_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"nibiru", "perp", "v2", "module_accounts"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_QueryMarkets_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"nibiru", "perp", "v2", "markets"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_QueryCollateral_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"nibiru", "perp", "v2", "collateral"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_QueryPosition_0 = runtime.ForwardResponseMessage - - forward_Query_QueryPositions_0 = runtime.ForwardResponseMessage - - forward_Query_QueryPositionStore_0 = runtime.ForwardResponseMessage - - forward_Query_ModuleAccounts_0 = runtime.ForwardResponseMessage - - forward_Query_QueryMarkets_0 = runtime.ForwardResponseMessage - - forward_Query_QueryCollateral_0 = runtime.ForwardResponseMessage -) diff --git a/x/perp/v2/types/snapshot.go b/x/perp/v2/types/snapshot.go deleted file mode 100644 index e7c273b74..000000000 --- a/x/perp/v2/types/snapshot.go +++ /dev/null @@ -1,43 +0,0 @@ -package types - -import ( - fmt "fmt" - time "time" -) - -func (s ReserveSnapshot) Validate() error { - err := s.Amm.Pair.Validate() - if err != nil { - return err - } - - if (s.Amm.BaseReserve.String() == "") || (s.Amm.QuoteReserve.String() == "") { - // prevents panics from usage of 'new(Dec)' or 'sdk.Dec{}' - return fmt.Errorf("nil dec value in snapshot. snapshot: %v", s.String()) - } - - if s.Amm.BaseReserve.IsNegative() { - return fmt.Errorf("base asset reserve from snapshot cannot be negative: %d", s.Amm.BaseReserve) - } - - if s.Amm.QuoteReserve.IsNegative() { - return fmt.Errorf("quote asset reserve from snapshot cannot be negative: %d", s.Amm.QuoteReserve) - } - - if s.Amm.PriceMultiplier.IsNegative() { - return fmt.Errorf("peg multiplier from snapshot cannot be negative: %d", s.Amm.PriceMultiplier) - } - - // -62135596800000 in Unix milliseconds is equivalent to "0001-01-01 00:00:00 +0000 UTC". - // This is the earliest possible value for a ctx.blockTime().UnixMilli() - const earliestMs int64 = -62135596800000 - if s.TimestampMs < earliestMs { - snapshotTime := time.Unix(s.TimestampMs/1e3, s.TimestampMs%1e3).UTC() - earliestTime := time.Unix(earliestMs/1e3, earliestMs%1e3).UTC() - return fmt.Errorf("snapshot time (%s, milli=%v) should not be before "+ - "earliest possible UTC time (%s, milli=%v): ", - snapshotTime, s.TimestampMs, earliestTime, earliestMs) - } - - return nil -} diff --git a/x/perp/v2/types/snapshot_test.go b/x/perp/v2/types/snapshot_test.go deleted file mode 100644 index 6feff3892..000000000 --- a/x/perp/v2/types/snapshot_test.go +++ /dev/null @@ -1,130 +0,0 @@ -package types - -import ( - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/asset" -) - -func TestReserveSnapshot_Validate(t *testing.T) { - validPair := asset.MustNewPair("ubtc:unusd") - invalidPair := asset.NewPair("//ubtc", "unusd") - - validDec := sdk.NewDec(1) - - validTimestamp := time.Now().UnixMilli() - - testCases := []struct { - name string - snapshot ReserveSnapshot - expectErr bool - expectedError string - }{ - { - name: "Valid snapshot", - snapshot: ReserveSnapshot{ - Amm: AMM{ - Pair: validPair, - BaseReserve: validDec, - QuoteReserve: validDec, - PriceMultiplier: validDec, - }, - TimestampMs: validTimestamp, - }, - expectErr: false, - }, - { - name: "Invalid pair", - snapshot: ReserveSnapshot{ - Amm: AMM{ - Pair: invalidPair, - BaseReserve: validDec, - QuoteReserve: validDec, - PriceMultiplier: validDec, - }, - TimestampMs: validTimestamp, - }, - expectErr: true, - }, - { - name: "Missing quote reserve", - snapshot: ReserveSnapshot{ - Amm: AMM{ - Pair: validPair, - BaseReserve: validDec, - PriceMultiplier: validDec, - }, - TimestampMs: validTimestamp, - }, - expectErr: true, - }, - { - name: "Negative base reserve", - snapshot: ReserveSnapshot{ - Amm: AMM{ - Pair: validPair, - BaseReserve: sdk.NewDec(-1), - QuoteReserve: sdk.NewDec(1), - PriceMultiplier: validDec, - }, - TimestampMs: validTimestamp, - }, - expectErr: true, - }, - { - name: "Negative quote reserve", - snapshot: ReserveSnapshot{ - Amm: AMM{ - Pair: validPair, - BaseReserve: sdk.NewDec(1), - QuoteReserve: sdk.NewDec(-1), - PriceMultiplier: validDec, - }, - TimestampMs: validTimestamp, - }, - expectErr: true, - }, - { - name: "Peg multiplier", - snapshot: ReserveSnapshot{ - Amm: AMM{ - Pair: validPair, - BaseReserve: validDec, - QuoteReserve: validDec, - PriceMultiplier: sdk.NewDec(-1), - }, - TimestampMs: validTimestamp, - }, - expectErr: true, - }, - { - name: "low timestamp", - snapshot: ReserveSnapshot{ - Amm: AMM{ - Pair: validPair, - BaseReserve: validDec, - QuoteReserve: validDec, - PriceMultiplier: validDec, - }, - TimestampMs: -62135596800001, - }, - expectErr: true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - err := tc.snapshot.Validate() - if tc.expectErr { - require.Error(t, err) - require.Contains(t, err.Error(), tc.expectedError) - } else { - require.NoError(t, err) - } - }) - } -} diff --git a/x/perp/v2/types/state.pb.go b/x/perp/v2/types/state.pb.go deleted file mode 100644 index de39cd3ea..000000000 --- a/x/perp/v2/types/state.pb.go +++ /dev/null @@ -1,2705 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: nibiru/perp/v2/state.proto - -package types - -import ( - fmt "fmt" - github_com_NibiruChain_nibiru_x_common_asset "github.com/NibiruChain/nibiru/x/common/asset" - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - github_com_cosmos_gogoproto_types "github.com/cosmos/gogoproto/types" - _ "google.golang.org/protobuf/types/known/durationpb" - io "io" - math "math" - math_bits "math/bits" - time "time" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf -var _ = time.Kitchen - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// The direction that the user is trading in -// LONG means the user is going long the base asset (e.g. buy BTC) -// SHORT means the user is shorting the base asset (e.g. sell BTC) -type Direction int32 - -const ( - Direction_DIRECTION_UNSPECIFIED Direction = 0 - Direction_LONG Direction = 1 - Direction_SHORT Direction = 2 -) - -var Direction_name = map[int32]string{ - 0: "DIRECTION_UNSPECIFIED", - 1: "LONG", - 2: "SHORT", -} - -var Direction_value = map[string]int32{ - "DIRECTION_UNSPECIFIED": 0, - "LONG": 1, - "SHORT": 2, -} - -func (x Direction) String() string { - return proto.EnumName(Direction_name, int32(x)) -} - -func (Direction) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_8f4829f34f7b8040, []int{0} -} - -// Enumerates different options of calculating twap. -type TwapCalcOption int32 - -const ( - TwapCalcOption_TWAP_CALC_OPTION_UNSPECIFIED TwapCalcOption = 0 - // Spot price from quote asset reserve / base asset reserve - TwapCalcOption_SPOT TwapCalcOption = 1 - // Swapping with quote assets, output denominated in base assets - TwapCalcOption_QUOTE_ASSET_SWAP TwapCalcOption = 2 - // Swapping with base assets, output denominated in quote assets - TwapCalcOption_BASE_ASSET_SWAP TwapCalcOption = 3 -) - -var TwapCalcOption_name = map[int32]string{ - 0: "TWAP_CALC_OPTION_UNSPECIFIED", - 1: "SPOT", - 2: "QUOTE_ASSET_SWAP", - 3: "BASE_ASSET_SWAP", -} - -var TwapCalcOption_value = map[string]int32{ - "TWAP_CALC_OPTION_UNSPECIFIED": 0, - "SPOT": 1, - "QUOTE_ASSET_SWAP": 2, - "BASE_ASSET_SWAP": 3, -} - -func (x TwapCalcOption) String() string { - return proto.EnumName(TwapCalcOption_name, int32(x)) -} - -func (TwapCalcOption) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_8f4829f34f7b8040, []int{1} -} - -type Market struct { - // the trading pair represented by this market - // always BASE:QUOTE, e.g. BTC:NUSD or ETH:NUSD - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,1,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - // whether or not the market is enabled - Enabled bool `protobuf:"varint,2,opt,name=enabled,proto3" json:"enabled,omitempty"` - // the version of the Market, only one market can exist per pair, when one is closed it cannot be reactivated, - // so a new market must be created, this is the version of the market - Version uint64 `protobuf:"varint,14,opt,name=version,proto3" json:"version,omitempty"` - // the minimum margin ratio which a user must maintain on this market - MaintenanceMarginRatio github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=maintenance_margin_ratio,json=maintenanceMarginRatio,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"maintenance_margin_ratio"` - // the maximum leverage a user is able to be taken on this market - MaxLeverage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=max_leverage,json=maxLeverage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"max_leverage"` - // Latest cumulative premium fraction for a given pair. - // Calculated once per funding rate interval. - // A premium fraction is the difference between mark and index, divided by the - // number of payments per day. (mark - index) / # payments in a day - LatestCumulativePremiumFraction github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=latest_cumulative_premium_fraction,json=latestCumulativePremiumFraction,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"latest_cumulative_premium_fraction"` - // the percentage of the notional given to the exchange when trading - ExchangeFeeRatio github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=exchange_fee_ratio,json=exchangeFeeRatio,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"exchange_fee_ratio"` - // the percentage of the notional transferred to the ecosystem fund when - // trading - EcosystemFundFeeRatio github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=ecosystem_fund_fee_ratio,json=ecosystemFundFeeRatio,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"ecosystem_fund_fee_ratio"` - // the percentage of liquidated position that will be - // given to out as a reward. Half of the liquidation fee is given to the - // liquidator, and the other half is given to the ecosystem fund. - LiquidationFeeRatio github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,8,opt,name=liquidation_fee_ratio,json=liquidationFeeRatio,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"liquidation_fee_ratio"` - // the portion of the position size we try to liquidate if the available - // margin is higher than liquidation fee - PartialLiquidationRatio github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,9,opt,name=partial_liquidation_ratio,json=partialLiquidationRatio,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"partial_liquidation_ratio"` - // specifies the interval on which the funding rate is updated - FundingRateEpochId string `protobuf:"bytes,10,opt,name=funding_rate_epoch_id,json=fundingRateEpochId,proto3" json:"funding_rate_epoch_id,omitempty"` - // amount of time to look back for TWAP calculations - TwapLookbackWindow time.Duration `protobuf:"bytes,11,opt,name=twap_lookback_window,json=twapLookbackWindow,proto3,stdduration" json:"twap_lookback_window"` - // the amount of collateral already credited from the ecosystem fund - PrepaidBadDebt types.Coin `protobuf:"bytes,12,opt,name=prepaid_bad_debt,json=prepaidBadDebt,proto3" json:"prepaid_bad_debt"` - // the maximum funding rate payment per epoch, this represents the maximum - // amount of funding that can be paid out per epoch as a percentage of the - // position size - MaxFundingRate github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,13,opt,name=max_funding_rate,json=maxFundingRate,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec,stdduration" json:"max_funding_rate"` - // the pair of the oracle that is used to determine the index price - // for the market - OraclePair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,15,opt,name=oracle_pair,json=oraclePair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"oracle_pair"` -} - -func (m *Market) Reset() { *m = Market{} } -func (m *Market) String() string { return proto.CompactTextString(m) } -func (*Market) ProtoMessage() {} -func (*Market) Descriptor() ([]byte, []int) { - return fileDescriptor_8f4829f34f7b8040, []int{0} -} -func (m *Market) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Market) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Market.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Market) XXX_Merge(src proto.Message) { - xxx_messageInfo_Market.Merge(m, src) -} -func (m *Market) XXX_Size() int { - return m.Size() -} -func (m *Market) XXX_DiscardUnknown() { - xxx_messageInfo_Market.DiscardUnknown(m) -} - -var xxx_messageInfo_Market proto.InternalMessageInfo - -func (m *Market) GetEnabled() bool { - if m != nil { - return m.Enabled - } - return false -} - -func (m *Market) GetVersion() uint64 { - if m != nil { - return m.Version - } - return 0 -} - -func (m *Market) GetFundingRateEpochId() string { - if m != nil { - return m.FundingRateEpochId - } - return "" -} - -func (m *Market) GetTwapLookbackWindow() time.Duration { - if m != nil { - return m.TwapLookbackWindow - } - return 0 -} - -func (m *Market) GetPrepaidBadDebt() types.Coin { - if m != nil { - return m.PrepaidBadDebt - } - return types.Coin{} -} - -// MarketLastVersion is used to store the last version of the market -type MarketLastVersion struct { - // version of the market - Version uint64 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` -} - -func (m *MarketLastVersion) Reset() { *m = MarketLastVersion{} } -func (m *MarketLastVersion) String() string { return proto.CompactTextString(m) } -func (*MarketLastVersion) ProtoMessage() {} -func (*MarketLastVersion) Descriptor() ([]byte, []int) { - return fileDescriptor_8f4829f34f7b8040, []int{1} -} -func (m *MarketLastVersion) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MarketLastVersion) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MarketLastVersion.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MarketLastVersion) XXX_Merge(src proto.Message) { - xxx_messageInfo_MarketLastVersion.Merge(m, src) -} -func (m *MarketLastVersion) XXX_Size() int { - return m.Size() -} -func (m *MarketLastVersion) XXX_DiscardUnknown() { - xxx_messageInfo_MarketLastVersion.DiscardUnknown(m) -} - -var xxx_messageInfo_MarketLastVersion proto.InternalMessageInfo - -func (m *MarketLastVersion) GetVersion() uint64 { - if m != nil { - return m.Version - } - return 0 -} - -type AMM struct { - // identifies the market this AMM belongs to - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,1,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - // the version of the AMM, only one AMM can exist per pair, when one is closed it cannot be reactivated, - // so a new AMM must be created, this is the version of the AMM - Version uint64 `protobuf:"varint,8,opt,name=version,proto3" json:"version,omitempty"` - // the amount of base reserves this AMM has - BaseReserve github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=base_reserve,json=baseReserve,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"base_reserve"` - // the amount of quote reserves this AMM has - QuoteReserve github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=quote_reserve,json=quoteReserve,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"quote_reserve"` - // sqrt(k) - SqrtDepth github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=sqrt_depth,json=sqrtDepth,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"sqrt_depth"` - // the price multiplier of the dynamic AMM - PriceMultiplier github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=price_multiplier,json=priceMultiplier,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"price_multiplier"` - // Total long refers to the sum of long open notional in base. - TotalLong github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=total_long,json=totalLong,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"total_long"` - // Total short refers to the sum of short open notional in base. - TotalShort github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=total_short,json=totalShort,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"total_short"` - // The settlement price if the AMM is settled. - SettlementPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,9,opt,name=settlement_price,json=settlementPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec,stdduration" json:"settlement_price"` -} - -func (m *AMM) Reset() { *m = AMM{} } -func (m *AMM) String() string { return proto.CompactTextString(m) } -func (*AMM) ProtoMessage() {} -func (*AMM) Descriptor() ([]byte, []int) { - return fileDescriptor_8f4829f34f7b8040, []int{2} -} -func (m *AMM) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AMM) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AMM.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *AMM) XXX_Merge(src proto.Message) { - xxx_messageInfo_AMM.Merge(m, src) -} -func (m *AMM) XXX_Size() int { - return m.Size() -} -func (m *AMM) XXX_DiscardUnknown() { - xxx_messageInfo_AMM.DiscardUnknown(m) -} - -var xxx_messageInfo_AMM proto.InternalMessageInfo - -func (m *AMM) GetVersion() uint64 { - if m != nil { - return m.Version - } - return 0 -} - -type Position struct { - // address identifies the address owner of this position - TraderAddress string `protobuf:"bytes,1,opt,name=trader_address,json=traderAddress,proto3" json:"trader_address,omitempty"` - // pair identifies the pair associated with this position - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,2,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - // the position size - Size_ github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=size,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"size"` - // amount of margin remaining in the position - Margin github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=margin,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"margin"` - // value of position in quote assets when opened - OpenNotional github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=open_notional,json=openNotional,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"open_notional"` - // The most recent cumulative premium fraction this position has. - // Used to calculate the next funding payment. - LatestCumulativePremiumFraction github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=latest_cumulative_premium_fraction,json=latestCumulativePremiumFraction,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"latest_cumulative_premium_fraction"` - // last block number this position was updated - LastUpdatedBlockNumber int64 `protobuf:"varint,7,opt,name=last_updated_block_number,json=lastUpdatedBlockNumber,proto3" json:"last_updated_block_number,omitempty"` -} - -func (m *Position) Reset() { *m = Position{} } -func (m *Position) String() string { return proto.CompactTextString(m) } -func (*Position) ProtoMessage() {} -func (*Position) Descriptor() ([]byte, []int) { - return fileDescriptor_8f4829f34f7b8040, []int{3} -} -func (m *Position) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Position) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Position.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Position) XXX_Merge(src proto.Message) { - xxx_messageInfo_Position.Merge(m, src) -} -func (m *Position) XXX_Size() int { - return m.Size() -} -func (m *Position) XXX_DiscardUnknown() { - xxx_messageInfo_Position.DiscardUnknown(m) -} - -var xxx_messageInfo_Position proto.InternalMessageInfo - -func (m *Position) GetTraderAddress() string { - if m != nil { - return m.TraderAddress - } - return "" -} - -func (m *Position) GetLastUpdatedBlockNumber() int64 { - if m != nil { - return m.LastUpdatedBlockNumber - } - return 0 -} - -// a snapshot of the perp.amm's reserves at a given point in time -type ReserveSnapshot struct { - Amm AMM `protobuf:"bytes,1,opt,name=amm,proto3" json:"amm"` - // milliseconds since unix epoch - TimestampMs int64 `protobuf:"varint,2,opt,name=timestamp_ms,json=timestampMs,proto3" json:"timestamp_ms,omitempty"` -} - -func (m *ReserveSnapshot) Reset() { *m = ReserveSnapshot{} } -func (m *ReserveSnapshot) String() string { return proto.CompactTextString(m) } -func (*ReserveSnapshot) ProtoMessage() {} -func (*ReserveSnapshot) Descriptor() ([]byte, []int) { - return fileDescriptor_8f4829f34f7b8040, []int{4} -} -func (m *ReserveSnapshot) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ReserveSnapshot) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ReserveSnapshot.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *ReserveSnapshot) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReserveSnapshot.Merge(m, src) -} -func (m *ReserveSnapshot) XXX_Size() int { - return m.Size() -} -func (m *ReserveSnapshot) XXX_DiscardUnknown() { - xxx_messageInfo_ReserveSnapshot.DiscardUnknown(m) -} - -var xxx_messageInfo_ReserveSnapshot proto.InternalMessageInfo - -func (m *ReserveSnapshot) GetAmm() AMM { - if m != nil { - return m.Amm - } - return AMM{} -} - -func (m *ReserveSnapshot) GetTimestampMs() int64 { - if m != nil { - return m.TimestampMs - } - return 0 -} - -// DNRAllocation represents a rebates allocation for a given epoch. -type DNRAllocation struct { - // epoch defines the reference epoch for the allocation. - Epoch uint64 `protobuf:"varint,1,opt,name=epoch,proto3" json:"epoch,omitempty"` - // amount of DNR allocated for the epoch. - Amount github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amount,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amount"` -} - -func (m *DNRAllocation) Reset() { *m = DNRAllocation{} } -func (m *DNRAllocation) String() string { return proto.CompactTextString(m) } -func (*DNRAllocation) ProtoMessage() {} -func (*DNRAllocation) Descriptor() ([]byte, []int) { - return fileDescriptor_8f4829f34f7b8040, []int{5} -} -func (m *DNRAllocation) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DNRAllocation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DNRAllocation.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DNRAllocation) XXX_Merge(src proto.Message) { - xxx_messageInfo_DNRAllocation.Merge(m, src) -} -func (m *DNRAllocation) XXX_Size() int { - return m.Size() -} -func (m *DNRAllocation) XXX_DiscardUnknown() { - xxx_messageInfo_DNRAllocation.DiscardUnknown(m) -} - -var xxx_messageInfo_DNRAllocation proto.InternalMessageInfo - -func (m *DNRAllocation) GetEpoch() uint64 { - if m != nil { - return m.Epoch - } - return 0 -} - -func (m *DNRAllocation) GetAmount() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Amount - } - return nil -} - -func init() { - proto.RegisterEnum("nibiru.perp.v2.Direction", Direction_name, Direction_value) - proto.RegisterEnum("nibiru.perp.v2.TwapCalcOption", TwapCalcOption_name, TwapCalcOption_value) - proto.RegisterType((*Market)(nil), "nibiru.perp.v2.Market") - proto.RegisterType((*MarketLastVersion)(nil), "nibiru.perp.v2.MarketLastVersion") - proto.RegisterType((*AMM)(nil), "nibiru.perp.v2.AMM") - proto.RegisterType((*Position)(nil), "nibiru.perp.v2.Position") - proto.RegisterType((*ReserveSnapshot)(nil), "nibiru.perp.v2.ReserveSnapshot") - proto.RegisterType((*DNRAllocation)(nil), "nibiru.perp.v2.DNRAllocation") -} - -func init() { proto.RegisterFile("nibiru/perp/v2/state.proto", fileDescriptor_8f4829f34f7b8040) } - -var fileDescriptor_8f4829f34f7b8040 = []byte{ - // 1197 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x97, 0x4d, 0x6f, 0xdb, 0x46, - 0x13, 0xc7, 0x4d, 0x4b, 0x76, 0xac, 0x95, 0x5f, 0xf4, 0x6c, 0xec, 0x3c, 0x74, 0xf0, 0x40, 0xf6, - 0x23, 0xa0, 0x85, 0x91, 0x22, 0x64, 0xed, 0x9e, 0x82, 0x9e, 0xf4, 0x62, 0xa7, 0x06, 0xf4, 0x16, - 0x4a, 0x6e, 0xd0, 0x20, 0xc5, 0x62, 0x49, 0xae, 0xa9, 0xad, 0x49, 0x2e, 0xb3, 0xbb, 0x94, 0x9d, - 0xf6, 0x1b, 0xf4, 0xd4, 0x63, 0xfb, 0x15, 0xfa, 0x25, 0x7a, 0xcd, 0x31, 0xc7, 0xa2, 0x87, 0xa4, - 0x48, 0x8e, 0xfd, 0x12, 0xc5, 0x2e, 0x29, 0x59, 0x06, 0x8a, 0x36, 0x65, 0x9b, 0x93, 0xb9, 0x1c, - 0xce, 0x6f, 0x86, 0xe3, 0x99, 0xff, 0x50, 0xe0, 0x6e, 0x4c, 0x5d, 0xca, 0x53, 0x3b, 0x21, 0x3c, - 0xb1, 0xa7, 0x47, 0xb6, 0x90, 0x58, 0x12, 0x2b, 0xe1, 0x4c, 0x32, 0xb8, 0x99, 0xd9, 0x2c, 0x65, - 0xb3, 0xa6, 0x47, 0x77, 0xb7, 0x03, 0x16, 0x30, 0x6d, 0xb2, 0xd5, 0x55, 0xf6, 0xd4, 0xdd, 0xba, - 0xc7, 0x44, 0xc4, 0x84, 0xed, 0x62, 0x41, 0xec, 0xe9, 0xa1, 0x4b, 0x24, 0x3e, 0xb4, 0x3d, 0x46, - 0xe3, 0xdc, 0xbe, 0x9b, 0xd9, 0x51, 0xe6, 0x98, 0x1d, 0x66, 0xae, 0x01, 0x63, 0x41, 0x48, 0x6c, - 0x7d, 0x72, 0xd3, 0x73, 0xdb, 0x4f, 0x39, 0x96, 0x94, 0xe5, 0xae, 0x8d, 0xdf, 0x2a, 0x60, 0xb5, - 0x87, 0xf9, 0x05, 0x91, 0xb0, 0x07, 0xca, 0x09, 0xa6, 0xdc, 0x34, 0xf6, 0x8d, 0x83, 0x4a, 0xeb, - 0xc1, 0x8b, 0x57, 0x7b, 0x4b, 0xbf, 0xbc, 0xda, 0x3b, 0x0c, 0xa8, 0x9c, 0xa4, 0xae, 0xe5, 0xb1, - 0xc8, 0xee, 0xeb, 0x64, 0xdb, 0x13, 0x4c, 0x63, 0x3b, 0x7f, 0xa9, 0x2b, 0xdb, 0x63, 0x51, 0xc4, - 0x62, 0x1b, 0x0b, 0x41, 0xa4, 0x35, 0xc4, 0x94, 0x3b, 0x1a, 0x03, 0x4d, 0x70, 0x8b, 0xc4, 0xd8, - 0x0d, 0x89, 0x6f, 0x2e, 0xef, 0x1b, 0x07, 0x6b, 0xce, 0xec, 0xa8, 0x2c, 0x53, 0xc2, 0x05, 0x65, - 0xb1, 0xb9, 0xb9, 0x6f, 0x1c, 0x94, 0x9d, 0xd9, 0x11, 0x4e, 0x80, 0x19, 0x61, 0x1a, 0x4b, 0x12, - 0xe3, 0xd8, 0x23, 0x28, 0xc2, 0x3c, 0xa0, 0x31, 0xd2, 0x09, 0x9b, 0x25, 0x9d, 0x96, 0x95, 0xa7, - 0xf5, 0xe1, 0x42, 0x5a, 0x79, 0x75, 0xb2, 0x3f, 0xf7, 0x85, 0x7f, 0x61, 0xcb, 0xe7, 0x09, 0x11, - 0x56, 0x87, 0x78, 0xce, 0x9d, 0x05, 0x5e, 0x4f, 0xe3, 0x1c, 0x45, 0x83, 0x8f, 0xc0, 0x7a, 0x84, - 0xaf, 0x50, 0x48, 0xa6, 0x84, 0xe3, 0x80, 0x98, 0xe5, 0x42, 0xf4, 0x6a, 0x84, 0xaf, 0xba, 0x39, - 0x02, 0x7e, 0x03, 0x1a, 0x21, 0x96, 0x44, 0x48, 0xe4, 0xa5, 0x51, 0x1a, 0x62, 0x49, 0xa7, 0x04, - 0x25, 0x9c, 0x44, 0x34, 0x8d, 0xd0, 0x39, 0xc7, 0x9e, 0x2a, 0xbb, 0xb9, 0x52, 0x28, 0xd0, 0x5e, - 0x46, 0x6e, 0xcf, 0xc1, 0xc3, 0x8c, 0x7b, 0x92, 0x63, 0xe1, 0x53, 0x00, 0xc9, 0x95, 0x37, 0xc1, - 0x71, 0x40, 0xd0, 0x39, 0x21, 0x79, 0xcd, 0x56, 0x0b, 0x05, 0xab, 0xcd, 0x48, 0x27, 0x84, 0x64, - 0xd5, 0x0a, 0x80, 0x49, 0x3c, 0x26, 0x9e, 0x0b, 0x49, 0x22, 0x74, 0x9e, 0xc6, 0xfe, 0x42, 0x8c, - 0x5b, 0x85, 0x62, 0xec, 0xcc, 0x79, 0x27, 0x69, 0xec, 0xcf, 0x03, 0xb9, 0x60, 0x27, 0xa4, 0xcf, - 0x52, 0xea, 0xeb, 0x1e, 0x5d, 0x88, 0xb2, 0x56, 0x28, 0xca, 0xed, 0x05, 0xd8, 0x3c, 0xc6, 0x57, - 0x60, 0x37, 0xc1, 0x5c, 0x52, 0x1c, 0xa2, 0xc5, 0x58, 0x59, 0x9c, 0x4a, 0xa1, 0x38, 0xff, 0xcd, - 0x81, 0xdd, 0x6b, 0x5e, 0x16, 0xeb, 0x10, 0xec, 0xa8, 0x72, 0xd1, 0x38, 0x50, 0x7c, 0x82, 0x48, - 0xc2, 0xbc, 0x09, 0xa2, 0xbe, 0x09, 0x54, 0x1c, 0x07, 0xe6, 0x46, 0x07, 0x4b, 0x72, 0xac, 0x4c, - 0xa7, 0x3e, 0x3c, 0x03, 0xdb, 0xf2, 0x12, 0x27, 0x28, 0x64, 0xec, 0xc2, 0xc5, 0xde, 0x05, 0xba, - 0xa4, 0xb1, 0xcf, 0x2e, 0xcd, 0xea, 0xbe, 0x71, 0x50, 0x3d, 0xda, 0xb5, 0xb2, 0x81, 0xb6, 0x66, - 0x03, 0x6d, 0x75, 0xf2, 0x81, 0x6e, 0xad, 0xa9, 0xa4, 0xbf, 0x7f, 0xbd, 0x67, 0x38, 0x50, 0x01, - 0xba, 0xb9, 0xff, 0x63, 0xed, 0x0e, 0x4f, 0x41, 0x2d, 0xe1, 0x24, 0xc1, 0xd4, 0x47, 0x2e, 0xf6, - 0x91, 0x4f, 0x5c, 0x69, 0xae, 0xe7, 0xc8, 0x5c, 0x31, 0x94, 0xbc, 0x58, 0xb9, 0xbc, 0x58, 0x6d, - 0x46, 0xe3, 0x56, 0x59, 0x21, 0x9d, 0xcd, 0xdc, 0xb1, 0x85, 0xfd, 0x0e, 0x71, 0x25, 0x7c, 0x0a, - 0x6a, 0x6a, 0x76, 0x16, 0x5f, 0xcc, 0xdc, 0xd0, 0x75, 0x3b, 0xfa, 0x7b, 0x75, 0xd3, 0xc9, 0x6e, - 0x46, 0xf8, 0xea, 0xe4, 0xba, 0x0c, 0xf0, 0x09, 0xa8, 0x32, 0x8e, 0xbd, 0x90, 0x20, 0xad, 0x46, - 0x5b, 0xff, 0x54, 0x8d, 0x40, 0x46, 0x53, 0xd7, 0x8d, 0xfb, 0xe0, 0x3f, 0x99, 0xd8, 0x75, 0xb1, - 0x90, 0x9f, 0xe7, 0xa2, 0xb3, 0x20, 0x47, 0xc6, 0x0d, 0x39, 0x6a, 0xfc, 0xb4, 0x02, 0x4a, 0xcd, - 0x5e, 0xef, 0x3d, 0x28, 0xe3, 0x2c, 0xe0, 0xda, 0x4d, 0xfd, 0x7b, 0x04, 0xd6, 0xd5, 0x3f, 0x01, - 0x71, 0x22, 0x08, 0x9f, 0x12, 0x2d, 0x9c, 0x05, 0x54, 0x49, 0x31, 0x9c, 0x0c, 0x01, 0x47, 0x60, - 0xe3, 0x59, 0xca, 0xe4, 0x35, 0xb3, 0x98, 0x8e, 0xae, 0x6b, 0xc8, 0x0c, 0xda, 0x03, 0x40, 0x3c, - 0xe3, 0x12, 0xf9, 0x24, 0x91, 0x93, 0x82, 0xda, 0x59, 0x51, 0x84, 0x8e, 0x02, 0xc0, 0x2f, 0x54, - 0x6f, 0x52, 0x25, 0xf8, 0x69, 0x28, 0x69, 0x12, 0x52, 0xc2, 0x0b, 0xea, 0xe4, 0x96, 0xe6, 0xf4, - 0xe6, 0x18, 0x95, 0xa9, 0x64, 0x52, 0x8d, 0x3a, 0x8b, 0x83, 0x82, 0x7a, 0x58, 0xd1, 0x84, 0x2e, - 0x8b, 0x03, 0x38, 0x00, 0xd5, 0x0c, 0x27, 0x26, 0x8c, 0xcb, 0x82, 0xda, 0x97, 0x65, 0x34, 0x52, - 0x04, 0xf8, 0x25, 0xa8, 0x09, 0x22, 0x65, 0x48, 0x22, 0x12, 0x4b, 0xa4, 0xb3, 0xcf, 0x35, 0xa8, - 0xc8, 0x2c, 0x6d, 0x5d, 0xb3, 0x86, 0x0a, 0xd5, 0xf8, 0xa1, 0x0c, 0xd6, 0x86, 0x4c, 0x50, 0xbd, - 0x23, 0x3e, 0x00, 0x9b, 0x92, 0x63, 0x9f, 0x70, 0x84, 0x7d, 0x9f, 0x13, 0x21, 0xb2, 0x86, 0x76, - 0x36, 0xb2, 0xbb, 0xcd, 0xec, 0xe6, 0xbc, 0xdb, 0x97, 0xff, 0x9d, 0x6e, 0x6f, 0x81, 0xb2, 0xa0, - 0x5f, 0x17, 0xed, 0x3b, 0xed, 0x0b, 0x4f, 0xc0, 0x6a, 0xf6, 0x2d, 0x50, 0xb0, 0xd7, 0x72, 0x6f, - 0x35, 0x0c, 0x2c, 0x21, 0x31, 0x8a, 0x99, 0x2a, 0x08, 0x0e, 0x0b, 0x76, 0xd9, 0xba, 0x82, 0xf4, - 0x73, 0xc6, 0x3b, 0xee, 0xfd, 0xd5, 0xf7, 0xb3, 0xf7, 0x1f, 0x80, 0xdd, 0x10, 0x0b, 0x89, 0xd2, - 0xc4, 0xc7, 0x92, 0xf8, 0xc8, 0x0d, 0x99, 0x77, 0x81, 0xe2, 0x34, 0x72, 0x09, 0xd7, 0xed, 0x59, - 0x72, 0xee, 0xa8, 0x07, 0xce, 0x32, 0x7b, 0x4b, 0x99, 0xfb, 0xda, 0xda, 0xc0, 0x60, 0x2b, 0x9f, - 0xe7, 0x51, 0x8c, 0x13, 0x31, 0x61, 0x12, 0x7e, 0x04, 0x4a, 0x38, 0x8a, 0x74, 0x5b, 0x54, 0x8f, - 0x6e, 0x5b, 0x37, 0x3f, 0x4e, 0xad, 0x66, 0xaf, 0x97, 0x6f, 0x04, 0xf5, 0x14, 0xfc, 0x3f, 0x58, - 0x97, 0x34, 0x22, 0x42, 0xe2, 0x28, 0x41, 0x91, 0xd0, 0xfd, 0x52, 0x72, 0xaa, 0xf3, 0x7b, 0x3d, - 0xd1, 0xf8, 0xd6, 0x00, 0x1b, 0x9d, 0xbe, 0xd3, 0x0c, 0x43, 0xe6, 0xe9, 0x25, 0x05, 0xb7, 0xc1, - 0x8a, 0xde, 0x81, 0xb9, 0xd4, 0x66, 0x07, 0xe8, 0x81, 0x55, 0x1c, 0xb1, 0x34, 0x96, 0xe6, 0xf2, - 0x7e, 0xe9, 0xcf, 0x57, 0xd2, 0xc7, 0x2a, 0x81, 0x1f, 0x5f, 0xef, 0x1d, 0xbc, 0x43, 0x05, 0x95, - 0x83, 0x70, 0x72, 0xf4, 0xbd, 0x4f, 0x41, 0xa5, 0x43, 0x39, 0xc9, 0xea, 0xb6, 0x0b, 0x76, 0x3a, - 0xa7, 0xce, 0x71, 0x7b, 0x7c, 0x3a, 0xe8, 0xa3, 0xb3, 0xfe, 0x68, 0x78, 0xdc, 0x3e, 0x3d, 0x39, - 0x3d, 0xee, 0xd4, 0x96, 0xe0, 0x1a, 0x28, 0x77, 0x07, 0xfd, 0x87, 0x35, 0x03, 0x56, 0xc0, 0xca, - 0xe8, 0xb3, 0x81, 0x33, 0xae, 0x2d, 0xdf, 0x0b, 0xc0, 0xe6, 0xf8, 0x12, 0x27, 0x6d, 0x1c, 0x7a, - 0x83, 0x44, 0x13, 0xf6, 0xc1, 0xff, 0xc6, 0x8f, 0x9b, 0x43, 0xd4, 0x6e, 0x76, 0xdb, 0x68, 0x30, - 0xfc, 0x63, 0xd0, 0x68, 0x38, 0x18, 0xd7, 0x0c, 0xb8, 0x0d, 0x6a, 0x8f, 0xce, 0x06, 0xe3, 0x63, - 0xd4, 0x1c, 0x8d, 0x8e, 0xc7, 0x68, 0xf4, 0xb8, 0x39, 0xac, 0x2d, 0xc3, 0xdb, 0x60, 0xab, 0xd5, - 0x1c, 0xdd, 0xb8, 0x59, 0x6a, 0x3d, 0x7c, 0xf1, 0xa6, 0x6e, 0xbc, 0x7c, 0x53, 0x37, 0x7e, 0x7d, - 0x53, 0x37, 0xbe, 0x7b, 0x5b, 0x5f, 0x7a, 0xf9, 0xb6, 0xbe, 0xf4, 0xf3, 0xdb, 0xfa, 0xd2, 0x93, - 0xfb, 0x7f, 0x35, 0x81, 0xb3, 0x1f, 0x18, 0xfa, 0xe5, 0xdd, 0x55, 0xfd, 0x85, 0xf0, 0xc9, 0xef, - 0x01, 0x00, 0x00, 0xff, 0xff, 0x43, 0xfe, 0x66, 0xfb, 0x7f, 0x0c, 0x00, 0x00, -} - -func (m *Market) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Market) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Market) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.OraclePair.Size() - i -= size - if _, err := m.OraclePair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x7a - if m.Version != 0 { - i = encodeVarintState(dAtA, i, uint64(m.Version)) - i-- - dAtA[i] = 0x70 - } - { - size := m.MaxFundingRate.Size() - i -= size - if _, err := m.MaxFundingRate.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x6a - { - size, err := m.PrepaidBadDebt.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x62 - n2, err2 := github_com_cosmos_gogoproto_types.StdDurationMarshalTo(m.TwapLookbackWindow, dAtA[i-github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TwapLookbackWindow):]) - if err2 != nil { - return 0, err2 - } - i -= n2 - i = encodeVarintState(dAtA, i, uint64(n2)) - i-- - dAtA[i] = 0x5a - if len(m.FundingRateEpochId) > 0 { - i -= len(m.FundingRateEpochId) - copy(dAtA[i:], m.FundingRateEpochId) - i = encodeVarintState(dAtA, i, uint64(len(m.FundingRateEpochId))) - i-- - dAtA[i] = 0x52 - } - { - size := m.PartialLiquidationRatio.Size() - i -= size - if _, err := m.PartialLiquidationRatio.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - { - size := m.LiquidationFeeRatio.Size() - i -= size - if _, err := m.LiquidationFeeRatio.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - { - size := m.EcosystemFundFeeRatio.Size() - i -= size - if _, err := m.EcosystemFundFeeRatio.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size := m.ExchangeFeeRatio.Size() - i -= size - if _, err := m.ExchangeFeeRatio.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size := m.LatestCumulativePremiumFraction.Size() - i -= size - if _, err := m.LatestCumulativePremiumFraction.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.MaxLeverage.Size() - i -= size - if _, err := m.MaxLeverage.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.MaintenanceMarginRatio.Size() - i -= size - if _, err := m.MaintenanceMarginRatio.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if m.Enabled { - i-- - if m.Enabled { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x10 - } - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *MarketLastVersion) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MarketLastVersion) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MarketLastVersion) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Version != 0 { - i = encodeVarintState(dAtA, i, uint64(m.Version)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *AMM) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AMM) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AMM) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.SettlementPrice.Size() - i -= size - if _, err := m.SettlementPrice.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - if m.Version != 0 { - i = encodeVarintState(dAtA, i, uint64(m.Version)) - i-- - dAtA[i] = 0x40 - } - { - size := m.TotalShort.Size() - i -= size - if _, err := m.TotalShort.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size := m.TotalLong.Size() - i -= size - if _, err := m.TotalLong.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size := m.PriceMultiplier.Size() - i -= size - if _, err := m.PriceMultiplier.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.SqrtDepth.Size() - i -= size - if _, err := m.SqrtDepth.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.QuoteReserve.Size() - i -= size - if _, err := m.QuoteReserve.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.BaseReserve.Size() - i -= size - if _, err := m.BaseReserve.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *Position) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Position) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Position) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.LastUpdatedBlockNumber != 0 { - i = encodeVarintState(dAtA, i, uint64(m.LastUpdatedBlockNumber)) - i-- - dAtA[i] = 0x38 - } - { - size := m.LatestCumulativePremiumFraction.Size() - i -= size - if _, err := m.LatestCumulativePremiumFraction.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size := m.OpenNotional.Size() - i -= size - if _, err := m.OpenNotional.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.Margin.Size() - i -= size - if _, err := m.Margin.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.Size_.Size() - i -= size - if _, err := m.Size_.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.TraderAddress) > 0 { - i -= len(m.TraderAddress) - copy(dAtA[i:], m.TraderAddress) - i = encodeVarintState(dAtA, i, uint64(len(m.TraderAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ReserveSnapshot) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ReserveSnapshot) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ReserveSnapshot) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.TimestampMs != 0 { - i = encodeVarintState(dAtA, i, uint64(m.TimestampMs)) - i-- - dAtA[i] = 0x10 - } - { - size, err := m.Amm.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *DNRAllocation) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DNRAllocation) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DNRAllocation) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amount) > 0 { - for iNdEx := len(m.Amount) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amount[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintState(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if m.Epoch != 0 { - i = encodeVarintState(dAtA, i, uint64(m.Epoch)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintState(dAtA []byte, offset int, v uint64) int { - offset -= sovState(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Market) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Pair.Size() - n += 1 + l + sovState(uint64(l)) - if m.Enabled { - n += 2 - } - l = m.MaintenanceMarginRatio.Size() - n += 1 + l + sovState(uint64(l)) - l = m.MaxLeverage.Size() - n += 1 + l + sovState(uint64(l)) - l = m.LatestCumulativePremiumFraction.Size() - n += 1 + l + sovState(uint64(l)) - l = m.ExchangeFeeRatio.Size() - n += 1 + l + sovState(uint64(l)) - l = m.EcosystemFundFeeRatio.Size() - n += 1 + l + sovState(uint64(l)) - l = m.LiquidationFeeRatio.Size() - n += 1 + l + sovState(uint64(l)) - l = m.PartialLiquidationRatio.Size() - n += 1 + l + sovState(uint64(l)) - l = len(m.FundingRateEpochId) - if l > 0 { - n += 1 + l + sovState(uint64(l)) - } - l = github_com_cosmos_gogoproto_types.SizeOfStdDuration(m.TwapLookbackWindow) - n += 1 + l + sovState(uint64(l)) - l = m.PrepaidBadDebt.Size() - n += 1 + l + sovState(uint64(l)) - l = m.MaxFundingRate.Size() - n += 1 + l + sovState(uint64(l)) - if m.Version != 0 { - n += 1 + sovState(uint64(m.Version)) - } - l = m.OraclePair.Size() - n += 1 + l + sovState(uint64(l)) - return n -} - -func (m *MarketLastVersion) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Version != 0 { - n += 1 + sovState(uint64(m.Version)) - } - return n -} - -func (m *AMM) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Pair.Size() - n += 1 + l + sovState(uint64(l)) - l = m.BaseReserve.Size() - n += 1 + l + sovState(uint64(l)) - l = m.QuoteReserve.Size() - n += 1 + l + sovState(uint64(l)) - l = m.SqrtDepth.Size() - n += 1 + l + sovState(uint64(l)) - l = m.PriceMultiplier.Size() - n += 1 + l + sovState(uint64(l)) - l = m.TotalLong.Size() - n += 1 + l + sovState(uint64(l)) - l = m.TotalShort.Size() - n += 1 + l + sovState(uint64(l)) - if m.Version != 0 { - n += 1 + sovState(uint64(m.Version)) - } - l = m.SettlementPrice.Size() - n += 1 + l + sovState(uint64(l)) - return n -} - -func (m *Position) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.TraderAddress) - if l > 0 { - n += 1 + l + sovState(uint64(l)) - } - l = m.Pair.Size() - n += 1 + l + sovState(uint64(l)) - l = m.Size_.Size() - n += 1 + l + sovState(uint64(l)) - l = m.Margin.Size() - n += 1 + l + sovState(uint64(l)) - l = m.OpenNotional.Size() - n += 1 + l + sovState(uint64(l)) - l = m.LatestCumulativePremiumFraction.Size() - n += 1 + l + sovState(uint64(l)) - if m.LastUpdatedBlockNumber != 0 { - n += 1 + sovState(uint64(m.LastUpdatedBlockNumber)) - } - return n -} - -func (m *ReserveSnapshot) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Amm.Size() - n += 1 + l + sovState(uint64(l)) - if m.TimestampMs != 0 { - n += 1 + sovState(uint64(m.TimestampMs)) - } - return n -} - -func (m *DNRAllocation) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Epoch != 0 { - n += 1 + sovState(uint64(m.Epoch)) - } - if len(m.Amount) > 0 { - for _, e := range m.Amount { - l = e.Size() - n += 1 + l + sovState(uint64(l)) - } - } - return n -} - -func sovState(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozState(x uint64) (n int) { - return sovState(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Market) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Market: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Market: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Enabled", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Enabled = bool(v != 0) - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaintenanceMarginRatio", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MaintenanceMarginRatio.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxLeverage", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MaxLeverage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LatestCumulativePremiumFraction", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.LatestCumulativePremiumFraction.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExchangeFeeRatio", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExchangeFeeRatio.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field EcosystemFundFeeRatio", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.EcosystemFundFeeRatio.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LiquidationFeeRatio", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.LiquidationFeeRatio.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PartialLiquidationRatio", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.PartialLiquidationRatio.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FundingRateEpochId", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.FundingRateEpochId = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TwapLookbackWindow", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := github_com_cosmos_gogoproto_types.StdDurationUnmarshal(&m.TwapLookbackWindow, dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 12: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PrepaidBadDebt", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.PrepaidBadDebt.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 13: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxFundingRate", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MaxFundingRate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 14: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) - } - m.Version = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Version |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 15: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OraclePair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OraclePair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipState(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthState - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MarketLastVersion) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MarketLastVersion: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MarketLastVersion: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) - } - m.Version = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Version |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipState(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthState - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *AMM) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AMM: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AMM: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseReserve", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseReserve.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field QuoteReserve", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.QuoteReserve.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SqrtDepth", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SqrtDepth.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PriceMultiplier", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.PriceMultiplier.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalLong", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalLong.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalShort", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalShort.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) - } - m.Version = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Version |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SettlementPrice", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SettlementPrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipState(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthState - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Position) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Position: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Position: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TraderAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TraderAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Size_", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Size_.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Margin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Margin.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OpenNotional", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OpenNotional.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LatestCumulativePremiumFraction", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.LatestCumulativePremiumFraction.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field LastUpdatedBlockNumber", wireType) - } - m.LastUpdatedBlockNumber = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.LastUpdatedBlockNumber |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipState(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthState - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ReserveSnapshot) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ReserveSnapshot: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ReserveSnapshot: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amm", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amm.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TimestampMs", wireType) - } - m.TimestampMs = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TimestampMs |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipState(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthState - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *DNRAllocation) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DNRAllocation: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DNRAllocation: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Epoch", wireType) - } - m.Epoch = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Epoch |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowState - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthState - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthState - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amount = append(m.Amount, types.Coin{}) - if err := m.Amount[len(m.Amount)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipState(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthState - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipState(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowState - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowState - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowState - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthState - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupState - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthState - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthState = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowState = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupState = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/perp/v2/types/tx.pb.go b/x/perp/v2/types/tx.pb.go deleted file mode 100644 index 1a57294d4..000000000 --- a/x/perp/v2/types/tx.pb.go +++ /dev/null @@ -1,8448 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: nibiru/perp/v2/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - github_com_NibiruChain_nibiru_x_common_asset "github.com/NibiruChain/nibiru/x/common/asset" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - grpc1 "github.com/cosmos/gogoproto/grpc" - proto "github.com/cosmos/gogoproto/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -// MsgSettlePosition: Msg to remove margin. -type MsgSettlePosition struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,2,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - Version uint64 `protobuf:"varint,3,opt,name=version,proto3" json:"version,omitempty"` -} - -func (m *MsgSettlePosition) Reset() { *m = MsgSettlePosition{} } -func (m *MsgSettlePosition) String() string { return proto.CompactTextString(m) } -func (*MsgSettlePosition) ProtoMessage() {} -func (*MsgSettlePosition) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{0} -} -func (m *MsgSettlePosition) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSettlePosition) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSettlePosition.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgSettlePosition) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSettlePosition.Merge(m, src) -} -func (m *MsgSettlePosition) XXX_Size() int { - return m.Size() -} -func (m *MsgSettlePosition) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSettlePosition.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSettlePosition proto.InternalMessageInfo - -func (m *MsgSettlePosition) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgSettlePosition) GetVersion() uint64 { - if m != nil { - return m.Version - } - return 0 -} - -// MsgRemoveMargin: Msg to remove margin. -type MsgRemoveMargin struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,2,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - Margin types.Coin `protobuf:"bytes,3,opt,name=margin,proto3" json:"margin"` -} - -func (m *MsgRemoveMargin) Reset() { *m = MsgRemoveMargin{} } -func (m *MsgRemoveMargin) String() string { return proto.CompactTextString(m) } -func (*MsgRemoveMargin) ProtoMessage() {} -func (*MsgRemoveMargin) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{1} -} -func (m *MsgRemoveMargin) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgRemoveMargin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgRemoveMargin.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgRemoveMargin) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgRemoveMargin.Merge(m, src) -} -func (m *MsgRemoveMargin) XXX_Size() int { - return m.Size() -} -func (m *MsgRemoveMargin) XXX_DiscardUnknown() { - xxx_messageInfo_MsgRemoveMargin.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgRemoveMargin proto.InternalMessageInfo - -func (m *MsgRemoveMargin) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgRemoveMargin) GetMargin() types.Coin { - if m != nil { - return m.Margin - } - return types.Coin{} -} - -type MsgRemoveMarginResponse struct { - // tokens transferred back to the trader - MarginOut types.Coin `protobuf:"bytes,1,opt,name=margin_out,json=marginOut,proto3" json:"margin_out"` - // the funding payment applied on this position interaction - FundingPayment github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=funding_payment,json=fundingPayment,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"funding_payment"` - // The resulting position - Position *Position `protobuf:"bytes,3,opt,name=position,proto3" json:"position,omitempty"` -} - -func (m *MsgRemoveMarginResponse) Reset() { *m = MsgRemoveMarginResponse{} } -func (m *MsgRemoveMarginResponse) String() string { return proto.CompactTextString(m) } -func (*MsgRemoveMarginResponse) ProtoMessage() {} -func (*MsgRemoveMarginResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{2} -} -func (m *MsgRemoveMarginResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgRemoveMarginResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgRemoveMarginResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgRemoveMarginResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgRemoveMarginResponse.Merge(m, src) -} -func (m *MsgRemoveMarginResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgRemoveMarginResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgRemoveMarginResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgRemoveMarginResponse proto.InternalMessageInfo - -func (m *MsgRemoveMarginResponse) GetMarginOut() types.Coin { - if m != nil { - return m.MarginOut - } - return types.Coin{} -} - -func (m *MsgRemoveMarginResponse) GetPosition() *Position { - if m != nil { - return m.Position - } - return nil -} - -// MsgAddMargin: Msg to remove margin. -type MsgAddMargin struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,2,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - Margin types.Coin `protobuf:"bytes,3,opt,name=margin,proto3" json:"margin"` -} - -func (m *MsgAddMargin) Reset() { *m = MsgAddMargin{} } -func (m *MsgAddMargin) String() string { return proto.CompactTextString(m) } -func (*MsgAddMargin) ProtoMessage() {} -func (*MsgAddMargin) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{3} -} -func (m *MsgAddMargin) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgAddMargin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgAddMargin.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgAddMargin) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgAddMargin.Merge(m, src) -} -func (m *MsgAddMargin) XXX_Size() int { - return m.Size() -} -func (m *MsgAddMargin) XXX_DiscardUnknown() { - xxx_messageInfo_MsgAddMargin.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgAddMargin proto.InternalMessageInfo - -func (m *MsgAddMargin) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgAddMargin) GetMargin() types.Coin { - if m != nil { - return m.Margin - } - return types.Coin{} -} - -type MsgAddMarginResponse struct { - FundingPayment github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=funding_payment,json=fundingPayment,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"funding_payment"` - Position *Position `protobuf:"bytes,2,opt,name=position,proto3" json:"position,omitempty"` -} - -func (m *MsgAddMarginResponse) Reset() { *m = MsgAddMarginResponse{} } -func (m *MsgAddMarginResponse) String() string { return proto.CompactTextString(m) } -func (*MsgAddMarginResponse) ProtoMessage() {} -func (*MsgAddMarginResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{4} -} -func (m *MsgAddMarginResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgAddMarginResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgAddMarginResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgAddMarginResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgAddMarginResponse.Merge(m, src) -} -func (m *MsgAddMarginResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgAddMarginResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgAddMarginResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgAddMarginResponse proto.InternalMessageInfo - -func (m *MsgAddMarginResponse) GetPosition() *Position { - if m != nil { - return m.Position - } - return nil -} - -type MsgMultiLiquidate struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Liquidations []*MsgMultiLiquidate_Liquidation `protobuf:"bytes,2,rep,name=liquidations,proto3" json:"liquidations,omitempty"` -} - -func (m *MsgMultiLiquidate) Reset() { *m = MsgMultiLiquidate{} } -func (m *MsgMultiLiquidate) String() string { return proto.CompactTextString(m) } -func (*MsgMultiLiquidate) ProtoMessage() {} -func (*MsgMultiLiquidate) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{5} -} -func (m *MsgMultiLiquidate) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMultiLiquidate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMultiLiquidate.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgMultiLiquidate) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMultiLiquidate.Merge(m, src) -} -func (m *MsgMultiLiquidate) XXX_Size() int { - return m.Size() -} -func (m *MsgMultiLiquidate) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMultiLiquidate.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMultiLiquidate proto.InternalMessageInfo - -func (m *MsgMultiLiquidate) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgMultiLiquidate) GetLiquidations() []*MsgMultiLiquidate_Liquidation { - if m != nil { - return m.Liquidations - } - return nil -} - -type MsgMultiLiquidate_Liquidation struct { - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,1,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - Trader string `protobuf:"bytes,2,opt,name=trader,proto3" json:"trader,omitempty"` -} - -func (m *MsgMultiLiquidate_Liquidation) Reset() { *m = MsgMultiLiquidate_Liquidation{} } -func (m *MsgMultiLiquidate_Liquidation) String() string { return proto.CompactTextString(m) } -func (*MsgMultiLiquidate_Liquidation) ProtoMessage() {} -func (*MsgMultiLiquidate_Liquidation) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{5, 0} -} -func (m *MsgMultiLiquidate_Liquidation) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMultiLiquidate_Liquidation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMultiLiquidate_Liquidation.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgMultiLiquidate_Liquidation) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMultiLiquidate_Liquidation.Merge(m, src) -} -func (m *MsgMultiLiquidate_Liquidation) XXX_Size() int { - return m.Size() -} -func (m *MsgMultiLiquidate_Liquidation) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMultiLiquidate_Liquidation.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMultiLiquidate_Liquidation proto.InternalMessageInfo - -func (m *MsgMultiLiquidate_Liquidation) GetTrader() string { - if m != nil { - return m.Trader - } - return "" -} - -type MsgMultiLiquidateResponse struct { - Liquidations []*MsgMultiLiquidateResponse_LiquidationResponse `protobuf:"bytes,1,rep,name=liquidations,proto3" json:"liquidations,omitempty"` -} - -func (m *MsgMultiLiquidateResponse) Reset() { *m = MsgMultiLiquidateResponse{} } -func (m *MsgMultiLiquidateResponse) String() string { return proto.CompactTextString(m) } -func (*MsgMultiLiquidateResponse) ProtoMessage() {} -func (*MsgMultiLiquidateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{6} -} -func (m *MsgMultiLiquidateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMultiLiquidateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMultiLiquidateResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgMultiLiquidateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMultiLiquidateResponse.Merge(m, src) -} -func (m *MsgMultiLiquidateResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgMultiLiquidateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMultiLiquidateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMultiLiquidateResponse proto.InternalMessageInfo - -func (m *MsgMultiLiquidateResponse) GetLiquidations() []*MsgMultiLiquidateResponse_LiquidationResponse { - if m != nil { - return m.Liquidations - } - return nil -} - -type MsgMultiLiquidateResponse_LiquidationResponse struct { - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` - LiquidatorFee *types.Coin `protobuf:"bytes,3,opt,name=liquidator_fee,json=liquidatorFee,proto3" json:"liquidator_fee,omitempty"` - PerpEfFee *types.Coin `protobuf:"bytes,4,opt,name=perp_ef_fee,json=perpEfFee,proto3" json:"perp_ef_fee,omitempty"` - Trader string `protobuf:"bytes,5,opt,name=trader,proto3" json:"trader,omitempty"` - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,6,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` -} - -func (m *MsgMultiLiquidateResponse_LiquidationResponse) Reset() { - *m = MsgMultiLiquidateResponse_LiquidationResponse{} -} -func (m *MsgMultiLiquidateResponse_LiquidationResponse) String() string { - return proto.CompactTextString(m) -} -func (*MsgMultiLiquidateResponse_LiquidationResponse) ProtoMessage() {} -func (*MsgMultiLiquidateResponse_LiquidationResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{6, 0} -} -func (m *MsgMultiLiquidateResponse_LiquidationResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMultiLiquidateResponse_LiquidationResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMultiLiquidateResponse_LiquidationResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgMultiLiquidateResponse_LiquidationResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMultiLiquidateResponse_LiquidationResponse.Merge(m, src) -} -func (m *MsgMultiLiquidateResponse_LiquidationResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgMultiLiquidateResponse_LiquidationResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMultiLiquidateResponse_LiquidationResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMultiLiquidateResponse_LiquidationResponse proto.InternalMessageInfo - -func (m *MsgMultiLiquidateResponse_LiquidationResponse) GetSuccess() bool { - if m != nil { - return m.Success - } - return false -} - -func (m *MsgMultiLiquidateResponse_LiquidationResponse) GetError() string { - if m != nil { - return m.Error - } - return "" -} - -func (m *MsgMultiLiquidateResponse_LiquidationResponse) GetLiquidatorFee() *types.Coin { - if m != nil { - return m.LiquidatorFee - } - return nil -} - -func (m *MsgMultiLiquidateResponse_LiquidationResponse) GetPerpEfFee() *types.Coin { - if m != nil { - return m.PerpEfFee - } - return nil -} - -func (m *MsgMultiLiquidateResponse_LiquidationResponse) GetTrader() string { - if m != nil { - return m.Trader - } - return "" -} - -type MsgMarketOrder struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,2,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - Side Direction `protobuf:"varint,3,opt,name=side,proto3,enum=nibiru.perp.v2.Direction" json:"side,omitempty"` - QuoteAssetAmount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=quote_asset_amount,json=quoteAssetAmount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"quote_asset_amount"` - Leverage github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=leverage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"leverage"` - BaseAssetAmountLimit github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,6,opt,name=base_asset_amount_limit,json=baseAssetAmountLimit,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"base_asset_amount_limit"` -} - -func (m *MsgMarketOrder) Reset() { *m = MsgMarketOrder{} } -func (m *MsgMarketOrder) String() string { return proto.CompactTextString(m) } -func (*MsgMarketOrder) ProtoMessage() {} -func (*MsgMarketOrder) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{7} -} -func (m *MsgMarketOrder) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMarketOrder) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMarketOrder.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgMarketOrder) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMarketOrder.Merge(m, src) -} -func (m *MsgMarketOrder) XXX_Size() int { - return m.Size() -} -func (m *MsgMarketOrder) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMarketOrder.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMarketOrder proto.InternalMessageInfo - -func (m *MsgMarketOrder) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgMarketOrder) GetSide() Direction { - if m != nil { - return m.Side - } - return Direction_DIRECTION_UNSPECIFIED -} - -type MsgMarketOrderResponse struct { - Position *Position `protobuf:"bytes,1,opt,name=position,proto3" json:"position,omitempty"` - // The amount of quote assets exchanged. - ExchangedNotionalValue github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=exchanged_notional_value,json=exchangedNotionalValue,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"exchanged_notional_value"` - // The amount of base assets exchanged. - ExchangedPositionSize github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=exchanged_position_size,json=exchangedPositionSize,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"exchanged_position_size"` - // The funding payment applied on this position change, measured in quote - // units. - FundingPayment github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=funding_payment,json=fundingPayment,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"funding_payment"` - // The amount of PnL realized on this position changed, measured in quote - // units. - RealizedPnl github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=realized_pnl,json=realizedPnl,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"realized_pnl"` - // The unrealized PnL in the position after the position change, measured in - // quote units. - UnrealizedPnlAfter github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=unrealized_pnl_after,json=unrealizedPnlAfter,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"unrealized_pnl_after"` - // The amount of margin the trader has to give to the vault. - // A negative value means the vault pays the trader. - MarginToVault github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=margin_to_vault,json=marginToVault,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"margin_to_vault"` - // The position's notional value after the position change, measured in quote - // units. - PositionNotional github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,8,opt,name=position_notional,json=positionNotional,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"position_notional"` -} - -func (m *MsgMarketOrderResponse) Reset() { *m = MsgMarketOrderResponse{} } -func (m *MsgMarketOrderResponse) String() string { return proto.CompactTextString(m) } -func (*MsgMarketOrderResponse) ProtoMessage() {} -func (*MsgMarketOrderResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{8} -} -func (m *MsgMarketOrderResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgMarketOrderResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMarketOrderResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgMarketOrderResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMarketOrderResponse.Merge(m, src) -} -func (m *MsgMarketOrderResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgMarketOrderResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMarketOrderResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMarketOrderResponse proto.InternalMessageInfo - -func (m *MsgMarketOrderResponse) GetPosition() *Position { - if m != nil { - return m.Position - } - return nil -} - -type MsgClosePosition struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,2,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` -} - -func (m *MsgClosePosition) Reset() { *m = MsgClosePosition{} } -func (m *MsgClosePosition) String() string { return proto.CompactTextString(m) } -func (*MsgClosePosition) ProtoMessage() {} -func (*MsgClosePosition) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{9} -} -func (m *MsgClosePosition) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClosePosition) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClosePosition.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgClosePosition) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClosePosition.Merge(m, src) -} -func (m *MsgClosePosition) XXX_Size() int { - return m.Size() -} -func (m *MsgClosePosition) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClosePosition.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClosePosition proto.InternalMessageInfo - -func (m *MsgClosePosition) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -type MsgClosePositionResponse struct { - // The amount of quote assets exchanged. - ExchangedNotionalValue github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=exchanged_notional_value,json=exchangedNotionalValue,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"exchanged_notional_value"` - // The amount of base assets exchanged. - ExchangedPositionSize github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=exchanged_position_size,json=exchangedPositionSize,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"exchanged_position_size"` - // The funding payment applied on this position change, measured in quote - // units. - FundingPayment github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=funding_payment,json=fundingPayment,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"funding_payment"` - // The amount of PnL realized on this position changed, measured in quote - // units. - RealizedPnl github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=realized_pnl,json=realizedPnl,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"realized_pnl"` - // The amount of margin the trader receives after closing the position, from - // the vault. Should never be negative. - MarginToTrader github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=margin_to_trader,json=marginToTrader,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"margin_to_trader"` -} - -func (m *MsgClosePositionResponse) Reset() { *m = MsgClosePositionResponse{} } -func (m *MsgClosePositionResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClosePositionResponse) ProtoMessage() {} -func (*MsgClosePositionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{10} -} -func (m *MsgClosePositionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgClosePositionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClosePositionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgClosePositionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClosePositionResponse.Merge(m, src) -} -func (m *MsgClosePositionResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgClosePositionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClosePositionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClosePositionResponse proto.InternalMessageInfo - -type MsgPartialClose struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,2,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - Size_ github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=size,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"size"` -} - -func (m *MsgPartialClose) Reset() { *m = MsgPartialClose{} } -func (m *MsgPartialClose) String() string { return proto.CompactTextString(m) } -func (*MsgPartialClose) ProtoMessage() {} -func (*MsgPartialClose) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{11} -} -func (m *MsgPartialClose) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgPartialClose) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgPartialClose.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgPartialClose) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgPartialClose.Merge(m, src) -} -func (m *MsgPartialClose) XXX_Size() int { - return m.Size() -} -func (m *MsgPartialClose) XXX_DiscardUnknown() { - xxx_messageInfo_MsgPartialClose.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgPartialClose proto.InternalMessageInfo - -func (m *MsgPartialClose) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -type MsgPartialCloseResponse struct { - // The amount of quote assets exchanged. - ExchangedNotionalValue github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=exchanged_notional_value,json=exchangedNotionalValue,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"exchanged_notional_value"` - // The amount of base assets exchanged. - ExchangedPositionSize github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=exchanged_position_size,json=exchangedPositionSize,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"exchanged_position_size"` - // The funding payment applied on this position change, measured in quote - // units. - FundingPayment github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=funding_payment,json=fundingPayment,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"funding_payment"` - // The amount of PnL realized on this position changed, measured in quote - // units. - RealizedPnl github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=realized_pnl,json=realizedPnl,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"realized_pnl"` - // The amount of margin the trader receives after closing the position, from - // the vault. Should never be negative. - MarginToTrader github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=margin_to_trader,json=marginToTrader,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"margin_to_trader"` -} - -func (m *MsgPartialCloseResponse) Reset() { *m = MsgPartialCloseResponse{} } -func (m *MsgPartialCloseResponse) String() string { return proto.CompactTextString(m) } -func (*MsgPartialCloseResponse) ProtoMessage() {} -func (*MsgPartialCloseResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{12} -} -func (m *MsgPartialCloseResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgPartialCloseResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgPartialCloseResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgPartialCloseResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgPartialCloseResponse.Merge(m, src) -} -func (m *MsgPartialCloseResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgPartialCloseResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgPartialCloseResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgPartialCloseResponse proto.InternalMessageInfo - -type MsgDonateToEcosystemFund struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // donation to the EF - Donation types.Coin `protobuf:"bytes,2,opt,name=donation,proto3" json:"donation" yaml:"donation"` -} - -func (m *MsgDonateToEcosystemFund) Reset() { *m = MsgDonateToEcosystemFund{} } -func (m *MsgDonateToEcosystemFund) String() string { return proto.CompactTextString(m) } -func (*MsgDonateToEcosystemFund) ProtoMessage() {} -func (*MsgDonateToEcosystemFund) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{13} -} -func (m *MsgDonateToEcosystemFund) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDonateToEcosystemFund) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDonateToEcosystemFund.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDonateToEcosystemFund) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDonateToEcosystemFund.Merge(m, src) -} -func (m *MsgDonateToEcosystemFund) XXX_Size() int { - return m.Size() -} -func (m *MsgDonateToEcosystemFund) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDonateToEcosystemFund.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDonateToEcosystemFund proto.InternalMessageInfo - -func (m *MsgDonateToEcosystemFund) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgDonateToEcosystemFund) GetDonation() types.Coin { - if m != nil { - return m.Donation - } - return types.Coin{} -} - -type MsgDonateToEcosystemFundResponse struct { -} - -func (m *MsgDonateToEcosystemFundResponse) Reset() { *m = MsgDonateToEcosystemFundResponse{} } -func (m *MsgDonateToEcosystemFundResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDonateToEcosystemFundResponse) ProtoMessage() {} -func (*MsgDonateToEcosystemFundResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{14} -} -func (m *MsgDonateToEcosystemFundResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgDonateToEcosystemFundResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDonateToEcosystemFundResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgDonateToEcosystemFundResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDonateToEcosystemFundResponse.Merge(m, src) -} -func (m *MsgDonateToEcosystemFundResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgDonateToEcosystemFundResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDonateToEcosystemFundResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDonateToEcosystemFundResponse proto.InternalMessageInfo - -// MsgChangeCollateralDenom: Changes the collateral denom for the module. -// [SUDO] Only callable by sudoers. -type MsgChangeCollateralDenom struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - NewDenom string `protobuf:"bytes,2,opt,name=new_denom,json=newDenom,proto3" json:"new_denom,omitempty"` -} - -func (m *MsgChangeCollateralDenom) Reset() { *m = MsgChangeCollateralDenom{} } -func (m *MsgChangeCollateralDenom) String() string { return proto.CompactTextString(m) } -func (*MsgChangeCollateralDenom) ProtoMessage() {} -func (*MsgChangeCollateralDenom) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{15} -} -func (m *MsgChangeCollateralDenom) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgChangeCollateralDenom) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgChangeCollateralDenom.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgChangeCollateralDenom) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgChangeCollateralDenom.Merge(m, src) -} -func (m *MsgChangeCollateralDenom) XXX_Size() int { - return m.Size() -} -func (m *MsgChangeCollateralDenom) XXX_DiscardUnknown() { - xxx_messageInfo_MsgChangeCollateralDenom.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgChangeCollateralDenom proto.InternalMessageInfo - -func (m *MsgChangeCollateralDenom) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgChangeCollateralDenom) GetNewDenom() string { - if m != nil { - return m.NewDenom - } - return "" -} - -type MsgChangeCollateralDenomResponse struct { -} - -func (m *MsgChangeCollateralDenomResponse) Reset() { *m = MsgChangeCollateralDenomResponse{} } -func (m *MsgChangeCollateralDenomResponse) String() string { return proto.CompactTextString(m) } -func (*MsgChangeCollateralDenomResponse) ProtoMessage() {} -func (*MsgChangeCollateralDenomResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{16} -} -func (m *MsgChangeCollateralDenomResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgChangeCollateralDenomResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgChangeCollateralDenomResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgChangeCollateralDenomResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgChangeCollateralDenomResponse.Merge(m, src) -} -func (m *MsgChangeCollateralDenomResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgChangeCollateralDenomResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgChangeCollateralDenomResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgChangeCollateralDenomResponse proto.InternalMessageInfo - -// -------------------------- AllocateEpochRebates -------------------------- -type MsgAllocateEpochRebates struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // rebates to allocate - Rebates github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=rebates,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"rebates"` -} - -func (m *MsgAllocateEpochRebates) Reset() { *m = MsgAllocateEpochRebates{} } -func (m *MsgAllocateEpochRebates) String() string { return proto.CompactTextString(m) } -func (*MsgAllocateEpochRebates) ProtoMessage() {} -func (*MsgAllocateEpochRebates) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{17} -} -func (m *MsgAllocateEpochRebates) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgAllocateEpochRebates) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgAllocateEpochRebates.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgAllocateEpochRebates) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgAllocateEpochRebates.Merge(m, src) -} -func (m *MsgAllocateEpochRebates) XXX_Size() int { - return m.Size() -} -func (m *MsgAllocateEpochRebates) XXX_DiscardUnknown() { - xxx_messageInfo_MsgAllocateEpochRebates.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgAllocateEpochRebates proto.InternalMessageInfo - -func (m *MsgAllocateEpochRebates) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgAllocateEpochRebates) GetRebates() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Rebates - } - return nil -} - -type MsgAllocateEpochRebatesResponse struct { - TotalEpochRebates github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=total_epoch_rebates,json=totalEpochRebates,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"total_epoch_rebates"` -} - -func (m *MsgAllocateEpochRebatesResponse) Reset() { *m = MsgAllocateEpochRebatesResponse{} } -func (m *MsgAllocateEpochRebatesResponse) String() string { return proto.CompactTextString(m) } -func (*MsgAllocateEpochRebatesResponse) ProtoMessage() {} -func (*MsgAllocateEpochRebatesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{18} -} -func (m *MsgAllocateEpochRebatesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgAllocateEpochRebatesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgAllocateEpochRebatesResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgAllocateEpochRebatesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgAllocateEpochRebatesResponse.Merge(m, src) -} -func (m *MsgAllocateEpochRebatesResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgAllocateEpochRebatesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgAllocateEpochRebatesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgAllocateEpochRebatesResponse proto.InternalMessageInfo - -func (m *MsgAllocateEpochRebatesResponse) GetTotalEpochRebates() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.TotalEpochRebates - } - return nil -} - -// -------------------------- WithdrawEpochRebates -------------------------- -type MsgWithdrawEpochRebates struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Epochs []uint64 `protobuf:"varint,2,rep,packed,name=epochs,proto3" json:"epochs,omitempty"` -} - -func (m *MsgWithdrawEpochRebates) Reset() { *m = MsgWithdrawEpochRebates{} } -func (m *MsgWithdrawEpochRebates) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawEpochRebates) ProtoMessage() {} -func (*MsgWithdrawEpochRebates) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{19} -} -func (m *MsgWithdrawEpochRebates) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawEpochRebates) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawEpochRebates.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdrawEpochRebates) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawEpochRebates.Merge(m, src) -} -func (m *MsgWithdrawEpochRebates) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawEpochRebates) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawEpochRebates.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawEpochRebates proto.InternalMessageInfo - -func (m *MsgWithdrawEpochRebates) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgWithdrawEpochRebates) GetEpochs() []uint64 { - if m != nil { - return m.Epochs - } - return nil -} - -type MsgWithdrawEpochRebatesResponse struct { - WithdrawnRebates github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=withdrawn_rebates,json=withdrawnRebates,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"withdrawn_rebates"` -} - -func (m *MsgWithdrawEpochRebatesResponse) Reset() { *m = MsgWithdrawEpochRebatesResponse{} } -func (m *MsgWithdrawEpochRebatesResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawEpochRebatesResponse) ProtoMessage() {} -func (*MsgWithdrawEpochRebatesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{20} -} -func (m *MsgWithdrawEpochRebatesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawEpochRebatesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawEpochRebatesResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdrawEpochRebatesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawEpochRebatesResponse.Merge(m, src) -} -func (m *MsgWithdrawEpochRebatesResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawEpochRebatesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawEpochRebatesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawEpochRebatesResponse proto.InternalMessageInfo - -func (m *MsgWithdrawEpochRebatesResponse) GetWithdrawnRebates() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.WithdrawnRebates - } - return nil -} - -// MsgShiftPegMultiplier: gRPC tx msg for changing the peg multiplier. -// [SUDO] Only callable sudoers. -type MsgShiftPegMultiplier struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,2,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - NewPegMult github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=new_peg_mult,json=newPegMult,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"new_peg_mult"` -} - -func (m *MsgShiftPegMultiplier) Reset() { *m = MsgShiftPegMultiplier{} } -func (m *MsgShiftPegMultiplier) String() string { return proto.CompactTextString(m) } -func (*MsgShiftPegMultiplier) ProtoMessage() {} -func (*MsgShiftPegMultiplier) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{21} -} -func (m *MsgShiftPegMultiplier) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgShiftPegMultiplier) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgShiftPegMultiplier.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgShiftPegMultiplier) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgShiftPegMultiplier.Merge(m, src) -} -func (m *MsgShiftPegMultiplier) XXX_Size() int { - return m.Size() -} -func (m *MsgShiftPegMultiplier) XXX_DiscardUnknown() { - xxx_messageInfo_MsgShiftPegMultiplier.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgShiftPegMultiplier proto.InternalMessageInfo - -func (m *MsgShiftPegMultiplier) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -type MsgShiftPegMultiplierResponse struct { -} - -func (m *MsgShiftPegMultiplierResponse) Reset() { *m = MsgShiftPegMultiplierResponse{} } -func (m *MsgShiftPegMultiplierResponse) String() string { return proto.CompactTextString(m) } -func (*MsgShiftPegMultiplierResponse) ProtoMessage() {} -func (*MsgShiftPegMultiplierResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{22} -} -func (m *MsgShiftPegMultiplierResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgShiftPegMultiplierResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgShiftPegMultiplierResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgShiftPegMultiplierResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgShiftPegMultiplierResponse.Merge(m, src) -} -func (m *MsgShiftPegMultiplierResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgShiftPegMultiplierResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgShiftPegMultiplierResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgShiftPegMultiplierResponse proto.InternalMessageInfo - -// MsgShiftSwapInvariant: gRPC tx msg for changing the swap invariant. -// [SUDO] Only callable sudoers. -type MsgShiftSwapInvariant struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,2,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` - NewSwapInvariant github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=new_swap_invariant,json=newSwapInvariant,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"new_swap_invariant"` -} - -func (m *MsgShiftSwapInvariant) Reset() { *m = MsgShiftSwapInvariant{} } -func (m *MsgShiftSwapInvariant) String() string { return proto.CompactTextString(m) } -func (*MsgShiftSwapInvariant) ProtoMessage() {} -func (*MsgShiftSwapInvariant) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{23} -} -func (m *MsgShiftSwapInvariant) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgShiftSwapInvariant) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgShiftSwapInvariant.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgShiftSwapInvariant) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgShiftSwapInvariant.Merge(m, src) -} -func (m *MsgShiftSwapInvariant) XXX_Size() int { - return m.Size() -} -func (m *MsgShiftSwapInvariant) XXX_DiscardUnknown() { - xxx_messageInfo_MsgShiftSwapInvariant.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgShiftSwapInvariant proto.InternalMessageInfo - -func (m *MsgShiftSwapInvariant) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -type MsgShiftSwapInvariantResponse struct { -} - -func (m *MsgShiftSwapInvariantResponse) Reset() { *m = MsgShiftSwapInvariantResponse{} } -func (m *MsgShiftSwapInvariantResponse) String() string { return proto.CompactTextString(m) } -func (*MsgShiftSwapInvariantResponse) ProtoMessage() {} -func (*MsgShiftSwapInvariantResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{24} -} -func (m *MsgShiftSwapInvariantResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgShiftSwapInvariantResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgShiftSwapInvariantResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgShiftSwapInvariantResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgShiftSwapInvariantResponse.Merge(m, src) -} -func (m *MsgShiftSwapInvariantResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgShiftSwapInvariantResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgShiftSwapInvariantResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgShiftSwapInvariantResponse proto.InternalMessageInfo - -// MsgWithdrawFromPerpFund: gRPC tx msg for changing the swap invariant. -// [SUDO] Only callable sudoers. -type MsgWithdrawFromPerpFund struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=amount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"amount"` - // Optional denom in case withdrawing assets aside from NUSD. - Denom string `protobuf:"bytes,3,opt,name=denom,proto3" json:"denom,omitempty"` - ToAddr string `protobuf:"bytes,4,opt,name=to_addr,json=toAddr,proto3" json:"to_addr,omitempty"` -} - -func (m *MsgWithdrawFromPerpFund) Reset() { *m = MsgWithdrawFromPerpFund{} } -func (m *MsgWithdrawFromPerpFund) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawFromPerpFund) ProtoMessage() {} -func (*MsgWithdrawFromPerpFund) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{25} -} -func (m *MsgWithdrawFromPerpFund) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawFromPerpFund) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawFromPerpFund.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdrawFromPerpFund) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawFromPerpFund.Merge(m, src) -} -func (m *MsgWithdrawFromPerpFund) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawFromPerpFund) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawFromPerpFund.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawFromPerpFund proto.InternalMessageInfo - -func (m *MsgWithdrawFromPerpFund) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgWithdrawFromPerpFund) GetDenom() string { - if m != nil { - return m.Denom - } - return "" -} - -func (m *MsgWithdrawFromPerpFund) GetToAddr() string { - if m != nil { - return m.ToAddr - } - return "" -} - -type MsgWithdrawFromPerpFundResponse struct { -} - -func (m *MsgWithdrawFromPerpFundResponse) Reset() { *m = MsgWithdrawFromPerpFundResponse{} } -func (m *MsgWithdrawFromPerpFundResponse) String() string { return proto.CompactTextString(m) } -func (*MsgWithdrawFromPerpFundResponse) ProtoMessage() {} -func (*MsgWithdrawFromPerpFundResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{26} -} -func (m *MsgWithdrawFromPerpFundResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgWithdrawFromPerpFundResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgWithdrawFromPerpFundResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgWithdrawFromPerpFundResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithdrawFromPerpFundResponse.Merge(m, src) -} -func (m *MsgWithdrawFromPerpFundResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgWithdrawFromPerpFundResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithdrawFromPerpFundResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithdrawFromPerpFundResponse proto.InternalMessageInfo - -// CloseMarket: gRPC tx msg for closing a market. -// Admin-only. -type MsgCloseMarket struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - Pair github_com_NibiruChain_nibiru_x_common_asset.Pair `protobuf:"bytes,2,opt,name=pair,proto3,customtype=github.com/NibiruChain/nibiru/x/common/asset.Pair" json:"pair"` -} - -func (m *MsgCloseMarket) Reset() { *m = MsgCloseMarket{} } -func (m *MsgCloseMarket) String() string { return proto.CompactTextString(m) } -func (*MsgCloseMarket) ProtoMessage() {} -func (*MsgCloseMarket) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{27} -} -func (m *MsgCloseMarket) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgCloseMarket) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCloseMarket.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgCloseMarket) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCloseMarket.Merge(m, src) -} -func (m *MsgCloseMarket) XXX_Size() int { - return m.Size() -} -func (m *MsgCloseMarket) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCloseMarket.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCloseMarket proto.InternalMessageInfo - -func (m *MsgCloseMarket) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -type MsgCloseMarketResponse struct { -} - -func (m *MsgCloseMarketResponse) Reset() { *m = MsgCloseMarketResponse{} } -func (m *MsgCloseMarketResponse) String() string { return proto.CompactTextString(m) } -func (*MsgCloseMarketResponse) ProtoMessage() {} -func (*MsgCloseMarketResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b95cda40bf0a0f91, []int{28} -} -func (m *MsgCloseMarketResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgCloseMarketResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCloseMarketResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MsgCloseMarketResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCloseMarketResponse.Merge(m, src) -} -func (m *MsgCloseMarketResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgCloseMarketResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCloseMarketResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCloseMarketResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgSettlePosition)(nil), "nibiru.perp.v2.MsgSettlePosition") - proto.RegisterType((*MsgRemoveMargin)(nil), "nibiru.perp.v2.MsgRemoveMargin") - proto.RegisterType((*MsgRemoveMarginResponse)(nil), "nibiru.perp.v2.MsgRemoveMarginResponse") - proto.RegisterType((*MsgAddMargin)(nil), "nibiru.perp.v2.MsgAddMargin") - proto.RegisterType((*MsgAddMarginResponse)(nil), "nibiru.perp.v2.MsgAddMarginResponse") - proto.RegisterType((*MsgMultiLiquidate)(nil), "nibiru.perp.v2.MsgMultiLiquidate") - proto.RegisterType((*MsgMultiLiquidate_Liquidation)(nil), "nibiru.perp.v2.MsgMultiLiquidate.Liquidation") - proto.RegisterType((*MsgMultiLiquidateResponse)(nil), "nibiru.perp.v2.MsgMultiLiquidateResponse") - proto.RegisterType((*MsgMultiLiquidateResponse_LiquidationResponse)(nil), "nibiru.perp.v2.MsgMultiLiquidateResponse.LiquidationResponse") - proto.RegisterType((*MsgMarketOrder)(nil), "nibiru.perp.v2.MsgMarketOrder") - proto.RegisterType((*MsgMarketOrderResponse)(nil), "nibiru.perp.v2.MsgMarketOrderResponse") - proto.RegisterType((*MsgClosePosition)(nil), "nibiru.perp.v2.MsgClosePosition") - proto.RegisterType((*MsgClosePositionResponse)(nil), "nibiru.perp.v2.MsgClosePositionResponse") - proto.RegisterType((*MsgPartialClose)(nil), "nibiru.perp.v2.MsgPartialClose") - proto.RegisterType((*MsgPartialCloseResponse)(nil), "nibiru.perp.v2.MsgPartialCloseResponse") - proto.RegisterType((*MsgDonateToEcosystemFund)(nil), "nibiru.perp.v2.MsgDonateToEcosystemFund") - proto.RegisterType((*MsgDonateToEcosystemFundResponse)(nil), "nibiru.perp.v2.MsgDonateToEcosystemFundResponse") - proto.RegisterType((*MsgChangeCollateralDenom)(nil), "nibiru.perp.v2.MsgChangeCollateralDenom") - proto.RegisterType((*MsgChangeCollateralDenomResponse)(nil), "nibiru.perp.v2.MsgChangeCollateralDenomResponse") - proto.RegisterType((*MsgAllocateEpochRebates)(nil), "nibiru.perp.v2.MsgAllocateEpochRebates") - proto.RegisterType((*MsgAllocateEpochRebatesResponse)(nil), "nibiru.perp.v2.MsgAllocateEpochRebatesResponse") - proto.RegisterType((*MsgWithdrawEpochRebates)(nil), "nibiru.perp.v2.MsgWithdrawEpochRebates") - proto.RegisterType((*MsgWithdrawEpochRebatesResponse)(nil), "nibiru.perp.v2.MsgWithdrawEpochRebatesResponse") - proto.RegisterType((*MsgShiftPegMultiplier)(nil), "nibiru.perp.v2.MsgShiftPegMultiplier") - proto.RegisterType((*MsgShiftPegMultiplierResponse)(nil), "nibiru.perp.v2.MsgShiftPegMultiplierResponse") - proto.RegisterType((*MsgShiftSwapInvariant)(nil), "nibiru.perp.v2.MsgShiftSwapInvariant") - proto.RegisterType((*MsgShiftSwapInvariantResponse)(nil), "nibiru.perp.v2.MsgShiftSwapInvariantResponse") - proto.RegisterType((*MsgWithdrawFromPerpFund)(nil), "nibiru.perp.v2.MsgWithdrawFromPerpFund") - proto.RegisterType((*MsgWithdrawFromPerpFundResponse)(nil), "nibiru.perp.v2.MsgWithdrawFromPerpFundResponse") - proto.RegisterType((*MsgCloseMarket)(nil), "nibiru.perp.v2.MsgCloseMarket") - proto.RegisterType((*MsgCloseMarketResponse)(nil), "nibiru.perp.v2.MsgCloseMarketResponse") -} - -func init() { proto.RegisterFile("nibiru/perp/v2/tx.proto", fileDescriptor_b95cda40bf0a0f91) } - -var fileDescriptor_b95cda40bf0a0f91 = []byte{ - // 1686 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x59, 0x4b, 0x6f, 0x1b, 0x47, - 0x12, 0xe6, 0x88, 0x14, 0x25, 0x95, 0x64, 0x3d, 0xc6, 0xb2, 0x44, 0x73, 0xbd, 0x94, 0x3c, 0xd8, - 0xf5, 0x6a, 0x0f, 0x22, 0x6d, 0xed, 0x02, 0x8b, 0x5d, 0x60, 0x77, 0xa1, 0x87, 0x15, 0x38, 0x30, - 0x6d, 0x7a, 0x64, 0xd8, 0x81, 0xe3, 0x60, 0xdc, 0xe2, 0xb4, 0x46, 0x03, 0x0f, 0xbb, 0xe9, 0x99, - 0x26, 0x29, 0x39, 0xb7, 0x1c, 0x73, 0xca, 0x21, 0x87, 0x00, 0x01, 0x72, 0x0b, 0x10, 0xe4, 0x10, - 0x20, 0x87, 0x24, 0x97, 0xfc, 0x00, 0x1f, 0x7d, 0x0c, 0x82, 0xc0, 0x09, 0xac, 0x4b, 0xae, 0x31, - 0xf2, 0x03, 0x82, 0xee, 0x79, 0x70, 0x86, 0x6e, 0x52, 0x14, 0x23, 0x13, 0x48, 0x90, 0x93, 0xd4, - 0xd3, 0xd5, 0x5f, 0xd5, 0x57, 0x55, 0xdd, 0x55, 0xdd, 0x84, 0x45, 0x62, 0xef, 0xda, 0x6e, 0xa3, - 0x54, 0xc7, 0x6e, 0xbd, 0xd4, 0x5c, 0x2b, 0xb1, 0x83, 0x62, 0xdd, 0xa5, 0x8c, 0xaa, 0xd3, 0xfe, - 0x44, 0x91, 0x4f, 0x14, 0x9b, 0x6b, 0xf9, 0x0b, 0x16, 0xa5, 0x96, 0x83, 0x4b, 0xa8, 0x6e, 0x97, - 0x10, 0x21, 0x94, 0x21, 0x66, 0x53, 0xe2, 0xf9, 0xd2, 0xf9, 0x42, 0x95, 0x7a, 0x35, 0xea, 0x95, - 0x76, 0x91, 0x87, 0x4b, 0xcd, 0x2b, 0xbb, 0x98, 0xa1, 0x2b, 0xa5, 0x2a, 0xb5, 0x49, 0x30, 0x3f, - 0x6f, 0x51, 0x8b, 0x8a, 0x7f, 0x4b, 0xfc, 0xbf, 0xe0, 0x6b, 0xbe, 0x43, 0xb9, 0xc7, 0x10, 0xc3, - 0xfe, 0x9c, 0xf6, 0xbe, 0x02, 0x73, 0x65, 0xcf, 0xda, 0xc1, 0x8c, 0x39, 0xb8, 0x42, 0x3d, 0x9b, - 0xab, 0x53, 0x17, 0x20, 0xeb, 0x61, 0x62, 0x62, 0x37, 0xa7, 0x2c, 0x2b, 0x2b, 0x13, 0x7a, 0x30, - 0x52, 0xcb, 0x90, 0xa9, 0x23, 0xdb, 0xcd, 0x8d, 0xf0, 0xaf, 0x1b, 0xff, 0x7e, 0xf2, 0x6c, 0x29, - 0xf5, 0xed, 0xb3, 0xa5, 0x2b, 0x96, 0xcd, 0xf6, 0x1b, 0xbb, 0xc5, 0x2a, 0xad, 0x95, 0x6e, 0x08, - 0x55, 0x9b, 0xfb, 0xc8, 0x26, 0xa5, 0x40, 0xed, 0x41, 0xa9, 0x4a, 0x6b, 0x35, 0x4a, 0x4a, 0xc8, - 0xf3, 0x30, 0x2b, 0x56, 0x90, 0xed, 0xea, 0x02, 0x46, 0xcd, 0xc1, 0x58, 0x13, 0xbb, 0x9e, 0x4d, - 0x49, 0x2e, 0xbd, 0xac, 0xac, 0x64, 0xf4, 0x70, 0xa8, 0x7d, 0xae, 0xc0, 0x4c, 0xd9, 0xb3, 0x74, - 0x5c, 0xa3, 0x4d, 0x5c, 0x46, 0xae, 0x65, 0x0f, 0xcd, 0xa8, 0x7f, 0x41, 0xb6, 0x26, 0x14, 0x0a, - 0x9b, 0x26, 0xd7, 0xce, 0x17, 0x7d, 0xa7, 0x17, 0xb9, 0xd3, 0x8b, 0x81, 0xd3, 0x8b, 0x9b, 0xd4, - 0x26, 0x1b, 0x19, 0xae, 0x4b, 0x0f, 0xc4, 0xb5, 0x1f, 0x15, 0x58, 0xec, 0xb0, 0x59, 0xc7, 0x5e, - 0x9d, 0x12, 0x0f, 0xab, 0xff, 0x03, 0xf0, 0xa5, 0x0c, 0xda, 0x60, 0xc2, 0xfe, 0x3e, 0x80, 0x27, - 0xfc, 0x25, 0x37, 0x1b, 0x4c, 0xbd, 0x0b, 0x33, 0x7b, 0x0d, 0x62, 0xda, 0xc4, 0x32, 0xea, 0xe8, - 0xb0, 0x86, 0x09, 0x0b, 0xe8, 0x16, 0x03, 0xba, 0x97, 0x62, 0x74, 0x83, 0x24, 0xf1, 0xff, 0xac, - 0x7a, 0xe6, 0xc3, 0x12, 0x3b, 0xac, 0x63, 0xaf, 0xb8, 0x85, 0xab, 0xfa, 0x74, 0x00, 0x53, 0xf1, - 0x51, 0xd4, 0x7f, 0xc2, 0x78, 0x3d, 0x88, 0x7a, 0xc0, 0x37, 0x57, 0x4c, 0xa6, 0x64, 0x31, 0xcc, - 0x0a, 0x3d, 0x92, 0xd4, 0x3e, 0x53, 0x60, 0xaa, 0xec, 0x59, 0xeb, 0xa6, 0xf9, 0x1b, 0x89, 0xcd, - 0xc7, 0x0a, 0xcc, 0xc7, 0x0d, 0x8e, 0x02, 0x23, 0x71, 0xac, 0x72, 0xea, 0x8e, 0x1d, 0xe9, 0xdb, - 0xb1, 0x3f, 0xfb, 0xdb, 0xb1, 0xdc, 0x70, 0x98, 0x7d, 0xdd, 0x7e, 0xd4, 0xb0, 0x4d, 0xc4, 0x70, - 0x57, 0xef, 0xde, 0x82, 0x29, 0x27, 0x10, 0xe2, 0x87, 0x44, 0x6e, 0x64, 0x39, 0xbd, 0x32, 0xb9, - 0xb6, 0xda, 0xa9, 0xe7, 0x25, 0xc0, 0xe2, 0xf5, 0xf6, 0x2a, 0x3d, 0x01, 0x91, 0x67, 0x30, 0x19, - 0x9b, 0x8c, 0xe2, 0xa7, 0x9c, 0x4e, 0xfc, 0x16, 0x20, 0xcb, 0x5c, 0xc4, 0x89, 0x8c, 0xf8, 0x44, - 0xfc, 0x91, 0xf6, 0x65, 0x1a, 0xce, 0xbf, 0x64, 0x65, 0x14, 0x23, 0xd4, 0x41, 0x53, 0x11, 0x34, - 0xff, 0x7b, 0x2c, 0xcd, 0x10, 0x20, 0x41, 0x37, 0xf8, 0xd6, 0x41, 0xfb, 0x8b, 0x11, 0x38, 0x2b, - 0x91, 0xe2, 0x27, 0x94, 0xd7, 0xa8, 0x56, 0xb1, 0xe7, 0x09, 0x17, 0x8c, 0xeb, 0xe1, 0x50, 0x9d, - 0x87, 0x51, 0xec, 0xba, 0x34, 0x64, 0xe2, 0x0f, 0xd4, 0x6d, 0x98, 0x0e, 0x71, 0xa9, 0x6b, 0xec, - 0x61, 0xdc, 0x5f, 0xa2, 0x2a, 0xfa, 0x99, 0xf6, 0xb2, 0x6d, 0x8c, 0xd5, 0xff, 0xc3, 0x24, 0xa7, - 0x65, 0xe0, 0x3d, 0x01, 0x92, 0xe9, 0x0f, 0x64, 0x82, 0xaf, 0xb9, 0xba, 0xc7, 0x01, 0xda, 0x9e, - 0x1e, 0x8d, 0x7b, 0x3a, 0x0a, 0x68, 0xf6, 0x54, 0x02, 0xaa, 0x7d, 0x95, 0x86, 0x69, 0xee, 0x77, - 0xe4, 0x3e, 0xc4, 0xec, 0xa6, 0xcb, 0x35, 0x0c, 0xe9, 0x28, 0x58, 0x85, 0x8c, 0x67, 0x9b, 0xbe, - 0x7f, 0xa7, 0xd7, 0xce, 0x77, 0x26, 0xc3, 0x96, 0xed, 0xe2, 0xaa, 0x08, 0xa5, 0x10, 0x53, 0xef, - 0x83, 0xfa, 0xa8, 0x41, 0x19, 0x36, 0x04, 0x90, 0x81, 0x6a, 0xb4, 0x41, 0x98, 0xf0, 0xeb, 0xc9, - 0xb6, 0xfa, 0x35, 0xc2, 0xf4, 0x59, 0x81, 0xb4, 0xce, 0x81, 0xd6, 0x05, 0x8e, 0xfa, 0x3a, 0x8c, - 0x3b, 0xb8, 0x89, 0x5d, 0x64, 0x61, 0xdf, 0xdf, 0x27, 0x3e, 0x3e, 0xa2, 0xf5, 0x2a, 0x86, 0x45, - 0x1e, 0xdf, 0x84, 0xa1, 0x86, 0x63, 0xd7, 0x6c, 0x16, 0x04, 0xed, 0xa4, 0xe6, 0xce, 0x73, 0xb8, - 0x98, 0xb5, 0xd7, 0x39, 0x96, 0x76, 0x34, 0x0a, 0x0b, 0xc9, 0xc8, 0x45, 0x49, 0x1f, 0x3f, 0xba, - 0x94, 0x7e, 0x8f, 0x2e, 0x75, 0x1f, 0x72, 0xf8, 0xa0, 0xba, 0x8f, 0x88, 0x85, 0x4d, 0x83, 0x50, - 0xfe, 0x0d, 0x39, 0x46, 0x13, 0x39, 0x0d, 0x3c, 0x60, 0xad, 0x5a, 0x88, 0xf0, 0x6e, 0x04, 0x70, - 0x77, 0x38, 0x9a, 0xba, 0x07, 0x8b, 0x6d, 0x4d, 0xa1, 0x7e, 0xc3, 0xb3, 0x1f, 0xfb, 0xd9, 0x70, - 0x72, 0x45, 0xe7, 0x22, 0xb8, 0x90, 0xd7, 0x8e, 0xfd, 0x58, 0x5a, 0x1b, 0x32, 0xa7, 0x52, 0x1b, - 0x6e, 0xc1, 0x94, 0x8b, 0x91, 0x63, 0x3f, 0xe6, 0xf6, 0x13, 0x67, 0xc0, 0x94, 0x99, 0x0c, 0x31, - 0x2a, 0xc4, 0x51, 0x1f, 0xc0, 0x7c, 0x83, 0xc4, 0x41, 0x0d, 0xb4, 0xc7, 0xb0, 0x3b, 0x40, 0xca, - 0x70, 0x68, 0xb5, 0x8d, 0x55, 0x21, 0xce, 0x3a, 0x47, 0x52, 0xef, 0xc0, 0x4c, 0xd0, 0xc2, 0x30, - 0x6a, 0x34, 0x51, 0xc3, 0x61, 0xb9, 0xb1, 0x81, 0xc0, 0xcf, 0xf8, 0x30, 0xb7, 0xe9, 0x1d, 0x0e, - 0xa2, 0xbe, 0x09, 0x73, 0x51, 0x0c, 0xc3, 0xb4, 0xc9, 0x8d, 0x0f, 0x84, 0x3c, 0x1b, 0x02, 0x85, - 0xf9, 0xa2, 0x1d, 0xc2, 0x6c, 0xd9, 0xb3, 0x36, 0x1d, 0xea, 0x0d, 0xbb, 0xb9, 0xd5, 0x5e, 0xa4, - 0x21, 0xd7, 0xa9, 0x3b, 0xda, 0x62, 0xbd, 0x36, 0x8b, 0x32, 0xac, 0xcd, 0x32, 0xf2, 0x8a, 0x37, - 0x4b, 0xfa, 0x95, 0x6c, 0x96, 0xcc, 0xaf, 0xdf, 0x2c, 0x6f, 0xc0, 0x6c, 0x3b, 0x95, 0xe3, 0x65, - 0xf2, 0xe4, 0xc6, 0x86, 0xb9, 0x7c, 0xdb, 0x6f, 0x64, 0xbe, 0xf6, 0xef, 0x2d, 0x15, 0xe4, 0x32, - 0x1b, 0x39, 0x22, 0xf6, 0xc3, 0x2a, 0x88, 0x1b, 0xbc, 0x20, 0x0e, 0x7c, 0x04, 0x8a, 0xb5, 0xda, - 0x4f, 0x69, 0x71, 0x85, 0x89, 0x9b, 0xff, 0x47, 0xca, 0xfe, 0xce, 0x53, 0xf6, 0x1d, 0x45, 0x9c, - 0x53, 0x5b, 0x94, 0x20, 0x86, 0x6f, 0xd3, 0xab, 0x55, 0xea, 0x1d, 0x7a, 0x0c, 0xd7, 0xb6, 0x1b, - 0xc4, 0xec, 0x9a, 0xbb, 0x37, 0x60, 0xdc, 0xe4, 0x0b, 0xda, 0xb7, 0x9b, 0x1e, 0xcd, 0xe9, 0x22, - 0xb7, 0xf0, 0xc5, 0xb3, 0xa5, 0x99, 0x43, 0x54, 0x73, 0xfe, 0xa3, 0x85, 0x0b, 0x35, 0x3d, 0xc2, - 0xd0, 0x34, 0x58, 0xee, 0x66, 0x43, 0x98, 0x80, 0xda, 0x4d, 0xff, 0x3c, 0x15, 0x81, 0xdc, 0xa4, - 0x8e, 0x83, 0x18, 0x76, 0x91, 0xb3, 0x85, 0x09, 0xad, 0x75, 0xb5, 0xf3, 0x4f, 0x30, 0x41, 0x70, - 0xcb, 0x30, 0xb9, 0x50, 0xd0, 0xa9, 0x8f, 0x13, 0xdc, 0x12, 0x8b, 0x02, 0xa5, 0x52, 0xc0, 0x48, - 0xe9, 0x07, 0xfe, 0xa5, 0x7e, 0xdd, 0x71, 0x68, 0x15, 0x31, 0x7c, 0xb5, 0x4e, 0xab, 0xfb, 0x3a, - 0xde, 0x45, 0x0c, 0x7b, 0x5d, 0x95, 0x62, 0x18, 0x73, 0x7d, 0x91, 0xe0, 0x46, 0xd6, 0xc3, 0x37, - 0x97, 0xb9, 0x6f, 0x3e, 0xfd, 0x7e, 0x69, 0xa5, 0x8f, 0xe8, 0xf1, 0x05, 0x9e, 0x1e, 0x62, 0x6b, - 0x1f, 0x29, 0xb0, 0xd4, 0xc5, 0xb4, 0x68, 0xd3, 0xbe, 0x0d, 0x67, 0x19, 0x65, 0xc8, 0x31, 0x30, - 0x9f, 0x35, 0x42, 0xb3, 0x94, 0xd3, 0x37, 0x6b, 0x4e, 0xe8, 0x89, 0x1b, 0xa1, 0x5d, 0x13, 0xae, - 0xbb, 0x6b, 0xb3, 0x7d, 0xd3, 0x45, 0xad, 0xbe, 0x5c, 0xb7, 0x00, 0x59, 0x61, 0xa9, 0xef, 0xb9, - 0x8c, 0x1e, 0x8c, 0xb4, 0x0f, 0x7d, 0xae, 0x32, 0xac, 0x88, 0xeb, 0x01, 0xcc, 0xb5, 0x82, 0x79, - 0xf2, 0x2a, 0x99, 0xce, 0x46, 0x5a, 0x42, 0xa2, 0x4f, 0x15, 0x38, 0x57, 0xf6, 0xac, 0x9d, 0x7d, - 0x7b, 0x8f, 0x55, 0xb0, 0x7f, 0x0b, 0xad, 0x3b, 0xf6, 0xf0, 0x2e, 0x43, 0x15, 0x98, 0xe2, 0x69, - 0x5e, 0xc7, 0x96, 0x51, 0xe3, 0x8d, 0xd9, 0x60, 0xc7, 0x18, 0x10, 0xdc, 0x0a, 0xcc, 0xd7, 0x96, - 0xe0, 0xcf, 0x52, 0x46, 0xd1, 0xc6, 0xf8, 0x2e, 0xc6, 0x79, 0xa7, 0x85, 0xea, 0xd7, 0x48, 0x13, - 0xb9, 0x36, 0x22, 0x6c, 0x58, 0x9c, 0xef, 0x83, 0xca, 0x39, 0x7b, 0x2d, 0x54, 0x37, 0xec, 0x50, - 0xf9, 0x00, 0xcc, 0xc5, 0x8d, 0x8e, 0xe0, 0x56, 0x82, 0x44, 0x9c, 0x7f, 0x62, 0x22, 0xe2, 0xff, - 0x89, 0x92, 0xc8, 0xee, 0x6d, 0x97, 0xd6, 0x2a, 0xd8, 0xad, 0xf7, 0x3c, 0x35, 0xb7, 0x21, 0x1b, - 0x5c, 0x3c, 0x47, 0x06, 0x32, 0x33, 0x58, 0xad, 0xce, 0xc3, 0xa8, 0x7f, 0xa2, 0xa5, 0xfd, 0xb7, - 0x07, 0x31, 0x50, 0x17, 0x61, 0x8c, 0x51, 0x03, 0x99, 0xa6, 0xeb, 0x17, 0x1c, 0x3d, 0xcb, 0xe8, - 0xba, 0x69, 0xba, 0xda, 0xc5, 0xc4, 0xde, 0x89, 0x5b, 0x1a, 0xb1, 0x69, 0x89, 0x6b, 0xbc, 0x28, - 0xf8, 0xfe, 0x8d, 0x70, 0x58, 0x5d, 0x72, 0x4e, 0xdc, 0x42, 0x63, 0x8a, 0x43, 0x93, 0xd6, 0xde, - 0x9d, 0x82, 0x74, 0xd9, 0xb3, 0xd4, 0x7b, 0x30, 0x95, 0x78, 0x06, 0x5e, 0x92, 0xbc, 0xfb, 0xc4, - 0x05, 0xf2, 0x7f, 0x3b, 0x46, 0x20, 0x22, 0x9d, 0x52, 0x6f, 0xc1, 0x44, 0xfb, 0x0d, 0xf3, 0x82, - 0x64, 0x5d, 0x34, 0x9b, 0xff, 0x4b, 0xaf, 0xd9, 0x18, 0xe4, 0x03, 0x98, 0xee, 0x78, 0xbd, 0xbb, - 0x78, 0xec, 0x43, 0x55, 0xfe, 0xef, 0x7d, 0xbf, 0x65, 0x69, 0x29, 0xf5, 0x2e, 0x4c, 0xc6, 0xdf, - 0x5b, 0x0a, 0xb2, 0xb5, 0xed, 0xf9, 0xfc, 0xa5, 0xde, 0xf3, 0x31, 0xe0, 0xb7, 0xe0, 0x4c, 0xf2, - 0xa6, 0xb4, 0x2c, 0x59, 0x9a, 0x90, 0xc8, 0xaf, 0x1c, 0x27, 0x11, 0x83, 0xbf, 0x07, 0x53, 0x89, - 0xbe, 0x58, 0x16, 0xc8, 0xb8, 0x80, 0x34, 0x90, 0xb2, 0xd6, 0x54, 0x4b, 0xa9, 0x06, 0x4c, 0x77, - 0xfc, 0x84, 0x21, 0xf3, 0x7a, 0x52, 0xe4, 0x44, 0xc6, 0x37, 0xe0, 0x9c, 0xbc, 0x43, 0x92, 0x81, - 0x48, 0x25, 0xf3, 0x97, 0xfb, 0x95, 0x4c, 0xaa, 0x95, 0x37, 0x3c, 0x52, 0xdb, 0x65, 0x92, 0x52, - 0xb5, 0xbd, 0x7b, 0x9e, 0x94, 0xea, 0xc2, 0xbc, 0xb4, 0xe3, 0x91, 0x45, 0x44, 0x26, 0x98, 0x2f, - 0xf5, 0x29, 0x98, 0xd4, 0x29, 0x6d, 0x15, 0x64, 0x3a, 0x65, 0x82, 0x52, 0x9d, 0xbd, 0x1a, 0x06, - 0x2d, 0xa5, 0x3a, 0xa0, 0x4a, 0x8a, 0xf6, 0x5f, 0x65, 0xa9, 0xf3, 0x92, 0x58, 0x7e, 0xb5, 0x2f, - 0x31, 0x89, 0xb6, 0x64, 0xb9, 0xec, 0xaa, 0x2d, 0x21, 0xd6, 0x5d, 0x9b, 0xbc, 0x3c, 0x25, 0xfc, - 0x99, 0x28, 0x4e, 0xbd, 0xfc, 0x19, 0x17, 0xec, 0xe9, 0x4f, 0x69, 0x11, 0x11, 0x47, 0x53, 0xbc, - 0x86, 0x14, 0xba, 0x6d, 0x30, 0x7f, 0x5e, 0x7a, 0x34, 0x49, 0x4a, 0x81, 0x96, 0xda, 0x78, 0xed, - 0xc9, 0xf3, 0x82, 0xf2, 0xf4, 0x79, 0x41, 0xf9, 0xe1, 0x79, 0x41, 0x79, 0xef, 0xa8, 0x90, 0x7a, - 0x7a, 0x54, 0x48, 0x7d, 0x73, 0x54, 0x48, 0xdd, 0x5b, 0x3d, 0xae, 0xf2, 0x44, 0x3f, 0xb9, 0xf2, - 0x32, 0xba, 0x9b, 0x15, 0x3f, 0x7b, 0xfe, 0xe3, 0x97, 0x00, 0x00, 0x00, 0xff, 0xff, 0x86, 0x40, - 0x26, 0x57, 0x91, 0x1d, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - RemoveMargin(ctx context.Context, in *MsgRemoveMargin, opts ...grpc.CallOption) (*MsgRemoveMarginResponse, error) - AddMargin(ctx context.Context, in *MsgAddMargin, opts ...grpc.CallOption) (*MsgAddMarginResponse, error) - MultiLiquidate(ctx context.Context, in *MsgMultiLiquidate, opts ...grpc.CallOption) (*MsgMultiLiquidateResponse, error) - MarketOrder(ctx context.Context, in *MsgMarketOrder, opts ...grpc.CallOption) (*MsgMarketOrderResponse, error) - ClosePosition(ctx context.Context, in *MsgClosePosition, opts ...grpc.CallOption) (*MsgClosePositionResponse, error) - PartialClose(ctx context.Context, in *MsgPartialClose, opts ...grpc.CallOption) (*MsgPartialCloseResponse, error) - SettlePosition(ctx context.Context, in *MsgSettlePosition, opts ...grpc.CallOption) (*MsgClosePositionResponse, error) - DonateToEcosystemFund(ctx context.Context, in *MsgDonateToEcosystemFund, opts ...grpc.CallOption) (*MsgDonateToEcosystemFundResponse, error) - // ChangeCollateralDenom: Updates the collateral denom. A denom is valid if it - // is possible to make an sdk.Coin using it. [SUDO] Only callable by sudoers. - ChangeCollateralDenom(ctx context.Context, in *MsgChangeCollateralDenom, opts ...grpc.CallOption) (*MsgChangeCollateralDenomResponse, error) - AllocateEpochRebates(ctx context.Context, in *MsgAllocateEpochRebates, opts ...grpc.CallOption) (*MsgAllocateEpochRebatesResponse, error) - WithdrawEpochRebates(ctx context.Context, in *MsgWithdrawEpochRebates, opts ...grpc.CallOption) (*MsgWithdrawEpochRebatesResponse, error) - // ShiftPegMultiplier: gRPC tx msg for changing a market's peg multiplier. - // [SUDO] Only callable by sudoers. - ShiftPegMultiplier(ctx context.Context, in *MsgShiftPegMultiplier, opts ...grpc.CallOption) (*MsgShiftPegMultiplierResponse, error) - // ShiftSwapInvariant: gRPC tx msg for changing a market's swap invariant. - // [SUDO] Only callable by sudoers. - ShiftSwapInvariant(ctx context.Context, in *MsgShiftSwapInvariant, opts ...grpc.CallOption) (*MsgShiftSwapInvariantResponse, error) - // WithdrawFromPerpFund: gRPC tx msg to withdraw from the perp fund module - // account. [SUDO] Only callable by sudoers. - WithdrawFromPerpFund(ctx context.Context, in *MsgWithdrawFromPerpFund, opts ...grpc.CallOption) (*MsgWithdrawFromPerpFundResponse, error) - // CloseMarket: gRPC tx msg for closing a market. - // [Admin] Only callable by sudoers. - CloseMarket(ctx context.Context, in *MsgCloseMarket, opts ...grpc.CallOption) (*MsgCloseMarketResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) RemoveMargin(ctx context.Context, in *MsgRemoveMargin, opts ...grpc.CallOption) (*MsgRemoveMarginResponse, error) { - out := new(MsgRemoveMarginResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/RemoveMargin", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) AddMargin(ctx context.Context, in *MsgAddMargin, opts ...grpc.CallOption) (*MsgAddMarginResponse, error) { - out := new(MsgAddMarginResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/AddMargin", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) MultiLiquidate(ctx context.Context, in *MsgMultiLiquidate, opts ...grpc.CallOption) (*MsgMultiLiquidateResponse, error) { - out := new(MsgMultiLiquidateResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/MultiLiquidate", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) MarketOrder(ctx context.Context, in *MsgMarketOrder, opts ...grpc.CallOption) (*MsgMarketOrderResponse, error) { - out := new(MsgMarketOrderResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/MarketOrder", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ClosePosition(ctx context.Context, in *MsgClosePosition, opts ...grpc.CallOption) (*MsgClosePositionResponse, error) { - out := new(MsgClosePositionResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/ClosePosition", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) PartialClose(ctx context.Context, in *MsgPartialClose, opts ...grpc.CallOption) (*MsgPartialCloseResponse, error) { - out := new(MsgPartialCloseResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/PartialClose", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) SettlePosition(ctx context.Context, in *MsgSettlePosition, opts ...grpc.CallOption) (*MsgClosePositionResponse, error) { - out := new(MsgClosePositionResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/SettlePosition", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) DonateToEcosystemFund(ctx context.Context, in *MsgDonateToEcosystemFund, opts ...grpc.CallOption) (*MsgDonateToEcosystemFundResponse, error) { - out := new(MsgDonateToEcosystemFundResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/DonateToEcosystemFund", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ChangeCollateralDenom(ctx context.Context, in *MsgChangeCollateralDenom, opts ...grpc.CallOption) (*MsgChangeCollateralDenomResponse, error) { - out := new(MsgChangeCollateralDenomResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/ChangeCollateralDenom", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) AllocateEpochRebates(ctx context.Context, in *MsgAllocateEpochRebates, opts ...grpc.CallOption) (*MsgAllocateEpochRebatesResponse, error) { - out := new(MsgAllocateEpochRebatesResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/AllocateEpochRebates", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) WithdrawEpochRebates(ctx context.Context, in *MsgWithdrawEpochRebates, opts ...grpc.CallOption) (*MsgWithdrawEpochRebatesResponse, error) { - out := new(MsgWithdrawEpochRebatesResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/WithdrawEpochRebates", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ShiftPegMultiplier(ctx context.Context, in *MsgShiftPegMultiplier, opts ...grpc.CallOption) (*MsgShiftPegMultiplierResponse, error) { - out := new(MsgShiftPegMultiplierResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/ShiftPegMultiplier", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ShiftSwapInvariant(ctx context.Context, in *MsgShiftSwapInvariant, opts ...grpc.CallOption) (*MsgShiftSwapInvariantResponse, error) { - out := new(MsgShiftSwapInvariantResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/ShiftSwapInvariant", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) WithdrawFromPerpFund(ctx context.Context, in *MsgWithdrawFromPerpFund, opts ...grpc.CallOption) (*MsgWithdrawFromPerpFundResponse, error) { - out := new(MsgWithdrawFromPerpFundResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/WithdrawFromPerpFund", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) CloseMarket(ctx context.Context, in *MsgCloseMarket, opts ...grpc.CallOption) (*MsgCloseMarketResponse, error) { - out := new(MsgCloseMarketResponse) - err := c.cc.Invoke(ctx, "/nibiru.perp.v2.Msg/CloseMarket", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - RemoveMargin(context.Context, *MsgRemoveMargin) (*MsgRemoveMarginResponse, error) - AddMargin(context.Context, *MsgAddMargin) (*MsgAddMarginResponse, error) - MultiLiquidate(context.Context, *MsgMultiLiquidate) (*MsgMultiLiquidateResponse, error) - MarketOrder(context.Context, *MsgMarketOrder) (*MsgMarketOrderResponse, error) - ClosePosition(context.Context, *MsgClosePosition) (*MsgClosePositionResponse, error) - PartialClose(context.Context, *MsgPartialClose) (*MsgPartialCloseResponse, error) - SettlePosition(context.Context, *MsgSettlePosition) (*MsgClosePositionResponse, error) - DonateToEcosystemFund(context.Context, *MsgDonateToEcosystemFund) (*MsgDonateToEcosystemFundResponse, error) - // ChangeCollateralDenom: Updates the collateral denom. A denom is valid if it - // is possible to make an sdk.Coin using it. [SUDO] Only callable by sudoers. - ChangeCollateralDenom(context.Context, *MsgChangeCollateralDenom) (*MsgChangeCollateralDenomResponse, error) - AllocateEpochRebates(context.Context, *MsgAllocateEpochRebates) (*MsgAllocateEpochRebatesResponse, error) - WithdrawEpochRebates(context.Context, *MsgWithdrawEpochRebates) (*MsgWithdrawEpochRebatesResponse, error) - // ShiftPegMultiplier: gRPC tx msg for changing a market's peg multiplier. - // [SUDO] Only callable by sudoers. - ShiftPegMultiplier(context.Context, *MsgShiftPegMultiplier) (*MsgShiftPegMultiplierResponse, error) - // ShiftSwapInvariant: gRPC tx msg for changing a market's swap invariant. - // [SUDO] Only callable by sudoers. - ShiftSwapInvariant(context.Context, *MsgShiftSwapInvariant) (*MsgShiftSwapInvariantResponse, error) - // WithdrawFromPerpFund: gRPC tx msg to withdraw from the perp fund module - // account. [SUDO] Only callable by sudoers. - WithdrawFromPerpFund(context.Context, *MsgWithdrawFromPerpFund) (*MsgWithdrawFromPerpFundResponse, error) - // CloseMarket: gRPC tx msg for closing a market. - // [Admin] Only callable by sudoers. - CloseMarket(context.Context, *MsgCloseMarket) (*MsgCloseMarketResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) RemoveMargin(ctx context.Context, req *MsgRemoveMargin) (*MsgRemoveMarginResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RemoveMargin not implemented") -} -func (*UnimplementedMsgServer) AddMargin(ctx context.Context, req *MsgAddMargin) (*MsgAddMarginResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method AddMargin not implemented") -} -func (*UnimplementedMsgServer) MultiLiquidate(ctx context.Context, req *MsgMultiLiquidate) (*MsgMultiLiquidateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method MultiLiquidate not implemented") -} -func (*UnimplementedMsgServer) MarketOrder(ctx context.Context, req *MsgMarketOrder) (*MsgMarketOrderResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method MarketOrder not implemented") -} -func (*UnimplementedMsgServer) ClosePosition(ctx context.Context, req *MsgClosePosition) (*MsgClosePositionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClosePosition not implemented") -} -func (*UnimplementedMsgServer) PartialClose(ctx context.Context, req *MsgPartialClose) (*MsgPartialCloseResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method PartialClose not implemented") -} -func (*UnimplementedMsgServer) SettlePosition(ctx context.Context, req *MsgSettlePosition) (*MsgClosePositionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SettlePosition not implemented") -} -func (*UnimplementedMsgServer) DonateToEcosystemFund(ctx context.Context, req *MsgDonateToEcosystemFund) (*MsgDonateToEcosystemFundResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DonateToEcosystemFund not implemented") -} -func (*UnimplementedMsgServer) ChangeCollateralDenom(ctx context.Context, req *MsgChangeCollateralDenom) (*MsgChangeCollateralDenomResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ChangeCollateralDenom not implemented") -} -func (*UnimplementedMsgServer) AllocateEpochRebates(ctx context.Context, req *MsgAllocateEpochRebates) (*MsgAllocateEpochRebatesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method AllocateEpochRebates not implemented") -} -func (*UnimplementedMsgServer) WithdrawEpochRebates(ctx context.Context, req *MsgWithdrawEpochRebates) (*MsgWithdrawEpochRebatesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method WithdrawEpochRebates not implemented") -} -func (*UnimplementedMsgServer) ShiftPegMultiplier(ctx context.Context, req *MsgShiftPegMultiplier) (*MsgShiftPegMultiplierResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ShiftPegMultiplier not implemented") -} -func (*UnimplementedMsgServer) ShiftSwapInvariant(ctx context.Context, req *MsgShiftSwapInvariant) (*MsgShiftSwapInvariantResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ShiftSwapInvariant not implemented") -} -func (*UnimplementedMsgServer) WithdrawFromPerpFund(ctx context.Context, req *MsgWithdrawFromPerpFund) (*MsgWithdrawFromPerpFundResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method WithdrawFromPerpFund not implemented") -} -func (*UnimplementedMsgServer) CloseMarket(ctx context.Context, req *MsgCloseMarket) (*MsgCloseMarketResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CloseMarket not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_RemoveMargin_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgRemoveMargin) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).RemoveMargin(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/RemoveMargin", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).RemoveMargin(ctx, req.(*MsgRemoveMargin)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_AddMargin_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgAddMargin) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).AddMargin(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/AddMargin", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).AddMargin(ctx, req.(*MsgAddMargin)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_MultiLiquidate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgMultiLiquidate) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).MultiLiquidate(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/MultiLiquidate", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).MultiLiquidate(ctx, req.(*MsgMultiLiquidate)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_MarketOrder_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgMarketOrder) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).MarketOrder(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/MarketOrder", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).MarketOrder(ctx, req.(*MsgMarketOrder)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ClosePosition_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClosePosition) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClosePosition(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/ClosePosition", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClosePosition(ctx, req.(*MsgClosePosition)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_PartialClose_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgPartialClose) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).PartialClose(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/PartialClose", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).PartialClose(ctx, req.(*MsgPartialClose)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_SettlePosition_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgSettlePosition) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).SettlePosition(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/SettlePosition", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).SettlePosition(ctx, req.(*MsgSettlePosition)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_DonateToEcosystemFund_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDonateToEcosystemFund) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).DonateToEcosystemFund(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/DonateToEcosystemFund", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).DonateToEcosystemFund(ctx, req.(*MsgDonateToEcosystemFund)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ChangeCollateralDenom_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgChangeCollateralDenom) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ChangeCollateralDenom(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/ChangeCollateralDenom", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ChangeCollateralDenom(ctx, req.(*MsgChangeCollateralDenom)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_AllocateEpochRebates_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgAllocateEpochRebates) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).AllocateEpochRebates(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/AllocateEpochRebates", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).AllocateEpochRebates(ctx, req.(*MsgAllocateEpochRebates)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_WithdrawEpochRebates_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdrawEpochRebates) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).WithdrawEpochRebates(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/WithdrawEpochRebates", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).WithdrawEpochRebates(ctx, req.(*MsgWithdrawEpochRebates)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ShiftPegMultiplier_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgShiftPegMultiplier) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ShiftPegMultiplier(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/ShiftPegMultiplier", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ShiftPegMultiplier(ctx, req.(*MsgShiftPegMultiplier)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ShiftSwapInvariant_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgShiftSwapInvariant) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ShiftSwapInvariant(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/ShiftSwapInvariant", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ShiftSwapInvariant(ctx, req.(*MsgShiftSwapInvariant)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_WithdrawFromPerpFund_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgWithdrawFromPerpFund) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).WithdrawFromPerpFund(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/WithdrawFromPerpFund", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).WithdrawFromPerpFund(ctx, req.(*MsgWithdrawFromPerpFund)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_CloseMarket_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgCloseMarket) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).CloseMarket(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.perp.v2.Msg/CloseMarket", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).CloseMarket(ctx, req.(*MsgCloseMarket)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "nibiru.perp.v2.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "RemoveMargin", - Handler: _Msg_RemoveMargin_Handler, - }, - { - MethodName: "AddMargin", - Handler: _Msg_AddMargin_Handler, - }, - { - MethodName: "MultiLiquidate", - Handler: _Msg_MultiLiquidate_Handler, - }, - { - MethodName: "MarketOrder", - Handler: _Msg_MarketOrder_Handler, - }, - { - MethodName: "ClosePosition", - Handler: _Msg_ClosePosition_Handler, - }, - { - MethodName: "PartialClose", - Handler: _Msg_PartialClose_Handler, - }, - { - MethodName: "SettlePosition", - Handler: _Msg_SettlePosition_Handler, - }, - { - MethodName: "DonateToEcosystemFund", - Handler: _Msg_DonateToEcosystemFund_Handler, - }, - { - MethodName: "ChangeCollateralDenom", - Handler: _Msg_ChangeCollateralDenom_Handler, - }, - { - MethodName: "AllocateEpochRebates", - Handler: _Msg_AllocateEpochRebates_Handler, - }, - { - MethodName: "WithdrawEpochRebates", - Handler: _Msg_WithdrawEpochRebates_Handler, - }, - { - MethodName: "ShiftPegMultiplier", - Handler: _Msg_ShiftPegMultiplier_Handler, - }, - { - MethodName: "ShiftSwapInvariant", - Handler: _Msg_ShiftSwapInvariant_Handler, - }, - { - MethodName: "WithdrawFromPerpFund", - Handler: _Msg_WithdrawFromPerpFund_Handler, - }, - { - MethodName: "CloseMarket", - Handler: _Msg_CloseMarket_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "nibiru/perp/v2/tx.proto", -} - -func (m *MsgSettlePosition) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgSettlePosition) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSettlePosition) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Version != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Version)) - i-- - dAtA[i] = 0x18 - } - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgRemoveMargin) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgRemoveMargin) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgRemoveMargin) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Margin.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgRemoveMarginResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgRemoveMarginResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgRemoveMarginResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Position != nil { - { - size, err := m.Position.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - { - size := m.FundingPayment.Size() - i -= size - if _, err := m.FundingPayment.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.MarginOut.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *MsgAddMargin) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgAddMargin) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgAddMargin) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Margin.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgAddMarginResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgAddMarginResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgAddMarginResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Position != nil { - { - size, err := m.Position.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - { - size := m.FundingPayment.Size() - i -= size - if _, err := m.FundingPayment.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *MsgMultiLiquidate) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgMultiLiquidate) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMultiLiquidate) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Liquidations) > 0 { - for iNdEx := len(m.Liquidations) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Liquidations[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgMultiLiquidate_Liquidation) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgMultiLiquidate_Liquidation) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMultiLiquidate_Liquidation) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Trader) > 0 { - i -= len(m.Trader) - copy(dAtA[i:], m.Trader) - i = encodeVarintTx(dAtA, i, uint64(len(m.Trader))) - i-- - dAtA[i] = 0x12 - } - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *MsgMultiLiquidateResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgMultiLiquidateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMultiLiquidateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Liquidations) > 0 { - for iNdEx := len(m.Liquidations) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Liquidations[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *MsgMultiLiquidateResponse_LiquidationResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgMultiLiquidateResponse_LiquidationResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMultiLiquidateResponse_LiquidationResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - if len(m.Trader) > 0 { - i -= len(m.Trader) - copy(dAtA[i:], m.Trader) - i = encodeVarintTx(dAtA, i, uint64(len(m.Trader))) - i-- - dAtA[i] = 0x2a - } - if m.PerpEfFee != nil { - { - size, err := m.PerpEfFee.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - if m.LiquidatorFee != nil { - { - size, err := m.LiquidatorFee.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if len(m.Error) > 0 { - i -= len(m.Error) - copy(dAtA[i:], m.Error) - i = encodeVarintTx(dAtA, i, uint64(len(m.Error))) - i-- - dAtA[i] = 0x12 - } - if m.Success { - i-- - if m.Success { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MsgMarketOrder) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgMarketOrder) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMarketOrder) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.BaseAssetAmountLimit.Size() - i -= size - if _, err := m.BaseAssetAmountLimit.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size := m.Leverage.Size() - i -= size - if _, err := m.Leverage.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.QuoteAssetAmount.Size() - i -= size - if _, err := m.QuoteAssetAmount.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if m.Side != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Side)) - i-- - dAtA[i] = 0x18 - } - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgMarketOrderResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgMarketOrderResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMarketOrderResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.PositionNotional.Size() - i -= size - if _, err := m.PositionNotional.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - { - size := m.MarginToVault.Size() - i -= size - if _, err := m.MarginToVault.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size := m.UnrealizedPnlAfter.Size() - i -= size - if _, err := m.UnrealizedPnlAfter.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size := m.RealizedPnl.Size() - i -= size - if _, err := m.RealizedPnl.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.FundingPayment.Size() - i -= size - if _, err := m.FundingPayment.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.ExchangedPositionSize.Size() - i -= size - if _, err := m.ExchangedPositionSize.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.ExchangedNotionalValue.Size() - i -= size - if _, err := m.ExchangedNotionalValue.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.Position != nil { - { - size, err := m.Position.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClosePosition) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClosePosition) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClosePosition) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgClosePositionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgClosePositionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClosePositionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.MarginToTrader.Size() - i -= size - if _, err := m.MarginToTrader.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.RealizedPnl.Size() - i -= size - if _, err := m.RealizedPnl.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.FundingPayment.Size() - i -= size - if _, err := m.FundingPayment.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.ExchangedPositionSize.Size() - i -= size - if _, err := m.ExchangedPositionSize.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.ExchangedNotionalValue.Size() - i -= size - if _, err := m.ExchangedNotionalValue.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *MsgPartialClose) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgPartialClose) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgPartialClose) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Size_.Size() - i -= size - if _, err := m.Size_.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgPartialCloseResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgPartialCloseResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgPartialCloseResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.MarginToTrader.Size() - i -= size - if _, err := m.MarginToTrader.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.RealizedPnl.Size() - i -= size - if _, err := m.RealizedPnl.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.FundingPayment.Size() - i -= size - if _, err := m.FundingPayment.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.ExchangedPositionSize.Size() - i -= size - if _, err := m.ExchangedPositionSize.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.ExchangedNotionalValue.Size() - i -= size - if _, err := m.ExchangedNotionalValue.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *MsgDonateToEcosystemFund) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDonateToEcosystemFund) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDonateToEcosystemFund) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Donation.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDonateToEcosystemFundResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgDonateToEcosystemFundResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDonateToEcosystemFundResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgChangeCollateralDenom) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgChangeCollateralDenom) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgChangeCollateralDenom) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.NewDenom) > 0 { - i -= len(m.NewDenom) - copy(dAtA[i:], m.NewDenom) - i = encodeVarintTx(dAtA, i, uint64(len(m.NewDenom))) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgChangeCollateralDenomResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgChangeCollateralDenomResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgChangeCollateralDenomResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgAllocateEpochRebates) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgAllocateEpochRebates) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgAllocateEpochRebates) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Rebates) > 0 { - for iNdEx := len(m.Rebates) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Rebates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgAllocateEpochRebatesResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgAllocateEpochRebatesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgAllocateEpochRebatesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TotalEpochRebates) > 0 { - for iNdEx := len(m.TotalEpochRebates) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TotalEpochRebates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawEpochRebates) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdrawEpochRebates) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawEpochRebates) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Epochs) > 0 { - dAtA11 := make([]byte, len(m.Epochs)*10) - var j10 int - for _, num := range m.Epochs { - for num >= 1<<7 { - dAtA11[j10] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j10++ - } - dAtA11[j10] = uint8(num) - j10++ - } - i -= j10 - copy(dAtA[i:], dAtA11[:j10]) - i = encodeVarintTx(dAtA, i, uint64(j10)) - i-- - dAtA[i] = 0x12 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawEpochRebatesResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdrawEpochRebatesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawEpochRebatesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.WithdrawnRebates) > 0 { - for iNdEx := len(m.WithdrawnRebates) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.WithdrawnRebates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *MsgShiftPegMultiplier) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgShiftPegMultiplier) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgShiftPegMultiplier) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.NewPegMult.Size() - i -= size - if _, err := m.NewPegMult.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgShiftPegMultiplierResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgShiftPegMultiplierResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgShiftPegMultiplierResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgShiftSwapInvariant) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgShiftSwapInvariant) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgShiftSwapInvariant) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.NewSwapInvariant.Size() - i -= size - if _, err := m.NewSwapInvariant.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgShiftSwapInvariantResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgShiftSwapInvariantResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgShiftSwapInvariantResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawFromPerpFund) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdrawFromPerpFund) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawFromPerpFund) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ToAddr) > 0 { - i -= len(m.ToAddr) - copy(dAtA[i:], m.ToAddr) - i = encodeVarintTx(dAtA, i, uint64(len(m.ToAddr))) - i-- - dAtA[i] = 0x22 - } - if len(m.Denom) > 0 { - i -= len(m.Denom) - copy(dAtA[i:], m.Denom) - i = encodeVarintTx(dAtA, i, uint64(len(m.Denom))) - i-- - dAtA[i] = 0x1a - } - { - size := m.Amount.Size() - i -= size - if _, err := m.Amount.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgWithdrawFromPerpFundResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgWithdrawFromPerpFundResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgWithdrawFromPerpFundResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgCloseMarket) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgCloseMarket) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCloseMarket) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Pair.Size() - i -= size - if _, err := m.Pair.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgCloseMarketResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MsgCloseMarketResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCloseMarketResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintTx(dAtA []byte, offset int, v uint64) int { - offset -= sovTx(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MsgSettlePosition) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Pair.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Version != 0 { - n += 1 + sovTx(uint64(m.Version)) - } - return n -} - -func (m *MsgRemoveMargin) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Pair.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.Margin.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgRemoveMarginResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.MarginOut.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.FundingPayment.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Position != nil { - l = m.Position.Size() - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgAddMargin) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Pair.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.Margin.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgAddMarginResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.FundingPayment.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Position != nil { - l = m.Position.Size() - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgMultiLiquidate) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Liquidations) > 0 { - for _, e := range m.Liquidations { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgMultiLiquidate_Liquidation) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Pair.Size() - n += 1 + l + sovTx(uint64(l)) - l = len(m.Trader) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgMultiLiquidateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Liquidations) > 0 { - for _, e := range m.Liquidations { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgMultiLiquidateResponse_LiquidationResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Success { - n += 2 - } - l = len(m.Error) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.LiquidatorFee != nil { - l = m.LiquidatorFee.Size() - n += 1 + l + sovTx(uint64(l)) - } - if m.PerpEfFee != nil { - l = m.PerpEfFee.Size() - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Trader) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Pair.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgMarketOrder) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Pair.Size() - n += 1 + l + sovTx(uint64(l)) - if m.Side != 0 { - n += 1 + sovTx(uint64(m.Side)) - } - l = m.QuoteAssetAmount.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.Leverage.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.BaseAssetAmountLimit.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgMarketOrderResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Position != nil { - l = m.Position.Size() - n += 1 + l + sovTx(uint64(l)) - } - l = m.ExchangedNotionalValue.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.ExchangedPositionSize.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.FundingPayment.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.RealizedPnl.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.UnrealizedPnlAfter.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.MarginToVault.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.PositionNotional.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgClosePosition) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Pair.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgClosePositionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ExchangedNotionalValue.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.ExchangedPositionSize.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.FundingPayment.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.RealizedPnl.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.MarginToTrader.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgPartialClose) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Pair.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.Size_.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgPartialCloseResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ExchangedNotionalValue.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.ExchangedPositionSize.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.FundingPayment.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.RealizedPnl.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.MarginToTrader.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgDonateToEcosystemFund) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Donation.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgDonateToEcosystemFundResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgChangeCollateralDenom) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.NewDenom) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgChangeCollateralDenomResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgAllocateEpochRebates) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Rebates) > 0 { - for _, e := range m.Rebates { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgAllocateEpochRebatesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.TotalEpochRebates) > 0 { - for _, e := range m.TotalEpochRebates { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgWithdrawEpochRebates) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Epochs) > 0 { - l = 0 - for _, e := range m.Epochs { - l += sovTx(uint64(e)) - } - n += 1 + sovTx(uint64(l)) + l - } - return n -} - -func (m *MsgWithdrawEpochRebatesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.WithdrawnRebates) > 0 { - for _, e := range m.WithdrawnRebates { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgShiftPegMultiplier) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Pair.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.NewPegMult.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgShiftPegMultiplierResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgShiftSwapInvariant) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Pair.Size() - n += 1 + l + sovTx(uint64(l)) - l = m.NewSwapInvariant.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgShiftSwapInvariantResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgWithdrawFromPerpFund) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Amount.Size() - n += 1 + l + sovTx(uint64(l)) - l = len(m.Denom) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.ToAddr) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgWithdrawFromPerpFundResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgCloseMarket) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Pair.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgCloseMarketResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovTx(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTx(x uint64) (n int) { - return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MsgSettlePosition) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgSettlePosition: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSettlePosition: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Version", wireType) - } - m.Version = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Version |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgRemoveMargin) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgRemoveMargin: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgRemoveMargin: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Margin", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Margin.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgRemoveMarginResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgRemoveMarginResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgRemoveMarginResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarginOut", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MarginOut.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FundingPayment", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FundingPayment.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Position", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Position == nil { - m.Position = &Position{} - } - if err := m.Position.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgAddMargin) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgAddMargin: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgAddMargin: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Margin", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Margin.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgAddMarginResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgAddMarginResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgAddMarginResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FundingPayment", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FundingPayment.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Position", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Position == nil { - m.Position = &Position{} - } - if err := m.Position.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgMultiLiquidate) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgMultiLiquidate: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMultiLiquidate: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Liquidations", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Liquidations = append(m.Liquidations, &MsgMultiLiquidate_Liquidation{}) - if err := m.Liquidations[len(m.Liquidations)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgMultiLiquidate_Liquidation) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Liquidation: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Liquidation: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Trader", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Trader = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgMultiLiquidateResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgMultiLiquidateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMultiLiquidateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Liquidations", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Liquidations = append(m.Liquidations, &MsgMultiLiquidateResponse_LiquidationResponse{}) - if err := m.Liquidations[len(m.Liquidations)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgMultiLiquidateResponse_LiquidationResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: LiquidationResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: LiquidationResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Success = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field LiquidatorFee", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.LiquidatorFee == nil { - m.LiquidatorFee = &types.Coin{} - } - if err := m.LiquidatorFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PerpEfFee", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.PerpEfFee == nil { - m.PerpEfFee = &types.Coin{} - } - if err := m.PerpEfFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Trader", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Trader = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgMarketOrder) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgMarketOrder: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMarketOrder: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Side", wireType) - } - m.Side = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Side |= Direction(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field QuoteAssetAmount", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.QuoteAssetAmount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Leverage", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Leverage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BaseAssetAmountLimit", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.BaseAssetAmountLimit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgMarketOrderResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgMarketOrderResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMarketOrderResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Position", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Position == nil { - m.Position = &Position{} - } - if err := m.Position.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExchangedNotionalValue", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExchangedNotionalValue.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExchangedPositionSize", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExchangedPositionSize.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FundingPayment", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FundingPayment.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RealizedPnl", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.RealizedPnl.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UnrealizedPnlAfter", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.UnrealizedPnlAfter.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarginToVault", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MarginToVault.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PositionNotional", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.PositionNotional.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClosePosition) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClosePosition: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClosePosition: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgClosePositionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgClosePositionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClosePositionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExchangedNotionalValue", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExchangedNotionalValue.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExchangedPositionSize", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExchangedPositionSize.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FundingPayment", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FundingPayment.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RealizedPnl", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.RealizedPnl.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarginToTrader", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MarginToTrader.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgPartialClose) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgPartialClose: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgPartialClose: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Size_", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Size_.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgPartialCloseResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgPartialCloseResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgPartialCloseResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExchangedNotionalValue", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExchangedNotionalValue.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExchangedPositionSize", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExchangedPositionSize.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FundingPayment", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FundingPayment.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RealizedPnl", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.RealizedPnl.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MarginToTrader", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MarginToTrader.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDonateToEcosystemFund) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDonateToEcosystemFund: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDonateToEcosystemFund: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Donation", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Donation.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgDonateToEcosystemFundResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgDonateToEcosystemFundResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDonateToEcosystemFundResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgChangeCollateralDenom) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgChangeCollateralDenom: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgChangeCollateralDenom: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NewDenom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.NewDenom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgChangeCollateralDenomResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgChangeCollateralDenomResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgChangeCollateralDenomResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgAllocateEpochRebates) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgAllocateEpochRebates: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgAllocateEpochRebates: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Rebates", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Rebates = append(m.Rebates, types.Coin{}) - if err := m.Rebates[len(m.Rebates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgAllocateEpochRebatesResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgAllocateEpochRebatesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgAllocateEpochRebatesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalEpochRebates", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.TotalEpochRebates = append(m.TotalEpochRebates, types.Coin{}) - if err := m.TotalEpochRebates[len(m.TotalEpochRebates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawEpochRebates) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawEpochRebates: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawEpochRebates: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType == 0 { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Epochs = append(m.Epochs, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.Epochs) == 0 { - m.Epochs = make([]uint64, 0, elementCount) - } - for iNdEx < postIndex { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Epochs = append(m.Epochs, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field Epochs", wireType) - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawEpochRebatesResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawEpochRebatesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawEpochRebatesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field WithdrawnRebates", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.WithdrawnRebates = append(m.WithdrawnRebates, types.Coin{}) - if err := m.WithdrawnRebates[len(m.WithdrawnRebates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgShiftPegMultiplier) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgShiftPegMultiplier: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgShiftPegMultiplier: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NewPegMult", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.NewPegMult.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgShiftPegMultiplierResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgShiftPegMultiplierResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgShiftPegMultiplierResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgShiftSwapInvariant) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgShiftSwapInvariant: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgShiftSwapInvariant: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NewSwapInvariant", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.NewSwapInvariant.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgShiftSwapInvariantResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgShiftSwapInvariantResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgShiftSwapInvariantResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawFromPerpFund) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawFromPerpFund: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawFromPerpFund: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Denom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ToAddr", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ToAddr = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgWithdrawFromPerpFundResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgWithdrawFromPerpFundResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgWithdrawFromPerpFundResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgCloseMarket) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgCloseMarket: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCloseMarket: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pair", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Pair.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgCloseMarketResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgCloseMarketResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCloseMarketResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTx(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTx - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTx - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTx - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTx - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/sudo/module.go b/x/sudo/module.go index 1e0031ad1..18a42eb46 100644 --- a/x/sudo/module.go +++ b/x/sudo/module.go @@ -44,7 +44,6 @@ func (AppModuleBasic) Name() string { return types.ModuleName } -// RegisterInterfaces registers interfaces and implementations of the perp module. func (AppModuleBasic) RegisterInterfaces(interfaceRegistry codectypes.InterfaceRegistry) { types.RegisterInterfaces(interfaceRegistry) }