From 3036618406e3992f3a959fb3f6c2ceacf2a5fb26 Mon Sep 17 00:00:00 2001 From: Matthias <97468149+matthiasmatt@users.noreply.github.com> Date: Mon, 22 Apr 2024 01:37:45 +0200 Subject: [PATCH] fix: unwire spot module for main branch (#1831) * feat: rest in peace * fix: fix e2e wasm test * fix: fix justfile and deplyo-wasm * fix: update localnet * feat: rest in peace * fix(localnet.sh): change order of operations in genesis config * fix(localnet.sh): change order of operations in genesis config * rm unused file --------- Co-authored-by: Unique-Divine Co-authored-by: Unique Divine <51418232+Unique-Divine@users.noreply.github.com> --- app/keepers.go | 15 - contrib/scripts/localnet.sh | 12 +- contrib/scripts/testing/stableswap_model.py | 238 - justfile | 2 +- proto/nibiru/spot/v1/event.proto | 86 - proto/nibiru/spot/v1/genesis.proto | 18 - proto/nibiru/spot/v1/params.proto | 27 - proto/nibiru/spot/v1/pool.proto | 97 - proto/nibiru/spot/v1/query.proto | 282 - proto/nibiru/spot/v1/tx.proto | 120 - simapp/sim_test.go | 2 - x/common/testutil/mock/dex_pool.go | 53 - x/spot/README.md | 374 -- x/spot/client/cli/flags.go | 86 - x/spot/client/cli/query.go | 194 - x/spot/client/cli/tx.go | 334 - x/spot/client/testutil/cli_test.go | 47 - x/spot/client/testutil/suite.go | 791 --- x/spot/client/testutil/test_helpers.go | 182 - x/spot/genesis.go | 27 - x/spot/genesis_test.go | 54 - x/spot/keeper/balances.go | 35 - x/spot/keeper/balances_test.go | 78 - x/spot/keeper/grpc_query.go | 334 - x/spot/keeper/grpc_query_test.go | 807 --- x/spot/keeper/keeper.go | 611 -- x/spot/keeper/keeper_test.go | 873 --- x/spot/keeper/liquidity.go | 156 - x/spot/keeper/liquidity_test.go | 127 - x/spot/keeper/msg_server.go | 166 - x/spot/keeper/msg_server_test.go | 1254 ---- x/spot/keeper/params.go | 18 - x/spot/keeper/params_test.go | 19 - x/spot/keeper/swap.go | 121 - x/spot/keeper/swap_test.go | 399 -- x/spot/math/constant_function.go | 40 - x/spot/math/constant_function_test.go | 59 - x/spot/module.go | 176 - x/spot/simulation/genesis.go | 34 - x/spot/simulation/operations.go | 441 -- x/spot/types/codec.go | 30 - x/spot/types/constants.go | 37 - x/spot/types/errors.go | 42 - x/spot/types/event.pb.go | 1816 ----- x/spot/types/expected_keepers.go | 53 - x/spot/types/export.go | 12 - x/spot/types/genesis.go | 15 - x/spot/types/genesis.pb.go | 387 -- x/spot/types/genesis_test.go | 37 - x/spot/types/keys.go | 54 - x/spot/types/message.go | 226 - x/spot/types/message_test.go | 350 - x/spot/types/misc/stabletests.csv | 200 - x/spot/types/params.go | 98 - x/spot/types/params.pb.go | 434 -- x/spot/types/pool.go | 504 -- x/spot/types/pool.pb.go | 1123 ---- x/spot/types/pool_asset.go | 50 - x/spot/types/pool_asset_test.go | 118 - x/spot/types/pool_test.go | 987 --- x/spot/types/price.go | 22 - x/spot/types/price_test.go | 104 - x/spot/types/query.pb.go | 6584 ------------------- x/spot/types/query.pb.gw.go | 1614 ----- x/spot/types/shares.go | 242 - x/spot/types/shares_test.go | 499 -- x/spot/types/swap.go | 193 - x/spot/types/swap_test.go | 362 - x/spot/types/tx.pb.go | 2363 ------- x/spot/types/tx.pb.gw.go | 528 -- x/spot/types/utils.go | 74 - x/spot/types/utils_test.go | 250 - 72 files changed, 3 insertions(+), 28194 deletions(-) delete mode 100644 contrib/scripts/testing/stableswap_model.py delete mode 100644 proto/nibiru/spot/v1/event.proto delete mode 100644 proto/nibiru/spot/v1/genesis.proto delete mode 100644 proto/nibiru/spot/v1/params.proto delete mode 100644 proto/nibiru/spot/v1/pool.proto delete mode 100644 proto/nibiru/spot/v1/query.proto delete mode 100644 proto/nibiru/spot/v1/tx.proto delete mode 100644 x/common/testutil/mock/dex_pool.go delete mode 100644 x/spot/README.md delete mode 100644 x/spot/client/cli/flags.go delete mode 100644 x/spot/client/cli/query.go delete mode 100644 x/spot/client/cli/tx.go delete mode 100644 x/spot/client/testutil/cli_test.go delete mode 100644 x/spot/client/testutil/suite.go delete mode 100644 x/spot/client/testutil/test_helpers.go delete mode 100644 x/spot/genesis.go delete mode 100644 x/spot/genesis_test.go delete mode 100644 x/spot/keeper/balances.go delete mode 100644 x/spot/keeper/balances_test.go delete mode 100644 x/spot/keeper/grpc_query.go delete mode 100644 x/spot/keeper/grpc_query_test.go delete mode 100644 x/spot/keeper/keeper.go delete mode 100644 x/spot/keeper/keeper_test.go delete mode 100644 x/spot/keeper/liquidity.go delete mode 100644 x/spot/keeper/liquidity_test.go delete mode 100644 x/spot/keeper/msg_server.go delete mode 100644 x/spot/keeper/msg_server_test.go delete mode 100644 x/spot/keeper/params.go delete mode 100644 x/spot/keeper/params_test.go delete mode 100644 x/spot/keeper/swap.go delete mode 100644 x/spot/keeper/swap_test.go delete mode 100644 x/spot/math/constant_function.go delete mode 100644 x/spot/math/constant_function_test.go delete mode 100644 x/spot/module.go delete mode 100644 x/spot/simulation/genesis.go delete mode 100644 x/spot/simulation/operations.go delete mode 100644 x/spot/types/codec.go delete mode 100644 x/spot/types/constants.go delete mode 100644 x/spot/types/errors.go delete mode 100644 x/spot/types/event.pb.go delete mode 100644 x/spot/types/expected_keepers.go delete mode 100644 x/spot/types/export.go delete mode 100644 x/spot/types/genesis.go delete mode 100644 x/spot/types/genesis.pb.go delete mode 100644 x/spot/types/genesis_test.go delete mode 100644 x/spot/types/keys.go delete mode 100644 x/spot/types/message.go delete mode 100644 x/spot/types/message_test.go delete mode 100644 x/spot/types/misc/stabletests.csv delete mode 100644 x/spot/types/params.go delete mode 100644 x/spot/types/params.pb.go delete mode 100644 x/spot/types/pool.go delete mode 100644 x/spot/types/pool.pb.go delete mode 100644 x/spot/types/pool_asset.go delete mode 100644 x/spot/types/pool_asset_test.go delete mode 100644 x/spot/types/pool_test.go delete mode 100644 x/spot/types/price.go delete mode 100644 x/spot/types/price_test.go delete mode 100644 x/spot/types/query.pb.go delete mode 100644 x/spot/types/query.pb.gw.go delete mode 100644 x/spot/types/shares.go delete mode 100644 x/spot/types/shares_test.go delete mode 100644 x/spot/types/swap.go delete mode 100644 x/spot/types/swap_test.go delete mode 100644 x/spot/types/tx.pb.go delete mode 100644 x/spot/types/tx.pb.gw.go delete mode 100644 x/spot/types/utils.go delete mode 100644 x/spot/types/utils_test.go diff --git a/app/keepers.go b/app/keepers.go index 2bcad97a8..8ea7df0da 100644 --- a/app/keepers.go +++ b/app/keepers.go @@ -111,10 +111,6 @@ import ( oraclekeeper "github.com/NibiruChain/nibiru/x/oracle/keeper" oracletypes "github.com/NibiruChain/nibiru/x/oracle/types" - "github.com/NibiruChain/nibiru/x/spot" - spotkeeper "github.com/NibiruChain/nibiru/x/spot/keeper" - spottypes "github.com/NibiruChain/nibiru/x/spot/types" - "github.com/NibiruChain/nibiru/x/sudo" "github.com/NibiruChain/nibiru/x/sudo/keeper" sudotypes "github.com/NibiruChain/nibiru/x/sudo/types" @@ -169,7 +165,6 @@ type AppKeepers struct { // Nibiru keepers // --------------- EpochsKeeper epochskeeper.Keeper - SpotKeeper spotkeeper.Keeper OracleKeeper oraclekeeper.Keeper InflationKeeper inflationkeeper.Keeper SudoKeeper keeper.Keeper @@ -208,7 +203,6 @@ func initStoreKeys() ( ibcexported.StoreKey, // nibiru x/ keys - spottypes.StoreKey, oracletypes.StoreKey, epochstypes.StoreKey, inflationtypes.StoreKey, @@ -348,10 +342,6 @@ func (app *NibiruApp) InitKeepers( // ---------------------------------- Nibiru Chain x/ keepers - app.SpotKeeper = spotkeeper.NewKeeper( - appCodec, keys[spottypes.StoreKey], app.GetSubspace(spottypes.ModuleName), - app.AccountKeeper, app.BankKeeper, app.DistrKeeper) - app.SudoKeeper = keeper.NewKeeper( appCodec, keys[sudotypes.StoreKey], ) @@ -578,7 +568,6 @@ func (app *NibiruApp) initAppModules( authzmodule.NewAppModule(appCodec, app.authzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), // Nibiru modules - spot.NewAppModule(appCodec, app.SpotKeeper, app.AccountKeeper, app.BankKeeper), oracle.NewAppModule(appCodec, app.OracleKeeper, app.AccountKeeper, app.BankKeeper), epochs.NewAppModule(appCodec, app.EpochsKeeper), inflation.NewAppModule(app.InflationKeeper, app.AccountKeeper, *app.stakingKeeper), @@ -649,7 +638,6 @@ func orderedModuleNames() []string { // -------------------------------------------------------------------- // Native x/ Modules epochstypes.ModuleName, - spottypes.ModuleName, oracletypes.ModuleName, inflationtypes.ModuleName, sudotypes.ModuleName, @@ -762,7 +750,6 @@ func ModuleBasicManager() module.BasicManager { ibctransfer.AppModuleBasic{}, ibctm.AppModuleBasic{}, // native x/ - spot.AppModuleBasic{}, oracle.AppModuleBasic{}, epochs.AppModuleBasic{}, inflation.AppModuleBasic{}, @@ -783,7 +770,6 @@ func ModuleAccPerms() map[string][]string { stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, govtypes.ModuleName: {authtypes.Burner}, - spottypes.ModuleName: {authtypes.Minter, authtypes.Burner}, oracletypes.ModuleName: {}, ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, ibcfeetypes.ModuleName: {}, @@ -810,7 +796,6 @@ func initParamsKeeper( paramsKeeper.Subspace(govtypes.ModuleName) paramsKeeper.Subspace(crisistypes.ModuleName) // Nibiru core params keepers | x/ - paramsKeeper.Subspace(spottypes.ModuleName) paramsKeeper.Subspace(epochstypes.ModuleName) paramsKeeper.Subspace(inflationtypes.ModuleName) // ibc params keepers diff --git a/contrib/scripts/localnet.sh b/contrib/scripts/localnet.sh index 59331148f..92afc9839 100755 --- a/contrib/scripts/localnet.sh +++ b/contrib/scripts/localnet.sh @@ -24,7 +24,7 @@ console_log_text_color() { } if [ console_log_text_color ]; then - echo "successfully toggled console coloring" + echo "succesfully toggled console coloring" else # For Ubuntu and Debian. MacOS has tput by default. apt-get install libncurses5-dbg -y @@ -58,8 +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_SPOT: Feature flag for x/spot. Enabled with `--features spot`. -FLAG_SPOT=false build_from_source() { echo_info "Building from source..." @@ -97,6 +95,7 @@ while [[ $# -gt 0 ]]; do esac done + # Check if FLAG_NO_BUILD was set to true if ! $FLAG_NO_BUILD; then build_from_source @@ -104,7 +103,6 @@ fi echo_info "Features flags:" echo "FLAG_NO_BUILD: $FLAG_NO_BUILD" -echo "FLAG_SPOT: $FLAG_SPOT" SEDOPTION="" if [[ "$OSTYPE" == "darwin"* ]]; then @@ -188,10 +186,6 @@ add_genesis_param() { echo_info "Configuring genesis params" -# if $FLAG_SPOT; then -# # Perform any actions specific to the x/spot feature -# fi - # set validator as sudoer add_genesis_param '.app_state.sudo.sudoers.root = "'"$val_address"'"' @@ -203,8 +197,6 @@ add_genesis_param '.app_state.oracle.exchange_rates[0].exchange_rate = "'"$price add_genesis_param '.app_state.oracle.exchange_rates[1].pair = "ueth:uuusd"' add_genesis_param '.app_state.oracle.exchange_rates[1].exchange_rate = "'"$price_eth"'"' -add_genesis_param '.app_state.inflation.params.inflation_enabled = false' - # ------------------------------------------------------------------------ # Gentx # ------------------------------------------------------------------------ diff --git a/contrib/scripts/testing/stableswap_model.py b/contrib/scripts/testing/stableswap_model.py deleted file mode 100644 index 6b9490c6d..000000000 --- a/contrib/scripts/testing/stableswap_model.py +++ /dev/null @@ -1,238 +0,0 @@ -""" -This script geenrates random test for swaps on balancer pools. -The objective is to compare the performance of golang uint256 unit used against Python3 integer values. - -Python3 int type have no limit in term of size, which means that we can make arbitrary operations on ints and consider them as float. -The curve class comes directly from the curve codebase, and is being used to create the tests, stored in `x/spot/types/misc/stabletests.csv`;. - -Theses test are then used to compare the value of python model's DY against the one obtained with our go code. -These are created for pools with random amount of assets (from 2 to 5), random amplification parameter (from 1 to 4* common.Precision) and for random coins of the pool. - -By computing this, we ensure the validity of our SolveConstantProductInvariant function. -""" - -from collections import deque -from itertools import permutations -import os - -import csv -import random - -DECIMALS = 6 - -N_TESTS = 200 - -# From https://github.com/curvefi/curve-contract/blob/master/tests/simulation.py -class Curve: - - """ - Python model of Curve pool math. - """ - - def __init__(self, A, D, n, p=None, tokens=None): - """ - A: Amplification coefficient - D: Total deposit size - n: number of currencies - p: target prices - """ - self.A = A # actually A * n ** (n - 1) because it's an invariant - self.n = n - self.fee = 0 # 10**7 - if p: - self.p = p - else: - self.p = [10**18] * n - if isinstance(D, list): - self.x = D - else: - self.x = [D // n * 10**18 // _p for _p in self.p] - self.tokens = tokens - - def xp(self): - return [x * p // 10**18 for x, p in zip(self.x, self.p)] - - def D(self): - """ - D invariant calculation in non-overflowing integer operations - iteratively - - A * sum(x_i) * n**n + D = A * D * n**n + D**(n+1) / (n**n * prod(x_i)) - - Converging solution: - $D_{j+1} = D_j \frac{An^n \sum x_i + nD_P}{(n+1)D_P+D_j(An^n-1)}$ - - with $D_p = \frac{D_j^{n+1}}{n^n \prod x_i}$ - """ - Dprev = 0 - xp = self.xp() - S = sum(xp) - D = S - Ann = self.A * self.n**self.n - while abs(D - Dprev) > 1: - D_P = D - for x in xp: - D_P = D_P * D // (self.n * x) - Dprev = D - D = (Ann * S + D_P * self.n) * D // ((Ann - 1) * D + (self.n + 1) * D_P) - - return D - - def y(self, i, j, x): - """ - Calculate x[j] if one makes x[i] = x - - Done by solving quadratic equation iteratively. - x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n+1)/(n ** (2 * n) * prod' * A) - x_1**2 + b*x_1 = c - - x_1 = (x_1**2 + c) / (2*x_1 + b) - """ - D = self.D() - xx = self.xp() - xx[i] = x # x is quantity of underlying asset brought to 1e18 precision - xx = [xx[k] for k in range(self.n) if k != j] - Ann = self.A * self.n**self.n - c = D - for y in xx: - c = c * D // (y * self.n) - c = c * D // (self.n * Ann) - b = sum(xx) + D // Ann - D - y_prev = 0 - y = D - while abs(y - y_prev) > 1: - y_prev = y - y = (y**2 + c) // (2 * y + b) - return y # the result is in underlying units too - - def y_D(self, i, _D): - """ - Calculate x[j] if one makes x[i] = x - - Done by solving quadratic equation iteratively. - x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n+1)/(n ** (2 * n) * prod' * A) - x_1**2 + b*x_1 = c - - x_1 = (x_1**2 + c) / (2*x_1 + b - D) - """ - xx = self.xp() - xx = [xx[k] for k in range(self.n) if k != i] - S = sum(xx) - Ann = self.A * self.n**self.n - c = _D - for y in xx: - c = c * _D // (y * self.n) - c = c * _D // (self.n * Ann) - b = S + _D // Ann - y_prev = 0 - y = _D - while abs(y - y_prev) > 1: - y_prev = y - y = (y**2 + c) // (2 * y + b - _D) - return y # the result is in underlying units too - - def dy(self, i, j, dx): - # dx and dy are in underlying units - xp = self.xp() - return xp[j] - self.y(i, j, xp[i] + dx) - - def exchange(self, i, j, dx): - xp = self.xp() - x = xp[i] + dx - y = self.y(i, j, x) - dy = xp[j] - y - fee = dy * self.fee // 10**10 - assert dy > 0 - self.x[i] = x * 10**18 // self.p[i] - self.x[j] = (y + fee) * 10**18 // self.p[j] - return dy - fee - - def remove_liquidity_imbalance(self, amounts): - _fee = self.fee * self.n // (4 * (self.n - 1)) - - old_balances = self.x - new_balances = self.x[:] - D0 = self.D() - for i in range(self.n): - new_balances[i] -= amounts[i] - self.x = new_balances - D1 = self.D() - self.x = old_balances - fees = [0] * self.n - for i in range(self.n): - ideal_balance = D1 * old_balances[i] // D0 - difference = abs(ideal_balance - new_balances[i]) - fees[i] = _fee * difference // 10**10 - new_balances[i] -= fees[i] - self.x = new_balances - D2 = self.D() - self.x = old_balances - - token_amount = (D0 - D2) * self.tokens // D0 - - return token_amount - - def calc_withdraw_one_coin(self, token_amount, i): - xp = self.xp() - if self.fee: - fee = self.fee - self.fee * xp[i] // sum(xp) + 5 * 10**5 - else: - fee = 0 - - D0 = self.D() - D1 = D0 - token_amount * D0 // self.tokens - dy = xp[i] - self.y_D(i, D1) - - return dy - dy * fee // 10**10 - - -def generate_test_cases(n: int): - """ - Create n test cases and store them in x/spot/types/misc/stable-swap-math.csv - - Args: - n (int): The number of test to create - """ - - test_cases = [] - - for _ in range(n): - n_coins = random.randint(2, 5) - exchange_pairs = deque(permutations(range(n_coins), 2)) - - # 10% chance of being 1 (constant product if A=1) - amplification = random.randint(1, 4_000) if random.random() < 0.9 else 1 - - exchange_pair = random.choice(exchange_pairs) - balances = [random.randint(1, 10e16) for i in range(n_coins)] - balances_save = balances.copy() - - curve_model = Curve(amplification, balances, n_coins) - - send, recv = exchange_pair - - dx = random.randint(1, balances[recv]) - dy = curve_model.exchange(send, recv, dx) - - test_cases.append( - [ - balances_save, - amplification, - send, - recv, - dx, - dy, - ] - ) - - file_path = os.path.join( - os.path.dirname(__file__), "../../x/spot/types/misc/stabletests.csv" - ) - - with open(file_path, "w") as f: - writer = csv.writer(f) - writer.writerows(test_cases) - - -if __name__ == "__main__": - generate_test_cases(N_TESTS) diff --git a/justfile b/justfile index 037b68db2..746366afc 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 spot" +# Runs a Nibiru local network. Ex: "just localnet", "just localnet --features featureA" localnet *PASS_FLAGS: make localnet FLAGS="{{PASS_FLAGS}}" diff --git a/proto/nibiru/spot/v1/event.proto b/proto/nibiru/spot/v1/event.proto deleted file mode 100644 index 3e4788d9a..000000000 --- a/proto/nibiru/spot/v1/event.proto +++ /dev/null @@ -1,86 +0,0 @@ -syntax = "proto3"; - -package nibiru.spot.v1; - -import "gogoproto/gogo.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "nibiru/spot/v1/pool.proto"; - -option go_package = "github.com/NibiruChain/nibiru/x/spot/types"; - -message EventPoolCreated { - // the address of the user who created the pool - string creator = 1; - - // the create pool fee - repeated cosmos.base.v1beta1.Coin fees = 2 [ (gogoproto.nullable) = false ]; - - // the final state of the pool - nibiru.spot.v1.Pool final_pool = 4 [ (gogoproto.nullable) = false ]; - - // the amount of pool shares that the user received - cosmos.base.v1beta1.Coin final_user_pool_shares = 5 - [ (gogoproto.nullable) = false ]; -} - -message EventPoolJoined { - // the address of the user who joined the pool - string address = 1; - - // the amount of tokens that the user deposited - repeated cosmos.base.v1beta1.Coin tokens_in = 2 - [ (gogoproto.nullable) = false ]; - - // the amount of pool shares that the user received - cosmos.base.v1beta1.Coin pool_shares_out = 3 [ (gogoproto.nullable) = false ]; - - // the amount of tokens remaining for the user - repeated cosmos.base.v1beta1.Coin rem_coins = 4 - [ (gogoproto.nullable) = false ]; - - // the final state of the pool - nibiru.spot.v1.Pool final_pool = 5 [ (gogoproto.nullable) = false ]; - - // the final amount of user pool shares - cosmos.base.v1beta1.Coin final_user_pool_shares = 6 - [ (gogoproto.nullable) = false ]; -} - -message EventPoolExited { - // the address of the user who exited the pool - string address = 1; - - // the amount of pool shares that the user exited with - cosmos.base.v1beta1.Coin pool_shares_in = 2 [ (gogoproto.nullable) = false ]; - - // the amount of tokens returned to the user - repeated cosmos.base.v1beta1.Coin tokens_out = 3 - [ (gogoproto.nullable) = false ]; - - // the amount of fees collected by the pool - repeated cosmos.base.v1beta1.Coin fees = 4 [ (gogoproto.nullable) = false ]; - - // the final state of the pool - nibiru.spot.v1.Pool final_pool = 5 [ (gogoproto.nullable) = false ]; - - // the final amount of user pool shares - cosmos.base.v1beta1.Coin final_user_pool_shares = 6 - [ (gogoproto.nullable) = false ]; -} - -message EventAssetsSwapped { - // the address of the user who swapped tokens - string address = 1; - - // the amount of tokens that the user deposited - cosmos.base.v1beta1.Coin token_in = 2 [ (gogoproto.nullable) = false ]; - - // the amount of tokens that the user received - cosmos.base.v1beta1.Coin token_out = 3 [ (gogoproto.nullable) = false ]; - - // the amount of fees collected by the pool - cosmos.base.v1beta1.Coin fee = 4 [ (gogoproto.nullable) = false ]; - - // the final state of the pool - nibiru.spot.v1.Pool final_pool = 5 [ (gogoproto.nullable) = false ]; -} diff --git a/proto/nibiru/spot/v1/genesis.proto b/proto/nibiru/spot/v1/genesis.proto deleted file mode 100644 index 0d2e222ee..000000000 --- a/proto/nibiru/spot/v1/genesis.proto +++ /dev/null @@ -1,18 +0,0 @@ -syntax = "proto3"; - -package nibiru.spot.v1; - -import "nibiru/spot/v1/params.proto"; -import "nibiru/spot/v1/pool.proto"; -import "gogoproto/gogo.proto"; - -option go_package = "github.com/NibiruChain/nibiru/x/spot/types"; - -// GenesisState defines the spot module's genesis state. -message GenesisState { - // params defines all the parameters of the module. - nibiru.spot.v1.Params params = 1 [ (gogoproto.nullable) = false ]; - - // pools defines all the pools of the module. - repeated nibiru.spot.v1.Pool pools = 2 [ (gogoproto.nullable) = false ]; -} diff --git a/proto/nibiru/spot/v1/params.proto b/proto/nibiru/spot/v1/params.proto deleted file mode 100644 index d16d71e85..000000000 --- a/proto/nibiru/spot/v1/params.proto +++ /dev/null @@ -1,27 +0,0 @@ -syntax = "proto3"; - -package nibiru.spot.v1; - -import "gogoproto/gogo.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; - -option go_package = "github.com/NibiruChain/nibiru/x/spot/types"; - -// Params defines the parameters for the module. -message Params { - option (gogoproto.goproto_stringer) = false; - - // The start pool number, i.e. the first pool number that isn't taken yet. - uint64 starting_pool_number = 1; - - // The cost of creating a pool, taken from the pool creator's account. - repeated cosmos.base.v1beta1.Coin pool_creation_fee = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.moretags) = "yaml:\"pool_creation_fee\"", - (gogoproto.nullable) = false - ]; - - // The assets that can be used to create liquidity pools - repeated string whitelisted_asset = 3; -} diff --git a/proto/nibiru/spot/v1/pool.proto b/proto/nibiru/spot/v1/pool.proto deleted file mode 100644 index d0e67f52d..000000000 --- a/proto/nibiru/spot/v1/pool.proto +++ /dev/null @@ -1,97 +0,0 @@ -syntax = "proto3"; - -package nibiru.spot.v1; - -import "gogoproto/gogo.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos_proto/cosmos.proto"; - -option go_package = "github.com/NibiruChain/nibiru/x/spot/types"; - -// Configuration parameters for the pool. -message PoolParams { - string swap_fee = 1 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.moretags) = "yaml:\"swap_fee\"", - (gogoproto.nullable) = false - ]; - - string exit_fee = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.moretags) = "yaml:\"exit_fee\"", - (gogoproto.nullable) = false - ]; - - // Amplification Parameter (A): Larger value of A make the curve better - // resemble a straight line in the center (when pool is near balance). Highly - // volatile assets should use a lower value, while assets that are closer - // together may be best with a higher value. This is only used if the - // pool_type is set to 1 (stableswap) - string A = 3 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.moretags) = "yaml:\"amplification\"", - (gogoproto.nullable) = false - ]; - - nibiru.spot.v1.PoolType pool_type = 4 - [ (gogoproto.moretags) = "yaml:\"pool_type\"" ]; -} - -// - `balancer`: Balancer are pools defined by the equation xy=k, extended by -// the weighs introduced by Balancer. -// - `stableswap`: Stableswap pools are defined by a combination of -// constant-product and constant-sum pool -enum PoolType { - BALANCER = 0; - STABLESWAP = 1; -} - -// Which assets the pool contains. -message PoolAsset { - // Coins we are talking about, - // the denomination must be unique amongst all PoolAssets for this pool. - cosmos.base.v1beta1.Coin token = 1 - [ (gogoproto.moretags) = "yaml:\"token\"", (gogoproto.nullable) = false ]; - // Weight that is not normalized. This weight must be less than 2^50 - string weight = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.moretags) = "yaml:\"weight\"", - (gogoproto.nullable) = false - ]; -} - -message Pool { - option (gogoproto.goproto_getters) = false; - - // The pool id. - uint64 id = 1; - - // The pool account address. - string address = 2 [ (gogoproto.moretags) = "yaml:\"address\"" ]; - - // Fees and other pool-specific parameters. - nibiru.spot.v1.PoolParams pool_params = 3 [ - (gogoproto.moretags) = "yaml:\"pool_params\"", - (gogoproto.nullable) = false - ]; - - // These are assumed to be sorted by denomiation. - // They contain the pool asset and the information about the weight - repeated PoolAsset pool_assets = 4 [ - (gogoproto.moretags) = "yaml:\"pool_assets\"", - (gogoproto.nullable) = false - ]; - - // sum of all non-normalized pool weights - string total_weight = 5 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.moretags) = "yaml:\"total_weight\"", - (gogoproto.nullable) = false - ]; - - // sum of all LP tokens sent out - cosmos.base.v1beta1.Coin total_shares = 6 [ - (gogoproto.moretags) = "yaml:\"total_shares\"", - (gogoproto.nullable) = false - ]; -} diff --git a/proto/nibiru/spot/v1/query.proto b/proto/nibiru/spot/v1/query.proto deleted file mode 100644 index 0bc6ad052..000000000 --- a/proto/nibiru/spot/v1/query.proto +++ /dev/null @@ -1,282 +0,0 @@ -syntax = "proto3"; - -package nibiru.spot.v1; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "cosmos/base/query/v1beta1/pagination.proto"; -import "nibiru/spot/v1/params.proto"; -import "nibiru/spot/v1/pool.proto"; -import "cosmos/base/v1beta1/coin.proto"; - -option go_package = "github.com/NibiruChain/nibiru/x/spot/types"; - -// Query defines the gRPC querier service. -service Query { - // Parameters of the spot module. - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/nibiru/spot/params"; - } - - // Next available pool id number. - rpc PoolNumber(QueryPoolNumberRequest) returns (QueryPoolNumberResponse) { - option (google.api.http).get = "/nibiru/spot/pool_number"; - } - - // Fetch a pool by id. - rpc Pool(QueryPoolRequest) returns (QueryPoolResponse) { - option (google.api.http).get = "/nibiru/spot/pool"; - } - - // Returns all pools. - rpc Pools(QueryPoolsRequest) returns (QueryPoolsResponse) { - option (google.api.http).get = "/nibiru/spot/pools"; - } - - // Parameters of a single pool. - rpc PoolParams(QueryPoolParamsRequest) returns (QueryPoolParamsResponse) { - option (google.api.http).get = "/nibiru/spot/pools/{pool_id}/params"; - } - - // Number of pools. - rpc NumPools(QueryNumPoolsRequest) returns (QueryNumPoolsResponse) { - option (google.api.http).get = "/nibiru/spot/num_pools"; - } - - // Total liquidity across all pools. - rpc TotalLiquidity(QueryTotalLiquidityRequest) - returns (QueryTotalLiquidityResponse) { - option (google.api.http).get = "/nibiru/spot/total_liquidity"; - } - - // Total liquidity in a single pool. - rpc TotalPoolLiquidity(QueryTotalPoolLiquidityRequest) - returns (QueryTotalPoolLiquidityResponse) { - option (google.api.http).get = - "/nibiru/spot/pools/{pool_id}/total_pool_liquidity"; - } - - // Total shares in a single pool. - rpc TotalShares(QueryTotalSharesRequest) returns (QueryTotalSharesResponse) { - option (google.api.http).get = "/nibiru/spot/pools/{pool_id}/total_shares"; - } - - // Instantaneous price of an asset in a pool. - rpc SpotPrice(QuerySpotPriceRequest) returns (QuerySpotPriceResponse) { - option (google.api.http).get = "/nibiru/spot/pools/{pool_id}/prices"; - } - - // Estimates the amount of assets returned given an exact amount of tokens to - // swap. - rpc EstimateSwapExactAmountIn(QuerySwapExactAmountInRequest) - returns (QuerySwapExactAmountInResponse) { - option (google.api.http).get = - "/nibiru/spot/{pool_id}/estimate/swap_exact_amount_in"; - } - - // Estimates the amount of tokens required to return the exact amount of - // assets requested. - rpc EstimateSwapExactAmountOut(QuerySwapExactAmountOutRequest) - returns (QuerySwapExactAmountOutResponse) { - option (google.api.http).get = - "/nibiru/spot/{pool_id}/estimate/swap_exact_amount_out"; - } - - // Estimates the amount of pool shares returned given an amount of tokens to - // join. - rpc EstimateJoinExactAmountIn(QueryJoinExactAmountInRequest) - returns (QueryJoinExactAmountInResponse) { - option (google.api.http).get = - "/nibiru/spot/{pool_id}/estimate/join_exact_amount_in"; - } - - // Estimates the amount of tokens required to obtain an exact amount of pool - // shares. - rpc EstimateJoinExactAmountOut(QueryJoinExactAmountOutRequest) - returns (QueryJoinExactAmountOutResponse) { - option (google.api.http).get = - "/nibiru/spot/{pool_id}/estimate/join_exact_amount_out"; - } - - // Estimates the amount of tokens returned to the user given an exact amount - // of pool shares. - rpc EstimateExitExactAmountIn(QueryExitExactAmountInRequest) - returns (QueryExitExactAmountInResponse) { - option (google.api.http).get = - "/nibiru/spot/{pool_id}/estimate/exit_exact_amount_in"; - } - - // Estimates the amount of pool shares required to extract an exact amount of - // tokens from the pool. - rpc EstimateExitExactAmountOut(QueryExitExactAmountOutRequest) - returns (QueryExitExactAmountOutResponse) { - option (google.api.http).get = - "/nibiru/spot/{pool_id}/estimate/exit_exact_amount_out"; - } -} - -// QueryParamsRequest is request type for the Query/Params RPC method. -message QueryParamsRequest {} -// QueryParamsResponse is response type for the Query/Params RPC method. -message QueryParamsResponse { - // params holds all the parameters of this module. - nibiru.spot.v1.Params params = 1 [ (gogoproto.nullable) = false ]; -} - -message QueryPoolNumberRequest {} -message QueryPoolNumberResponse { uint64 pool_id = 1; } - -message QueryPoolRequest { uint64 pool_id = 1; } -message QueryPoolResponse { nibiru.spot.v1.Pool pool = 1; } - -message QueryPoolsRequest { - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 1; -} -message QueryPoolsResponse { - repeated nibiru.spot.v1.Pool pools = 1; - - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -message QueryPoolParamsRequest { uint64 pool_id = 1; } -message QueryPoolParamsResponse { nibiru.spot.v1.PoolParams pool_params = 1; } - -message QueryNumPoolsRequest {} -message QueryNumPoolsResponse { uint64 num_pools = 1; } - -// -------------------------------------------- -// Query total liquidity the protocol -message QueryTotalLiquidityRequest {} -message QueryTotalLiquidityResponse { - repeated cosmos.base.v1beta1.Coin liquidity = 1 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.moretags) = "yaml:\"liquidity\"", - (gogoproto.nullable) = false - ]; -} - -// -------------------------------------------- -// Query total liquidity for a pool -message QueryTotalPoolLiquidityRequest { uint64 pool_id = 1; } - -message QueryTotalPoolLiquidityResponse { - repeated cosmos.base.v1beta1.Coin liquidity = 1 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.moretags) = "yaml:\"liquidity\"", - (gogoproto.nullable) = false - ]; -} - -message QueryTotalSharesRequest { uint64 pool_id = 1; } -message QueryTotalSharesResponse { - // sum of all LP tokens sent out - cosmos.base.v1beta1.Coin total_shares = 1 [ - (gogoproto.moretags) = "yaml:\"total_shares\"", - (gogoproto.nullable) = false - ]; -} - -// Returns the amount of tokenInDenom to produce 1 tokenOutDenom -// For example, if the price of NIBI = 9.123 NUSD, then setting -// tokenInDenom=NUSD and tokenOutDenom=NIBI would give "9.123". -message QuerySpotPriceRequest { - uint64 pool_id = 1; - // the denomination of the token you are giving into the pool - string token_in_denom = 2; - // the denomination of the token you are taking out of the pool - string token_out_denom = 3; -} -message QuerySpotPriceResponse { string spot_price = 1; } - -// Given an exact amount of tokens in and a target tokenOutDenom, calculates -// the expected amount of tokens out received from a swap. -message QuerySwapExactAmountInRequest { - uint64 pool_id = 1; - cosmos.base.v1beta1.Coin token_in = 2 [ - (gogoproto.moretags) = "yaml:\"token_in\"", - (gogoproto.nullable) = false - ]; - string token_out_denom = 3; -} -message QuerySwapExactAmountInResponse { - cosmos.base.v1beta1.Coin token_out = 2 [ - (gogoproto.moretags) = "yaml:\"token_out\"", - (gogoproto.nullable) = false - ]; - cosmos.base.v1beta1.Coin fee = 3 - [ (gogoproto.moretags) = "yaml:\"fee\"", (gogoproto.nullable) = false ]; -} - -// Given an exact amount of tokens out and a target tokenInDenom, calculates -// the expected amount of tokens in required to do the swap. -message QuerySwapExactAmountOutRequest { - uint64 pool_id = 1; - cosmos.base.v1beta1.Coin token_out = 2 [ - (gogoproto.moretags) = "yaml:\"token_out\"", - (gogoproto.nullable) = false - ]; - string token_in_denom = 3; -} -message QuerySwapExactAmountOutResponse { - cosmos.base.v1beta1.Coin token_in = 2 [ - (gogoproto.moretags) = "yaml:\"token_in\"", - (gogoproto.nullable) = false - ]; -} - -message QueryJoinExactAmountInRequest { - uint64 pool_id = 1; - repeated cosmos.base.v1beta1.Coin tokens_in = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.moretags) = "yaml:\"tokens_in\"", - (gogoproto.nullable) = false - ]; -} -message QueryJoinExactAmountInResponse { - - // amount of pool shares returned to user after join - string pool_shares_out = 1 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.moretags) = "yaml:\"pool_shares_out\"", - (gogoproto.nullable) = false - ]; - - // coins remaining after pool join - repeated cosmos.base.v1beta1.Coin rem_coins = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.moretags) = "yaml:\"rem_coins\"", - (gogoproto.nullable) = false - ]; -} - -message QueryJoinExactAmountOutRequest { uint64 pool_id = 1; } -message QueryJoinExactAmountOutResponse {} - -message QueryExitExactAmountInRequest { - uint64 pool_id = 1; - // amount of pool shares to return to pool - string pool_shares_in = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", - (gogoproto.moretags) = "yaml:\"pool_shares_in\"", - (gogoproto.nullable) = false - ]; -} -message QueryExitExactAmountInResponse { - // coins obtained after exiting - repeated cosmos.base.v1beta1.Coin tokens_out = 1 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.moretags) = "yaml:\"tokens_out\"", - (gogoproto.nullable) = false - ]; - - repeated cosmos.base.v1beta1.Coin fees = 2 [ - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", - (gogoproto.moretags) = "yaml:\"fees\"", - (gogoproto.nullable) = false - ]; -} - -message QueryExitExactAmountOutRequest { uint64 pool_id = 1; } -message QueryExitExactAmountOutResponse {} diff --git a/proto/nibiru/spot/v1/tx.proto b/proto/nibiru/spot/v1/tx.proto deleted file mode 100644 index 8e9a3fc1c..000000000 --- a/proto/nibiru/spot/v1/tx.proto +++ /dev/null @@ -1,120 +0,0 @@ -syntax = "proto3"; - -package nibiru.spot.v1; - -import "nibiru/spot/v1/pool.proto"; -import "gogoproto/gogo.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "google/api/annotations.proto"; - -option go_package = "github.com/NibiruChain/nibiru/x/spot/types"; - -// Msg defines the Msg service. -service Msg { - // Used to create a pool. - rpc CreatePool(MsgCreatePool) returns (MsgCreatePoolResponse) { - option (google.api.http).post = "/nibiru/spot/pool"; - } - - // Join a pool as a liquidity provider. - rpc JoinPool(MsgJoinPool) returns (MsgJoinPoolResponse) { - option (google.api.http).post = "/nibiru/spot/{pool_id}/join"; - } - - // Exit a pool position by returning LP shares - rpc ExitPool(MsgExitPool) returns (MsgExitPoolResponse) { - option (google.api.http).post = "/nibiru/spot/{pool_id}/exit"; - } - - // Swap assets in a pool - rpc SwapAssets(MsgSwapAssets) returns (MsgSwapAssetsResponse) { - option (google.api.http).post = "/nibiru/spot/{pool_id}/swap"; - } -} - -message MsgCreatePool { - string creator = 1; - - nibiru.spot.v1.PoolParams pool_params = 2 - [ (gogoproto.moretags) = "yaml:\"pool_params\"" ]; - - repeated nibiru.spot.v1.PoolAsset pool_assets = 3 - [ (gogoproto.nullable) = false ]; -} - -message MsgCreatePoolResponse { uint64 pool_id = 1; } - -/* -Message to join a pool (identified by poolId) with a set of tokens to deposit. -*/ -message MsgJoinPool { - string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; - - uint64 pool_id = 2 [ (gogoproto.moretags) = "yaml:\"pool_id\"" ]; - - repeated cosmos.base.v1beta1.Coin tokens_in = 3 [ - (gogoproto.moretags) = "yaml:\"tokens_in\"", - (gogoproto.nullable) = false - ]; - - bool use_all_coins = 4 [ (gogoproto.moretags) = "yaml:\"use_all_coins\"" ]; -} - -/* -Response when a user joins a pool. -*/ -message MsgJoinPoolResponse { - // the final state of the pool after a join - nibiru.spot.v1.Pool pool = 1; - - // sum of LP tokens minted from the join - cosmos.base.v1beta1.Coin num_pool_shares_out = 2 [ - (gogoproto.moretags) = "yaml:\"num_pool_shares_out\"", - (gogoproto.nullable) = false - ]; - - // remaining tokens from attempting to join the pool - repeated cosmos.base.v1beta1.Coin remaining_coins = 3 [ - (gogoproto.moretags) = "yaml:\"tokens_in\"", - (gogoproto.nullable) = false - ]; -} - -message MsgExitPool { - string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; - - uint64 pool_id = 2 [ (gogoproto.moretags) = "yaml:\"pool_id\"" ]; - - cosmos.base.v1beta1.Coin pool_shares = 3 [ - (gogoproto.moretags) = "yaml:\"pool_shares\"", - (gogoproto.nullable) = false - ]; -} - -message MsgExitPoolResponse { - repeated cosmos.base.v1beta1.Coin tokens_out = 3 [ - (gogoproto.moretags) = "yaml:\"tokens_out\"", - (gogoproto.nullable) = false - ]; -} - -message MsgSwapAssets { - string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; - - uint64 pool_id = 2 [ (gogoproto.moretags) = "yaml:\"pool_id\"" ]; - - cosmos.base.v1beta1.Coin token_in = 3 [ - (gogoproto.moretags) = "yaml:\"token_in\"", - (gogoproto.nullable) = false - ]; - - string token_out_denom = 4 - [ (gogoproto.moretags) = "yaml:\"token_out_denom\"" ]; -} - -message MsgSwapAssetsResponse { - cosmos.base.v1beta1.Coin token_out = 3 [ - (gogoproto.moretags) = "yaml:\"token_out\"", - (gogoproto.nullable) = false - ]; -} diff --git a/simapp/sim_test.go b/simapp/sim_test.go index 5f3e5a2fd..52466eac9 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" - spottypes "github.com/NibiruChain/nibiru/x/spot/types" sudotypes "github.com/NibiruChain/nibiru/x/sudo/types" tokenfactorytypes "github.com/NibiruChain/nibiru/x/tokenfactory/types" ) @@ -281,7 +280,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(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/mock/dex_pool.go b/x/common/testutil/mock/dex_pool.go deleted file mode 100644 index 4b8deaf6d..000000000 --- a/x/common/testutil/mock/dex_pool.go +++ /dev/null @@ -1,53 +0,0 @@ -package mock - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/spot/types" -) - -// helper function to create dummy test pools -func SpotPool(poolId uint64, assets sdk.Coins, shares int64) types.Pool { - poolAssets := make([]types.PoolAsset, len(assets)) - for i, asset := range assets { - poolAssets[i] = types.PoolAsset{ - Token: asset, - Weight: sdk.OneInt(), - } - } - return types.Pool{ - Id: poolId, - PoolParams: types.PoolParams{ - SwapFee: sdk.SmallestDec(), - ExitFee: sdk.SmallestDec(), - PoolType: types.PoolType_BALANCER, - A: sdk.ZeroInt(), - }, - PoolAssets: poolAssets, - TotalShares: sdk.NewInt64Coin(types.GetPoolShareBaseDenom(poolId), shares), - TotalWeight: sdk.NewInt(2), - } -} - -// helper function to create dummy test pools -func SpotStablePool(poolId uint64, assets sdk.Coins, shares int64) types.Pool { - poolAssets := make([]types.PoolAsset, len(assets)) - for i, asset := range assets { - poolAssets[i] = types.PoolAsset{ - Token: asset, - Weight: sdk.OneInt(), - } - } - return types.Pool{ - Id: poolId, - PoolParams: types.PoolParams{ - SwapFee: sdk.ZeroDec(), - ExitFee: sdk.ZeroDec(), - PoolType: types.PoolType_STABLESWAP, - A: sdk.NewInt(100), - }, - PoolAssets: poolAssets, - TotalShares: sdk.NewInt64Coin(types.GetPoolShareBaseDenom(poolId), shares), - TotalWeight: sdk.NewInt(2), - } -} diff --git a/x/spot/README.md b/x/spot/README.md deleted file mode 100644 index d6cdcdb54..000000000 --- a/x/spot/README.md +++ /dev/null @@ -1,374 +0,0 @@ -# Spot Module - -The x/spot module is 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. - -- [Spot Module](#spot-module) -- [Concepts](#concepts) - - [Pool](#pool) - - [Creation of Pool](#creation-of-pool) - - [Joining Pool](#joining-pool) - - [Exiting Pool](#exiting-pool) - - [Swap](#swap) - - [Spot Price](#spot-price) -- [State](#state) - - [Next Pool Number](#next-pool-number) - - [Pools](#pools) - - [Total Liquidity](#total-liquidity) -- [Messages](#messages) - - [MsgCreatePool](#msgcreatepool) - - [MsgCreatePoolResponse](#msgcreatepoolresponse) - - [MsgJoinPool](#msgjoinpool) - - [MsgJoinPoolResponse](#msgjoinpoolresponse) -- [CLI](#cli) - - [Query](#query) - - [params](#params) - - [get-pool-number](#get-pool-number) - - [get-pool](#get-pool) - - [total-liquidity](#total-liquidity-1) - - [pool-liquidity](#pool-liquidity) - - [Transactions](#transactions) - - [create-pool](#create-pool) - - [join-pool](#join-pool) -- [GRPC and REST](#grpc-and-rest) -- [Parameters](#parameters) - - [StartingPoolNumber](#startingpoolnumber) - - [PoolCreationFee](#poolcreationfee) -- [Events](#events) -- [Hooks](#hooks) - - [Begin Block](#begin-block) - - [End Block](#end-block) -- [Future Improvements](#future-improvements) -- [Acceptance Tests](#acceptance-tests) - -# Concepts - -The `x/spot` module is responsible for for creating, joining, and exiting -liquidity pools that are dictated by an AMM for swaps. - -## Pool - -### Creation of Pool - -When a pool is created, a fixed amount of 100 LP shares is minted and sent to the pool creator. The base pool share denom is in the format of nibiru/pool/{poolId} and is displayed in the format of NIBIRU-POOL-{poolId} to the user. One NIBIRU-POOL-{poolId} token is equivalent to 10^18 nibiru/pool/{poolId} tokens. - -Pool assets are sorted in alphabetical order by default. - -### Joining Pool - -When joining a pool, users provide the tokens they are willing to deposit. The application will try to deposit as many tokens as it can while maintaining equal weight ratios across the pool's assets. Usually this means one asset acts as a limiting factor and all other tokens are deposited in proportion to the limited token. - -For example, assume there is a 50/50 pool with 100 `tokenA` and 100 `tokenB`. A user wishes to LP 10 `tokenA` and 5 `tokenB` into the pool. Because `tokenB` is the limiting factor, all of `tokenB` will be deposited and only 5 of `tokenA` will be deposited. The user will be left with 5 `tokenA` and receive LP shares for the liquidity they provided. - -### Exiting Pool - -When exiting the pool, the user also provides the number of LP shares they are returning to the pool, and will receive assets in proportion to the LP shares returned. However, unlike joining a pool, exiting a pool requires the user to pay the exit fee, which is set as the param of the pool. The share of the user gets burnt. - -For example, assume there is a 50/50 pool with 50 `tokenA` and 150 `tokenB` and 200 total LP shares minted. A user wishes to return 20 LP shares to the pool and withdraw their liquidity. Because 20/200 = 10%, the user will receive 5 `tokenA` and 15 `tokenB` from the pool, minus exit fees. - -## Swap - -During the process of swapping a specific asset, the token user is putting into the pool is justified as `tokenIn`, while the token that would be omitted after the swap is justified as `tokenOut` throughout the module. - -Given a tokenIn, the following calculations are done to calculate how much tokens are to be swapped and omitted from the pool. - -- `tokenBalanceOut * [ 1 - { tokenBalanceIn / (tokenBalanceIn+(1-swapFee) * tokenAmountIn)}^(tokenWeightIn/tokenWeightOut)]` - -The whole process is also able vice versa, the case where user provides tokenOut. The calculation for the amount of token that the user should be putting in is done through the following formula. - -- `tokenBalanceIn * [{tokenBalanceOut / (tokenBalanceOut - tokenAmountOut)}^(tokenWeightOut/tokenWeightIn)-1] / tokenAmountIn` - -### Spot Price - -Meanwhile, calculation of the spot price with a swap fee is done using the following formula - -- `spotPrice / (1-swapFee)` - -where spotPrice is - -- `(tokenBalanceIn / tokenWeightIn) / (tokenBalanceOut / tokenWeightOut)` -# State - -## Next Pool Number - -The spot module stores a monotonically increasing counter denoting the next available integer pool number. Pool numbers start at 1 and increase every time a pool is created. The `Keeper.GetNextPoolNumberAndIncrement` function always fetches the next available pool number and increments the stored value by 1. - -## Pools - -Serialized protobufs representing pools are stored in the state, with the key 0x02 | poolId. See the [pool proto file](../../../proto/spot/v1/pool.proto) for what fields a pool has. - -## Total Liquidity - -The spot module also stores the total liquidity in the module's account, which is the sum of all assets aggregated across all pools. The total liquidity is updated every time a pool's liquidity is updated (either through creation, joining, exiting, or swaps). - -The total liquidity is stored with key 0x03 | denom. -# Messages - -## MsgCreatePool - -Message to create a pool. Requires parameters specifying swap fee & exit fee, as well as the initial assets to deposit into the pool. The initial assets also determine the target weight of the pool (e.g. 50/50). - -For now we only support two-asset pools, but could expand to >2 assets in the future. - -### MsgCreatePoolResponse - -Contains the poolId. - -## MsgJoinPool - -Message to join a pool. Users specify the poolId they wish to join and the assets they wish to deposit. The number of distinct assets provided by the user must match the number of distinct assets in the pool, or else the message will error. - -### MsgJoinPoolResponse - -Contains the updated pool liquidity, the number of LP shares minted and transferred to the user, and the remaining coins that could not be deposited due to a ratio mismatch (see [Concepts](01_concepts.md)). - -# CLI - -A user can query and interact with the `spot` module using the CLI. - -## Query - -The `query` commands allow users to query `spot` state. - -```bash -nibid query spot --help -``` - -### params - -The `params` command allows users to query genesis parameters for the spot module. - -```bash -nibid query spot params [flags] -``` - -Example: - -```bash -nibid query spot params -``` - -Example Output: - -```bash -params: - pool_creation_fee: - - amount: "1000000000" - denom: unibi - startingPoolNumber: "1" -``` - -### get-pool-number - -The `get-pool-number` command allows users to query the next available pool id number. - -```bash -nibid query spot get-pool-number [flags] -``` - -Example: - -```bash -nibid query spot get-pool-number -``` - -Example Output: - -```bash -poolId: "1" -``` - -### get-pool - -The `get-pool` command allows users to query a pool by id number. - -```bash -nibid query spot get-pool [pool-id] [flags] -``` - -Example: - -```bash -nibid query spot get-pool 1 -``` - -Example Output: - -```bash -pool: - address: nibi1w00c7pqkr5z7ptewg5z87j2ncvxd88w43ug679 - id: "1" - poolAssets: - - token: - amount: "100" - denom: stake - weight: "1073741824" - - token: - amount: "100" - denom: validatortoken - weight: "1073741824" - poolParams: - exitFee: "0.010000000000000000" - swapFee: "0.010000000000000000" - totalShares: - amount: "100000000000000000000" - denom: nibiru/pool/1 - totalWeight: "2147483648" -``` - -### total-liquidity - -The `total-liquidity` command allows users to query the total amount of liquidity in the spot. - -```bash -nibid query spot total-liquidity [flags] -``` - -Example: - -```bash -nibid query spot total-liquidity -``` - -Example Output: - -```bash -liquidity: -- amount: "100" - denom: stake -- amount: "100" - denom: validatortoken -``` - -### pool-liquidity - -The `pool-liquidity` command allows users to query the total amount of liquidity in the spot. - -```bash -nibid query spot pool-liquidity [pool-id] [flags] -``` - -Example: - -```bash -nibid query spot pool-liquidity 1 -``` - -Example Output: - -```bash -liquidity: -- amount: "100" - denom: stake -- amount: "100" - denom: validatortoken -``` - -## Transactions - -The `tx` commands allow users to interact with the `spot` module. - -```bash -nibid tx spot --help -``` - -### create-pool - -The `create-pool` command allows users to create pools. - -```bash -nibid tx spot create-pool [flags] -``` - -Example: - -```bash -nibid tx spot create-pool --pool-file ./new-pool.json -``` - -Where the pool file JSON has format: - -```json -{ - "weights": "1stake,1validatortoken", - "initial-deposit": "100stake,100validatortoken", - "swap-fee": "0.01", - "exit-fee": "0.01" -} -``` - -### join-pool - -The `join-pool` command allows users to join pools with liquidty. - -```bash -nibid tx spot join-pool [flags] -``` - -Example: - -```bash -nibid tx spot join-pool --pool-id 1 --tokens-in 1validatortoken,1stake -``` - -# GRPC and REST - -(): Add gRPC and REST docs. - -# Parameters - -The spot module contains the following parameters: - -| Key | Type | Example | -| ------------------ | --------- | ------------ | -| StartingPoolNumber | uint64 | 1 | -| PoolCreationFee | sdk.Coins | 1000000ubini | - -## StartingPoolNumber - -The initial pool number to start creating pools at. - -## PoolCreationFee - -The amount of coins taken as a fee for creating a pool, from the pool creator's address. -# Events - -| Event Type | Attribute Key | Attribute Value | Attribute Type | -|----------------|-----------------|----------------------------------------------|----------------| -| pool_joined | sender | sender's address | string | -| pool_joined | pool_id | the numeric pool identifier | uint64 | -| pool_joined | tokens_in | the tokens sent by the user | sdk.Coins | -| pool_joined | pool_shares_out | the number of LP tokens returned to the user | sdk.Coin | -| pool_joined | rem_coins | the tokens remaining after joining the pool | sdk.Coins | -| pool_created | sender | sender's address | string | -| pool_created | pool_id | pool identifier | uint64 | -| pool_exited | sender | sender's address | string | -| pool_exited | pool_id | pool identifier | uint64 | -| pool_exited | num_shares_in | number of LP tokens in | sdk.Coin | -| pool_exited | tokens_out | tokens returned to the user | sdk.Coins | -| assets_swapped | sender | sender's address | string | -| assets_swapped | pool_id | pool identifier | uint64 | -| assets_swapped | token_in | token to swap in | sdk.Coin | -| assets_swapped | token_out | token returned to user | sdk.Coin | -# Hooks - -As of this time, there are no hooks into the x/spot module. - -## Begin Block - -Nothing happens in begin block yet. - -## End Block - -Nothing happens in end block yet. - -# Future Improvements - -- Constant product solver for pools with different weights () -- Safe shutdown where the pools freeze and swaps are not possible, but liquidity providers can still redeem their LP shares. - -# Acceptance Tests - -1. create pool -2. join pool -3. swap assets against pool -4. exit pool diff --git a/x/spot/client/cli/flags.go b/x/spot/client/cli/flags.go deleted file mode 100644 index deb5939c9..000000000 --- a/x/spot/client/cli/flags.go +++ /dev/null @@ -1,86 +0,0 @@ -package cli - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" - flag "github.com/spf13/pflag" - - "github.com/NibiruChain/nibiru/x/spot/types" -) - -const ( - // FlagPoolFile Will be parsed to string. - FlagPoolFile = "pool-file" - - // FlagPoolId Will be parsed to uint64. - FlagPoolId = "pool-id" - - // FlagUseAllCoins Will be parsed to uint64. - FlagUseAllCoins = "use-all-coins" - - // FlagTokensIn Will be parsed to []sdk.Coin. - FlagTokensIn = "tokens-in" - - // FlagPoolSharesOut Will be parsed to sdk.Coin. - FlagPoolSharesOut = "pool-shares-out" - - // FlagTokenIn Will be parsed to sdk.Coin. - FlagTokenIn = "token-in" - - // FlagTokenOutDenom Will be parsed to string. - FlagTokenOutDenom = "token-out-denom" -) - -type createPoolInputs struct { - Weights string `json:"weights"` - InitialDeposit string `json:"initial-deposit"` - SwapFee string `json:"swap-fee"` - ExitFee string `json:"exit-fee"` - PoolType string `json:"pool-type"` - Amplification string `json:"amplification"` -} - -func FlagSetCreatePool() *flag.FlagSet { - fs := flag.NewFlagSet("create-pool", flag.PanicOnError) - - fs.String(FlagPoolFile, "", "Pool json file path") - return fs -} - -func FlagSetJoinPool() *flag.FlagSet { - fs := flag.NewFlagSet("join-pool", flag.PanicOnError) - - fs.Uint64(FlagPoolId, 0, "The id of pool") - fs.StringArray(FlagTokensIn, []string{""}, "Amount of each denom to send into the pool (specify multiple denoms with: --tokens-in=1uusdc --tokens-in=1unusd)") - fs.Bool(FlagUseAllCoins, false, "Whether to use all the tokens in tokens-in to maximize shares out with a swap first") - return fs -} - -func FlagSetExitPool() *flag.FlagSet { - fs := flag.NewFlagSet("exit-pool", flag.ContinueOnError) - - fs.Uint64(FlagPoolId, 0, "The pool id to withdraw from.") - fs.String(FlagPoolSharesOut, "", "The amount of pool share tokens to burn.") - return fs -} - -func FlagSetSwapAssets() *flag.FlagSet { - fs := flag.NewFlagSet("swap-assets", flag.ContinueOnError) - - fs.Uint64(FlagPoolId, 0, "The pool id to withdraw from.") - fs.String(FlagTokenIn, "", "The amount of tokens to swap in.") - fs.String(FlagTokenOutDenom, "", "The denom of the token to extract.") - return fs -} - -func (cpi createPoolInputs) AmplificationInt() (sdkmath.Int, error) { - amplificationInt, ok := sdk.NewIntFromString(cpi.Amplification) - if !ok { - return sdkmath.Int{}, fmt.Errorf( - "%w: %v", types.ErrAmplificationIntable, cpi.Amplification) - } - return amplificationInt, nil -} diff --git a/x/spot/client/cli/query.go b/x/spot/client/cli/query.go deleted file mode 100644 index f5616bc8a..000000000 --- a/x/spot/client/cli/query.go +++ /dev/null @@ -1,194 +0,0 @@ -package cli - -import ( - "context" - "fmt" - "strconv" - "strings" - - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - "github.com/spf13/cobra" - - "github.com/NibiruChain/nibiru/x/spot/types" - - "github.com/cosmos/cosmos-sdk/client/flags" -) - -var _ = strconv.Itoa(0) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd() *cobra.Command { - // Group spot queries under a subcommand - spotQueryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf( - "Querying commands for the %s module", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - spotQueryCmd.AddCommand( - CmdQueryParams(), - CmdGetPoolNumber(), - CmdGetPool(), - CmdTotalLiquidity(), - CmdTotalPoolLiquidity(), - ) - - return spotQueryCmd -} - -func CmdGetPoolNumber() *cobra.Command { - cmd := &cobra.Command{ - Use: "get-pool-number", - Short: "Returns the next available pool ID", - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) (err error) { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - params := &types.QueryPoolNumberRequest{} - - res, err := queryClient.PoolNumber(cmd.Context(), params) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} - -func CmdGetPool() *cobra.Command { - cmd := &cobra.Command{ - Use: "pool [pool-id]", - Short: "Get a pool by its ID", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) (err error) { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - poolId, _ := sdk.NewIntFromString(args[0]) - - queryClient := types.NewQueryClient(clientCtx) - - params := &types.QueryPoolRequest{ - PoolId: poolId.Uint64(), - } - - res, err := queryClient.Pool(cmd.Context(), params) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} - -func CmdQueryParams() *cobra.Command { - cmd := &cobra.Command{ - Use: "params", - Short: "shows the parameters of the module", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx := client.GetClientContextFromCmd(cmd) - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Params(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} - -func CmdTotalLiquidity() *cobra.Command { - cmd := &cobra.Command{ - Use: "total-liquidity", - Short: "Show liquidity of protocol", - Long: strings.TrimSpace( - fmt.Sprintf(`Query total-liquidity. -Example: -$ %s query spot total-liquidity -`, version.AppName, - ), - ), - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx := client.GetClientContextFromCmd(cmd) - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.TotalLiquidity(context.Background(), &types.QueryTotalLiquidityRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} - -func CmdTotalPoolLiquidity() *cobra.Command { - cmd := &cobra.Command{ - Use: "pool-liquidity [pool-id]", - Short: "Show liquidity of pool", - Long: strings.TrimSpace( - fmt.Sprintf(`Query total-liquidity. -Example: -$ %s query spot pool-liquidity 1 -`, version.AppName, - ), - ), - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx := client.GetClientContextFromCmd(cmd) - - queryClient := types.NewQueryClient(clientCtx) - poolId, _ := sdk.NewIntFromString(args[0]) - - res, err := queryClient.TotalPoolLiquidity( - context.Background(), - &types.QueryTotalPoolLiquidityRequest{PoolId: poolId.Uint64()}, - ) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} diff --git a/x/spot/client/cli/tx.go b/x/spot/client/cli/tx.go deleted file mode 100644 index 9879e15c3..000000000 --- a/x/spot/client/cli/tx.go +++ /dev/null @@ -1,334 +0,0 @@ -package cli - -import ( - "encoding/json" - "fmt" - "os" - "strings" - - sdkmath "cosmossdk.io/math" - - "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/spot/types" -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand( - CmdCreatePool(), - CmdJoinPool(), - CmdExitPool(), - CmdSwapAssets(), - ) - - return cmd -} - -func CmdSwapAssets() *cobra.Command { - cmd := &cobra.Command{ - Use: "swap-assets", - Short: "swap assets by specifying tokens in and a token out denom", - Long: strings.TrimSpace( - fmt.Sprintf(` -Example: -$ %s tx spot swap-assets --pool-id 1 --tokens-in 100stake --token-out-denom validatortoken --from validator -`, - version.AppName, - ), - ), - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) (err error) { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - flagSet := cmd.Flags() - - poolId, err := flagSet.GetUint64(FlagPoolId) - if err != nil { - return err - } - - tokenInStr, err := cmd.Flags().GetString(FlagTokenIn) - if err != nil { - return err - } - - tokenIn, err := sdk.ParseCoinNormalized(tokenInStr) - if err != nil { - return err - } - - tokenOutDenom, err := cmd.Flags().GetString(FlagTokenOutDenom) - if err != nil { - return err - } - - msg := types.NewMsgSwapAssets( - clientCtx.GetFromAddress().String(), - poolId, - tokenIn, - tokenOutDenom, - ) - if err := msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - cmd.Flags().AddFlagSet(FlagSetSwapAssets()) - flags.AddTxFlagsToCmd(cmd) - - _ = cmd.MarkFlagRequired(FlagPoolId) - _ = cmd.MarkFlagRequired(FlagTokenIn) - _ = cmd.MarkFlagRequired(FlagTokenOutDenom) - - return cmd -} - -func CmdJoinPool() *cobra.Command { - cmd := &cobra.Command{ - Use: "join-pool", - Short: "join a new pool and provide the liquidity to it", - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - flagSet := cmd.Flags() - - poolId, err := flagSet.GetUint64(FlagPoolId) - if err != nil { - return err - } - - tokensInStrs, err := flagSet.GetStringArray(FlagTokensIn) - if err != nil { - return err - } - - tokensIn := sdk.Coins{} - for i := 0; i < len(tokensInStrs); i++ { - parsed, err := sdk.ParseCoinsNormalized(tokensInStrs[i]) - if err != nil { - return err - } - tokensIn = tokensIn.Add(parsed...) - } - - useAllCoins, err := flagSet.GetBool(FlagUseAllCoins) - if err != nil { - return err - } - - msg := types.NewMsgJoinPool( - /*sender=*/ clientCtx.GetFromAddress().String(), - poolId, - tokensIn, - useAllCoins, - ) - - return tx.GenerateOrBroadcastTxCLI(clientCtx, flagSet, msg) - }, - } - - cmd.Flags().AddFlagSet(FlagSetJoinPool()) - flags.AddTxFlagsToCmd(cmd) - - _ = cmd.MarkFlagRequired(FlagPoolId) - _ = cmd.MarkFlagRequired(FlagTokensIn) - _ = cmd.MarkFlagRequired(FlagUseAllCoins) - - return cmd -} - -func CmdExitPool() *cobra.Command { - cmd := &cobra.Command{ - Use: "exit-pool", - Short: "exit a pool by burning pool share tokens", - Long: strings.TrimSpace( - fmt.Sprintf(` -Example: -$ %s tx spot exit-pool --pool-id 1 --pool-shares-out 100nibiru/pool/1 --from validator -`, - version.AppName, - ), - ), - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) (err error) { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - flagSet := cmd.Flags() - - poolId, err := flagSet.GetUint64(FlagPoolId) - if err != nil { - return err - } - - poolSharesOut, err := cmd.Flags().GetString(FlagPoolSharesOut) - if err != nil { - return err - } - - parsedPoolSharesOut, err := sdk.ParseCoinNormalized(poolSharesOut) - if err != nil { - return err - } - - msg := types.NewMsgExitPool( - clientCtx.GetFromAddress().String(), - poolId, - parsedPoolSharesOut, - ) - - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - cmd.Flags().AddFlagSet(FlagSetExitPool()) - flags.AddTxFlagsToCmd(cmd) - - _ = cmd.MarkFlagRequired(FlagPoolId) - _ = cmd.MarkFlagRequired(FlagPoolSharesOut) - - return cmd -} - -func CmdCreatePool() *cobra.Command { - cmd := &cobra.Command{ - Use: "create-pool [flags]", - Short: "create a new pool and provide the liquidity to it", - Long: strings.TrimSpace( - fmt.Sprintf(`create a new pool and provide the liquidity to it. -Pool initialization parameters must be provided through a pool JSON file. - -Example: -$ %s tx spot create-pool --pool-file="path/to/pool.json" --from validator - -Where pool.json contains: -{ - "weights": "1unusd,1uusdc", - "initial-deposit": "100unusd,100uusdc", - "swap-fee": "0.01", - "exit-fee": "0.01", - "pool-type": "balancer", // 'balancer' or 'stableswap' - "amplification": "10" // Amplification parameter for the stableswap pool -} -`, - version.AppName, - ), - ), - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) (err error) { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - poolFile, err := cmd.Flags().GetString(FlagPoolFile) - if err != nil { - return err - } - if poolFile == "" { - return types.ErrMissingPoolFileFlag - } - - contents, err := os.ReadFile(poolFile) - if err != nil { - return err - } - - // make exception if unknown field exists - pool := &createPoolInputs{} - if err = json.Unmarshal(contents, pool); err != nil { - return err - } - - initialDepositCoins, err := sdk.ParseCoinsNormalized(pool.InitialDeposit) - if err != nil { - return err - } - - poolWeights, err := sdk.ParseDecCoins(pool.Weights) - if err != nil { - return err - } - - if len(initialDepositCoins) != len(poolWeights) { - return types.ErrInvalidCreatePoolArgs - } - - poolAssets := make([]types.PoolAsset, len(poolWeights)) - for i := 0; i < len(poolWeights); i++ { - if poolWeights[i].Denom != initialDepositCoins[i].Denom { - return types.ErrInvalidCreatePoolArgs - } - - poolAssets[i] = types.PoolAsset{ - Token: initialDepositCoins[i], - Weight: poolWeights[i].Amount.RoundInt(), - } - } - - var poolType types.PoolType - if pool.PoolType == "balancer" { - poolType = types.PoolType_BALANCER - } else if pool.PoolType == "stableswap" { - poolType = types.PoolType_STABLESWAP - } else { - return types.ErrInvalidCreatePoolArgs - } - - var amplification sdkmath.Int - if poolType == types.PoolType_STABLESWAP { - amplification, err = pool.AmplificationInt() - if err != nil { - return err - } - } - - msg := types.NewMsgCreatePool( - /*sender=*/ clientCtx.GetFromAddress().String(), - poolAssets, - &types.PoolParams{ - SwapFee: sdk.MustNewDecFromStr(pool.SwapFee), - ExitFee: sdk.MustNewDecFromStr(pool.ExitFee), - PoolType: poolType, - A: amplification, - }, - ) - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - cmd.Flags().AddFlagSet(FlagSetCreatePool()) - flags.AddTxFlagsToCmd(cmd) - - _ = cmd.MarkFlagRequired(FlagPoolFile) - - return cmd -} diff --git a/x/spot/client/testutil/cli_test.go b/x/spot/client/testutil/cli_test.go deleted file mode 100644 index df0297bb6..000000000 --- a/x/spot/client/testutil/cli_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package testutil - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/denoms" - testutilcli "github.com/NibiruChain/nibiru/x/common/testutil/cli" - genesis "github.com/NibiruChain/nibiru/x/common/testutil/genesis" - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" -) - -func TestIntegrationTestSuite(t *testing.T) { - coinsFromGenesis := []string{ - denoms.NIBI, - denoms.NUSD, - denoms.USDC, - "coin-1", - "coin-2", - "coin-3", - "coin-4", - "coin-5", - } - - testapp.EnsureNibiruPrefix() - genesisState := genesis.NewTestGenesisState(app.MakeEncodingConfig()) - - genesisState = WhitelistGenesisAssets( - genesisState, - coinsFromGenesis, - ) - - homeDir := t.TempDir() - cfg := testutilcli.BuildNetworkConfig(genesisState) - cfg.StartingTokens = sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 2e12), // for pool creation fee and more for tx fees - ) - - for _, coin := range coinsFromGenesis { - cfg.StartingTokens = cfg.StartingTokens.Add(sdk.NewInt64Coin(coin, 40000)) - } - - suite.Run(t, NewIntegrationTestSuite(homeDir, cfg)) -} diff --git a/x/spot/client/testutil/suite.go b/x/spot/client/testutil/suite.go deleted file mode 100644 index c1ade770d..000000000 --- a/x/spot/client/testutil/suite.go +++ /dev/null @@ -1,791 +0,0 @@ -package testutil - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - - tmcli "github.com/cometbft/cometbft/libs/cli" - sdktestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/stretchr/testify/suite" - - "github.com/NibiruChain/nibiru/x/common/testutil" - testutilcli "github.com/NibiruChain/nibiru/x/common/testutil/cli" - "github.com/NibiruChain/nibiru/x/spot/client/cli" - "github.com/NibiruChain/nibiru/x/spot/types" -) - -type IntegrationTestSuite struct { - suite.Suite - - homeDir string - cfg testutilcli.Config - network *testutilcli.Network -} - -func NewIntegrationTestSuite(homeDir string, cfg testutilcli.Config) *IntegrationTestSuite { - return &IntegrationTestSuite{homeDir: homeDir, cfg: cfg} -} - -func (s *IntegrationTestSuite) SetupSuite() { - testutil.BeforeIntegrationSuite(s.T()) - - network, err := testutilcli.New( - s.T(), - s.homeDir, - s.cfg, - ) - s.Require().NoError(err) - - s.network = network - _, err = s.network.WaitForHeight(1) - s.NoError(err) -} - -func (s *IntegrationTestSuite) TearDownSuite() { - s.T().Log("tearing down integration test suite") - s.network.Cleanup() -} - -func (s *IntegrationTestSuite) TestCreatePoolCmd() { - val := s.network.Validators[0] - - tc := []struct { - name string - tokenWeights string - initialDeposit string - poolType string - amplification string - - expectedErr error - expectedCode uint32 - }{ - { - name: "create pool with insufficient funds", - tokenWeights: fmt.Sprintf("1%s, 1%s", "coin-1", "coin-2"), - initialDeposit: fmt.Sprintf("1000000000%s,10000000000%s", "coin-1", "coin-2"), - poolType: "balancer", - amplification: "0", - expectedCode: 5, // bankKeeper code for insufficient funds - }, - { - name: "create pool with invalid weights", - tokenWeights: fmt.Sprintf("0%s, 1%s", "coin-1", "coin-2"), - initialDeposit: fmt.Sprintf("10000%s,10000%s", "coin-1", "coin-2"), - poolType: "balancer", - amplification: "0", - expectedErr: types.ErrInvalidCreatePoolArgs, - }, - { - name: "create pool with deposit not matching weights", - tokenWeights: fmt.Sprintf("1%s, 1%s", "coin-1", "coin-2"), - initialDeposit: "1000foo,10000uusdc", - poolType: "balancer", - amplification: "0", - expectedErr: types.ErrInvalidCreatePoolArgs, - }, - { - name: "create a stableswap pool, amplification parameter below 1", - tokenWeights: fmt.Sprintf("1%s, 1%s", "coin-1", "coin-2"), - initialDeposit: fmt.Sprintf("1000%s,10000%s", "coin-1", "coin-2"), - amplification: "0", - poolType: "stableswap", - expectedErr: types.ErrAmplificationTooLow, - }, - { - name: "happy path - balancer", - tokenWeights: "1unibi,1uusdc", - initialDeposit: "100unibi,100uusdc", - poolType: "balancer", - amplification: "0", - }, - { - name: "happy path - stable", - tokenWeights: "1unusd,1uusdc", - initialDeposit: "100unusd,100uusdc", - poolType: "stableswap", - amplification: "4", - }, - } - - for _, tc := range tc { - tc := tc - - s.Run(tc.name, func() { - out, err := ExecMsgCreatePool( - s.T(), - val.ClientCtx, - val.Address, - tc.tokenWeights, - tc.initialDeposit, - "0.003", - "0.003", - tc.poolType, - tc.amplification, - ) - - if tc.expectedErr != nil { - s.Require().ErrorIs(err, tc.expectedErr, out.String()) - } else { - s.Require().NoError(err) - s.Require().NoError(s.network.WaitForNextBlock()) - - txResp := sdk.TxResponse{} - val.ClientCtx.Codec.MustUnmarshalJSON(out.Bytes(), &txResp) - resp, err := testutilcli.QueryTx(val.ClientCtx, txResp.TxHash) - s.Require().NoError(err) - - s.Assert().Equal(tc.expectedCode, resp.Code, string(val.ClientCtx.Codec.MustMarshalJSON(resp))) - } - }) - } -} - -func (s *IntegrationTestSuite) TestNewJoinPoolCmd() { - val := s.network.Validators[0] - - // create a new pool - out, err := ExecMsgCreatePool( - s.T(), - val.ClientCtx, - /*owner-*/ val.Address, - /*tokenWeights=*/ fmt.Sprintf("5%s,5%s", "coin-2", "coin-3"), - /*tokenWeights=*/ fmt.Sprintf("100%s,100%s", "coin-2", "coin-3"), - /*swapFee=*/ "0.01", - /*exitFee=*/ "0.01", - /*poolType=*/ "balancer", - /*amplification=*/ "0", - ) - s.Require().NoError(err) - s.Require().NoError(s.network.WaitForNextBlock()) - - resp := &sdk.TxResponse{} - val.ClientCtx.Codec.MustUnmarshalJSON(out.Bytes(), resp) - resp, err = testutilcli.QueryTx(s.network.Validators[0].ClientCtx, resp.TxHash) - s.Require().NoError(err, out.String()) - - poolID, err := ExtractPoolIDFromCreatePoolResponse(val.ClientCtx.Codec, resp) - s.Require().NoError(err) - - testCases := []struct { - name string - poolId uint64 - tokensIn string - expectErr bool - expectedCode uint32 - }{ - { - name: "join pool with insufficient balance", - poolId: poolID, - tokensIn: fmt.Sprintf("1000000000%s,10000000000%s", "coin-2", "coin-3"), - expectErr: false, - expectedCode: 5, // bankKeeper code for insufficient funds - }, - { - name: "join pool with wrong tokens", - poolId: poolID, - tokensIn: fmt.Sprintf("1000000000%s,10000000000%s", "coin-1", "coin-3"), - expectErr: false, - expectedCode: 13, // bankKeeper code for insufficient funds - }, - { - name: "join pool with sufficient balance", - poolId: poolID, - tokensIn: fmt.Sprintf("100%s,100%s", "coin-2", "coin-3"), - expectErr: false, - expectedCode: 0, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - ctx := val.ClientCtx - - out, err := ExecMsgJoinPool(ctx, tc.poolId, val.Address, tc.tokensIn, "false") - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(s.network.WaitForNextBlock()) - resp := &sdk.TxResponse{} - ctx.Codec.MustUnmarshalJSON(out.Bytes(), resp) - - resp, err = testutilcli.QueryTx(ctx, resp.TxHash) - s.Require().NoError(err, out.String()) - s.Require().Equal(tc.expectedCode, resp.Code, out.String()) - } - }) - } -} - -func (s *IntegrationTestSuite) TestNewJoinStablePoolCmd() { - val := s.network.Validators[0] - - // create a new pool - out, err := ExecMsgCreatePool( - s.T(), - val.ClientCtx, - /*owner-*/ val.Address, - /*tokenWeights=*/ fmt.Sprintf("5%s,5%s", "coin-1", "coin-3"), - /*tokenWeights=*/ fmt.Sprintf("100%s,100%s", "coin-1", "coin-3"), - /*swapFee=*/ "0.01", - /*exitFee=*/ "0.01", - /*poolType=*/ "stableswap", - /*amplification=*/ "10", - ) - s.Require().NoError(err) - s.Require().NoError(s.network.WaitForNextBlock()) - - resp := &sdk.TxResponse{} - val.ClientCtx.Codec.MustUnmarshalJSON(out.Bytes(), resp) - resp, err = testutilcli.QueryTx(s.network.Validators[0].ClientCtx, resp.TxHash) - s.Require().NoError(err) - - poolID, err := ExtractPoolIDFromCreatePoolResponse(val.ClientCtx.Codec, resp) - s.Require().NoError(err, out.String()) - - testCases := []struct { - name string - poolId uint64 - tokensIn string - expectErr bool - expectedCode uint32 - }{ - { - name: "join pool with insufficient balance", - poolId: poolID, - tokensIn: fmt.Sprintf("1000000000%s,10000000000%s", "coin-1", "coin-3"), - expectErr: false, - expectedCode: 5, // bankKeeper code for insufficient funds - }, - { - name: "join pool with sufficient balance", - poolId: poolID, - tokensIn: fmt.Sprintf("100%s,50%s", "coin-1", "coin-3"), - expectErr: false, - expectedCode: 0, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - ctx := val.ClientCtx - - out, err := ExecMsgJoinPool(ctx, tc.poolId, val.Address, tc.tokensIn, "false") - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(s.network.WaitForNextBlock()) - resp := &sdk.TxResponse{} - ctx.Codec.MustUnmarshalJSON(out.Bytes(), resp) - resp, err = testutilcli.QueryTx(ctx, resp.TxHash) - s.Require().NoError(err, out.String()) - - s.Require().Equal(tc.expectedCode, resp.Code, out.String()) - } - }) - } -} - -func (s *IntegrationTestSuite) TestNewExitPoolCmd() { - val := s.network.Validators[0] - - // create a new pool - out, err := ExecMsgCreatePool( - s.T(), - val.ClientCtx, - /*owner-*/ val.Address, - /*tokenWeights=*/ fmt.Sprintf("1%s,1%s", "coin-3", "coin-4"), - /*initialDeposit=*/ fmt.Sprintf("100%s,100%s", "coin-3", "coin-4"), - /*swapFee=*/ "0.01", - /*exitFee=*/ "0.01", - /*poolType=*/ "balancer", - /*amplification=*/ "0", - ) - s.Require().NoError(err) - s.Require().NoError(s.network.WaitForNextBlock()) - - resp := &sdk.TxResponse{} - val.ClientCtx.Codec.MustUnmarshalJSON(out.Bytes(), resp) - resp, err = testutilcli.QueryTx(s.network.Validators[0].ClientCtx, resp.TxHash) - s.Require().NoError(err) - - poolID, err := ExtractPoolIDFromCreatePoolResponse(val.ClientCtx.Codec, resp) - s.Require().NoError(err, out.String()) - - testCases := []struct { - name string - poolId uint64 - poolSharesOut string - - expectErr bool - expectedCode uint32 - - expectedCoin3 sdkmath.Int - expectedCoin4 sdkmath.Int - }{ - { - name: "exit pool from invalid pool", - poolId: 100, - poolSharesOut: "100nibiru/pool/100", - expectErr: false, - expectedCode: 1, // spot.types.ErrNonExistingPool - expectedCoin3: sdk.ZeroInt(), - expectedCoin4: sdk.ZeroInt(), - }, - { - name: "exit pool for too many shares", - poolId: poolID, - poolSharesOut: fmt.Sprintf("1001000000000000000000nibiru/pool/%d", poolID), - expectErr: false, - expectedCode: 1, - expectedCoin3: sdk.ZeroInt(), - expectedCoin4: sdk.ZeroInt(), - }, - { - name: "exit pool for zero shares", - poolId: poolID, - poolSharesOut: fmt.Sprintf("0nibiru/pool/%d", poolID), - expectErr: false, - expectedCode: 1, - expectedCoin3: sdk.ZeroInt(), - expectedCoin4: sdk.ZeroInt(), - }, - { // Looks with a bug - name: "exit pool with sufficient balance", - poolId: poolID, - poolSharesOut: fmt.Sprintf("100000000000000000000nibiru/pool/%d", poolID), - expectErr: false, - expectedCode: 0, - expectedCoin3: sdk.NewInt(99), // Received coin-3 minus 1 exit pool fee - expectedCoin4: sdk.NewInt(99), // Received coin-4 minus 1 exit pool fee - }, - } - - for _, tc := range testCases { - tc := tc - ctx := val.ClientCtx - - s.Run(tc.name, func() { - // Get original balance - resp, err := sdktestutil.QueryBalancesExec(ctx, val.Address) - s.Require().NoError(err) - var originalBalance banktypes.QueryAllBalancesResponse - ctx.Codec.MustUnmarshalJSON(resp.Bytes(), &originalBalance) - - out, err := ExecMsgExitPool(ctx, tc.poolId, val.Address, tc.poolSharesOut) - - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(s.network.WaitForNextBlock()) - - resp := &sdk.TxResponse{} - ctx.Codec.MustUnmarshalJSON(out.Bytes(), resp) - resp, err = testutilcli.QueryTx(ctx, resp.TxHash) - s.Require().NoError(err, out.String()) - s.Require().Equal(tc.expectedCode, resp.Code, out.String()) - - // Ensure balance is ok - out, err = sdktestutil.QueryBalancesExec(ctx, val.Address) - s.Require().NoError(err) - var finalBalance banktypes.QueryAllBalancesResponse - ctx.Codec.MustUnmarshalJSON(out.Bytes(), &finalBalance) - - s.Assert().Equal( - originalBalance.Balances.AmountOf("coin-3").Add(tc.expectedCoin3), - finalBalance.Balances.AmountOf("coin-3"), - ) - s.Assert().Equal( - originalBalance.Balances.AmountOf("coin-4").Add(tc.expectedCoin4), - finalBalance.Balances.AmountOf("coin-4"), - ) - } - }) - } -} - -func (s *IntegrationTestSuite) TestNewExitStablePoolCmd() { - val := s.network.Validators[0] - - // create a new pool - out, err := ExecMsgCreatePool( - s.T(), - val.ClientCtx, - /*owner-*/ val.Address, - /*tokenWeights=*/ fmt.Sprintf("1%s,1%s", "coin-3", "coin-5"), - /*tokenWeights=*/ fmt.Sprintf("100%s,100%s", "coin-3", "coin-5"), - /*swapFee=*/ "0.01", - /*exitFee=*/ "0.01", - /*poolType=*/ "stableswap", - /*amplification=*/ "4242", - ) - s.Require().NoError(err) - s.Require().NoError(s.network.WaitForNextBlock()) - - resp := &sdk.TxResponse{} - val.ClientCtx.Codec.MustUnmarshalJSON(out.Bytes(), resp) - resp, err = testutilcli.QueryTx(s.network.Validators[0].ClientCtx, resp.TxHash) - s.Require().NoErrorf(err, "cmd output: %s", out) - - poolID, err := ExtractPoolIDFromCreatePoolResponse(val.ClientCtx.Codec, resp) - s.Require().NoErrorf(err, "cmd output: %s", out) - - testCases := []struct { - name string - poolId uint64 - poolSharesOut string - expectErr bool - expectedCode uint32 - expectedCoin3 sdkmath.Int - expectedCoin5 sdkmath.Int - }{ - { - name: "exit pool from invalid pool", - poolId: 100, - poolSharesOut: "100nibiru/pool/100", - expectErr: false, - expectedCode: 1, // spot.types.ErrNonExistingPool - expectedCoin3: sdk.ZeroInt(), - expectedCoin5: sdk.ZeroInt(), - }, - { - name: "exit pool for too many shares", - poolId: poolID, - poolSharesOut: fmt.Sprintf("1001000000000000000000nibiru/pool/%d", poolID), - expectErr: false, - expectedCode: 1, - expectedCoin3: sdk.ZeroInt(), - expectedCoin5: sdk.ZeroInt(), - }, - { - name: "exit pool for zero shares", - poolId: poolID, - poolSharesOut: fmt.Sprintf("0nibiru/pool/%d", poolID), - expectErr: false, - expectedCode: 1, - expectedCoin3: sdk.ZeroInt(), - expectedCoin5: sdk.ZeroInt(), - }, - { // Looks with a bug - name: "exit pool with sufficient balance", - poolId: poolID, - poolSharesOut: fmt.Sprintf("100000000000000000000nibiru/pool/%d", poolID), - expectErr: false, - expectedCode: 0, - expectedCoin3: sdk.NewInt(99), // Received coin-3 minus 1 exit pool fee - expectedCoin5: sdk.NewInt(99), // Received coin-5 minus 1 exit pool fee - }, - } - - for _, tc := range testCases { - tc := tc - ctx := val.ClientCtx - - s.Run(tc.name, func() { - // Get original balance - resp, err := sdktestutil.QueryBalancesExec(ctx, val.Address) - s.Require().NoError(err) - var originalBalance banktypes.QueryAllBalancesResponse - ctx.Codec.MustUnmarshalJSON(resp.Bytes(), &originalBalance) - - out, err := ExecMsgExitPool(ctx, tc.poolId, val.Address, tc.poolSharesOut) - - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(s.network.WaitForNextBlock()) - - resp := &sdk.TxResponse{} - ctx.Codec.MustUnmarshalJSON(out.Bytes(), resp) - resp, err = testutilcli.QueryTx(ctx, resp.TxHash) - s.Require().NoError(err) - - s.Require().Equal(tc.expectedCode, resp.Code, out.String()) - - // Ensure balance is ok - out, err := sdktestutil.QueryBalancesExec(ctx, val.Address) - s.Require().NoError(err) - var finalBalance banktypes.QueryAllBalancesResponse - ctx.Codec.MustUnmarshalJSON(out.Bytes(), &finalBalance) - - s.Assert().Equal( - originalBalance.Balances.AmountOf("coin-3").Add(tc.expectedCoin3), - finalBalance.Balances.AmountOf("coin-3"), - ) - s.Assert().Equal( - originalBalance.Balances.AmountOf("coin-5").Add(tc.expectedCoin5), - finalBalance.Balances.AmountOf("coin-5"), - ) - } - }) - } -} - -func (s *IntegrationTestSuite) TestGetCmdTotalLiquidity() { - val := s.network.Validators[0] - - testCases := []struct { - name string - args []string - expectErr bool - }{ - { - "query total liquidity", // nibid query spot total-liquidity - []string{ - fmt.Sprintf("--%s=%s", tmcli.OutputFlag, "json"), - }, - false, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - cmd := cli.CmdTotalLiquidity() - clientCtx := val.ClientCtx - - out, err := sdktestutil.ExecTestCLICmd(clientCtx, cmd, tc.args) - if tc.expectErr { - s.Require().Error(err) - } else { - resp := types.QueryTotalLiquidityResponse{} - s.Require().NoError(err, out.String()) - s.Require().NoError(clientCtx.Codec.UnmarshalJSON(out.Bytes(), &resp), out.String()) - } - }) - } -} - -func (s *IntegrationTestSuite) TestSwapAssets() { - val := s.network.Validators[0] - - // create a new pool - out, err := ExecMsgCreatePool( - s.T(), - val.ClientCtx, - /*owner-*/ val.Address, - /*tokenWeights=*/ fmt.Sprintf("1%s,1%s", "coin-4", "coin-5"), - /*tokenWeights=*/ fmt.Sprintf("100%s,100%s", "coin-4", "coin-5"), - /*swapFee=*/ "0.01", - /*exitFee=*/ "0.01", - /*poolType=*/ "balancer", - /*amplification=*/ "0", - ) - s.Require().NoError(err) - s.Require().NoError(s.network.WaitForNextBlock()) - - resp := &sdk.TxResponse{} - val.ClientCtx.Codec.MustUnmarshalJSON(out.Bytes(), resp) - resp, err = testutilcli.QueryTx(s.network.Validators[0].ClientCtx, resp.TxHash) - s.Require().NoError(err) - - poolID, err := ExtractPoolIDFromCreatePoolResponse(val.ClientCtx.Codec, resp) - s.Require().NoError(err, out.String()) - - testCases := []struct { - name string - poolId uint64 - tokenIn string - tokenOutDenom string - expectedCode uint32 - expectErr bool - }{ - { - name: "zero pool id", - poolId: 0, - tokenIn: "50unibi", - tokenOutDenom: "uusdc", - expectErr: true, - }, - { - name: "invalid token in", - poolId: poolID, - tokenIn: "0coin-4", - tokenOutDenom: "uusdc", - expectErr: true, - }, - { - name: "invalid token out denom", - poolId: poolID, - tokenIn: "50coin-4", - tokenOutDenom: "", - expectErr: true, - }, - { - name: "pool not found", - poolId: 1000000, - tokenIn: "50unibi", - tokenOutDenom: "uusdc", - expectedCode: types.ErrPoolNotFound.ABCICode(), - expectErr: false, - }, - { - name: "token in denom not found", - poolId: poolID, - tokenIn: "50foo", - tokenOutDenom: "coin-5", - expectedCode: types.ErrTokenDenomNotFound.ABCICode(), - expectErr: false, - }, - { - name: "token out denom not found", - poolId: poolID, - tokenIn: "50coin-4", - tokenOutDenom: "foo", - expectedCode: types.ErrTokenDenomNotFound.ABCICode(), - expectErr: false, - }, - { - name: "successful swap", - poolId: poolID, - tokenIn: "50coin-4", - tokenOutDenom: "coin-5", - expectedCode: 0, - expectErr: false, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - out, err := ExecMsgSwapAssets(val.ClientCtx, tc.poolId, val.Address, tc.tokenIn, tc.tokenOutDenom) - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(s.network.WaitForNextBlock()) - - resp := &sdk.TxResponse{} - val.ClientCtx.Codec.MustUnmarshalJSON(out.Bytes(), resp) - resp, err = testutilcli.QueryTx(val.ClientCtx, resp.TxHash) - s.Require().NoError(err) - - s.Assert().Equal(tc.expectedCode, resp.Code, out.String()) - } - }) - } -} - -func (s *IntegrationTestSuite) TestSwapStableAssets() { - s.Require().NoError(s.network.WaitForNextBlock()) - val := s.network.Validators[0] - - // create a new pool - out, err := ExecMsgCreatePool( - s.T(), - val.ClientCtx, - /*owner-*/ val.Address, - /*tokenWeights=*/ fmt.Sprintf("1%s,1%s", "coin-1", "coin-5"), - /*initialDeposit=*/ fmt.Sprintf("100%s,100%s", "coin-1", "coin-5"), - /*swapFee=*/ "0.01", - /*exitFee=*/ "0.01", - /*poolType=*/ "stableswap", - /*amplification=*/ "42", - ) - s.Require().NoError(err) - s.Require().NoError(s.network.WaitForNextBlock()) - - resp := &sdk.TxResponse{} - val.ClientCtx.Codec.MustUnmarshalJSON(out.Bytes(), resp) - resp, err = testutilcli.QueryTx(s.network.Validators[0].ClientCtx, resp.TxHash) - s.Require().NoError(err) - - poolID, err := ExtractPoolIDFromCreatePoolResponse(val.ClientCtx.Codec, resp) - s.Require().NoError(err, out.String()) - - testCases := []struct { - name string - poolId uint64 - tokenIn string - tokenOutDenom string - expectedCode uint32 - expectErr bool - }{ - { - name: "zero pool id", - poolId: 0, - tokenIn: "50unibi", - tokenOutDenom: "uusdc", - expectErr: true, - }, - { - name: "invalid token in", - poolId: poolID, - tokenIn: "0coin-1", - tokenOutDenom: "uusdc", - expectErr: true, - }, - { - name: "invalid token out denom", - poolId: poolID, - tokenIn: "50coin-1", - tokenOutDenom: "", - expectErr: true, - }, - { - name: "pool not found", - poolId: 1000000, - tokenIn: "50unibi", - tokenOutDenom: "uusdc", - expectedCode: types.ErrPoolNotFound.ABCICode(), - expectErr: false, - }, - { - name: "token in denom not found", - poolId: poolID, - tokenIn: "50foo", - tokenOutDenom: "coin-5", - expectedCode: types.ErrTokenDenomNotFound.ABCICode(), - expectErr: false, - }, - { - name: "token out denom not found", - poolId: poolID, - tokenIn: "50coin-1", - tokenOutDenom: "foo", - expectedCode: types.ErrTokenDenomNotFound.ABCICode(), - expectErr: false, - }, - { - name: "successful swap", - poolId: poolID, - tokenIn: "50coin-1", - tokenOutDenom: "coin-5", - expectedCode: 0, - expectErr: false, - }, - } - - for _, tc := range testCases { - tc := tc - - s.Run(tc.name, func() { - out, err := ExecMsgSwapAssets(val.ClientCtx, tc.poolId, val.Address, tc.tokenIn, tc.tokenOutDenom) - if tc.expectErr { - s.Require().Error(err) - } else { - s.Require().NoError(err, out.String()) - s.Require().NoError(s.network.WaitForNextBlock()) - - resp := &sdk.TxResponse{} - val.ClientCtx.Codec.MustUnmarshalJSON(out.Bytes(), resp) - resp, err = testutilcli.QueryTx(val.ClientCtx, resp.TxHash) - s.Require().NoError(err) - - s.Assert().Equal(tc.expectedCode, resp.Code, out.String()) - } - }) - } -} diff --git a/x/spot/client/testutil/test_helpers.go b/x/spot/client/testutil/test_helpers.go deleted file mode 100644 index af093b723..000000000 --- a/x/spot/client/testutil/test_helpers.go +++ /dev/null @@ -1,182 +0,0 @@ -package testutil - -import ( - "encoding/hex" - "fmt" - "testing" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/testutil" - sdktestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/app" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/spot/client/cli" - "github.com/NibiruChain/nibiru/x/spot/types" -) - -// commonArgs is args for CLI test commands. -var commonArgs = []string{ - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastSync), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(denoms.NIBI, sdk.NewInt(10))).String()), -} - -// ExecMsgCreatePool broadcast a pool creation message. -func ExecMsgCreatePool( - t *testing.T, - clientCtx client.Context, - owner fmt.Stringer, - tokenWeights string, - initialDeposit string, - swapFee string, - exitFee string, - poolType string, - amplification string, - extraArgs ...string, -) (testutil.BufferWriter, error) { - args := []string{} - - jsonFile := testutil.WriteToNewTempFile(t, - fmt.Sprintf(` - { - "weights": "%s", - "initial-deposit": "%s", - "swap-fee": "%s", - "exit-fee": "%s", - "pool-type": "%s", - "amplification": "%s" - } - `, - tokenWeights, - initialDeposit, - swapFee, - exitFee, - poolType, - amplification, - ), - ) - - args = append(args, - fmt.Sprintf("--%s=%s", cli.FlagPoolFile, jsonFile.Name()), - fmt.Sprintf("--%s=%s", flags.FlagFrom, owner.String()), - fmt.Sprintf("--%s=%d", flags.FlagGas, 300000), - ) - - args = append(args, commonArgs...) - args = append(args, extraArgs...) - - return sdktestutil.ExecTestCLICmd(clientCtx, cli.CmdCreatePool(), args) -} - -// ExecMsgJoinPool broadcast a join pool message. -func ExecMsgJoinPool( - clientCtx client.Context, - poolId uint64, - sender fmt.Stringer, - tokensIn string, - useAllCoins string, - extraArgs ...string, -) (testutil.BufferWriter, error) { - args := []string{ - fmt.Sprintf("--%s=%d", cli.FlagPoolId, poolId), - fmt.Sprintf("--%s=%s", cli.FlagTokensIn, tokensIn), - fmt.Sprintf("--%s=%s", cli.FlagUseAllCoins, useAllCoins), - fmt.Sprintf("--%s=%s", flags.FlagFrom, sender.String()), - fmt.Sprintf("--%s=%d", flags.FlagGas, 300000), - } - - args = append(args, commonArgs...) - args = append(args, extraArgs...) - - return sdktestutil.ExecTestCLICmd(clientCtx, cli.CmdJoinPool(), args) -} - -// ExecMsgExitPool broadcast an exit pool message. -func ExecMsgExitPool( - clientCtx client.Context, - poolId uint64, - sender fmt.Stringer, - poolSharesOut string, - extraArgs ...string, -) (testutil.BufferWriter, error) { - args := []string{ - fmt.Sprintf("--%s=%d", cli.FlagPoolId, poolId), - fmt.Sprintf("--%s=%s", cli.FlagPoolSharesOut, poolSharesOut), - fmt.Sprintf("--%s=%s", flags.FlagFrom, sender.String()), - fmt.Sprintf("--%s=%d", flags.FlagGas, 300000), - } - - args = append(args, commonArgs...) - args = append(args, extraArgs...) - - return sdktestutil.ExecTestCLICmd(clientCtx, cli.CmdExitPool(), args) -} - -// ExecMsgSwapAssets broadcast a swap assets message. -func ExecMsgSwapAssets( - clientCtx client.Context, - poolId uint64, - sender fmt.Stringer, - tokenIn string, - tokenOutDenom string, - extraArgs ...string, -) (testutil.BufferWriter, error) { - args := []string{ - fmt.Sprintf("--%s=%d", cli.FlagPoolId, poolId), - fmt.Sprintf("--%s=%s", cli.FlagTokenIn, tokenIn), - fmt.Sprintf("--%s=%s", cli.FlagTokenOutDenom, tokenOutDenom), - fmt.Sprintf("--%s=%s", flags.FlagFrom, sender.String()), - fmt.Sprintf("--%s=%d", flags.FlagGas, 300_000), - } - - args = append(args, commonArgs...) - args = append(args, extraArgs...) - - return sdktestutil.ExecTestCLICmd(clientCtx, cli.CmdSwapAssets(), args) -} - -// WhitelistGenesisAssets given a testapp.GenesisState includes the whitelisted assets into spot Whitelisted assets. -func WhitelistGenesisAssets(state app.GenesisState, assets []string) app.GenesisState { - encConfig := app.MakeEncodingConfig() - - jsonState := state[types.ModuleName] - - var genesis types.GenesisState - encConfig.Marshaler.MustUnmarshalJSON(jsonState, &genesis) - genesis.Params.WhitelistedAsset = assets - - json, _ := encConfig.Marshaler.MarshalJSON(&genesis) - state[types.ModuleName] = json - - return state -} - -// ExtractPoolIDFromCreatePoolResponse extracts the created PoolID from a MsgCreatePool command. -func ExtractPoolIDFromCreatePoolResponse(codec codec.Codec, resp *sdk.TxResponse) (uint64, error) { - decodedResult, err := hex.DecodeString(resp.Data) - if err != nil { - return 0, err - } - - respData := sdk.TxMsgData{} - err = codec.Unmarshal(decodedResult, &respData) - if err != nil { - return 0, err - } - - if len(respData.MsgResponses) < 1 { - return 0, fmt.Errorf("invalid response") - } - - var createPoolResponse types.MsgCreatePoolResponse - err = codec.Unmarshal(respData.MsgResponses[0].Value, &createPoolResponse) - if err != nil { - return 0, err - } - - return createPoolResponse.PoolId, nil -} diff --git a/x/spot/genesis.go b/x/spot/genesis.go deleted file mode 100644 index 4decad06e..000000000 --- a/x/spot/genesis.go +++ /dev/null @@ -1,27 +0,0 @@ -package spot - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/spot/keeper" - "github.com/NibiruChain/nibiru/x/spot/types" -) - -// InitGenesis initializes the spot module's state from a provided genesis state. -func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) { - k.SetParams(ctx, genState.Params) - k.SetNextPoolNumber(ctx, uint64(genState.Params.StartingPoolNumber)) - - for _, pool := range genState.Pools { - k.SetPool(ctx, pool) - } -} - -// ExportGenesis returns the spot module's exported genesis. -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { - genesis := types.DefaultGenesis() - genesis.Params = k.GetParams(ctx) - genesis.Pools = k.FetchAllPools(ctx) - - return genesis -} diff --git a/x/spot/genesis_test.go b/x/spot/genesis_test.go deleted file mode 100644 index 837d4de0a..000000000 --- a/x/spot/genesis_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package spot_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/testutil" - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - "github.com/NibiruChain/nibiru/x/spot" - "github.com/NibiruChain/nibiru/x/spot/types" -) - -func TestGenesis(t *testing.T) { - testapp.EnsureNibiruPrefix() - genesisState := types.GenesisState{ - Params: types.DefaultParams(), - Pools: []types.Pool{ - { - Id: 1, - Address: "addr1", - PoolParams: types.PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.01"), - ExitFee: sdk.MustNewDecFromStr("0.01"), - A: sdk.ZeroInt(), - PoolType: types.PoolType_BALANCER, - }, - PoolAssets: []types.PoolAsset{ - { - Token: sdk.NewCoin("token1", sdk.NewInt(100)), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewCoin("token2", sdk.NewInt(100)), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - TotalShares: sdk.NewCoin("nibiru/pool/1", sdk.NewInt(100)), - }, - }, - } - - app, ctx := testapp.NewNibiruTestAppAndContext() - spot.InitGenesis(ctx, app.SpotKeeper, genesisState) - got := spot.ExportGenesis(ctx, app.SpotKeeper) - require.NotNil(t, got) - - testutil.Fill(&genesisState) - testutil.Fill(got) - - require.Equal(t, genesisState, *got) -} diff --git a/x/spot/keeper/balances.go b/x/spot/keeper/balances.go deleted file mode 100644 index dffc68520..000000000 --- a/x/spot/keeper/balances.go +++ /dev/null @@ -1,35 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -/* -Checks if account has enough balance to spend coins. - -args: - - ctx: cosmos-sdk context - - coinsToSpend: the coins that the account wishes to spend - - account: the address of the account spending the coins - -ret: - - error: an error if insufficient balance -*/ -func (k Keeper) CheckEnoughBalances( - ctx sdk.Context, - coinsToSpend sdk.Coins, - account sdk.AccAddress, -) error { - accCoins := k.bankKeeper.SpendableCoins(ctx, account) - - if accCoins.IsAllGTE(coinsToSpend) { - return nil - } - - return sdkerrors.ErrInsufficientFunds.Wrapf( - "acc %s does not have enough to spend %s", - account.String(), - coinsToSpend.String(), - ) -} diff --git a/x/spot/keeper/balances_test.go b/x/spot/keeper/balances_test.go deleted file mode 100644 index 053da1e86..000000000 --- a/x/spot/keeper/balances_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" -) - -func TestCheckBalances(t *testing.T) { - tests := []struct { - name string - - // test setup - userInitialFunds sdk.Coins - coinsToSpend sdk.Coins - - // expected results - expectedError error - }{ - { - name: "has enough funds", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - coinsToSpend: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - expectedError: nil, - }, - { - name: "not enough user funds", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - ), - coinsToSpend: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - expectedError: sdkerrors.ErrInsufficientFunds, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - testapp.EnsureNibiruPrefix() - app, ctx := testapp.NewNibiruTestAppAndContext() - - // fund user account - sender := testutil.AccAddress() - require.NoError(t, testapp.FundAccount(app.BankKeeper, ctx, sender, tc.userInitialFunds)) - - // swap assets - err := app.SpotKeeper.CheckEnoughBalances(ctx, tc.coinsToSpend, sender) - - if tc.expectedError != nil { - require.ErrorIs(t, err, tc.expectedError) - } else { - require.NoError(t, err) - } - - // check user's final funds did not change - require.Equal(t, - tc.userInitialFunds, - app.BankKeeper.GetAllBalances(ctx, sender), - ) - }) - } -} diff --git a/x/spot/keeper/grpc_query.go b/x/spot/keeper/grpc_query.go deleted file mode 100644 index b692f2c49..000000000 --- a/x/spot/keeper/grpc_query.go +++ /dev/null @@ -1,334 +0,0 @@ -package keeper - -import ( - "context" - "fmt" - - "github.com/cosmos/cosmos-sdk/store/prefix" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - gogotypes "github.com/cosmos/gogoproto/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/NibiruChain/nibiru/x/spot/types" -) - -type queryServer struct { - Keeper -} - -func NewQuerier(k Keeper) queryServer { - return queryServer{Keeper: k} -} - -var _ types.QueryServer = queryServer{} - -/* -Handler for the QueryParamsRequest query. - -args - - ctx: the cosmos-sdk context - req: a QueryParamsRequest proto object - -ret - - QueryParamsResponse: the QueryParamsResponse proto object response, containing the params - error: an error if any occurred -*/ -func (k queryServer) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - ctx := sdk.UnwrapSDKContext(c) - - return &types.QueryParamsResponse{Params: k.GetParams(ctx)}, nil -} - -/* -Handler for the QueryPoolRequest query. - -args - - ctx: the cosmos-sdk context - req: a QueryPoolRequest proto object - -ret - - QueryPoolResponse: the QueryPoolResponse proto object response, containing the pool - error: an error if any occurred -*/ -func (k queryServer) Pool(goCtx context.Context, req *types.QueryPoolRequest) (*types.QueryPoolResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - pool, err := k.FetchPool(sdk.UnwrapSDKContext(goCtx), req.PoolId) - if err != nil { - return nil, err - } - - return &types.QueryPoolResponse{ - Pool: &pool, - }, nil -} - -/* -Handler for the QueryPoolNumberRequest query. - -args - - ctx: the cosmos-sdk context - req: a QueryPoolNumberRequest proto object - -ret - - QueryPoolNumberResponse: the QueryPoolNumberResponse proto object response, containing the next pool id number - error: an error if any occurred -*/ -func (k queryServer) PoolNumber(goCtx context.Context, req *types.QueryPoolNumberRequest) (*types.QueryPoolNumberResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - ctx := sdk.UnwrapSDKContext(goCtx) - var poolNumber uint64 - - bz := ctx.KVStore(k.storeKey).Get(types.KeyNextGlobalPoolNumber) - if bz == nil { - return nil, fmt.Errorf("pool number has not been initialized -- Should have been done in InitGenesis") - } else { - val := gogotypes.UInt64Value{} - k.cdc.MustUnmarshal(bz, &val) - poolNumber = val.GetValue() - } - - return &types.QueryPoolNumberResponse{ - PoolId: poolNumber, - }, nil -} - -func (k queryServer) Pools(goCtx context.Context, req *types.QueryPoolsRequest) ( - *types.QueryPoolsResponse, error, -) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - ctx := sdk.UnwrapSDKContext(goCtx) - store := ctx.KVStore(k.Keeper.storeKey) - poolStore := prefix.NewStore(store, types.KeyPrefixPools) - - pools := []*types.Pool{} - pageRes, err := query.Paginate( - poolStore, - req.Pagination, - func(key []byte, value []byte) error { - var pool types.Pool - err := k.Keeper.cdc.Unmarshal(value, &pool) - if err != nil { - return err - } - pools = append(pools, &pool) - return nil - }, - ) - if err != nil { - return nil, status.Error(codes.Internal, err.Error()) - } - - return &types.QueryPoolsResponse{ - Pools: pools, - Pagination: pageRes, - }, nil -} - -// Parameters of a single pool. -func (k queryServer) PoolParams(goCtx context.Context, req *types.QueryPoolParamsRequest) ( - resp *types.QueryPoolParamsResponse, err error, -) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - ctx := sdk.UnwrapSDKContext(goCtx) - - pool, err := k.FetchPool(ctx, req.PoolId) - if err != nil { - return nil, err - } - - return &types.QueryPoolParamsResponse{ - PoolParams: &pool.PoolParams, - }, nil -} - -// Number of pools. -func (k queryServer) NumPools(ctx context.Context, _ *types.QueryNumPoolsRequest) ( - *types.QueryNumPoolsResponse, error, -) { - nextPoolNumber, err := k.GetNextPoolNumber(sdk.UnwrapSDKContext(ctx)) - if err != nil { - return nil, err - } - return &types.QueryNumPoolsResponse{ - // next pool number is the id of the next pool, - // so we have one less than that in number of pools (id starts at 1) - NumPools: nextPoolNumber - 1, - }, nil -} - -// Total liquidity across all pools. -func (k queryServer) TotalLiquidity(ctx context.Context, req *types.QueryTotalLiquidityRequest) (*types.QueryTotalLiquidityResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - - return &types.QueryTotalLiquidityResponse{ - Liquidity: k.Keeper.GetTotalLiquidity(sdkCtx), - }, nil -} - -// Total liquidity in a single pool. -func (k queryServer) TotalPoolLiquidity(ctx context.Context, req *types.QueryTotalPoolLiquidityRequest) (*types.QueryTotalPoolLiquidityResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - - sdkCtx := sdk.UnwrapSDKContext(ctx) - pool, err := k.FetchPool(sdkCtx, req.PoolId) - if err != nil { - return &types.QueryTotalPoolLiquidityResponse{}, err - } - return &types.QueryTotalPoolLiquidityResponse{ - Liquidity: k.bankKeeper.GetAllBalances(sdkCtx, pool.GetAddress()), - }, nil -} - -// Total shares in a single pool. -func (k queryServer) TotalShares(ctx context.Context, req *types.QueryTotalSharesRequest) ( - *types.QueryTotalSharesResponse, error, -) { - pool, err := k.FetchPool(sdk.UnwrapSDKContext(ctx), req.PoolId) - if err != nil { - return nil, err - } - - return &types.QueryTotalSharesResponse{ - TotalShares: pool.TotalShares, - }, nil -} - -// Instantaneous price of an asset in a pool. -func (k queryServer) SpotPrice(ctx context.Context, req *types.QuerySpotPriceRequest) ( - *types.QuerySpotPriceResponse, error, -) { - pool, err := k.FetchPool(sdk.UnwrapSDKContext(ctx), req.PoolId) - if err != nil { - return nil, err - } - - price, err := pool.CalcSpotPrice(req.TokenInDenom, req.TokenOutDenom) - if err != nil { - return nil, err - } - - return &types.QuerySpotPriceResponse{ - SpotPrice: price.String(), - }, nil -} - -// Estimates the amount of assets returned given an exact amount of tokens to -// swap. -func (k queryServer) EstimateSwapExactAmountIn( - ctx context.Context, req *types.QuerySwapExactAmountInRequest, -) (*types.QuerySwapExactAmountInResponse, error) { - pool, err := k.FetchPool(sdk.UnwrapSDKContext(ctx), req.PoolId) - if err != nil { - return nil, err - } - - tokenOut, fee, err := pool.CalcOutAmtGivenIn(req.TokenIn, req.TokenOutDenom, false) - if err != nil { - return nil, err - } - - return &types.QuerySwapExactAmountInResponse{ - TokenOut: tokenOut, - Fee: fee, - }, nil -} - -// Estimates the amount of tokens required to return the exact amount of -// assets requested. -func (k queryServer) EstimateSwapExactAmountOut( - ctx context.Context, req *types.QuerySwapExactAmountOutRequest, -) (*types.QuerySwapExactAmountOutResponse, error) { - pool, err := k.FetchPool(sdk.UnwrapSDKContext(ctx), req.PoolId) - if err != nil { - return nil, err - } - - tokenIn, err := pool.CalcInAmtGivenOut(req.TokenOut, req.TokenInDenom) - if err != nil { - return nil, err - } - - return &types.QuerySwapExactAmountOutResponse{ - TokenIn: tokenIn, - }, nil -} - -// Estimates the amount of pool shares returned given an amount of tokens to -// join. -func (k queryServer) EstimateJoinExactAmountIn( - ctx context.Context, req *types.QueryJoinExactAmountInRequest, -) (*types.QueryJoinExactAmountInResponse, error) { - pool, err := k.FetchPool(sdk.UnwrapSDKContext(ctx), req.PoolId) - if err != nil { - return nil, err - } - numShares, remCoins, err := pool.AddTokensToPool(req.TokensIn) - if err != nil { - return nil, err - } - return &types.QueryJoinExactAmountInResponse{ - PoolSharesOut: numShares, - RemCoins: remCoins, - }, nil -} - -// Estimates the amount of tokens required to obtain an exact amount of pool -// shares. -func (k queryServer) EstimateJoinExactAmountOut(context.Context, *types.QueryJoinExactAmountOutRequest) (*types.QueryJoinExactAmountOutResponse, error) { - return nil, status.Error(codes.Unimplemented, "Not Implemented") -} - -// Estimates the amount of tokens returned to the user given an exact amount -// of pool shares. -func (k queryServer) EstimateExitExactAmountIn( - ctx context.Context, req *types.QueryExitExactAmountInRequest, -) (*types.QueryExitExactAmountInResponse, error) { - pool, err := k.FetchPool(sdk.UnwrapSDKContext(ctx), req.PoolId) - if err != nil { - return nil, err - } - tokensOut, fees, err := pool.ExitPool(req.PoolSharesIn) - if err != nil { - return nil, err - } - return &types.QueryExitExactAmountInResponse{ - TokensOut: tokensOut, - Fees: fees, - }, nil -} - -// Estimates the amount of pool shares required to extract an exact amount of -// tokens from the pool. -func (k queryServer) EstimateExitExactAmountOut(context.Context, *types.QueryExitExactAmountOutRequest) (*types.QueryExitExactAmountOutResponse, error) { - return nil, status.Error(codes.Unimplemented, "Not Implemented") -} diff --git a/x/spot/keeper/grpc_query_test.go b/x/spot/keeper/grpc_query_test.go deleted file mode 100644 index 53ecfe90a..000000000 --- a/x/spot/keeper/grpc_query_test.go +++ /dev/null @@ -1,807 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - "github.com/stretchr/testify/require" - - "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" - "github.com/NibiruChain/nibiru/x/spot/keeper" - "github.com/NibiruChain/nibiru/x/spot/types" -) - -func TestParamsQuery(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - params := types.DefaultParams() - app.SpotKeeper.SetParams(ctx, params) - - queryServer := keeper.NewQuerier(app.SpotKeeper) - - response, err := queryServer.Params(sdk.WrapSDKContext(ctx), &types.QueryParamsRequest{}) - require.NoError(t, err) - require.Equal(t, &types.QueryParamsResponse{Params: params}, response) -} - -func TestQueryPoolHappyPath(t *testing.T) { - tests := []struct { - name string - existingPool types.Pool - }{ - { - name: "correct fetch pool", - existingPool: types.Pool{ - Id: 1, - Address: testutil.AccAddress().String(), - PoolParams: types.PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.03"), - ExitFee: sdk.MustNewDecFromStr("0.03"), - PoolType: types.PoolType_BALANCER, - A: sdk.ZeroInt(), - }, - PoolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 200), - }, - }, - { - name: "correct fetch pool", - existingPool: types.Pool{ - Id: 1, - Address: testutil.AccAddress().String(), - PoolParams: types.PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.03"), - ExitFee: sdk.MustNewDecFromStr("0.03"), - PoolType: types.PoolType_STABLESWAP, - A: sdk.OneInt(), - }, - PoolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 200), - }, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - app.SpotKeeper.SetPool(ctx, tc.existingPool) - - queryServer := keeper.NewQuerier(app.SpotKeeper) - - resp, err := queryServer.Pool(sdk.WrapSDKContext(ctx), &types.QueryPoolRequest{ - PoolId: 1, - }) - require.NoError(t, err) - require.Equal(t, tc.existingPool, *resp.Pool) - }) - } -} - -func TestQueryPoolFail(t *testing.T) { - tests := []struct { - name string - }{ - { - name: "invalid request", - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - queryServer := keeper.NewQuerier(app.SpotKeeper) - resp, err := queryServer.Pool(sdk.WrapSDKContext(ctx), nil) - require.Error(t, err) - require.Nil(t, resp) - }) - } -} - -func TestQueryPools(t *testing.T) { - tests := []struct { - name string - existingPools []types.Pool - pagination query.PageRequest - expectedPools []types.Pool - }{ - { - name: "successful query single pool", - existingPools: []types.Pool{ - mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("foo", 100), - sdk.NewInt64Coin("bar", 100), - ), - /*shares=*/ 100, - ), - }, - expectedPools: []types.Pool{ - mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("foo", 100), - sdk.NewInt64Coin("bar", 100), - ), - /*shares=*/ 100, - ), - }, - }, - { - name: "successful query multiple pools", - existingPools: []types.Pool{ - mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("foo", 100), - sdk.NewInt64Coin("bar", 100), - ), - /*shares=*/ 100, - ), - mock.SpotPool( - /*poolId=*/ 2, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("baz", 100), - ), - /*shares=*/ 100, - ), - }, - expectedPools: []types.Pool{ - mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("foo", 100), - sdk.NewInt64Coin("bar", 100), - ), - /*shares=*/ 100, - ), - mock.SpotPool( - /*poolId=*/ 2, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("baz", 100), - ), - /*shares=*/ 100, - ), - }, - }, - { - name: "query pools with pagination", - existingPools: []types.Pool{ - mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("foo", 100), - sdk.NewInt64Coin("bar", 100), - ), - /*shares=*/ 100, - ), - mock.SpotPool( - /*poolId=*/ 2, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("baz", 100), - ), - /*shares=*/ 100, - ), - }, - pagination: query.PageRequest{ - Limit: 1, - }, - expectedPools: []types.Pool{ - mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("foo", 100), - sdk.NewInt64Coin("bar", 100), - ), - /*shares=*/ 100, - ), - }, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - for _, existingPool := range tc.existingPools { - app.SpotKeeper.SetPool(ctx, existingPool) - } - - queryServer := keeper.NewQuerier(app.SpotKeeper) - - resp, err := queryServer.Pools( - sdk.WrapSDKContext(ctx), - &types.QueryPoolsRequest{ - Pagination: &tc.pagination, - }, - ) - require.NoError(t, err) - - var responsePools []types.Pool - for _, p := range resp.Pools { - responsePools = append(responsePools, *p) - } - require.Equal(t, tc.expectedPools, responsePools) - }) - } -} - -func TestQueryNumPools(t *testing.T) { - tests := []struct { - name string - newPools []types.Pool - expectedNumPools uint64 - }{ - { - name: "one pool", - newPools: []types.Pool{ - mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - }, - expectedNumPools: 1, - }, - { - name: "multiple pools", - newPools: []types.Pool{ - mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.USDC, 100), - ), - /*shares=*/ 100, - ), - mock.SpotPool( - /*poolId=*/ 2, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.USDC, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - mock.SpotPool( - /*poolId=*/ 3, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NUSD, 100), - sdk.NewInt64Coin("unibi", 100), - ), - /*shares=*/ 100, - ), - }, - expectedNumPools: 3, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - sender := testutil.AccAddress() - // need funds to create pools - require.NoError(t, testapp.FundAccount( - app.BankKeeper, - ctx, - sender, - sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1e18), - sdk.NewInt64Coin(denoms.NUSD, 1e18), - sdk.NewInt64Coin(denoms.USDC, 1e18), - ), - )) - - for _, newPool := range tc.newPools { - _, err := app.SpotKeeper.NewPool( - ctx, - sender, - newPool.PoolParams, - newPool.PoolAssets, - ) - require.NoError(t, err) - } - - queryServer := keeper.NewQuerier(app.SpotKeeper) - - resp, err := queryServer.NumPools( - sdk.WrapSDKContext(ctx), - &types.QueryNumPoolsRequest{}, - ) - require.NoError(t, err) - require.Equal(t, tc.expectedNumPools, resp.NumPools) - }) - } -} - -func TestQueryPoolParams(t *testing.T) { - tests := []struct { - name string - existingPool types.Pool - expectedPoolParams types.PoolParams - }{ - { - name: "successful fetch pool params", - existingPool: types.Pool{ - Id: 1, - Address: testutil.AccAddress().String(), - PoolParams: types.PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.03"), - ExitFee: sdk.MustNewDecFromStr("0.03"), - PoolType: types.PoolType_BALANCER, - A: sdk.ZeroInt(), - }, - PoolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 200), - }, - expectedPoolParams: types.PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.03"), - ExitFee: sdk.MustNewDecFromStr("0.03"), - PoolType: types.PoolType_BALANCER, - A: sdk.ZeroInt(), - }, - }, - { - name: "successful fetch pool params", - existingPool: types.Pool{ - Id: 1, - Address: testutil.AccAddress().String(), - PoolParams: types.PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.03"), - ExitFee: sdk.MustNewDecFromStr("0.03"), - PoolType: types.PoolType_STABLESWAP, - A: sdk.OneInt(), - }, - PoolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 200), - }, - expectedPoolParams: types.PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.03"), - ExitFee: sdk.MustNewDecFromStr("0.03"), - PoolType: types.PoolType_STABLESWAP, - A: sdk.OneInt(), - }, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - app.SpotKeeper.SetPool(ctx, tc.existingPool) - - queryServer := keeper.NewQuerier(app.SpotKeeper) - - resp, err := queryServer.PoolParams(sdk.WrapSDKContext(ctx), &types.QueryPoolParamsRequest{ - PoolId: 1, - }) - require.NoError(t, err) - require.Equal(t, tc.expectedPoolParams, *resp.PoolParams) - }) - } -} - -func TestQueryTotalShares(t *testing.T) { - tests := []struct { - name string - existingPool types.Pool - expectedTotalShares sdk.Coin - }{ - { - name: "successfully get existing shares", - existingPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - expectedTotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - app.SpotKeeper.SetPool(ctx, tc.existingPool) - - queryServer := keeper.NewQuerier(app.SpotKeeper) - - resp, err := queryServer.TotalShares( - sdk.WrapSDKContext(ctx), - &types.QueryTotalSharesRequest{ - PoolId: 1, - }, - ) - require.NoError(t, err) - require.Equal(t, tc.expectedTotalShares, resp.TotalShares) - }) - } -} - -func TestQuerySpotPrice(t *testing.T) { - tests := []struct { - name string - existingPool types.Pool - tokenInDenom string - tokenOutDenom string - expectedPrice sdk.Dec - }{ - { - name: "same quantity", - existingPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenInDenom: denoms.NUSD, - tokenOutDenom: "unibi", - expectedPrice: sdk.OneDec(), - }, - { - name: "price of 2 unusd per unibi", - existingPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 200), - ), - /*shares=*/ 100, - ), - tokenInDenom: denoms.NUSD, - tokenOutDenom: "unibi", - expectedPrice: sdk.MustNewDecFromStr("2"), - }, - { - name: "price of 0.5 unibi per unusd", - existingPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 200), - ), - /*shares=*/ 100, - ), - tokenInDenom: "unibi", - tokenOutDenom: denoms.NUSD, - expectedPrice: sdk.MustNewDecFromStr("0.5"), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - app.SpotKeeper.SetPool(ctx, tc.existingPool) - - queryServer := keeper.NewQuerier(app.SpotKeeper) - - resp, err := queryServer.SpotPrice( - sdk.WrapSDKContext(ctx), - &types.QuerySpotPriceRequest{ - PoolId: 1, - TokenInDenom: tc.tokenInDenom, - TokenOutDenom: tc.tokenOutDenom, - }, - ) - require.NoError(t, err) - require.Equal(t, tc.expectedPrice, sdk.MustNewDecFromStr(resp.SpotPrice)) - }) - } -} - -func TestQueryEstimateSwapExactAmountIn(t *testing.T) { - tests := []struct { - name string - existingPool types.Pool - tokenIn sdk.Coin - tokenOutDenom string - expectedTokenOut sdk.Coin - }{ - { - name: "simple swap", - existingPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin(denoms.NUSD, 100), - tokenOutDenom: "unibi", - expectedTokenOut: sdk.NewInt64Coin("unibi", 50), - }, - { - name: "complex swap", - existingPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 34844867), - sdk.NewInt64Coin(denoms.NUSD, 4684496849), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin("unibi", 586848), - tokenOutDenom: denoms.NUSD, - // https://www.wolframalpha.com/input?i=4684496849+-+%2834844867+*+4684496849+%2F+%2834844867%2B586848%29+%29 - expectedTokenOut: sdk.NewInt64Coin(denoms.NUSD, 77588330), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - app.SpotKeeper.SetPool(ctx, tc.existingPool) - queryServer := keeper.NewQuerier(app.SpotKeeper) - - resp, err := queryServer.EstimateSwapExactAmountIn( - sdk.WrapSDKContext(ctx), - &types.QuerySwapExactAmountInRequest{ - PoolId: 1, - TokenIn: tc.tokenIn, - TokenOutDenom: tc.tokenOutDenom, - }, - ) - - require.NoError(t, err) - require.Equal(t, tc.expectedTokenOut, resp.TokenOut) - }) - } -} - -func TestQueryEstimateSwapExactAmountOut(t *testing.T) { - tests := []struct { - name string - existingPool types.Pool - tokenOut sdk.Coin - tokenInDenom string - expectedTokenIn sdk.Coin - }{ - { - name: "simple swap", - existingPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenOut: sdk.NewInt64Coin("unibi", 50), - tokenInDenom: denoms.NUSD, - // there's a swap fee that we take the ceiling of to round int - expectedTokenIn: sdk.NewInt64Coin(denoms.NUSD, 101), - }, - { - name: "complex swap", - existingPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 34844867), - sdk.NewInt64Coin(denoms.NUSD, 4684496849), - ), - /*shares=*/ 100, - ), - tokenOut: sdk.NewInt64Coin(denoms.NUSD, 77588330), - tokenInDenom: "unibi", - // https://www.wolframalpha.com/input?i=4684496849+-+%2834844867+*+4684496849+%2F+%2834844867%2B586848%29+%29 - expectedTokenIn: sdk.NewInt64Coin("unibi", 586848), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - app.SpotKeeper.SetPool(ctx, tc.existingPool) - queryServer := keeper.NewQuerier(app.SpotKeeper) - - resp, err := queryServer.EstimateSwapExactAmountOut( - sdk.WrapSDKContext(ctx), - &types.QuerySwapExactAmountOutRequest{ - PoolId: 1, - TokenOut: tc.tokenOut, - TokenInDenom: tc.tokenInDenom, - }, - ) - - require.NoError(t, err) - require.Equal(t, tc.expectedTokenIn, resp.TokenIn) - }) - } -} - -func TestQueryEstimateJoinExactAmountIn(t *testing.T) { - tests := []struct { - name string - existingPool types.Pool - tokensIn sdk.Coins - expectedPoolSharesOut sdkmath.Int - expectedRemCoins sdk.Coins - }{ - { - name: "complete join", - existingPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - expectedPoolSharesOut: sdk.NewIntFromUint64(100), - expectedRemCoins: sdk.NewCoins(), - }, - { - name: "leftover coins", - existingPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 50), - sdk.NewInt64Coin(denoms.NUSD, 75), - ), - expectedPoolSharesOut: sdk.NewIntFromUint64(50), - expectedRemCoins: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NUSD, 25), - ), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - app.SpotKeeper.SetPool(ctx, tc.existingPool) - queryServer := keeper.NewQuerier(app.SpotKeeper) - - resp, err := queryServer.EstimateJoinExactAmountIn( - sdk.WrapSDKContext(ctx), - &types.QueryJoinExactAmountInRequest{ - PoolId: 1, - TokensIn: tc.tokensIn, - }, - ) - - require.NoError(t, err) - require.Equal(t, tc.expectedPoolSharesOut, resp.PoolSharesOut) - require.Equal(t, tc.expectedRemCoins, resp.RemCoins) - }) - } -} - -func TestQueryEstimateExitExactAmountIn(t *testing.T) { - tests := []struct { - name string - existingPool types.Pool - poolSharesIn sdkmath.Int - expectedTokensOut sdk.Coins - }{ - { - name: "complete exit", - existingPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - poolSharesIn: sdk.NewIntFromUint64(100), - // exit fee leaves some tokens in pool - expectedTokensOut: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 99), - sdk.NewInt64Coin(denoms.NUSD, 99), - ), - }, - { - name: "leftover coins", - existingPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - poolSharesIn: sdk.NewIntFromUint64(50), - // exit fee leaves some tokens in pool - expectedTokensOut: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 49), - sdk.NewInt64Coin(denoms.NUSD, 49), - ), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - app.SpotKeeper.SetPool(ctx, tc.existingPool) - queryServer := keeper.NewQuerier(app.SpotKeeper) - - resp, err := queryServer.EstimateExitExactAmountIn( - sdk.WrapSDKContext(ctx), - &types.QueryExitExactAmountInRequest{ - PoolId: 1, - PoolSharesIn: tc.poolSharesIn, - }, - ) - - require.NoError(t, err) - require.Equal(t, tc.expectedTokensOut, resp.TokensOut) - }) - } -} diff --git a/x/spot/keeper/keeper.go b/x/spot/keeper/keeper.go deleted file mode 100644 index d7b6ec978..000000000 --- a/x/spot/keeper/keeper.go +++ /dev/null @@ -1,611 +0,0 @@ -package keeper - -import ( - "errors" - "fmt" - - storetypes "github.com/cosmos/cosmos-sdk/store/types" - - sdkmath "cosmossdk.io/math" - - "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - gogotypes "github.com/cosmos/gogoproto/types" - - "github.com/NibiruChain/nibiru/x/spot/types" -) - -type ( - Keeper struct { - cdc codec.BinaryCodec - storeKey storetypes.StoreKey - paramstore paramtypes.Subspace - - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper - distrKeeper types.DistrKeeper - } -) - -/* -NewKeeper Creates a new keeper for the spot module. - -args - - cdc: a codec - storeKey: the key-value store key that this keeper uses - ps: the param subspace for this keeper - accountKeeper: the auth module\'s keeper for accounts - bankKeeper: the bank module\'s keeper for bank transfers - -ret - - Keeper: a keeper for the spot module -*/ -func NewKeeper( - cdc codec.BinaryCodec, - storeKey storetypes.StoreKey, - ps paramtypes.Subspace, - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, - distrKeeper types.DistrKeeper, -) Keeper { - // set KeyTable if it has not already been set - if !ps.HasKeyTable() { - ps = ps.WithKeyTable(types.ParamKeyTable()) - } - - return Keeper{ - cdc: cdc, - storeKey: storeKey, - paramstore: ps, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - distrKeeper: distrKeeper, - } -} - -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} - -/* -Sets the next pool id that should be chosen when a new pool is created. -This function changes the state. - -args - - ctx: the cosmos-sdk context - poolNumber: the numeric id of the next pool number to use -*/ -func (k Keeper) SetNextPoolNumber(ctx sdk.Context, poolNumber uint64) { - store := ctx.KVStore(k.storeKey) - store.Set(types.KeyNextGlobalPoolNumber, - k.cdc.MustMarshal(&gogotypes.UInt64Value{Value: poolNumber})) -} - -/* -GetNextPoolNumber Retrieves the next pool id number to use when creating a new pool. -This function is idempotent (does not change state). - -args - - ctx: the cosmos-sdk context - -ret - - uint64: a pool id number -*/ -func (k Keeper) GetNextPoolNumber(ctx sdk.Context) (poolNumber uint64, err error) { - bz := ctx.KVStore(k.storeKey).Get(types.KeyNextGlobalPoolNumber) - if bz == nil { - return poolNumber, fmt.Errorf("pool number has not been initialized -- Should have been done in InitGenesis") - } - val := gogotypes.UInt64Value{} - k.cdc.MustUnmarshal(bz, &val) - return val.GetValue(), err -} - -/* -GetNextPoolNumberAndIncrement Returns the next pool id number, and increments the state's next pool id number by one -so that the next pool creation uses an autoincremented id number. - -args - - ctx: the cosmos-sdk context - -ret - - uint64: a pool id number -*/ -func (k Keeper) GetNextPoolNumberAndIncrement(ctx sdk.Context) (uint64, error) { - poolNumber, err := k.GetNextPoolNumber(ctx) - if err != nil { - return 0, err - } - k.SetNextPoolNumber(ctx, poolNumber+1) - return poolNumber, err -} - -/* -FetchPool Fetches a pool by id number. -Does not modify state. -Panics if the bytes could not be unmarshalled to a Pool proto object. - -args - - ctx: the cosmos-sdk context - poolId: the pool id number - -ret - - pool: a Pool proto object -*/ -func (k Keeper) FetchPool(ctx sdk.Context, poolId uint64) (pool types.Pool, err error) { - store := ctx.KVStore(k.storeKey) - k.cdc.MustUnmarshal(store.Get(types.GetKeyPrefixPools(poolId)), &pool) - - if len(pool.PoolAssets) == 0 { - return pool, types.ErrPoolNotFound.Wrapf("could not find pool with id %d", poolId) - } - return pool, nil -} - -/* -FetchPoolFromPair Given a pair of denom, find the corresponding pool id if it exists. - -args: - - denomA: One denom - - denomB: A second denom - -ret: - - poolId: the pool id - - err: error if any -*/ -func (k Keeper) FetchPoolFromPair(ctx sdk.Context, denomA string, denomB string) ( - pool types.Pool, err error, -) { - store := ctx.KVStore(k.storeKey) - - poolid := sdk.BigEndianToUint64(store.Get(types.GetDenomPrefixPoolIds(denomA, denomB))) - pool, err = k.FetchPool(ctx, poolid) - - if err != nil { - return pool, err - } - - return pool, nil -} - -/* -FetchAllPools fetch all pools from the store and returns them. -*/ -func (k Keeper) FetchAllPools(ctx sdk.Context) (pools []types.Pool) { - iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.KeyPrefixPools) - defer iterator.Close() - for ; iterator.Valid(); iterator.Next() { - var pool types.Pool - k.cdc.MustUnmarshal(iterator.Value(), &pool) - pools = append(pools, pool) - } - - return pools -} - -/* -SetPool Writes a pool to the state. -Panics if the pool proto could not be marshaled. - -args: - - ctx: the cosmos-sdk context - - pool: the Pool proto object -*/ -func (k Keeper) SetPool(ctx sdk.Context, pool types.Pool) { - store := ctx.KVStore(k.storeKey) - store.Set(types.GetKeyPrefixPools(pool.Id), k.cdc.MustMarshal(&pool)) - - k.SetPoolIdByDenom(ctx, pool) -} - -/* -SetPoolIdByDenom Writes a pool to the state accessible with the PoolId. -Panics if the pool proto could not be marshaled. - -args: - - ctx: the cosmos-sdk context - - pool: the Pool proto object -*/ -func (k Keeper) SetPoolIdByDenom(ctx sdk.Context, pool types.Pool) { - denomA := pool.PoolAssets[0].Token.Denom - denomB := pool.PoolAssets[1].Token.Denom - - store := ctx.KVStore(k.storeKey) - store.Set( - types.GetDenomPrefixPoolIds(denomA, denomB), - sdk.Uint64ToBigEndian(pool.Id), - ) -} - -/* -Mints new pool share tokens and sends them to an account. - -args: - - ctx: the cosmos-sdk context - poolId: the pool id number - recipientAddr: the address of the recipient - amountPoolShares: the amount of pool shares to mint to the recipient - -ret: - - err: returns an error if something errored out -*/ -func (k Keeper) mintPoolShareToAccount(ctx sdk.Context, poolId uint64, recipientAddr sdk.AccAddress, amount sdkmath.Int) (poolShares sdk.Coin, err error) { - poolShares = sdk.NewCoin(types.GetPoolShareBaseDenom(poolId), amount) - newCoins := sdk.NewCoins(poolShares) - - err = k.bankKeeper.MintCoins(ctx, types.ModuleName, newCoins) - if err != nil { - return sdk.Coin{}, err - } - - err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, recipientAddr, newCoins) - if err != nil { - return sdk.Coin{}, err - } - - return poolShares, nil -} - -/* -Burns takes an amount of pool shares from an account and burns them. -It's the inverse of mintPoolShareToAccount. - -args: - - ctx: the cosmos-sdk context - poolId: the pool id number - recipientAddr: the address of the recipient - amountPoolShares: the amount of pool shares to mint to the recipient - -ret: - - err: returns an error if something errored out -*/ -func (k Keeper) burnPoolShareFromAccount( - ctx sdk.Context, - fromAddr sdk.AccAddress, - poolSharesOut sdk.Coin, -) (err error) { - if err = k.bankKeeper.SendCoinsFromAccountToModule( - ctx, - fromAddr, - types.ModuleName, - sdk.Coins{poolSharesOut}, - ); err != nil { - return err - } - - if err = k.bankKeeper.BurnCoins( - ctx, - types.ModuleName, - sdk.Coins{poolSharesOut}, - ); err != nil { - return err - } - - return nil -} - -/* -NewPool Creates a brand new pool and writes it to the state. - -args - - ctx: the cosmos-sdk context - sender: the pool creator's address - poolParams: parameters of the pool, represented by a PoolParams proto object - poolAssets: initial assets in the pool, represented by a PoolAssets proto object array - -ret - - poolId: the pool id number - err: an error if any occurred -*/ -func (k Keeper) NewPool( - ctx sdk.Context, - sender sdk.AccAddress, - poolParams types.PoolParams, - poolAssets []types.PoolAsset, -) (poolId uint64, err error) { - if len(poolAssets) < types.MinPoolAssets { - return 0, types.ErrTooFewPoolAssets - } - - if len(poolAssets) > types.MaxPoolAssets { - return 0, types.ErrTooManyPoolAssets - } - - if !k.areAllAssetsWhitelisted(ctx, poolAssets) { - return 0, types.ErrTokenNotAllowed - } - - _, err = k.FetchPoolFromPair(ctx, poolAssets[0].Token.Denom, poolAssets[1].Token.Denom) - if err == nil { - return 0, types.ErrPoolWithSameAssetsExists - } - - // send pool creation fee to community pool - params := k.GetParams(ctx) - err = k.distrKeeper.FundCommunityPool(ctx, params.PoolCreationFee, sender) - if err != nil { - return 0, err - } - - poolId, err = k.GetNextPoolNumberAndIncrement(ctx) - if err != nil { - return 0, err - } - poolName := fmt.Sprintf("nibiru-pool-%d", poolId) - // Create a new account for the pool to hold funds. - poolAccount := k.accountKeeper.NewAccount(ctx, authtypes.NewEmptyModuleAccount(poolName)) - k.accountKeeper.SetAccount(ctx, poolAccount) - - pool, err := types.NewPool(poolId, poolAccount.GetAddress(), poolParams, poolAssets) - if err != nil { - return 0, err - } - - // Transfer the PoolAssets tokens to the pool's module account from the user account. - var coins sdk.Coins - for _, asset := range poolAssets { - coins = append(coins, asset.Token) - } - coins = sdk.NewCoins(coins...) - - if err = k.bankKeeper.SendCoins(ctx, sender, poolAccount.GetAddress(), coins); err != nil { - return 0, err - } - - // Mint the initial 100.000000000000000000 pool share tokens to the sender - newPoolShares, err := k.mintPoolShareToAccount(ctx, pool.Id, sender, types.InitPoolSharesSupply) - if err != nil { - return 0, err - } - - // Finally, add the share token's meta data to the bank keeper. - poolShareBaseDenom := types.GetPoolShareBaseDenom(pool.Id) - poolShareDisplayDenom := types.GetPoolShareDisplayDenom(pool.Id) - k.bankKeeper.SetDenomMetaData(ctx, banktypes.Metadata{ - Description: fmt.Sprintf("The share token of the nibiru spot amm pool %d", pool.Id), - DenomUnits: []*banktypes.DenomUnit{ - { - Denom: poolShareBaseDenom, - Exponent: 0, - }, - { - Denom: poolShareDisplayDenom, - Exponent: 18, - }, - }, - Base: poolShareBaseDenom, - Display: poolShareDisplayDenom, - Name: fmt.Sprintf("Nibiru Pool %d Share Token", pool.Id), - Symbol: poolShareDisplayDenom, - }) - - k.SetPool(ctx, pool) - if err = k.RecordTotalLiquidityIncrease(ctx, coins); err != nil { - return poolId, err - } - - err = ctx.EventManager().EmitTypedEvent(&types.EventPoolCreated{ - Creator: sender.String(), - Fees: params.PoolCreationFee, - FinalPool: pool, - FinalUserPoolShares: newPoolShares, - }) - if err != nil { - return - } - - return poolId, nil -} - -// areAllAssetsWhitelisted checks if all assets are in whitelist -func (k Keeper) areAllAssetsWhitelisted(ctx sdk.Context, assets []types.PoolAsset) bool { - whitelistedAssets := k.GetParams(ctx).GetWhitelistedAssetsAsMap() - for _, a := range assets { - if _, ok := whitelistedAssets[a.Token.Denom]; !ok { - return false - } - } - - return true -} - -/* -JoinPool Joins a pool without swapping leftover assets if the ratios don't exactly match the pool's asset ratios. - -For example, if a pool has 100 pool shares, 100foo, 100bar, -and JoinPool is called with 75foo and bar, only 50foo and 50bar would be deposited. -25foo in remCoins would be returned to the user, along with 50 pool shares would be minted -and given to the user. - -Inverse of ExitPool. - -args: - - ctx: the cosmos-sdk context - - joinerAddr: the user who wishes to withdraw tokens - - poolId: the pool's numeric id - - tokensIn: the amount of liquidity to provide - -ret: - - pool: the updated pool after joining - - numSharesOut: the pool shares minted and returned to the user - - remCoins: the number of remaining coins from the user's initial deposit attempt - - err: error if any -*/ -func (k Keeper) JoinPool( - ctx sdk.Context, - joinerAddr sdk.AccAddress, - poolId uint64, - tokensIn sdk.Coins, - shouldSwap bool, -) (pool types.Pool, numSharesOut sdk.Coin, remCoins sdk.Coins, err error) { - pool, _ = k.FetchPool(ctx, poolId) - - if len(tokensIn) != len(pool.PoolAssets) && !shouldSwap { - return pool, numSharesOut, remCoins, errors.New("too few assets to join this pool") - } - - if !pool.AreTokensInDenomInPoolAssets(tokensIn) { - err = types.ErrTokenDenomNotFound - return - } - - poolAddr := pool.GetAddress() - - var numShares sdkmath.Int - if !shouldSwap || pool.PoolParams.PoolType == types.PoolType_STABLESWAP { - numShares, remCoins, err = pool.AddTokensToPool(tokensIn) - } else { - numShares, remCoins, err = pool.AddAllTokensToPool(tokensIn) - } - if err != nil { - return types.Pool{}, sdk.Coin{}, sdk.Coins{}, err - } - - tokensConsumed := tokensIn.Sub(remCoins...) - - // take coins from joiner to pool - if err = k.bankKeeper.SendCoins( - ctx, - /*from=*/ joinerAddr, - /*to=*/ poolAddr, - /*amount=*/ tokensConsumed, - ); err != nil { - return pool, numSharesOut, remCoins, err - } - - // give joiner LP shares - newPoolShares, err := k.mintPoolShareToAccount( - ctx, - /*from=*/ pool.Id, - /*to=*/ joinerAddr, - /*amount=*/ numShares, - ) - if err != nil { - return types.Pool{}, sdk.Coin{}, sdk.Coins{}, err - } - - // record changes to store - k.SetPool(ctx, pool) - if err = k.RecordTotalLiquidityIncrease(ctx, tokensConsumed); err != nil { - return pool, numSharesOut, remCoins, err - } - - existingPoolShares := k.bankKeeper.GetBalance(ctx, joinerAddr, newPoolShares.Denom) - - err = ctx.EventManager().EmitTypedEvent(&types.EventPoolJoined{ - Address: joinerAddr.String(), - TokensIn: tokensIn, - PoolSharesOut: newPoolShares, - RemCoins: remCoins, - FinalPool: pool, - FinalUserPoolShares: existingPoolShares.Add(newPoolShares), - }) - if err != nil { - return - } - - return pool, newPoolShares, remCoins, nil -} - -/* -ExitPool Exits a pool by taking out tokens relative to the amount of pool shares -in proportion to the total amount of pool shares. - -For example, if a pool has 100 pool shares and ExitPool is called with 50 pool shares, -half of the tokens (minus exit fees) are returned to the user. - -Inverse of JoinPool. - -Throws an error if the provided pool shares doesn't match up with the pool's actual pool share. - -args: - - ctx: the cosmos-sdk context - - sender: the user who wishes to withdraw tokens - - poolId: the pool's numeric id - - poolSharesOut: the amount of pool shares to burn - -ret: - - tokensOut: the amount of liquidity withdrawn from the pool - - err: error if any -*/ -func (k Keeper) ExitPool( - ctx sdk.Context, - sender sdk.AccAddress, - poolId uint64, - poolSharesOut sdk.Coin, -) (tokensOut sdk.Coins, err error) { - pool, _ := k.FetchPool(ctx, poolId) - - // sanity checks - if poolSharesOut.Denom != pool.TotalShares.Denom { - return sdk.Coins{}, - fmt.Errorf("invalid pool share denom. expected %s, got %s", - pool.TotalShares.Denom, - poolSharesOut.Denom, - ) - } - - if poolSharesOut.Amount.GT(pool.TotalShares.Amount) || - poolSharesOut.Amount.LTE(sdk.ZeroInt()) { - return sdk.Coins{}, fmt.Errorf( - "invalid number of pool shares %s must be between 0 and %s", - poolSharesOut.Amount, pool.TotalShares.Amount, - ) - } - - existingPoolShares := k.bankKeeper.GetBalance(ctx, sender, poolSharesOut.Denom) - - // calculate withdrawn liquidity - tokensOut, fees, err := pool.ExitPool(poolSharesOut.Amount) - if err != nil { - return sdk.Coins{}, err - } - - // apply exchange of pool shares for tokens - if err = k.bankKeeper.SendCoins(ctx, pool.GetAddress(), sender, tokensOut); err != nil { - return sdk.Coins{}, err - } - - if err = k.burnPoolShareFromAccount(ctx, sender, poolSharesOut); err != nil { - return sdk.Coins{}, err - } - - // record state changes - k.SetPool(ctx, pool) - if err = k.RecordTotalLiquidityDecrease(ctx, tokensOut); err != nil { - return sdk.Coins{}, err - } - - err = ctx.EventManager().EmitTypedEvent(&types.EventPoolExited{ - Address: sender.String(), - PoolSharesIn: poolSharesOut, - TokensOut: tokensOut, - Fees: fees, - FinalPool: pool, - FinalUserPoolShares: existingPoolShares.Sub(poolSharesOut), - }) - if err != nil { - return sdk.Coins{}, err - } - - return tokensOut, nil -} diff --git a/x/spot/keeper/keeper_test.go b/x/spot/keeper/keeper_test.go deleted file mode 100644 index 5c1d7fa51..000000000 --- a/x/spot/keeper/keeper_test.go +++ /dev/null @@ -1,873 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - - "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - - "github.com/cometbft/cometbft/crypto/ed25519" - 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/spot/types" -) - -func TestGetAndSetNextPoolNumber(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - // Write to store - app.SpotKeeper.SetNextPoolNumber(ctx, 150) - - // Read from store - poolNumber, err := app.SpotKeeper.GetNextPoolNumber(ctx) - assert.NoError(t, err) - require.EqualValues(t, poolNumber, 150) -} - -func TestGetNextPoolNumberAndIncrement(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - // Write a pool number - app.SpotKeeper.SetNextPoolNumber(ctx, 200) - - // Get next and increment should return the current pool number - poolNumber, err := app.SpotKeeper.GetNextPoolNumberAndIncrement(ctx) - assert.NoError(t, err) - require.EqualValues(t, poolNumber, 200) - - // Check that the previous call incremented the number - poolNumber, err = app.SpotKeeper.GetNextPoolNumber(ctx) - assert.NoError(t, err) - require.EqualValues(t, poolNumber, 201) -} - -func TestSetAndFetchPool(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - pool := types.Pool{ - Id: 150, - PoolParams: types.PoolParams{ - SwapFee: sdk.NewDecWithPrec(3, 2), - ExitFee: sdk.NewDecWithPrec(3, 2), - PoolType: types.PoolType_BALANCER, - A: sdk.ZeroInt(), - }, - PoolAssets: []types.PoolAsset{ - { - Token: sdk.NewCoin(denoms.BTC, sdk.NewInt(1000)), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewCoin(denoms.NUSD, sdk.NewInt(1000)), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - TotalShares: sdk.NewInt64Coin("nibiru/pool/150", 100), - } - - app.SpotKeeper.SetPool(ctx, pool) - - retrievedPool, err := app.SpotKeeper.FetchPool(ctx, 150) - assert.NoError(t, err) - require.Equal(t, pool, retrievedPool) -} - -func TestFetchPoolFromPair(t *testing.T) { - tests := []struct { - name string - firstToken string - secondToken string - expectedPass bool - expectedPoolId uint64 - }{ - { - name: "Correct parse pool 1", - firstToken: "tokenA", - secondToken: "tokenB", - expectedPass: true, - expectedPoolId: 1, - }, - { - name: "Correct parse pool 1 inverted", - firstToken: "tokenB", - secondToken: "tokenA", - expectedPass: true, - expectedPoolId: sdk.OneInt().Uint64(), - }, - { - name: "Correct parse pool 2", - firstToken: "tokenB", - secondToken: "tokenC", - expectedPass: true, - expectedPoolId: sdk.NewInt(2).Uint64(), - }, - { - name: "Correct parse pool 2 inverted", - firstToken: "tokenC", - secondToken: "tokenB", - expectedPass: true, - expectedPoolId: sdk.NewInt(2).Uint64(), - }, - { - name: "Correct parse pool 2 inverted", - firstToken: "tokenC", - secondToken: "tokenB", - expectedPass: true, - expectedPoolId: sdk.NewInt(2).Uint64(), - }, - { - name: "Incorrect token denom, raise", - firstToken: "tokenA", - secondToken: "tokenC", - expectedPass: false, - }, - { - name: "Incorrect token denom, inverted", - firstToken: "tokenC", - secondToken: "tokenA", - expectedPass: false, - }, - { - name: "Incorrect token denom, same token", - firstToken: "tokenA", - secondToken: "tokenA", - expectedPass: false, - }, - { - name: "Incorrect token denom, missing token", - firstToken: "", - secondToken: "tokenA", - expectedPass: false, - }, - { - name: "Incorrect token denom, missing tokens", - firstToken: "", - secondToken: "", - expectedPass: false, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - app.SpotKeeper.SetPool(ctx, types.Pool{ - Id: 1, - PoolParams: types.PoolParams{ - SwapFee: sdk.NewDecWithPrec(3, 2), - ExitFee: sdk.NewDecWithPrec(3, 2), - PoolType: types.PoolType_BALANCER, - A: sdk.ZeroInt(), - }, - PoolAssets: []types.PoolAsset{ - { - Token: sdk.NewCoin("tokenB", sdk.NewInt(1000)), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewCoin("tokenA", sdk.NewInt(1000)), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - Address: "address1", - }) - - app.SpotKeeper.SetPool(ctx, types.Pool{ - Id: 2, - PoolParams: types.PoolParams{ - SwapFee: sdk.NewDecWithPrec(3, 2), - ExitFee: sdk.NewDecWithPrec(3, 2), - PoolType: types.PoolType_BALANCER, - A: sdk.ZeroInt(), - }, - PoolAssets: []types.PoolAsset{ - { - Token: sdk.NewCoin("tokenB", sdk.NewInt(1000)), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewCoin("tokenC", sdk.NewInt(1000)), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - Address: "address2", - }) - - retrievedPool, err := app.SpotKeeper.FetchPoolFromPair(ctx, tc.firstToken, tc.secondToken) - retrievedPoolId := retrievedPool.Id - if tc.expectedPass { - require.NoError(t, err) - - require.Equal(t, tc.expectedPoolId, retrievedPoolId) - } else { - require.Error(t, err) - } - }) - } -} - -func TestNewPool(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - poolCreationFeeCoin := sdk.NewInt64Coin(denoms.NIBI, 1000*common.TO_MICRO) - app.SpotKeeper.SetParams(ctx, types.NewParams( - /*startingPoolNumber=*/ 1, - /*poolCreationFee=*/ sdk.NewCoins(poolCreationFeeCoin), - /*whitelistedAssets*/ []string{ - "uatom", - "uosmo", - }, - )) - - userAddr := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address().Bytes()) - - err := testapp.FundAccount(app.BankKeeper, ctx, userAddr, sdk.NewCoins( - sdk.NewCoin("uatom", sdk.NewInt(1000)), - sdk.NewCoin("uosmo", sdk.NewInt(1000)), - poolCreationFeeCoin, - )) - require.NoError(t, err) - - poolId, err := app.SpotKeeper.NewPool(ctx, - // sender - userAddr, - // poolParams - types.PoolParams{ - SwapFee: sdk.NewDecWithPrec(3, 2), - ExitFee: sdk.NewDecWithPrec(3, 2), - PoolType: types.PoolType_BALANCER, - A: sdk.ZeroInt(), - }, - // poolAssets - []types.PoolAsset{ - { - Token: sdk.NewCoin("uatom", sdk.NewInt(1000)), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewCoin("uosmo", sdk.NewInt(1000)), - Weight: sdk.OneInt(), - }, - }) - require.NoError(t, err) - - retrievedPool, _ := app.SpotKeeper.FetchPool(ctx, poolId) - - require.Equal(t, types.Pool{ - Id: 1, - Address: retrievedPool.Address, // address is random so can't test, just reuse value - PoolParams: types.PoolParams{ - SwapFee: sdk.NewDecWithPrec(3, 2), - ExitFee: sdk.NewDecWithPrec(3, 2), - PoolType: types.PoolType_BALANCER, - A: sdk.ZeroInt(), - }, - PoolAssets: []types.PoolAsset{ - { - Token: sdk.NewCoin("uatom", sdk.NewInt(1000)), - Weight: sdk.NewInt(1 << 30), - }, - { - Token: sdk.NewCoin("uosmo", sdk.NewInt(1000)), - Weight: sdk.NewInt(1 << 30), - }, - }, - TotalWeight: sdk.NewInt(2 << 30), - TotalShares: sdk.NewCoin("nibiru/pool/1", sdkmath.NewIntWithDecimal(100, 18)), - }, retrievedPool) -} - -func TestNewPoolNotEnoughFunds(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - app.SpotKeeper.SetParams(ctx, types.NewParams( - /*startingPoolNumber=*/ 1, - /*poolCreationFee=*/ sdk.NewCoins(sdk.NewInt64Coin(denoms.NIBI, 1000*common.TO_MICRO)), - /*whitelistedAssets*/ []string{}, - )) - - userAddr := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address().Bytes()) - - err := testapp.FundAccount(app.BankKeeper, ctx, userAddr, sdk.NewCoins( - sdk.NewCoin("uatom", sdk.NewInt(1000)), - sdk.NewCoin("uosmo", sdk.NewInt(1000)), - sdk.NewCoin("unibi", sdk.NewInt(999*common.TO_MICRO)), - )) - require.NoError(t, err) - - _, err = app.SpotKeeper.NewPool(ctx, - // sender - userAddr, - // poolParams - types.PoolParams{ - SwapFee: sdk.NewDecWithPrec(3, 2), - ExitFee: sdk.NewDecWithPrec(3, 2), - PoolType: types.PoolType_BALANCER, - }, - // poolAssets - []types.PoolAsset{ - { - Token: sdk.NewCoin("uatom", sdk.NewInt(1000)), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewCoin("uosmo", sdk.NewInt(1000)), - Weight: sdk.OneInt(), - }, - }) - require.Error(t, err) -} - -func TestNewPoolTooLittleAssets(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - userAddr, err := sdk.AccAddressFromBech32(testutil.AccAddress().String()) - require.NoError(t, err) - - poolParams := types.PoolParams{ - SwapFee: sdk.NewDecWithPrec(3, 2), - ExitFee: sdk.NewDecWithPrec(3, 2), - PoolType: types.PoolType_BALANCER, - } - poolAssets := []types.PoolAsset{ - { - Token: sdk.NewCoin("uatom", sdk.NewInt(1000)), - }, - } - - poolId, err := app.SpotKeeper.NewPool(ctx, userAddr, poolParams, poolAssets) - require.ErrorIs(t, err, types.ErrTooFewPoolAssets) - require.Equal(t, uint64(0), poolId) -} - -func TestKeeperNewPoolNotWhitelistedAssets(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - userAddr, err := sdk.AccAddressFromBech32(testutil.AccAddress().String()) - require.NoError(t, err) - - poolParams := types.PoolParams{ - SwapFee: sdk.NewDecWithPrec(3, 2), - ExitFee: sdk.NewDecWithPrec(3, 2), - PoolType: types.PoolType_BALANCER, - } - - poolAssets := []types.PoolAsset{ - { - Token: sdk.NewCoin("uatom1", sdk.NewInt(1000)), - }, - { - Token: sdk.NewCoin("uatom2", sdk.NewInt(1000)), - }, - } - - poolId, err := app.SpotKeeper.NewPool(ctx, userAddr, poolParams, poolAssets) - require.ErrorIs(t, err, types.ErrTokenNotAllowed) - require.Equal(t, uint64(0), poolId) -} - -func TestNewPoolTooManyAssets(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - userAddr, err := sdk.AccAddressFromBech32(testutil.AccAddress().String()) - require.NoError(t, err) - - poolParams := types.PoolParams{ - SwapFee: sdk.NewDecWithPrec(3, 2), - ExitFee: sdk.NewDecWithPrec(3, 2), - PoolType: types.PoolType_BALANCER, - } - poolAssets := []types.PoolAsset{ - { - Token: sdk.NewCoin("uatom1", sdk.NewInt(1000)), - }, - { - Token: sdk.NewCoin("uatom2", sdk.NewInt(1000)), - }, - { - Token: sdk.NewCoin("uatom3", sdk.NewInt(1000)), - }, - { - Token: sdk.NewCoin("uatom4", sdk.NewInt(1000)), - }, - { - Token: sdk.NewCoin("uatom5", sdk.NewInt(1000)), - }, - { - Token: sdk.NewCoin("uatom6", sdk.NewInt(1000)), - }, - { - Token: sdk.NewCoin("uatom7", sdk.NewInt(1000)), - }, - { - Token: sdk.NewCoin("uatom8", sdk.NewInt(1000)), - }, - { - Token: sdk.NewCoin("uatom9", sdk.NewInt(1000)), - }, - } - - poolId, err := app.SpotKeeper.NewPool(ctx, userAddr, poolParams, poolAssets) - require.ErrorIs(t, err, types.ErrTooManyPoolAssets) - require.Equal(t, uint64(0), poolId) -} - -func TestNewPoolDups(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - userAddr, err := sdk.AccAddressFromBech32(testutil.AccAddress().String()) - require.NoError(t, err) - - poolCreationFeeCoin := sdk.NewCoins(sdk.NewInt64Coin(denoms.NIBI, 1)) - err = testapp.FundAccount(app.BankKeeper, ctx, userAddr, sdk.NewCoins( - sdk.NewCoin(denoms.NIBI, sdk.NewInt(1000)), - sdk.NewCoin("bar", sdk.NewInt(1000)), - sdk.NewCoin("foo", sdk.NewInt(1000)), - )) - require.NoError(t, err) - app.SpotKeeper.SetParams(ctx, types.NewParams( - /*startingPoolNumber=*/ 1, - /*poolCreationFee=*/ poolCreationFeeCoin, - /*whitelistedAssets*/ []string{ - "bar", - "foo", - }, - )) - - poolParams := types.PoolParams{ - SwapFee: sdk.NewDecWithPrec(3, 2), - ExitFee: sdk.NewDecWithPrec(3, 2), - } - poolAssets := []types.PoolAsset{ - { - Token: sdk.NewCoin("bar", sdk.NewInt(10)), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewCoin("foo", sdk.NewInt(10)), - Weight: sdk.OneInt(), - }, - } - - poolId, err := app.SpotKeeper.NewPool(ctx, userAddr, poolParams, poolAssets) - require.NoError(t, err) - require.Equal(t, uint64(1), poolId) - - _, err = app.SpotKeeper.NewPool(ctx, userAddr, poolParams, poolAssets) - require.ErrorIs(t, err, types.ErrPoolWithSameAssetsExists) -} - -func TestJoinPool(t *testing.T) { - const shareDenom = "nibiru/pool/1" - - tests := []struct { - name string - joinerInitialFunds sdk.Coins - initialPool types.Pool - tokensIn sdk.Coins - expectedNumSharesOut sdk.Coin - expectedRemCoins sdk.Coins - expectedJoinerFinalFunds sdk.Coins - expectedFinalPool types.Pool - }{ - { - name: "join with all assets", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - /*shares=*/ 100), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - expectedNumSharesOut: sdk.NewInt64Coin(shareDenom, 100), - expectedRemCoins: sdk.NewCoins(), - expectedJoinerFinalFunds: sdk.NewCoins(sdk.NewInt64Coin(shareDenom, 100)), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 200), - sdk.NewInt64Coin("foo", 200), - ), - /*shares=*/ 200), - }, - { - name: "join with some assets, none remaining", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - /*shares=*/ 100), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("bar", 50), - sdk.NewInt64Coin("foo", 50), - ), - expectedNumSharesOut: sdk.NewInt64Coin(shareDenom, 50), - expectedRemCoins: sdk.NewCoins(), - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(shareDenom, 50), - sdk.NewInt64Coin("bar", 50), - sdk.NewInt64Coin("foo", 50), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 150), - sdk.NewInt64Coin("foo", 150), - ), - /*shares=*/ 150), - }, - { - name: "join with some assets, some remaining", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - /*shares=*/ 100), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("bar", 50), - sdk.NewInt64Coin("foo", 75), - ), - expectedNumSharesOut: sdk.NewInt64Coin(shareDenom, 50), - expectedRemCoins: sdk.NewCoins( - sdk.NewInt64Coin("foo", 25), - ), - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(shareDenom, 50), - sdk.NewInt64Coin("bar", 50), - sdk.NewInt64Coin("foo", 50), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 150), - sdk.NewInt64Coin("foo", 150), - ), - /*shares=*/ 150), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - poolAddr := testutil.AccAddress() - tc.initialPool.Address = poolAddr.String() - tc.expectedFinalPool.Address = poolAddr.String() - app.SpotKeeper.SetPool(ctx, tc.initialPool) - - joinerAddr := testutil.AccAddress() - require.NoError(t, testapp.FundAccount(app.BankKeeper, ctx, joinerAddr, tc.joinerInitialFunds)) - - pool, numSharesOut, remCoins, err := app.SpotKeeper.JoinPool(ctx, joinerAddr, 1, tc.tokensIn, false) - require.NoError(t, err) - require.Equal(t, tc.expectedFinalPool, pool) - require.Equal(t, tc.expectedNumSharesOut, numSharesOut) - require.Equal(t, tc.expectedRemCoins, remCoins) - }) - } -} - -func TestJoinPoolAllAssets(t *testing.T) { - const shareDenom = "nibiru/pool/1" - - tests := []struct { - name string - joinerInitialFunds sdk.Coins - initialPool types.Pool - tokensIn sdk.Coins - expectedNumSharesOut sdk.Coin - expectedRemCoins sdk.Coins - expectedJoinerFinalFunds sdk.Coins - expectedFinalPool types.Pool - }{ - { - name: "join with all assets", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - /*shares=*/ 100), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - expectedNumSharesOut: sdk.NewInt64Coin(shareDenom, 100), - expectedRemCoins: sdk.NewCoins(), - expectedJoinerFinalFunds: sdk.NewCoins(sdk.NewInt64Coin(shareDenom, 100)), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 200), - sdk.NewInt64Coin("foo", 200), - ), - /*shares=*/ 200), - }, - { - name: "join with some assets, none remaining", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - /*shares=*/ 100), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("bar", 50), - sdk.NewInt64Coin("foo", 50), - ), - expectedNumSharesOut: sdk.NewInt64Coin(shareDenom, 50), - expectedRemCoins: sdk.NewCoins(), - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(shareDenom, 50), - sdk.NewInt64Coin("bar", 50), - sdk.NewInt64Coin("foo", 50), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 150), - sdk.NewInt64Coin("foo", 150), - ), - /*shares=*/ 150), - }, - { - name: "join with some assets, pool empty in one side, none remaining", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("foo", 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 1), - ), - /*shares=*/ 100), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("foo", 100), - ), - expectedNumSharesOut: sdk.NewInt64Coin(shareDenom, 904), - expectedRemCoins: sdk.NewCoins(), - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(shareDenom, 904), - sdk.NewInt64Coin("bar", 0), - sdk.NewInt64Coin("foo", 0), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 101), - ), - /*shares=*/ 1004), - }, - { - name: "join with some assets, but swap done", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - /*shares=*/ 100), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("bar", 50), - sdk.NewInt64Coin("foo", 75), - ), - expectedNumSharesOut: sdk.NewInt64Coin(shareDenom, 62), - expectedRemCoins: sdk.NewCoins(), - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(shareDenom, 62), - sdk.NewInt64Coin("bar", 50), - sdk.NewInt64Coin("foo", 25), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 150), - sdk.NewInt64Coin("foo", 175), - ), - /*shares=*/ 162), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - poolAddr := testutil.AccAddress() - tc.initialPool.Address = poolAddr.String() - tc.expectedFinalPool.Address = poolAddr.String() - app.SpotKeeper.SetPool(ctx, tc.initialPool) - - joinerAddr := testutil.AccAddress() - require.NoError(t, testapp.FundAccount(app.BankKeeper, ctx, joinerAddr, tc.joinerInitialFunds)) - - pool, numSharesOut, remCoins, err := app.SpotKeeper.JoinPool(ctx, joinerAddr, 1, tc.tokensIn, true) - require.NoError(t, err) - require.Equal(t, tc.expectedFinalPool, pool) - require.Equal(t, tc.expectedNumSharesOut, numSharesOut) - require.Equal(t, tc.expectedRemCoins, remCoins) - require.Equal(t, tc.expectedJoinerFinalFunds, app.BankKeeper.GetAllBalances(ctx, joinerAddr)) - }) - } -} - -func TestExitPool(t *testing.T) { - const shareDenom = "nibiru/pool/1" - - tests := []struct { - name string - joinerInitialFunds sdk.Coins - initialPoolFunds sdk.Coins - initialPool types.Pool - poolSharesIn sdk.Coin - expectedTokensOut sdk.Coins - expectedJoinerFinalFunds sdk.Coins - expectedFinalPool types.Pool - }{ - { - name: "exit all pool shares", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - sdk.NewInt64Coin(shareDenom, 100), - ), - initialPoolFunds: sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - /*shares=*/ 100, - ), - poolSharesIn: sdk.NewInt64Coin(shareDenom, 100), - expectedTokensOut: sdk.NewCoins( - sdk.NewInt64Coin("bar", 99), - sdk.NewInt64Coin("foo", 99), - ), - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin("bar", 199), - sdk.NewInt64Coin("foo", 199), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 1), - sdk.NewInt64Coin("foo", 1), - ), - /*shares=*/ 0, - ), - }, - { - name: "exit half pool shares", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - sdk.NewInt64Coin(shareDenom, 100), - ), - initialPoolFunds: sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 100), - ), - /*shares=*/ 100, - ), - poolSharesIn: sdk.NewInt64Coin(shareDenom, 50), - expectedTokensOut: sdk.NewCoins( - sdk.NewInt64Coin("bar", 49), - sdk.NewInt64Coin("foo", 49), - ), - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin("bar", 149), - sdk.NewInt64Coin("foo", 149), - sdk.NewInt64Coin(shareDenom, 50), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("bar", 51), - sdk.NewInt64Coin("foo", 51), - ), - /*shares=*/ 50, - ), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - poolAddr := testutil.AccAddress() - tc.initialPool.Address = poolAddr.String() - tc.expectedFinalPool.Address = poolAddr.String() - app.SpotKeeper.SetPool(ctx, tc.initialPool) - - sender := testutil.AccAddress() - require.NoError(t, testapp.FundAccount(app.BankKeeper, ctx, sender, tc.joinerInitialFunds)) - require.NoError(t, testapp.FundAccount(app.BankKeeper, ctx, tc.initialPool.GetAddress(), tc.initialPoolFunds)) - - tokensOut, err := app.SpotKeeper.ExitPool(ctx, sender, 1, tc.poolSharesIn) - require.NoError(t, err) - require.Equal(t, tc.expectedTokensOut, tokensOut) - require.Equal(t, tc.expectedJoinerFinalFunds, app.BankKeeper.GetAllBalances(ctx, sender)) - pool, _ := app.SpotKeeper.FetchPool(ctx, 1) - require.Equal(t, tc.expectedFinalPool, pool) - }) - } -} diff --git a/x/spot/keeper/liquidity.go b/x/spot/keeper/liquidity.go deleted file mode 100644 index 6151af626..000000000 --- a/x/spot/keeper/liquidity.go +++ /dev/null @@ -1,156 +0,0 @@ -package keeper - -// Everything to do with total liquidity in the spot and liquidity of specific coin denoms. - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/store/prefix" - - spottypes "github.com/NibiruChain/nibiru/x/spot/types" - - sdkmath "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/common" -) - -/* -Fetches the liquidity for a specific coin denom. - -args: - - ctx: the cosmos-sdk context - denom: the coin denom - -ret: - - amount: the amount of liquidity for the provided coin. Returns 0 if not found. -*/ -func (k Keeper) GetDenomLiquidity(ctx sdk.Context, denom string) (amount sdkmath.Int, err error) { - store := ctx.KVStore(k.storeKey) - bz := store.Get(spottypes.GetDenomLiquidityPrefix(denom)) - if bz == nil { - return sdk.ZeroInt(), nil - } - - if err := amount.Unmarshal(bz); err != nil { - return amount, common.CombineErrors( - fmt.Errorf("failed to GetDenomLiquidty for denom %s", denom), - err) - } - - return amount, nil -} - -/* -Sets the liquidity for a specific coin denom. - -args: - - ctx: the cosmos-sdk context - denom: the coin denom - amount: the amount of liquidity for the coin -*/ -func (k Keeper) SetDenomLiquidity(ctx sdk.Context, denom string, amount sdkmath.Int) error { - store := ctx.KVStore(k.storeKey) - bz, err := amount.Marshal() - if err != nil { - return err - } - store.Set(spottypes.GetDenomLiquidityPrefix(denom), bz) - return nil -} - -/* -Fetches the liquidity for all tokens in the spot. - -args: - - ctx: the cosmos-sdk context - -ret: - - coins: an array of liquidities in the spot -*/ -func (k Keeper) GetTotalLiquidity(ctx sdk.Context) (coins sdk.Coins) { - store := ctx.KVStore(k.storeKey) - prefixStore := prefix.NewStore(store, spottypes.KeyTotalLiquidity) - - iterator := prefixStore.Iterator(nil, nil) - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - denom := string(iterator.Key()) - amount, err := k.GetDenomLiquidity(ctx, denom) - if err != nil { - ctx.Logger().Error(err.Error()) - } else { - coins = coins.Add(sdk.NewCoin(denom, amount)) - } - } - - return coins -} - -/* -Sets the total liquidity for each coin. - -args: - - ctx: the cosmos-sdk context - coins: the array of liquidities to update with -*/ -func (k Keeper) SetTotalLiquidity(ctx sdk.Context, coins sdk.Coins) error { - for _, coin := range coins { - if err := k.SetDenomLiquidity(ctx, coin.Denom, coin.Amount); err != nil { - return err - } - } - return nil -} - -/* -Increases the total liquidity of the provided coins by the coin amount. - -args: - - ctx: the cosmos-sdk context - coins: the coins added to the spot -*/ -func (k Keeper) RecordTotalLiquidityIncrease(ctx sdk.Context, coins sdk.Coins) error { - for _, coin := range coins { - amount, err := k.GetDenomLiquidity(ctx, coin.Denom) - if err != nil { - return err - } - amount = amount.Add(coin.Amount) - if err := k.SetDenomLiquidity(ctx, coin.Denom, amount); err != nil { - return err - } - } - return nil -} - -/* -Increases the total liquidity of the provided coins by the coin amount. - -args: - - ctx: the cosmos-sdk context - coins: the coins removed from the spot -*/ -func (k Keeper) RecordTotalLiquidityDecrease(ctx sdk.Context, coins sdk.Coins) error { - for _, coin := range coins { - amount, err := k.GetDenomLiquidity(ctx, coin.Denom) - if err != nil { - return err - } - amount = amount.Sub(coin.Amount) - if err := k.SetDenomLiquidity(ctx, coin.Denom, amount); err != nil { - return err - } - } - return nil -} diff --git a/x/spot/keeper/liquidity_test.go b/x/spot/keeper/liquidity_test.go deleted file mode 100644 index cd1409c38..000000000 --- a/x/spot/keeper/liquidity_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package keeper_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/testutil/testapp" - "github.com/NibiruChain/nibiru/x/spot/keeper" -) - -func TestGetSetDenomLiquidity(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - // Write to store - coin := sdk.NewCoin("nibi", sdk.NewInt(1_000)) - assert.NoError(t, app.SpotKeeper.SetDenomLiquidity(ctx, coin.Denom, coin.Amount)) - - // Read from store - amount, err := app.SpotKeeper.GetDenomLiquidity(ctx, "nibi") - assert.NoError(t, err) - require.EqualValues(t, sdk.NewInt(1000), amount) -} - -func TestGetTotalLiquidity(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - // Write to store - coinMap := map[string]sdkmath.Int{ - "atom": sdk.NewInt(123), - "nibi": sdk.NewInt(456), - "foo": sdk.NewInt(789), - } - for denom, amount := range coinMap { - coin := sdk.NewCoin(denom, amount) - assert.NoError(t, app.SpotKeeper.SetDenomLiquidity(ctx, coin.Denom, coin.Amount)) - } - - // Read from store - coins := app.SpotKeeper.GetTotalLiquidity(ctx) - - require.EqualValues(t, sdk.NewCoins( - sdk.NewCoin("atom", coinMap["atom"]), - sdk.NewCoin("nibi", coinMap["nibi"]), - sdk.NewCoin("foo", coinMap["foo"]), - ), coins) -} - -// assertLiqValues checks if the total liquidity for each denom (key) of the -// expected map matches what's given by the SpotKeeper -func assertLiqValues( - t *testing.T, - ctx sdk.Context, - spotKeeper keeper.Keeper, - expected map[string]sdkmath.Int, -) { - for denom, expectedLiq := range expected { - liq, err := spotKeeper.GetDenomLiquidity(ctx, denom) - assert.NoError(t, err) - assert.EqualValues(t, liq, expectedLiq) - } -} - -func TestSetTotalLiquidity(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - // Write to store - assert.NoError(t, app.SpotKeeper.SetTotalLiquidity(ctx, sdk.NewCoins( - sdk.NewCoin("atom", sdk.NewInt(123)), - sdk.NewCoin("nibi", sdk.NewInt(456)), - sdk.NewCoin("foo", sdk.NewInt(789)), - ))) - - // Read from store - expectedLiqValues := map[string]sdkmath.Int{ - "atom": sdk.NewInt(123), - "nibi": sdk.NewInt(456), - "foo": sdk.NewInt(789), - } - assertLiqValues(t, ctx, app.SpotKeeper, expectedLiqValues) -} - -func TestRecordTotalLiquidityIncrease(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - // Write to store - assert.NoError(t, app.SpotKeeper.SetTotalLiquidity(ctx, sdk.NewCoins( - sdk.NewCoin("atom", sdk.NewInt(100)), - sdk.NewCoin("nibi", sdk.NewInt(200)), - ))) - err := app.SpotKeeper.RecordTotalLiquidityIncrease(ctx, sdk.NewCoins( - sdk.NewCoin("atom", sdk.NewInt(50)), - sdk.NewCoin("nibi", sdk.NewInt(75)), - )) - assert.NoError(t, err) - - expectedLiqValues := map[string]sdkmath.Int{ - "atom": sdk.NewInt(150), - "nibi": sdk.NewInt(275), - } - assertLiqValues(t, ctx, app.SpotKeeper, expectedLiqValues) -} - -func TestRecordTotalLiquidityDecrease(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - // Write to store - assert.NoError(t, app.SpotKeeper.SetTotalLiquidity(ctx, sdk.NewCoins( - sdk.NewCoin("atom", sdk.NewInt(100)), - sdk.NewCoin("nibi", sdk.NewInt(200)), - ))) - err := app.SpotKeeper.RecordTotalLiquidityDecrease(ctx, sdk.NewCoins( - sdk.NewCoin("atom", sdk.NewInt(50)), - sdk.NewCoin("nibi", sdk.NewInt(75)), - )) - assert.NoError(t, err) - - expectedLiqValues := map[string]sdkmath.Int{ - "atom": sdk.NewInt(50), - "nibi": sdk.NewInt(125), - } - assertLiqValues(t, ctx, app.SpotKeeper, expectedLiqValues) -} diff --git a/x/spot/keeper/msg_server.go b/x/spot/keeper/msg_server.go deleted file mode 100644 index 2c1fb63d9..000000000 --- a/x/spot/keeper/msg_server.go +++ /dev/null @@ -1,166 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/spot/types" -) - -type msgServer struct { - Keeper -} - -// NewMsgServerImpl returns an implementation of the MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{Keeper: keeper} -} - -var _ types.MsgServer = msgServer{} - -/* -CreatePool Handler for the MsgCreatePool transaction. - -args - - ctx: the cosmos-sdk context - msg: a MsgCreatePool proto object - -ret - - MsgCreatePoolResponse: the MsgCreatePoolResponse proto object response, containing the pool id number - error: an error if any occurred -*/ -func (k msgServer) CreatePool(goCtx context.Context, msg *types.MsgCreatePool) (*types.MsgCreatePoolResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - sender, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - return nil, err - } - - poolId, err := k.NewPool(ctx, sender, *msg.PoolParams, msg.PoolAssets) - if err != nil { - return nil, err - } - - return &types.MsgCreatePoolResponse{ - PoolId: poolId, - }, nil -} - -/* -JoinPool Handler for the MsgJoinPool transaction. - -args - - ctx: the cosmos-sdk context - msg: a MsgJoinPool proto object - -ret - - MsgJoinPoolResponse: the MsgJoinPoolResponse proto object response, containing the pool id number - error: an error if any occurred -*/ -func (k msgServer) JoinPool(ctx context.Context, msg *types.MsgJoinPool) (*types.MsgJoinPoolResponse, error) { - sdkContext := sdk.UnwrapSDKContext(ctx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - pool, numSharesOut, remCoins, err := k.Keeper.JoinPool( - sdkContext, - sender, - msg.PoolId, - msg.TokensIn, - msg.UseAllCoins, - ) - if err != nil { - return nil, err - } - - return &types.MsgJoinPoolResponse{ - Pool: &pool, - NumPoolSharesOut: numSharesOut, - RemainingCoins: remCoins, - }, nil -} - -/* -ExitPool Handler for the MsgExitPool transaction. - -args - - ctx: the cosmos-sdk context - msg: a MsgExitPool proto object - -ret - - MsgExitPoolResponse: the MsgExitPoolResponse proto object response, containing the amount of tokens returned to the user - error: an error if any occurred -*/ -func (k msgServer) ExitPool(ctx context.Context, msg *types.MsgExitPool) (*types.MsgExitPoolResponse, error) { - sdkContext := sdk.UnwrapSDKContext(ctx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - tokensOut, err := k.Keeper.ExitPool( - sdkContext, - sender, - msg.PoolId, - msg.PoolShares, - ) - if err != nil { - return nil, err - } - - return &types.MsgExitPoolResponse{ - TokensOut: tokensOut, - }, nil -} - -/* -SwapAssets Handler for the MsgJoinPool transaction. - -args - - ctx: the cosmos-sdk context - msg: a MsgJoinPool proto object - -ret - - MsgJoinPoolResponse: the MsgJoinPoolResponse proto object response, containing the pool id number - error: an error if any occurred -*/ -func (k msgServer) SwapAssets(ctx context.Context, msg *types.MsgSwapAssets) ( - *types.MsgSwapAssetsResponse, error, -) { - sdkContext := sdk.UnwrapSDKContext(ctx) - - sender, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, err - } - - tokenOut, err := k.Keeper.SwapExactAmountIn( - sdkContext, - sender, - msg.PoolId, - msg.TokenIn, - msg.TokenOutDenom, - ) - if err != nil { - return nil, err - } - - return &types.MsgSwapAssetsResponse{ - TokenOut: tokenOut, - }, nil -} diff --git a/x/spot/keeper/msg_server_test.go b/x/spot/keeper/msg_server_test.go deleted file mode 100644 index 0b57f1698..000000000 --- a/x/spot/keeper/msg_server_test.go +++ /dev/null @@ -1,1254 +0,0 @@ -package keeper_test - -import ( - "fmt" - "testing" - - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - - "github.com/cometbft/cometbft/crypto/ed25519" - 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/testutil/mock" - "github.com/NibiruChain/nibiru/x/spot/keeper" - "github.com/NibiruChain/nibiru/x/spot/types" -) - -func TestCreatePool(t *testing.T) { - tests := []struct { - name string - creatorAddr sdk.AccAddress - poolParams types.PoolParams - poolAssets []types.PoolAsset - senderInitialFunds sdk.Coins - expectedErr error - }{ - { - name: "invalid creator addr", - creatorAddr: []byte{}, - poolParams: types.PoolParams{PoolType: types.PoolType_BALANCER}, - poolAssets: []types.PoolAsset{}, - expectedErr: fmt.Errorf("empty address string is not allowed"), - }, - { - name: "not enough assets", - poolParams: types.PoolParams{PoolType: types.PoolType_BALANCER}, - poolAssets: []types.PoolAsset{}, - expectedErr: types.ErrTooFewPoolAssets, - }, - { - name: "too many assets", - poolParams: types.PoolParams{PoolType: types.PoolType_BALANCER}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("ccc", 1), - Weight: sdk.OneInt(), - }, - }, - expectedErr: types.ErrTooManyPoolAssets, - }, - { - name: "asset not whitelisted 1", - poolParams: types.PoolParams{PoolType: types.PoolType_BALANCER}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin(denoms.USDC, 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("aaaa", 1), - Weight: sdk.OneInt(), - }, - }, - expectedErr: types.ErrTokenNotAllowed, - }, - { - name: "asset not whitelisted 2", - poolParams: types.PoolParams{PoolType: types.PoolType_BALANCER}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin(denoms.USDC, 1), - Weight: sdk.OneInt(), - }, - }, - expectedErr: types.ErrTokenNotAllowed, - }, - { - name: "insufficient pool creation fee", - poolParams: types.PoolParams{PoolType: types.PoolType_BALANCER}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin(denoms.USDC, 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin(denoms.NUSD, 1), - Weight: sdk.OneInt(), - }, - }, - senderInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1e9-1), - sdk.NewInt64Coin("aaa", 1), - sdk.NewInt64Coin("bbb", 1), - ), - expectedErr: fmt.Errorf("999999999unibi is smaller than 1000000000unibi: insufficient funds"), - }, - { - name: "insufficient initial deposit", - poolParams: types.PoolParams{PoolType: types.PoolType_BALANCER}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin(denoms.NIBI, 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin(denoms.USDC, 1), - Weight: sdk.OneInt(), - }, - }, - senderInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1e9), - ), - expectedErr: fmt.Errorf("is smaller than 1unibi: insufficient funds"), // SDK does not print 0nibi - }, - { - name: "successful pool creation", - poolParams: types.PoolParams{PoolType: types.PoolType_BALANCER}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin(denoms.NUSD, 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin(denoms.USDC, 1), - Weight: sdk.OneInt(), - }, - }, - senderInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1e9), - sdk.NewInt64Coin(denoms.NUSD, 1), - sdk.NewInt64Coin(denoms.USDC, 1), - ), - expectedErr: nil, - }, - { - name: "invalid creator addr - Stableswap", - creatorAddr: []byte{}, - poolParams: types.PoolParams{PoolType: types.PoolType_STABLESWAP, A: sdk.OneInt()}, - poolAssets: []types.PoolAsset{}, - expectedErr: fmt.Errorf("empty address string is not allowed"), - }, - { - name: "not enough assets - Stableswap", - poolParams: types.PoolParams{PoolType: types.PoolType_STABLESWAP, A: sdk.OneInt()}, - poolAssets: []types.PoolAsset{}, - expectedErr: types.ErrTooFewPoolAssets, - }, - { - name: "too many assets - Stableswap", - poolParams: types.PoolParams{PoolType: types.PoolType_STABLESWAP, A: sdk.OneInt()}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("ccc", 1), - Weight: sdk.OneInt(), - }, - }, - expectedErr: types.ErrTooManyPoolAssets, - }, - { - name: "asset not whitelisted 1 - Stableswap", - poolParams: types.PoolParams{PoolType: types.PoolType_STABLESWAP, A: sdk.OneInt()}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin(denoms.USDC, 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("aaaa", 1), - Weight: sdk.OneInt(), - }, - }, - expectedErr: types.ErrTokenNotAllowed, - }, - { - name: "asset not whitelisted 2 - Stableswap", - poolParams: types.PoolParams{PoolType: types.PoolType_STABLESWAP, A: sdk.OneInt()}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin(denoms.USDC, 1), - Weight: sdk.OneInt(), - }, - }, - expectedErr: types.ErrTokenNotAllowed, - }, - { - name: "insufficient pool creation fee - Stableswap", - poolParams: types.PoolParams{PoolType: types.PoolType_STABLESWAP, A: sdk.OneInt()}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin(denoms.USDC, 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin(denoms.NUSD, 1), - Weight: sdk.OneInt(), - }, - }, - senderInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1e9-1), - sdk.NewInt64Coin("aaa", 1), - sdk.NewInt64Coin("bbb", 1), - ), - expectedErr: fmt.Errorf("999999999unibi is smaller than 1000000000unibi: insufficient funds"), - }, - { - name: "insufficient initial deposit - Stableswap", - poolParams: types.PoolParams{PoolType: types.PoolType_STABLESWAP, A: sdk.OneInt()}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin(denoms.NIBI, 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin(denoms.USDC, 1), - Weight: sdk.OneInt(), - }, - }, - senderInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1e9), - ), - expectedErr: fmt.Errorf("is smaller than 1unibi: insufficient funds"), // SDK cannot print 0unibi - }, - { - name: "successful pool creation - Stableswap", - poolParams: types.PoolParams{PoolType: types.PoolType_STABLESWAP, A: sdk.OneInt()}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin(denoms.NUSD, 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin(denoms.USDC, 1), - Weight: sdk.OneInt(), - }, - }, - senderInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1e9), - sdk.NewInt64Coin(denoms.NUSD, 1), - sdk.NewInt64Coin(denoms.USDC, 1), - ), - expectedErr: nil, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - msgServer := keeper.NewMsgServerImpl(app.SpotKeeper) - - if tc.creatorAddr == nil { - tc.creatorAddr = ed25519.GenPrivKey().PubKey().Address().Bytes() - } - if tc.senderInitialFunds != nil { - require.NoError(t, testapp.FundAccount(app.BankKeeper, ctx, tc.creatorAddr, tc.senderInitialFunds)) - } - - msgCreatePool := types.MsgCreatePool{ - Creator: tc.creatorAddr.String(), - PoolParams: &tc.poolParams, - PoolAssets: tc.poolAssets, - } - - _, err := msgServer.CreatePool(sdk.WrapSDKContext(ctx), &msgCreatePool) - if tc.expectedErr != nil { - require.Contains(t, err.Error(), tc.expectedErr.Error()) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestCreateExitJoinPool(t *testing.T) { - tests := []struct { - name string - creatorAddr sdk.AccAddress - poolParams types.PoolParams - poolAssets []types.PoolAsset - senderInitialFunds sdk.Coins - expectedErr error - useAllCoins bool - }{ - { - name: "happy path", - poolParams: types.PoolParams{PoolType: types.PoolType_BALANCER, A: sdk.OneInt()}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin(denoms.NUSD, 1_000), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin(denoms.USDC, 1_000), - Weight: sdk.OneInt(), - }, - }, - senderInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1e9), - sdk.NewInt64Coin(denoms.NUSD, 1_000), - sdk.NewInt64Coin(denoms.USDC, 1_000), - ), - expectedErr: nil, - useAllCoins: true, - }, - { - name: "happy path - stableswap", - poolParams: types.PoolParams{PoolType: types.PoolType_STABLESWAP, A: sdk.OneInt()}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin(denoms.NUSD, 1_000), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin(denoms.USDC, 1_000), - Weight: sdk.OneInt(), - }, - }, - senderInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1e9), - sdk.NewInt64Coin(denoms.NUSD, 1_000), - sdk.NewInt64Coin(denoms.USDC, 1_000), - ), - expectedErr: nil, - useAllCoins: true, - }, - { - name: "happy path - no use all coins", - poolParams: types.PoolParams{PoolType: types.PoolType_BALANCER, A: sdk.OneInt()}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin(denoms.NUSD, 1_000), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin(denoms.USDC, 1_000), - Weight: sdk.OneInt(), - }, - }, - senderInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1e9), - sdk.NewInt64Coin(denoms.NUSD, 1_000), - sdk.NewInt64Coin(denoms.USDC, 1_000), - ), - expectedErr: nil, - useAllCoins: false, - }, - { - name: "happy path - stableswap - no use all coins", - poolParams: types.PoolParams{PoolType: types.PoolType_STABLESWAP, A: sdk.OneInt()}, - poolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin(denoms.NUSD, 1_000), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin(denoms.USDC, 1_000), - Weight: sdk.OneInt(), - }, - }, - senderInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1e9), - sdk.NewInt64Coin(denoms.NUSD, 1_000), - sdk.NewInt64Coin(denoms.USDC, 1_000), - ), - expectedErr: nil, - useAllCoins: false, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - msgServer := keeper.NewMsgServerImpl(app.SpotKeeper) - - if tc.creatorAddr == nil { - tc.creatorAddr = ed25519.GenPrivKey().PubKey().Address().Bytes() - } - if tc.senderInitialFunds != nil { - require.NoError(t, testapp.FundAccount(app.BankKeeper, ctx, tc.creatorAddr, tc.senderInitialFunds)) - } - - msgCreatePool := types.MsgCreatePool{ - Creator: tc.creatorAddr.String(), - PoolParams: &tc.poolParams, - PoolAssets: tc.poolAssets, - } - - _, err := msgServer.CreatePool(sdk.WrapSDKContext(ctx), &msgCreatePool) - require.NoError(t, err) - - poolShares := app.BankKeeper.GetBalance(ctx, tc.creatorAddr, "nibiru/pool/1") - msgExitPool := types.MsgExitPool{ - Sender: tc.creatorAddr.String(), - PoolId: 1, - PoolShares: poolShares, - } - _, err = msgServer.ExitPool(sdk.WrapSDKContext(ctx), &msgExitPool) - require.NoError(t, err) - - require.Equal( - t, - tc.senderInitialFunds.Sub(sdk.NewInt64Coin(denoms.NIBI, 1e9)), - app.BankKeeper.GetAllBalances(ctx, tc.creatorAddr), - ) - - msgJoinPool := types.MsgJoinPool{ - Sender: tc.creatorAddr.String(), - PoolId: 1, - TokensIn: tc.senderInitialFunds.Sub(sdk.NewInt64Coin(denoms.NIBI, 1e9)), - UseAllCoins: tc.useAllCoins, - } - _, err = msgServer.JoinPool(sdk.WrapSDKContext(ctx), &msgJoinPool) - require.NoError(t, err) - - require.Equal( - t, - sdk.NewCoins(poolShares), - app.BankKeeper.GetAllBalances(ctx, tc.creatorAddr), - ) - }) - } -} - -func TestMsgServerJoinPool(t *testing.T) { - const shareDenom = "nibiru/pool/1" - tests := []struct { - name string - joinerInitialFunds sdk.Coins - initialPool types.Pool - tokensIn sdk.Coins - expectedNumSharesOut sdk.Coin - expectedRemCoins sdk.Coins - expectedJoinerFinalFunds sdk.Coins - expectedFinalPool types.Pool - }{ - { - name: "join with all assets", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - expectedNumSharesOut: sdk.NewInt64Coin(shareDenom, 100), - expectedRemCoins: sdk.NewCoins(), - expectedJoinerFinalFunds: sdk.NewCoins(sdk.NewInt64Coin(shareDenom, 100)), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 200), - sdk.NewInt64Coin(denoms.NUSD, 200), - ), - /*shares=*/ 200), - }, - { - name: "join with some assets, none remaining", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 50), - sdk.NewInt64Coin(denoms.NUSD, 50), - ), - expectedNumSharesOut: sdk.NewInt64Coin(shareDenom, 50), - expectedRemCoins: sdk.NewCoins(), - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(shareDenom, 50), - sdk.NewInt64Coin(denoms.NIBI, 50), - sdk.NewInt64Coin(denoms.NUSD, 50), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 150), - sdk.NewInt64Coin(denoms.NUSD, 150), - ), - /*shares=*/ 150), - }, - { - name: "join with some assets, some remaining", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 50), - sdk.NewInt64Coin(denoms.NUSD, 75), - ), - expectedNumSharesOut: sdk.NewInt64Coin(shareDenom, 50), - expectedRemCoins: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NUSD, 25), - ), - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(shareDenom, 50), - sdk.NewInt64Coin(denoms.NIBI, 50), - sdk.NewInt64Coin(denoms.NUSD, 50), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 150), - sdk.NewInt64Coin(denoms.NUSD, 150), - ), - /*shares=*/ 150), - }, - { - name: "join with all assets - Stablepool", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - initialPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - expectedNumSharesOut: sdk.NewInt64Coin(shareDenom, 100), - expectedRemCoins: sdk.NewCoins(), - expectedJoinerFinalFunds: sdk.NewCoins(sdk.NewInt64Coin(shareDenom, 100)), - expectedFinalPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 200), - sdk.NewInt64Coin(denoms.NUSD, 200), - ), - /*shares=*/ 200), - }, - { - name: "join with some assets, none remaining - Stablepool", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - initialPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 50), - sdk.NewInt64Coin(denoms.NUSD, 50), - ), - expectedNumSharesOut: sdk.NewInt64Coin(shareDenom, 50), - expectedRemCoins: []sdk.Coin{}, - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(shareDenom, 50), - sdk.NewInt64Coin(denoms.NIBI, 50), - sdk.NewInt64Coin(denoms.NUSD, 50), - ), - expectedFinalPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 150), - sdk.NewInt64Coin(denoms.NUSD, 150), - ), - /*shares=*/ 150), - }, - { - name: "join with some assets, some remaining - Stablepool", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - initialPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100), - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 50), - sdk.NewInt64Coin(denoms.NUSD, 75), - ), - expectedNumSharesOut: sdk.NewInt64Coin(shareDenom, 62), - expectedRemCoins: []sdk.Coin{}, - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(shareDenom, 62), - sdk.NewInt64Coin(denoms.NIBI, 50), - sdk.NewInt64Coin(denoms.NUSD, 25), - ), - expectedFinalPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 150), - sdk.NewInt64Coin(denoms.NUSD, 175), - ), - /*shares=*/ 162), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - poolAddr := testutil.AccAddress() - tc.initialPool.Address = poolAddr.String() - tc.expectedFinalPool.Address = poolAddr.String() - app.SpotKeeper.SetPool(ctx, tc.initialPool) - - joinerAddr := testutil.AccAddress() - require.NoError(t, testapp.FundAccount(app.BankKeeper, ctx, joinerAddr, tc.joinerInitialFunds)) - - msgServer := keeper.NewMsgServerImpl(app.SpotKeeper) - resp, err := msgServer.JoinPool( - sdk.WrapSDKContext(ctx), - types.NewMsgJoinPool(joinerAddr.String(), tc.initialPool.Id, tc.tokensIn, false), - ) - - require.NoError(t, err) - require.Equal(t, types.MsgJoinPoolResponse{ - Pool: &tc.expectedFinalPool, - NumPoolSharesOut: tc.expectedNumSharesOut, - RemainingCoins: tc.expectedRemCoins, - }, *resp) - require.Equal(t, tc.expectedJoinerFinalFunds, app.BankKeeper.GetAllBalances(ctx, joinerAddr)) - }) - } -} - -func TestMsgServerExitPool(t *testing.T) { - const shareDenom = "nibiru/pool/1" - tests := []struct { - name string - joinerInitialFunds sdk.Coins - poolFundsToAdd sdk.Coins - initialPool types.Pool - poolSharesIn sdk.Coin - expectedTokensOut sdk.Coins - expectedJoinerFinalFunds sdk.Coins - expectedFinalPool types.Pool - expectedFees sdk.Coins - }{ - { - name: "exit all pool shares", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - sdk.NewInt64Coin(shareDenom, 100), - ), - poolFundsToAdd: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - poolSharesIn: sdk.NewInt64Coin(shareDenom, 100), - expectedTokensOut: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 99), - sdk.NewInt64Coin(denoms.NUSD, 99), - ), - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 199), - sdk.NewInt64Coin(denoms.NUSD, 199), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1), - sdk.NewInt64Coin(denoms.NUSD, 1), - ), - /*shares=*/ 0, - ), - expectedFees: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1), - sdk.NewInt64Coin(denoms.NUSD, 1), - ), - }, - { - name: "exit half pool shares", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - sdk.NewInt64Coin(shareDenom, 100), - ), - poolFundsToAdd: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - poolSharesIn: sdk.NewInt64Coin(shareDenom, 50), - expectedTokensOut: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 49), - sdk.NewInt64Coin(denoms.NUSD, 49), - ), - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 149), - sdk.NewInt64Coin(denoms.NUSD, 149), - sdk.NewInt64Coin(shareDenom, 50), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 51), - sdk.NewInt64Coin(denoms.NUSD, 51), - ), - /*shares=*/ 50, - ), - expectedFees: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1), - sdk.NewInt64Coin(denoms.NUSD, 1), - ), - }, - { - name: "exit all pool shares - StablePool", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - sdk.NewInt64Coin(shareDenom, 100), - ), - poolFundsToAdd: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - initialPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - poolSharesIn: sdk.NewInt64Coin(shareDenom, 100), - expectedTokensOut: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 200), - sdk.NewInt64Coin(denoms.NUSD, 200), - ), - expectedFinalPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1), - sdk.NewInt64Coin(denoms.NUSD, 1), - ), - /*shares=*/ 0, - ), - expectedFees: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 0), - sdk.NewInt64Coin(denoms.NUSD, 0), - ), - }, - { - name: "exit half pool shares - StablePool", - joinerInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - sdk.NewInt64Coin(shareDenom, 100), - ), - poolFundsToAdd: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - initialPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - poolSharesIn: sdk.NewInt64Coin(shareDenom, 50), - expectedTokensOut: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 50), - sdk.NewInt64Coin(denoms.NUSD, 50), - ), - expectedJoinerFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 150), - sdk.NewInt64Coin(denoms.NUSD, 150), - sdk.NewInt64Coin(shareDenom, 50), - ), - expectedFinalPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 50), - sdk.NewInt64Coin(denoms.NUSD, 50), - ), - /*shares=*/ 50, - ), - expectedFees: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 0), - sdk.NewInt64Coin(denoms.NUSD, 0), - ), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - poolAddr := testutil.AccAddress() - tc.initialPool.Address = poolAddr.String() - tc.expectedFinalPool.Address = poolAddr.String() - app.SpotKeeper.SetPool(ctx, tc.initialPool) - - sender := testutil.AccAddress() - require.NoError(t, testapp.FundAccount( - app.BankKeeper, ctx, sender, tc.joinerInitialFunds)) - require.NoError(t, testapp.FundAccount( - app.BankKeeper, ctx, tc.initialPool.GetAddress(), tc.poolFundsToAdd)) - - msgServer := keeper.NewMsgServerImpl(app.SpotKeeper) - resp, err := msgServer.ExitPool( - sdk.WrapSDKContext(ctx), - types.NewMsgExitPool(sender.String(), tc.initialPool.Id, tc.poolSharesIn), - ) - require.NoError(t, err) - require.Equal(t, - types.MsgExitPoolResponse{ - TokensOut: tc.expectedTokensOut, - }, - *resp, - ) - require.Equal(t, - tc.expectedJoinerFinalFunds, - app.BankKeeper.GetAllBalances(ctx, sender), - ) - }) - } -} - -func TestMsgServerSwapAssets(t *testing.T) { - tests := []struct { - name string - - // test setup - userInitialFunds sdk.Coins - initialPool types.Pool - tokenIn sdk.Coin - tokenOutDenom string - - // expected results - expectedError error - expectedTokenOut sdk.Coin - expectedUserFinalFunds sdk.Coins - expectedFinalPool types.Pool - }{ - { - name: "regular swap", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin(denoms.NIBI, 100), - tokenOutDenom: denoms.NUSD, - expectedTokenOut: sdk.NewInt64Coin(denoms.NUSD, 50), - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NUSD, 50), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 200), - sdk.NewInt64Coin(denoms.NUSD, 50), - ), - /*shares=*/ 100, - ), - expectedError: nil, - }, - { - name: "not enough user funds", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin(denoms.NIBI, 100), - tokenOutDenom: denoms.NUSD, - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - expectedError: sdkerrors.ErrInsufficientFunds, - }, - { - name: "invalid token in denom", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("foo", 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin("foo", 100), - tokenOutDenom: denoms.NUSD, - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin("foo", 100), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - expectedError: types.ErrTokenDenomNotFound, - }, - { - name: "invalid token out denom", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin(denoms.NIBI, 100), - tokenOutDenom: "foo", - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - expectedError: types.ErrTokenDenomNotFound, - }, - { - name: "same token in and token out denom", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin(denoms.NIBI, 100), - tokenOutDenom: denoms.NIBI, - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - expectedError: types.ErrSameTokenDenom, - }, - { - name: "regular swap - StableSwap", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - ), - initialPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin(denoms.NIBI, 100), - tokenOutDenom: denoms.NUSD, - expectedTokenOut: sdk.NewInt64Coin(denoms.NUSD, 95), - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NUSD, 95), - ), - expectedFinalPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 200), - sdk.NewInt64Coin(denoms.NUSD, 5), - ), - /*shares=*/ 100, - ), - expectedError: nil, - }, - { - name: "not enough user funds - StableSwap", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1), - ), - initialPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin(denoms.NIBI, 100), - tokenOutDenom: denoms.NUSD, - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 1), - ), - expectedFinalPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - expectedError: sdkerrors.ErrInsufficientFunds, - }, - { - name: "invalid token in denom - StableSwap", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("foo", 100), - ), - initialPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin("foo", 100), - tokenOutDenom: denoms.NUSD, - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin("foo", 100), - ), - expectedFinalPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - expectedError: types.ErrTokenDenomNotFound, - }, - { - name: "invalid token out denom - StableSwap", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - ), - initialPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin(denoms.NIBI, 100), - tokenOutDenom: "foo", - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - ), - expectedFinalPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - expectedError: types.ErrTokenDenomNotFound, - }, - { - name: "same token in and token out denom - StableSwap", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - ), - initialPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin(denoms.NIBI, 100), - tokenOutDenom: denoms.NIBI, - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - ), - expectedFinalPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.NIBI, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - expectedError: types.ErrSameTokenDenom, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - msgServer := keeper.NewMsgServerImpl(app.SpotKeeper) - - // fund pool account - poolAddr := testutil.AccAddress() - tc.initialPool.Address = poolAddr.String() - tc.expectedFinalPool.Address = poolAddr.String() - require.NoError(t, - testapp.FundAccount( - app.BankKeeper, - ctx, - poolAddr, - tc.initialPool.PoolBalances(), - ), - ) - app.SpotKeeper.SetPool(ctx, tc.initialPool) - - // fund user account - sender := testutil.AccAddress() - require.NoError(t, testapp.FundAccount(app.BankKeeper, ctx, sender, tc.userInitialFunds)) - - // swap assets - resp, err := msgServer.SwapAssets( - sdk.WrapSDKContext(ctx), - types.NewMsgSwapAssets(sender.String(), tc.initialPool.Id, tc.tokenIn, tc.tokenOutDenom), - ) - - if tc.expectedError != nil { - require.ErrorIs(t, err, tc.expectedError) - } else { - require.NoError(t, err) - require.Equal(t, - types.MsgSwapAssetsResponse{ - TokenOut: tc.expectedTokenOut, - }, - *resp, - ) - } - - // check user's final funds - require.Equal(t, - tc.expectedUserFinalFunds, - app.BankKeeper.GetAllBalances(ctx, sender), - ) - - // check final pool state - finalPool, err := app.SpotKeeper.FetchPool(ctx, tc.initialPool.Id) - require.NoError(t, err) - require.Equal(t, tc.expectedFinalPool, finalPool) - }) - } -} diff --git a/x/spot/keeper/params.go b/x/spot/keeper/params.go deleted file mode 100644 index f59a429ee..000000000 --- a/x/spot/keeper/params.go +++ /dev/null @@ -1,18 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/spot/types" -) - -// GetParams get all parameters as types.Params -func (k Keeper) GetParams(ctx sdk.Context) (p types.Params) { - k.paramstore.GetParamSet(ctx, &p) - return p -} - -// SetParams set the params -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramstore.SetParamSet(ctx, ¶ms) -} diff --git a/x/spot/keeper/params_test.go b/x/spot/keeper/params_test.go deleted file mode 100644 index 5791cf2fe..000000000 --- a/x/spot/keeper/params_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - "github.com/NibiruChain/nibiru/x/spot/types" -) - -func TestGetParams(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - params := types.DefaultParams() - app.SpotKeeper.SetParams(ctx, params) - - require.EqualValues(t, params, app.SpotKeeper.GetParams(ctx)) -} diff --git a/x/spot/keeper/swap.go b/x/spot/keeper/swap.go deleted file mode 100644 index 305afef73..000000000 --- a/x/spot/keeper/swap.go +++ /dev/null @@ -1,121 +0,0 @@ -package keeper - -import ( - "errors" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/spot/types" -) - -func (k Keeper) updatePoolForSwap( - ctx sdk.Context, - pool types.Pool, - sender sdk.AccAddress, - tokenIn sdk.Coin, - tokenOut sdk.Coin, -) (err error) { - if err = k.bankKeeper.SendCoins( - ctx, - /*from=*/ sender, - /*to=*/ pool.GetAddress(), - /*coins=*/ sdk.Coins{tokenIn}, - ); err != nil { - return err - } - - if err = k.bankKeeper.SendCoins( - ctx, - /*from=*/ pool.GetAddress(), - /*to=*/ sender, - /*coins=*/ sdk.Coins{tokenOut}, - ); err != nil { - return err - } - - if err = pool.ApplySwap(tokenIn, tokenOut); err != nil { - return err - } - k.SetPool(ctx, pool) - - if err = k.RecordTotalLiquidityIncrease(ctx, sdk.Coins{tokenIn}); err != nil { - return err - } - if err = k.RecordTotalLiquidityDecrease(ctx, sdk.Coins{tokenOut}); err != nil { - return err - } - - return err -} - -/* -SwapExactAmountIn Given a poolId and the amount of tokens to swap in, returns the number of tokens out -received, specified by the tokenOutDenom. - -For example, if pool 1 has 100foo and 100bar, this function can be called with -tokenIn=10foo and tokenOutDenom=bar. - -args: - - ctx: the cosmos-sdk context - - sender: the address wishing to perform the swap - - poolId: the pool id number - - tokenIn: the amount of tokens to given to the pool - - tokenOutDenom: the denom of the token taken out of the pool - -ret: - - tokenOut: the amount of tokens taken out of the pool - - err: error if any -*/ -func (k Keeper) SwapExactAmountIn( - ctx sdk.Context, - sender sdk.AccAddress, - poolId uint64, - tokenIn sdk.Coin, - tokenOutDenom string, -) (tokenOut sdk.Coin, err error) { - if tokenIn.Denom == tokenOutDenom { - return sdk.Coin{}, types.ErrSameTokenDenom - } - - pool, err := k.FetchPool(ctx, poolId) - if err != nil { - return sdk.Coin{}, err - } - - // calculate tokenOut and validate - tokenOut, fee, err := pool.CalcOutAmtGivenIn(tokenIn, tokenOutDenom, false) - if err != nil { - return sdk.Coin{}, err - } - if tokenOut.Amount.LTE(sdk.ZeroInt()) { - return sdk.Coin{}, errors.New("tokenOut amount must be greater than zero") - } - - // check sender has enough tokenIn - if err = k.CheckEnoughBalances(ctx, sdk.Coins{tokenIn}, sender); err != nil { - return sdk.Coin{}, err - } - - // check pool has enough tokenOut - if err = k.CheckEnoughBalances(ctx, sdk.Coins{tokenOut}, pool.GetAddress()); err != nil { - return sdk.Coin{}, err - } - - err = k.updatePoolForSwap(ctx, pool, sender, tokenIn, tokenOut) - if err != nil { - return sdk.Coin{}, err - } - - err = ctx.EventManager().EmitTypedEvent(&types.EventAssetsSwapped{ - Address: sender.String(), - TokenIn: tokenIn, - TokenOut: tokenOut, - Fee: fee, - FinalPool: pool, - }) - if err != nil { - return tokenOut, err - } - - return tokenOut, nil -} diff --git a/x/spot/keeper/swap_test.go b/x/spot/keeper/swap_test.go deleted file mode 100644 index 04476fcd1..000000000 --- a/x/spot/keeper/swap_test.go +++ /dev/null @@ -1,399 +0,0 @@ -package keeper_test - -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/denoms" - "github.com/NibiruChain/nibiru/x/common/testutil" - "github.com/NibiruChain/nibiru/x/common/testutil/mock" - "github.com/NibiruChain/nibiru/x/common/testutil/testapp" - "github.com/NibiruChain/nibiru/x/spot/types" -) - -func TestSwapExactAmountIn(t *testing.T) { - tests := []struct { - name string - - // test setup - userInitialFunds sdk.Coins - initialPool types.Pool - tokenIn sdk.Coin - tokenOutDenom string - - // expected results - expectedError error - expectedTokenOut sdk.Coin - expectedUserFinalFunds sdk.Coins - expectedFinalPool types.Pool - }{ - { - name: "testnet 2 BUG, should not panic", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 236534500), - sdk.NewInt64Coin("unusd", 1700000000), - sdk.NewInt64Coin("uusdt", 701785070), - ), - initialPool: types.Pool{ - Id: 1, - PoolParams: types.PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.01"), - ExitFee: sdk.MustNewDecFromStr("0.01"), - PoolType: types.PoolType_STABLESWAP, - A: sdk.NewInt(10), - }, - PoolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin("unusd", 1_510_778_598), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("uusdt", 7_712_056), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - }, - tokenIn: sdk.NewInt64Coin("unusd", 1_500_000_000), - tokenOutDenom: "uusdt", - expectedTokenOut: sdk.NewInt64Coin("uusdt", 6_670_336), - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 236_534_500), - sdk.NewInt64Coin("unusd", 200_000_000), - sdk.NewInt64Coin("uusdt", 708_455_406), - ), - expectedFinalPool: types.Pool{ - Id: 1, - PoolParams: types.PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.01"), - ExitFee: sdk.MustNewDecFromStr("0.01"), - PoolType: types.PoolType_STABLESWAP, - A: sdk.NewInt(10), - }, - PoolAssets: []types.PoolAsset{ - { - Token: sdk.NewInt64Coin("unusd", 3_010_778_598), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("uusdt", 1_041_720), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - }, - expectedError: nil, - }, - { - name: "regular stableswap", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.USDC, 10), - ), - initialPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.USDC, 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin(denoms.USDC, 10), - tokenOutDenom: denoms.NUSD, - expectedTokenOut: sdk.NewInt64Coin(denoms.NUSD, 10), - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NUSD, 10), - ), - expectedFinalPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.USDC, 110), - sdk.NewInt64Coin(denoms.NUSD, 90), - ), - /*shares=*/ 100, - ), - expectedError: nil, - }, - { - name: "regular swap", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin("unibi", 100), - tokenOutDenom: denoms.NUSD, - expectedTokenOut: sdk.NewInt64Coin(denoms.NUSD, 50), - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.NUSD, 50), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 200), - sdk.NewInt64Coin(denoms.NUSD, 50), - ), - /*shares=*/ 100, - ), - expectedError: nil, - }, - { - name: "not enough user funds", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 1), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin("unibi", 100), - tokenOutDenom: denoms.NUSD, - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 1), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - expectedError: sdkerrors.ErrInsufficientFunds, - }, - { - name: "invalid token in denom", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("foo", 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin("foo", 100), - tokenOutDenom: denoms.NUSD, - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin("foo", 100), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - expectedError: types.ErrTokenDenomNotFound, - }, - { - name: "invalid token out denom", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin("unibi", 100), - tokenOutDenom: "foo", - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - expectedError: types.ErrTokenDenomNotFound, - }, - { - name: "same token in and token out denom", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - ), - initialPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - tokenIn: sdk.NewInt64Coin("unibi", 100), - tokenOutDenom: "unibi", - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - ), - expectedFinalPool: mock.SpotPool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin("unibi", 100), - sdk.NewInt64Coin(denoms.NUSD, 100), - ), - /*shares=*/ 100, - ), - expectedError: types.ErrSameTokenDenom, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - // fund pool account - poolAddr := testutil.AccAddress() - tc.initialPool.Address = poolAddr.String() - tc.expectedFinalPool.Address = poolAddr.String() - require.NoError(t, - testapp.FundAccount( - app.BankKeeper, - ctx, - poolAddr, - tc.initialPool.PoolBalances(), - ), - ) - app.SpotKeeper.SetPool(ctx, tc.initialPool) - - // fund user account - sender := testutil.AccAddress() - require.NoError(t, testapp.FundAccount(app.BankKeeper, ctx, sender, tc.userInitialFunds)) - - // swap assets - tokenOut, err := app.SpotKeeper.SwapExactAmountIn(ctx, sender, tc.initialPool.Id, tc.tokenIn, tc.tokenOutDenom) - - if tc.expectedError != nil { - require.ErrorIs(t, err, tc.expectedError) - } else { - require.NoError(t, err) - require.Equal(t, tc.expectedTokenOut, tokenOut) - } - - // check user's final funds - require.Equal(t, - tc.expectedUserFinalFunds, - app.BankKeeper.GetAllBalances(ctx, sender), - ) - - // check final pool state - finalPool, err := app.SpotKeeper.FetchPool(ctx, tc.initialPool.Id) - require.NoError(t, err) - require.Equal(t, tc.expectedFinalPool, finalPool) - }) - } -} - -func TestDoubleSwapExactAmountIn(t *testing.T) { - tests := []struct { - name string - - // test setup - userInitialFunds sdk.Coins - initialPool types.Pool - tokenIns []sdk.Coin - tokenOutDenoms []string - - // expected results - expectedTokenOuts []sdk.Coin - expectedUserFinalFunds sdk.Coins - expectedFinalPool types.Pool - }{ - { - name: "double stableswap", - userInitialFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.USDC, 10_000), - ), - initialPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.USDC, 100_000_000), - sdk.NewInt64Coin(denoms.NUSD, 100_000_000), - ), - /*shares=*/ 100, - ), - tokenIns: []sdk.Coin{sdk.NewInt64Coin(denoms.USDC, 10_000), sdk.NewInt64Coin(denoms.NUSD, 10_000)}, - tokenOutDenoms: []string{denoms.NUSD, denoms.USDC}, - expectedTokenOuts: []sdk.Coin{sdk.NewInt64Coin(denoms.NUSD, 10_000), sdk.NewInt64Coin(denoms.USDC, 10_001)}, - expectedUserFinalFunds: sdk.NewCoins( - sdk.NewInt64Coin(denoms.USDC, 10_001), - ), - expectedFinalPool: mock.SpotStablePool( - /*poolId=*/ 1, - /*assets=*/ sdk.NewCoins( - sdk.NewInt64Coin(denoms.USDC, 99_999_999), - sdk.NewInt64Coin(denoms.NUSD, 100_000_000), - ), - /*shares=*/ 100, - ), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - app, ctx := testapp.NewNibiruTestAppAndContext() - - // fund pool account - poolAddr := testutil.AccAddress() - tc.initialPool.Address = poolAddr.String() - tc.expectedFinalPool.Address = poolAddr.String() - require.NoError(t, - testapp.FundAccount( - app.BankKeeper, - ctx, - poolAddr, - tc.initialPool.PoolBalances(), - ), - ) - app.SpotKeeper.SetPool(ctx, tc.initialPool) - - // fund user account - sender := testutil.AccAddress() - require.NoError(t, testapp.FundAccount(app.BankKeeper, ctx, sender, tc.userInitialFunds)) - - // swap assets - for i, tokenIn := range tc.tokenIns { - tokenOut, err := app.SpotKeeper.SwapExactAmountIn(ctx, sender, tc.initialPool.Id, tokenIn, tc.tokenOutDenoms[i]) - require.NoError(t, err) - - require.Equal(t, tc.expectedTokenOuts[i], tokenOut) - } - - // check user's final funds - require.Equal(t, - tc.expectedUserFinalFunds, - app.BankKeeper.GetAllBalances(ctx, sender), - ) - - // check final pool state - finalPool, err := app.SpotKeeper.FetchPool(ctx, tc.initialPool.Id) - require.NoError(t, err) - require.Equal(t, tc.expectedFinalPool, finalPool) - }) - } -} diff --git a/x/spot/math/constant_function.go b/x/spot/math/constant_function.go deleted file mode 100644 index f4393aa7d..000000000 --- a/x/spot/math/constant_function.go +++ /dev/null @@ -1,40 +0,0 @@ -package math - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// solveConstantFunctionInvariant solves the constant function of an AMM -// that determines the relationship between the differences of two sides -// of assets inside the pool. -// For fixed xPrior, xAfter, xWeight, yPrior, yWeight, -// we could deduce the deltaY, calculated by: -// deltaY = balanceY * (1 - (xPrior/xAfter)^(xWeight/yWeight)) -// deltaY is positive when y's balance liquidity decreases. -// deltaY is negative when y's balance liquidity increases. -// panics if yWeight is 0. -// -// TODO(https://github.com/NibiruChain/nibiru/issues/141): Currently always calculates the invariant assuming constant weight (xy=k). -// Once we figure out the floating point arithmetic conversions for exponentiation, we can -// add unequal weights. -func SolveConstantProductInvariant( - xPrior, - xAfter, - /*unused*/ _xWeight, - yPrior, - /*unused*/ _yWeight sdk.Dec, -) (deltaY sdk.Dec) { - // // weightRatio = (xWeight/yWeight) - // weightRatio := xWeight.Quo(yWeight) - - // r = xPrior/xAfter - r := xPrior.Quo(xAfter) - - // TODO(https://github.com/NibiruChain/nibiru/issues/141): Figure out floating point arithmetic for exponentation. - // Naive calculation could lead to significant rounding errors with large numbers - // amountY = yPrior * (1 - (r ^ weightRatio)) - // rToWeightRatio := sdk.MustNewDecFromStr( - // fmt.Sprintf("%f", math.Pow(r.MustFloat64(), weightRatio.MustFloat64())), - // ) - return yPrior.Mul(sdk.OneDec().Sub(r)) -} diff --git a/x/spot/math/constant_function_test.go b/x/spot/math/constant_function_test.go deleted file mode 100644 index 914443bbb..000000000 --- a/x/spot/math/constant_function_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package math - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestSolveConstantProductInvariantHappyPath(t *testing.T) { - for _, tc := range []struct { - name string - xPrior sdk.Dec - xAfter sdk.Dec - xWeight sdk.Dec - yPrior sdk.Dec - yWeight sdk.Dec - expectedDeltaY sdk.Dec - }{ - { - // 100*(1-(100/200)^(.50/.50)) - name: "simple numbers", - xPrior: sdk.NewDec(100), - xAfter: sdk.NewDec(200), - xWeight: sdk.NewDecWithPrec(5, 1), - yPrior: sdk.NewDec(100), - yWeight: sdk.NewDecWithPrec(5, 1), - expectedDeltaY: sdk.NewDec(50), - }, - { - // 33*(1-(33/50)^(.50/.50)) - name: "difficult numbers", - xPrior: sdk.NewDec(33), - xAfter: sdk.NewDec(50), - xWeight: sdk.NewDecWithPrec(5, 1), - yPrior: sdk.NewDec(33), - yWeight: sdk.NewDecWithPrec(5, 1), - expectedDeltaY: sdk.NewDecWithPrec(1122, 2), - }, - // TODO(https://github.com/NibiruChain/nibiru/issues/141): allow for uneven weights - // { - // // 44*(1-(86/35)^(.75/.25)) - // name: "difficult numbers - uneven weights", - // xPrior: sdk.NewDec(86), - // xAfter: sdk.NewDec(35), - // xWeight: sdk.NewDecWithPrec(75, 2), - // yPrior: sdk.NewDec(44), - // yWeight: sdk.NewDecWithPrec(25, 2), - // expectedDeltaY: sdk.NewDecWithPrec(-60874551603, 8), - // }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - deltaY := SolveConstantProductInvariant( - tc.xPrior, tc.xAfter, tc.xWeight, tc.yPrior, tc.yWeight) - require.InDelta(t, tc.expectedDeltaY.MustFloat64(), deltaY.MustFloat64(), 0.0001) - }) - } -} diff --git a/x/spot/module.go b/x/spot/module.go deleted file mode 100644 index 9bd9cca72..000000000 --- a/x/spot/module.go +++ /dev/null @@ -1,176 +0,0 @@ -package spot - -import ( - "context" - "encoding/json" - "fmt" - - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/client" - "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/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/spot/client/cli" - "github.com/NibiruChain/nibiru/x/spot/keeper" - "github.com/NibiruChain/nibiru/x/spot/simulation" - "github.com/NibiruChain/nibiru/x/spot/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModule{} -) - -// ---------------------------------------------------------------------------- -// AppModuleBasic -// ---------------------------------------------------------------------------- - -// AppModuleBasic implements the AppModuleBasic interface for the capability module. -type AppModuleBasic struct { - cdc codec.BinaryCodec -} - -func NewAppModuleBasic(cdc codec.BinaryCodec) AppModuleBasic { - return AppModuleBasic{cdc: cdc} -} - -// Name returns the capability module's name. -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterLegacyAminoCodec(cdc) -} - -// RegisterInterfaces registers the module's interface types -func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { - types.RegisterInterfaces(reg) -} - -// DefaultGenesis returns the capability module's default genesis state. -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.GetTxCmd() -} - -// GetQueryCmd returns the capability module's root query command. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -// ---------------------------------------------------------------------------- -// AppModule -// ---------------------------------------------------------------------------- - -// AppModule implements the AppModule interface for the module. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper -} - -func NewAppModule( - cdc codec.Codec, - keeper keeper.Keeper, - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, -) AppModule { - return AppModule{ - AppModuleBasic: NewAppModuleBasic(cdc), - keeper: keeper, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - -// 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) - - 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 2 } - -// 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(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} - -// GenerateGenesisState creates a default GenState of the module -func (AppModule) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// ProposalContents doesn't return any content functions for governance proposals -func (AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedProposalMsg { - return nil -} - -// RegisterStoreDecoder registers a decoder -func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} - -// WeightedOperations returns the all the spot module operations with their respective weights. -func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { - return simulation.WeightedOperations(am.accountKeeper, am.bankKeeper, am.keeper) -} diff --git a/x/spot/simulation/genesis.go b/x/spot/simulation/genesis.go deleted file mode 100644 index 46904391f..000000000 --- a/x/spot/simulation/genesis.go +++ /dev/null @@ -1,34 +0,0 @@ -package simulation - -// DONTCOVER - -import ( - "encoding/json" - "fmt" - "math/rand" - - "github.com/cosmos/cosmos-sdk/types/module" - - "github.com/NibiruChain/nibiru/x/tokenfactory/types" -) - -const ( - DenomCreationGasConsume = "denom_creation_gas_consume" -) - -func GenDenomCreationGasConsume(r *rand.Rand) uint64 { - return uint64(r.Intn(4e6)) -} - -// RandomizedGenState generates a random GenesisState for distribution -func RandomizedGenState(simState *module.SimulationState) { - spotGenesis := types.DefaultGenesis() - - bz, err := json.MarshalIndent(&spotGenesis, "", " ") - if err != nil { - panic(err) - } - - fmt.Printf("Selected randomly generated x/spot parameters:\n%s\n", bz) - simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(spotGenesis) -} diff --git a/x/spot/simulation/operations.go b/x/spot/simulation/operations.go deleted file mode 100644 index bf3d71f9e..000000000 --- a/x/spot/simulation/operations.go +++ /dev/null @@ -1,441 +0,0 @@ -package simulation - -import ( - "fmt" - "math/rand" - "strings" - "time" - - "github.com/cosmos/cosmos-sdk/types/module/testutil" - - sdkmath "cosmossdk.io/math" - - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" - - "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/common/denoms" - "github.com/NibiruChain/nibiru/x/spot/keeper" - "github.com/NibiruChain/nibiru/x/spot/types" -) - -const defaultWeight = 100 - -// WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations( - ak types.AccountKeeper, - bk types.BankKeeper, - k keeper.Keeper, -) simulation.WeightedOperations { - return simulation.WeightedOperations{ - simulation.NewWeightedOperation( - defaultWeight, - SimulateMsgCreatePool(ak, bk, k), - ), - simulation.NewWeightedOperation( - defaultWeight, - SimulateMsgSwap(ak, bk, k), - ), - simulation.NewWeightedOperation( - defaultWeight, - SimulateJoinPool(ak, bk, k), - ), - simulation.NewWeightedOperation( - defaultWeight, - SimulateExitPool(ak, bk, k), - ), - } -} - -// SimulateMsgCreatePool generates a MsgCreatePool with random values. -func SimulateMsgCreatePool(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { - return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - simAccount, _ := simtypes.RandomAcc(r, accs) - params := k.GetParams(ctx) - - fundAccountWithTokens(ctx, simAccount.Address, bk) - spendableCoins := bk.SpendableCoins(ctx, simAccount.Address) - - whitelistedAssets := params.GetWhitelistedAssetsAsMap() - - poolAssets := genPoolAssets(r, spendableCoins, whitelistedAssets) - poolParams := genBalancerPoolParams(r, ctx.BlockTime(), poolAssets) - - // set the pool params to set the pool creation fee to dust amount of denom - params.PoolCreationFee = sdk.Coins{sdk.NewInt64Coin(spendableCoins[0].Denom, 1)} - k.SetParams(ctx, params) - - msg := &types.MsgCreatePool{ - Creator: simAccount.Address.String(), - PoolParams: &poolParams, - PoolAssets: poolAssets, - } - _, err := k.FetchPoolFromPair(ctx, poolAssets[0].Token.Denom, poolAssets[1].Token.Denom) - if err == nil { - // types.ErrPoolWithSameAssetsExists - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "pool already exists for these tokens"), nil, nil - } - - return simulation.GenAndDeliverTxWithRandFees( - simulation.OperationInput{ - R: r, - App: app, - TxGen: testutil.MakeTestEncodingConfig().TxConfig, - Cdc: nil, - Msg: msg, - MsgType: msg.Type(), - Context: ctx, - SimAccount: simAccount, - AccountKeeper: ak, - Bankkeeper: bk, - ModuleName: types.ModuleName, - CoinsSpentInMsg: PoolAssetsCoins(poolAssets), - }, - ) - } -} - -/* -SimulateMsgSwap generates a MsgSwap with random values -*/ -func SimulateMsgSwap(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { - return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - msg := &types.MsgSwapAssets{} - - simAccount, _ := simtypes.RandomAcc(r, accs) - fundAccountWithTokens(ctx, simAccount.Address, bk) - spendableCoins := bk.SpendableCoins(ctx, simAccount.Address) - - denomIn, denomOut, poolId, balanceIn := findRandomPoolWithDenom(ctx, r, spendableCoins, k) - - if denomIn == "" { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "No pool existing yet for account tokens"), nil, nil - } - if balanceIn.IsZero() { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "No tokens to swap in"), nil, nil - } - - tokenIn := sdk.NewCoin(denomIn, balanceIn) - msg = &types.MsgSwapAssets{ - Sender: simAccount.Address.String(), - PoolId: poolId, - TokenIn: tokenIn, - TokenOutDenom: denomOut, - } - pool, _ := k.FetchPool(ctx, poolId) - _, _, err := pool.CalcOutAmtGivenIn(tokenIn, denomOut, false) - if err != nil { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "pool imbalanced and not enough swap amount"), nil, nil - } - - return simulation.GenAndDeliverTxWithRandFees( - simulation.OperationInput{ - R: r, - App: app, - TxGen: testutil.MakeTestEncodingConfig().TxConfig, - Cdc: nil, - Msg: msg, - MsgType: msg.Type(), - Context: ctx, - SimAccount: simAccount, - AccountKeeper: ak, - Bankkeeper: bk, - ModuleName: types.ModuleName, - CoinsSpentInMsg: sdk.NewCoins(tokenIn), - }, - ) - } -} - -/* -SimulateJoinPool generates a MsgJoinPool with random values -This function has a 33% chance of swapping a random fraction of the balance of a random token -*/ -func SimulateJoinPool(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { - return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - msg := &types.MsgJoinPool{} - // run only 1/3 of the time - if simtypes.RandomDecAmount(r, sdk.OneDec()).GTE(sdk.MustNewDecFromStr("0.33")) { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "No join pool done"), nil, nil - } - - simAccount, _ := simtypes.RandomAcc(r, accs) - fundAccountWithTokens(ctx, simAccount.Address, bk) - spendableCoins := bk.SpendableCoins(ctx, simAccount.Address) - - pool, err, index1, index2 := findRandomPoolWithDenomPair(ctx, r, spendableCoins, k) - if err != nil { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "No pool existing yet for tokens in account"), nil, nil - } - - intensityFactorToken0 := simtypes.RandomDecAmount(r, sdk.MustNewDecFromStr("0.499")).Add(sdk.MustNewDecFromStr("0.5")) - intensityFactorToken1 := simtypes.RandomDecAmount(r, sdk.MustNewDecFromStr("0.499")).Add(sdk.MustNewDecFromStr("0.5")) - - tokensIn := sdk.NewCoins( - sdk.NewCoin( - pool.PoolAssets[0].Token.Denom, - intensityFactorToken0.Mul(sdk.NewDecFromInt(spendableCoins[index1].Amount)).TruncateInt()), - sdk.NewCoin( - pool.PoolAssets[1].Token.Denom, - intensityFactorToken1.Mul(sdk.NewDecFromInt(spendableCoins[index2].Amount)).TruncateInt()), - ) - - msg = &types.MsgJoinPool{ - Sender: simAccount.Address.String(), - PoolId: pool.Id, - TokensIn: tokensIn, - } - - _, err = pool.GetD(pool.PoolAssets) - if err != nil { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "borked pool"), nil, nil - } - - return simulation.GenAndDeliverTxWithRandFees( - simulation.OperationInput{ - R: r, - App: app, - TxGen: testutil.MakeTestEncodingConfig().TxConfig, - Cdc: nil, - Msg: msg, - MsgType: msg.Type(), - Context: ctx, - SimAccount: simAccount, - AccountKeeper: ak, - Bankkeeper: bk, - ModuleName: types.ModuleName, - CoinsSpentInMsg: tokensIn, - }, - ) - } -} - -/* -SimulateExitPool generates a MsgExitPool with random values -This function has a 33% chance of swapping a random fraction of the balance of a random token -*/ -func SimulateExitPool(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Keeper) simtypes.Operation { - return func( - r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, - ) (opMsg simtypes.OperationMsg, futureOp []simtypes.FutureOperation, err error) { - simAccount, _ := simtypes.RandomAcc(r, accs) - spendableCoins := bk.SpendableCoins(ctx, simAccount.Address) - - // Search for LP tokens in sim coins - randomIndices := r.Perm(spendableCoins.Len()) - var shareTokens sdk.Coin - - for _, index := range randomIndices { - coin := spendableCoins[index] - if strings.Contains(coin.Denom, "nibiru/pool/") { - shareTokens = coin - break - } - } - msg := &types.MsgExitPool{} - - if shareTokens.Denom == "" { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "No pool share token found in wallet"), nil, nil - } - - intensityFactor := simtypes.RandomDecAmount(r, sdk.MustNewDecFromStr("0.499")).Add(sdk.MustNewDecFromStr("0.5")) - shareTokensIn := sdk.NewCoin( - shareTokens.Denom, - intensityFactor.MulInt(shareTokens.Amount).TruncateInt(), - ) - - // Ugly but does the job - poolId := sdk.MustNewDecFromStr(strings.Replace(shareTokensIn.Denom, "nibiru/pool/", "", 1)).TruncateInt().Uint64() - - // check if there are enough tokens to withdraw - pool, err := k.FetchPool(ctx, poolId) - if err != nil { - return opMsg, futureOp, err - } - tokensOut, _, err := pool.TokensOutFromPoolSharesIn(shareTokensIn.Amount) - if err != nil { - return opMsg, futureOp, err - } - - // this is necessary, as invalid tokens will be considered as wrong inputs in simulations - if !tokensOut.IsValid() { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "not enough pool tokens to exit pool"), nil, nil - } - - msg = &types.MsgExitPool{ - Sender: simAccount.Address.String(), - PoolId: poolId, - PoolShares: shareTokensIn, - } - - return simulation.GenAndDeliverTxWithRandFees( - simulation.OperationInput{ - R: r, - App: app, - TxGen: testutil.MakeTestEncodingConfig().TxConfig, - Cdc: nil, - Msg: msg, - MsgType: msg.Type(), - Context: ctx, - SimAccount: simAccount, - AccountKeeper: ak, - Bankkeeper: bk, - ModuleName: types.ModuleName, - CoinsSpentInMsg: sdk.NewCoins(shareTokensIn), - }, - ) - } -} - -// PoolAssetsCoins returns all the coins corresponding to a slice of pool assets. -func PoolAssetsCoins(assets []types.PoolAsset) sdk.Coins { - coins := sdk.Coins{} - for _, asset := range assets { - coins = coins.Add(asset.Token) - } - return sdk.NewCoins(coins...) -} - -// genBalancerPoolParams creates random parameters for the swap and exit fee of the pool -// The pool has 50% chance of being a stableswap pool. -func genBalancerPoolParams(r *rand.Rand, blockTime time.Time, assets []types.PoolAsset) types.PoolParams { - // swapFeeInt := int64(r.Intn(1e5)) - // swapFee := sdk.NewDecWithPrec(swapFeeInt, 6) - - exitFeeInt := int64(r.Intn(1e5)) - exitFee := sdk.NewDecWithPrec(exitFeeInt, 6) - isBalancer := r.Intn(2) - - var poolType types.PoolType - if isBalancer == 0 { - poolType = types.PoolType_BALANCER - } else { - poolType = types.PoolType_STABLESWAP - } - - A := sdk.NewInt(int64(r.Intn(4_000) + 1)) - - // Create swap fee between 0% and 5% - swapFeeFloat := r.Float64() * .05 - swapFee := sdk.MustNewDecFromStr(fmt.Sprintf("%.5f", swapFeeFloat)) - - return types.PoolParams{ - SwapFee: swapFee, - ExitFee: exitFee, - PoolType: poolType, - A: A, - } -} - -// genPoolAssets creates a pool asset object based on current balance of the account -func genPoolAssets( - r *rand.Rand, - coins sdk.Coins, - whitelistedAssets map[string]bool, -) []types.PoolAsset { - denomIndices := r.Perm(coins.Len()) - var assets []types.PoolAsset - - for _, denomIndex := range denomIndices { - denom := coins[denomIndex].Denom - - if _, ok := whitelistedAssets[denom]; ok { - amt, _ := simtypes.RandPositiveInt(r, coins[denomIndex].Amount.QuoRaw(10)) - reserveAmt := sdk.NewCoin(denom, amt) - - // Weight is useless for stableswap pools. - weight := sdk.NewInt(r.Int63n(9) + 1) - assets = append(assets, types.PoolAsset{Token: reserveAmt, Weight: weight}) - - if len(assets) == 2 { - return assets - } - } - } - - panic("amm pool must have 2 assets") -} - -// fundAccountWithTokens fund the account with some gov, coll and stable denom. -// when simulation for stablecoin is done, we should consider only funding with stable. -func fundAccountWithTokens(ctx sdk.Context, address sdk.AccAddress, bk types.BankKeeper) { - million := 1 * common.TO_MICRO - newTokens := sdk.NewCoins( - sdk.NewCoin(denoms.NIBI, sdk.NewInt(int64(10*million))), - sdk.NewCoin(denoms.USDC, sdk.NewInt(int64(10*million))), - sdk.NewCoin(denoms.NUSD, sdk.NewInt(int64(10*million))), - ) - - err := bk.MintCoins(ctx, types.ModuleName, newTokens) - if err != nil { - panic(err) - } - err = bk.SendCoinsFromModuleToAccount( - ctx, - types.ModuleName, - address, - newTokens, - ) - if err != nil { - panic(err) - } -} - -// findRandomPoolWithDenom search possible pool available to swap from a set of coins -func findRandomPoolWithDenom(ctx sdk.Context, r *rand.Rand, spendableCoins sdk.Coins, k keeper.Keeper) ( - denomIn string, denomOut string, poolId uint64, balanceIn sdkmath.Int, -) { - randomIndices := r.Perm(spendableCoins.Len()) - whitelistedAssets := k.GetParams(ctx).GetWhitelistedAssetsAsMap() - - pools := k.FetchAllPools(ctx) - for _, index := range randomIndices { - coin := spendableCoins[index] - if _, ok := whitelistedAssets[coin.Denom]; ok { - for _, pool := range pools { - if pool.PoolAssets[0].Token.Denom == coin.Denom { - return coin.Denom, pool.PoolAssets[1].Token.Denom, pool.Id, spendableCoins[index].Amount - } else if pool.PoolAssets[1].Token.Denom == coin.Denom { - return coin.Denom, pool.PoolAssets[0].Token.Denom, pool.Id, spendableCoins[index].Amount - } - } - } - } - - return "", "", 0, sdk.ZeroInt() -} - -// findRandomPoolWithDenomPair search one pool available from a pair of coins of simCoins -func findRandomPoolWithDenomPair(ctx sdk.Context, r *rand.Rand, simCoins sdk.Coins, k keeper.Keeper) ( - pool types.Pool, err error, index1 int, index2 int, -) { - whitelistedAssets := k.GetParams(ctx).GetWhitelistedAssetsAsMap() - randomIndices1 := r.Perm(simCoins.Len()) - randomIndices2 := r.Perm(simCoins.Len()) - - for _, index1 := range randomIndices1 { - coin1 := simCoins[index1] - if _, ok := whitelistedAssets[coin1.Denom]; ok { - for _, index2 := range randomIndices2 { - if index1 != index2 { - coin2 := simCoins[index2] - if _, ok := whitelistedAssets[coin2.Denom]; ok { - pool, err := k.FetchPoolFromPair(ctx, coin1.Denom, coin2.Denom) - if err == nil { - return pool, nil, index1, index2 - } - } - } - } - } - } - return types.Pool{}, types.ErrPoolNotFound.Wrapf("could not find pool compatible with any pair of assets"), 0, 0 -} diff --git a/x/spot/types/codec.go b/x/spot/types/codec.go deleted file mode 100644 index 04d538125..000000000 --- a/x/spot/types/codec.go +++ /dev/null @@ -1,30 +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(&MsgCreatePool{}, "spot/CreatePool", nil) - cdc.RegisterConcrete(&MsgJoinPool{}, "spot/JoinPool", nil) - cdc.RegisterConcrete(&MsgExitPool{}, "spot/ExitPool", nil) - cdc.RegisterConcrete(&MsgSwapAssets{}, "spot/SwapAssets", nil) -} - -func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { - registry.RegisterImplementations( - /* interface */ (*sdk.Msg)(nil), - /* implementations */ - &MsgCreatePool{}, - &MsgJoinPool{}, - &MsgExitPool{}, - &MsgSwapAssets{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) diff --git a/x/spot/types/constants.go b/x/spot/types/constants.go deleted file mode 100644 index 6958edd70..000000000 --- a/x/spot/types/constants.go +++ /dev/null @@ -1,37 +0,0 @@ -package types - -import ( - sdkmath "cosmossdk.io/math" -) - -const ( - // MinPoolAssets minimum number of assets a pool may have - MinPoolAssets = 2 - // MaxPoolAssets maximum number of assets a pool may have - MaxPoolAssets = 2 - - // DisplayPoolShareExponent the exponent of a pool display share compared to a pool base share (one pool display share = 10^18 pool base shares) - DisplayPoolShareExponent = 18 - - // GuaranteedWeightPrecision Scaling factor for every weight. The pool weight is: - // weight_in_MsgCreateBalancerPool * GuaranteedWeightPrecision - // - // This is done so that smooth weight changes have enough precision to actually be smooth. - GuaranteedWeightPrecision int64 = 1 << 30 -) - -var ( - // OneDisplayPoolShare represents one display pool share - OneDisplayPoolShare = sdkmath.NewIntWithDecimal(1, DisplayPoolShareExponent) - - // InitPoolSharesSupply is the amount of new shares to initialize a pool with. - InitPoolSharesSupply = OneDisplayPoolShare.MulRaw(100) - - // MaxUserSpecifiedWeight Pool creators can specify a weight in [1, MaxUserSpecifiedWeight) - // for every token in the balancer pool. - // - // The weight used in the balancer equation is then creator-specified-weight * GuaranteedWeightPrecision. - // This is done so that LBP's / smooth weight changes can actually happen smoothly, - // without complex precision loss / edge effects. - MaxUserSpecifiedWeight = sdkmath.NewIntFromUint64(1 << 20) -) diff --git a/x/spot/types/errors.go b/x/spot/types/errors.go deleted file mode 100644 index a78559bc9..000000000 --- a/x/spot/types/errors.go +++ /dev/null @@ -1,42 +0,0 @@ -package types - -// DONTCOVER - -import ( - sdkerrors "cosmossdk.io/errors" -) - -// x/spot module sentinel errors -var ( - ErrTooFewPoolAssets = sdkerrors.Register(ModuleName, 1, "pool should have at least 2 assets, as they must be swapping between at least two assets") - ErrTooManyPoolAssets = sdkerrors.Register(ModuleName, 2, "pool has too many assets (currently capped at 2 assets per pool)") - ErrInvalidSwapFee = sdkerrors.Register(ModuleName, 3, "invalid pool swap fee, must be between [0, 1]") - ErrInvalidExitFee = sdkerrors.Register(ModuleName, 4, "invalid pool exit fee, must be between [0, 1]") - ErrInvalidTokenWeight = sdkerrors.Register(ModuleName, 5, "token weight must be greater than zero") - ErrTokenNotAllowed = sdkerrors.Register(ModuleName, 8, "token not allowed") - ErrInvalidPoolType = sdkerrors.Register(ModuleName, 15, "pool_type needs to be either `balancer` or `stableswap`") - ErrAmplificationMissing = sdkerrors.Register(ModuleName, 16, "amplification parameter is missing") - ErrAmplificationTooLow = sdkerrors.Register(ModuleName, 17, "amplification parameter a needs to be greater than 1") - ErrInitialDeposit = sdkerrors.Register(ModuleName, 19, "initial deposit requires all coins deposited") - ErrPoolWithSameAssetsExists = sdkerrors.Register(ModuleName, 20, "a pool with the same denoms already exists") - ErrBorkedPool = sdkerrors.Register(ModuleName, 21, "the pool is borked") - ErrInvariantLowerAfterJoining = sdkerrors.Register(ModuleName, 22, "the invariant was unexpectedly lower after joining") - - // create-pool tx cli errors - ErrMissingPoolFileFlag = sdkerrors.Register(ModuleName, 6, "must pass in a pool json using the --pool-file flag") - ErrInvalidCreatePoolArgs = sdkerrors.Register(ModuleName, 7, "deposit tokens and token weights should have same length and denom order") - ErrAmplificationIntable = sdkerrors.Register(ModuleName, 23, - "amplification string failed to parse as int256") - - // Invalid MsgSwapAsset - ErrInvalidPoolId = sdkerrors.Register(ModuleName, 9, "invalid pool id") - ErrInvalidTokenIn = sdkerrors.Register(ModuleName, 10, "invalid tokens in") - ErrInvalidTokenOutDenom = sdkerrors.Register(ModuleName, 11, "invalid token out denom") - - // Errors when swapping assets - ErrPoolNotFound = sdkerrors.Register(ModuleName, 12, "pool not found") - ErrTokenDenomNotFound = sdkerrors.Register(ModuleName, 13, "token denom not found in pool") - ErrSameTokenDenom = sdkerrors.Register(ModuleName, 14, "cannot use same token denom to swap in and out") - - ErrNotImplemented = sdkerrors.Register(ModuleName, 18, "not implemented") -) diff --git a/x/spot/types/event.pb.go b/x/spot/types/event.pb.go deleted file mode 100644 index 1fff8349b..000000000 --- a/x/spot/types/event.pb.go +++ /dev/null @@ -1,1816 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: nibiru/spot/v1/event.proto - -package types - -import ( - fmt "fmt" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - 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 EventPoolCreated struct { - // the address of the user who created the pool - Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` - // the create pool fee - Fees []types.Coin `protobuf:"bytes,2,rep,name=fees,proto3" json:"fees"` - // the final state of the pool - FinalPool Pool `protobuf:"bytes,4,opt,name=final_pool,json=finalPool,proto3" json:"final_pool"` - // the amount of pool shares that the user received - FinalUserPoolShares types.Coin `protobuf:"bytes,5,opt,name=final_user_pool_shares,json=finalUserPoolShares,proto3" json:"final_user_pool_shares"` -} - -func (m *EventPoolCreated) Reset() { *m = EventPoolCreated{} } -func (m *EventPoolCreated) String() string { return proto.CompactTextString(m) } -func (*EventPoolCreated) ProtoMessage() {} -func (*EventPoolCreated) Descriptor() ([]byte, []int) { - return fileDescriptor_23fa99c8c3a21a65, []int{0} -} -func (m *EventPoolCreated) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *EventPoolCreated) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_EventPoolCreated.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 *EventPoolCreated) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventPoolCreated.Merge(m, src) -} -func (m *EventPoolCreated) XXX_Size() int { - return m.Size() -} -func (m *EventPoolCreated) XXX_DiscardUnknown() { - xxx_messageInfo_EventPoolCreated.DiscardUnknown(m) -} - -var xxx_messageInfo_EventPoolCreated proto.InternalMessageInfo - -func (m *EventPoolCreated) GetCreator() string { - if m != nil { - return m.Creator - } - return "" -} - -func (m *EventPoolCreated) GetFees() []types.Coin { - if m != nil { - return m.Fees - } - return nil -} - -func (m *EventPoolCreated) GetFinalPool() Pool { - if m != nil { - return m.FinalPool - } - return Pool{} -} - -func (m *EventPoolCreated) GetFinalUserPoolShares() types.Coin { - if m != nil { - return m.FinalUserPoolShares - } - return types.Coin{} -} - -type EventPoolJoined struct { - // the address of the user who joined the pool - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // the amount of tokens that the user deposited - TokensIn []types.Coin `protobuf:"bytes,2,rep,name=tokens_in,json=tokensIn,proto3" json:"tokens_in"` - // the amount of pool shares that the user received - PoolSharesOut types.Coin `protobuf:"bytes,3,opt,name=pool_shares_out,json=poolSharesOut,proto3" json:"pool_shares_out"` - // the amount of tokens remaining for the user - RemCoins []types.Coin `protobuf:"bytes,4,rep,name=rem_coins,json=remCoins,proto3" json:"rem_coins"` - // the final state of the pool - FinalPool Pool `protobuf:"bytes,5,opt,name=final_pool,json=finalPool,proto3" json:"final_pool"` - // the final amount of user pool shares - FinalUserPoolShares types.Coin `protobuf:"bytes,6,opt,name=final_user_pool_shares,json=finalUserPoolShares,proto3" json:"final_user_pool_shares"` -} - -func (m *EventPoolJoined) Reset() { *m = EventPoolJoined{} } -func (m *EventPoolJoined) String() string { return proto.CompactTextString(m) } -func (*EventPoolJoined) ProtoMessage() {} -func (*EventPoolJoined) Descriptor() ([]byte, []int) { - return fileDescriptor_23fa99c8c3a21a65, []int{1} -} -func (m *EventPoolJoined) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *EventPoolJoined) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_EventPoolJoined.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 *EventPoolJoined) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventPoolJoined.Merge(m, src) -} -func (m *EventPoolJoined) XXX_Size() int { - return m.Size() -} -func (m *EventPoolJoined) XXX_DiscardUnknown() { - xxx_messageInfo_EventPoolJoined.DiscardUnknown(m) -} - -var xxx_messageInfo_EventPoolJoined proto.InternalMessageInfo - -func (m *EventPoolJoined) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func (m *EventPoolJoined) GetTokensIn() []types.Coin { - if m != nil { - return m.TokensIn - } - return nil -} - -func (m *EventPoolJoined) GetPoolSharesOut() types.Coin { - if m != nil { - return m.PoolSharesOut - } - return types.Coin{} -} - -func (m *EventPoolJoined) GetRemCoins() []types.Coin { - if m != nil { - return m.RemCoins - } - return nil -} - -func (m *EventPoolJoined) GetFinalPool() Pool { - if m != nil { - return m.FinalPool - } - return Pool{} -} - -func (m *EventPoolJoined) GetFinalUserPoolShares() types.Coin { - if m != nil { - return m.FinalUserPoolShares - } - return types.Coin{} -} - -type EventPoolExited struct { - // the address of the user who exited the pool - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // the amount of pool shares that the user exited with - PoolSharesIn types.Coin `protobuf:"bytes,2,opt,name=pool_shares_in,json=poolSharesIn,proto3" json:"pool_shares_in"` - // the amount of tokens returned to the user - TokensOut []types.Coin `protobuf:"bytes,3,rep,name=tokens_out,json=tokensOut,proto3" json:"tokens_out"` - // the amount of fees collected by the pool - Fees []types.Coin `protobuf:"bytes,4,rep,name=fees,proto3" json:"fees"` - // the final state of the pool - FinalPool Pool `protobuf:"bytes,5,opt,name=final_pool,json=finalPool,proto3" json:"final_pool"` - // the final amount of user pool shares - FinalUserPoolShares types.Coin `protobuf:"bytes,6,opt,name=final_user_pool_shares,json=finalUserPoolShares,proto3" json:"final_user_pool_shares"` -} - -func (m *EventPoolExited) Reset() { *m = EventPoolExited{} } -func (m *EventPoolExited) String() string { return proto.CompactTextString(m) } -func (*EventPoolExited) ProtoMessage() {} -func (*EventPoolExited) Descriptor() ([]byte, []int) { - return fileDescriptor_23fa99c8c3a21a65, []int{2} -} -func (m *EventPoolExited) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *EventPoolExited) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_EventPoolExited.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 *EventPoolExited) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventPoolExited.Merge(m, src) -} -func (m *EventPoolExited) XXX_Size() int { - return m.Size() -} -func (m *EventPoolExited) XXX_DiscardUnknown() { - xxx_messageInfo_EventPoolExited.DiscardUnknown(m) -} - -var xxx_messageInfo_EventPoolExited proto.InternalMessageInfo - -func (m *EventPoolExited) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func (m *EventPoolExited) GetPoolSharesIn() types.Coin { - if m != nil { - return m.PoolSharesIn - } - return types.Coin{} -} - -func (m *EventPoolExited) GetTokensOut() []types.Coin { - if m != nil { - return m.TokensOut - } - return nil -} - -func (m *EventPoolExited) GetFees() []types.Coin { - if m != nil { - return m.Fees - } - return nil -} - -func (m *EventPoolExited) GetFinalPool() Pool { - if m != nil { - return m.FinalPool - } - return Pool{} -} - -func (m *EventPoolExited) GetFinalUserPoolShares() types.Coin { - if m != nil { - return m.FinalUserPoolShares - } - return types.Coin{} -} - -type EventAssetsSwapped struct { - // the address of the user who swapped tokens - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // the amount of tokens that the user deposited - TokenIn types.Coin `protobuf:"bytes,2,opt,name=token_in,json=tokenIn,proto3" json:"token_in"` - // the amount of tokens that the user received - TokenOut types.Coin `protobuf:"bytes,3,opt,name=token_out,json=tokenOut,proto3" json:"token_out"` - // the amount of fees collected by the pool - Fee types.Coin `protobuf:"bytes,4,opt,name=fee,proto3" json:"fee"` - // the final state of the pool - FinalPool Pool `protobuf:"bytes,5,opt,name=final_pool,json=finalPool,proto3" json:"final_pool"` -} - -func (m *EventAssetsSwapped) Reset() { *m = EventAssetsSwapped{} } -func (m *EventAssetsSwapped) String() string { return proto.CompactTextString(m) } -func (*EventAssetsSwapped) ProtoMessage() {} -func (*EventAssetsSwapped) Descriptor() ([]byte, []int) { - return fileDescriptor_23fa99c8c3a21a65, []int{3} -} -func (m *EventAssetsSwapped) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *EventAssetsSwapped) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_EventAssetsSwapped.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 *EventAssetsSwapped) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventAssetsSwapped.Merge(m, src) -} -func (m *EventAssetsSwapped) XXX_Size() int { - return m.Size() -} -func (m *EventAssetsSwapped) XXX_DiscardUnknown() { - xxx_messageInfo_EventAssetsSwapped.DiscardUnknown(m) -} - -var xxx_messageInfo_EventAssetsSwapped proto.InternalMessageInfo - -func (m *EventAssetsSwapped) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func (m *EventAssetsSwapped) GetTokenIn() types.Coin { - if m != nil { - return m.TokenIn - } - return types.Coin{} -} - -func (m *EventAssetsSwapped) GetTokenOut() types.Coin { - if m != nil { - return m.TokenOut - } - return types.Coin{} -} - -func (m *EventAssetsSwapped) GetFee() types.Coin { - if m != nil { - return m.Fee - } - return types.Coin{} -} - -func (m *EventAssetsSwapped) GetFinalPool() Pool { - if m != nil { - return m.FinalPool - } - return Pool{} -} - -func init() { - proto.RegisterType((*EventPoolCreated)(nil), "nibiru.spot.v1.EventPoolCreated") - proto.RegisterType((*EventPoolJoined)(nil), "nibiru.spot.v1.EventPoolJoined") - proto.RegisterType((*EventPoolExited)(nil), "nibiru.spot.v1.EventPoolExited") - proto.RegisterType((*EventAssetsSwapped)(nil), "nibiru.spot.v1.EventAssetsSwapped") -} - -func init() { proto.RegisterFile("nibiru/spot/v1/event.proto", fileDescriptor_23fa99c8c3a21a65) } - -var fileDescriptor_23fa99c8c3a21a65 = []byte{ - // 514 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x54, 0x31, 0x6f, 0xd3, 0x40, - 0x14, 0x8e, 0x13, 0xb7, 0x25, 0x57, 0x68, 0x91, 0xa9, 0x90, 0x9b, 0xc1, 0x44, 0x9d, 0x22, 0x86, - 0xb3, 0xdc, 0x4e, 0x20, 0x84, 0x44, 0x43, 0x84, 0xc2, 0x00, 0xa8, 0x85, 0x85, 0xc5, 0xb2, 0x93, - 0x97, 0xe4, 0x44, 0x72, 0xcf, 0xba, 0x3b, 0x87, 0x32, 0xf2, 0x0f, 0x98, 0xf8, 0x4d, 0x1d, 0x3b, - 0x32, 0x21, 0x94, 0xfc, 0x03, 0x26, 0x46, 0x74, 0x77, 0x4e, 0x08, 0x1d, 0x5a, 0x97, 0x32, 0x74, - 0xbb, 0xf3, 0x7b, 0xdf, 0x7d, 0xef, 0x7d, 0xdf, 0xf3, 0x23, 0x0d, 0xce, 0x52, 0x26, 0xf2, 0x50, - 0x66, 0xa8, 0xc2, 0x69, 0x14, 0xc2, 0x14, 0xb8, 0xa2, 0x99, 0x40, 0x85, 0xde, 0x96, 0x8d, 0x51, - 0x1d, 0xa3, 0xd3, 0xa8, 0xb1, 0x33, 0xc4, 0x21, 0x9a, 0x50, 0xa8, 0x4f, 0x36, 0xab, 0x11, 0xf4, - 0x50, 0x4e, 0x50, 0x86, 0x69, 0x22, 0x21, 0x9c, 0x46, 0x29, 0xa8, 0x24, 0x0a, 0x7b, 0xc8, 0x78, - 0x11, 0xdf, 0x3d, 0xc7, 0x90, 0x21, 0x8e, 0x6d, 0x68, 0xef, 0xa7, 0x43, 0xee, 0x76, 0x34, 0xe1, - 0x1b, 0xc4, 0x71, 0x5b, 0x40, 0xa2, 0xa0, 0xef, 0xf9, 0x64, 0xa3, 0xa7, 0x8f, 0x28, 0x7c, 0xa7, - 0xe9, 0xb4, 0xea, 0x47, 0x8b, 0xab, 0x77, 0x40, 0xdc, 0x01, 0x80, 0xf4, 0xab, 0xcd, 0x5a, 0x6b, - 0x73, 0x7f, 0x97, 0x5a, 0x62, 0xaa, 0x89, 0x69, 0x41, 0x4c, 0xdb, 0xc8, 0xf8, 0xa1, 0x7b, 0xfa, - 0xfd, 0x41, 0xe5, 0xc8, 0x24, 0x7b, 0x8f, 0x08, 0x19, 0x30, 0x9e, 0x8c, 0x63, 0xcd, 0xeb, 0xbb, - 0x4d, 0xa7, 0xb5, 0xb9, 0xbf, 0x43, 0xff, 0xee, 0x8c, 0x6a, 0xfe, 0x02, 0x55, 0x37, 0xd9, 0xfa, - 0x83, 0xf7, 0x96, 0xdc, 0xb7, 0xd0, 0x5c, 0x82, 0x30, 0xf8, 0x58, 0x8e, 0x12, 0x01, 0xd2, 0x5f, - 0x33, 0xcf, 0x5c, 0x5a, 0xc1, 0x3d, 0x03, 0x7f, 0x27, 0x41, 0xe8, 0xf7, 0x8e, 0x0d, 0x76, 0xef, - 0x73, 0x8d, 0x6c, 0x2f, 0x9b, 0x7e, 0x89, 0x8c, 0xdb, 0x9e, 0x93, 0x7e, 0x5f, 0x80, 0x94, 0x8b, - 0x9e, 0x8b, 0xab, 0xf7, 0x84, 0xd4, 0x15, 0x7e, 0x00, 0x2e, 0x63, 0xc6, 0xcb, 0x36, 0x7e, 0xcb, - 0x22, 0xba, 0xdc, 0x7b, 0x41, 0xb6, 0x57, 0xca, 0x8e, 0x31, 0x57, 0x7e, 0xad, 0x5c, 0xe9, 0x77, - 0xb2, 0x65, 0xc5, 0xaf, 0x73, 0xa5, 0xcb, 0x10, 0x30, 0x89, 0xb5, 0xad, 0xd2, 0x77, 0x4b, 0x96, - 0x21, 0x60, 0xa2, 0xaf, 0xe7, 0x3d, 0x58, 0xfb, 0x3f, 0x1e, 0xac, 0x5f, 0xc3, 0x83, 0x5f, 0xd5, - 0x15, 0x0f, 0x3a, 0x27, 0x4c, 0x5d, 0xe8, 0x41, 0x87, 0x6c, 0xad, 0xaa, 0x68, 0x8c, 0x28, 0xc5, - 0x7d, 0xfb, 0x8f, 0x88, 0x5d, 0xee, 0x3d, 0x25, 0xa4, 0xb0, 0xd2, 0xfa, 0x50, 0x4a, 0xc4, 0xc2, - 0x7d, 0xed, 0xc1, 0x62, 0xfc, 0xdd, 0x7f, 0x1f, 0xff, 0x1b, 0x20, 0xfd, 0xd7, 0x2a, 0xf1, 0x8c, - 0xf4, 0xcf, 0xa4, 0x04, 0x25, 0x8f, 0x3f, 0x26, 0x59, 0x76, 0xa1, 0xfa, 0x8f, 0x89, 0x9d, 0xe7, - 0x2b, 0xe8, 0xbe, 0x61, 0x00, 0x5d, 0xbe, 0xfc, 0x7b, 0xae, 0x32, 0xf9, 0x96, 0x4d, 0x0b, 0x1e, - 0x91, 0xda, 0x00, 0xa0, 0xd8, 0x19, 0x97, 0xe2, 0x74, 0xee, 0x35, 0xe4, 0x3e, 0x7c, 0x7e, 0x3a, - 0x0b, 0x9c, 0xb3, 0x59, 0xe0, 0xfc, 0x98, 0x05, 0xce, 0x97, 0x79, 0x50, 0x39, 0x9b, 0x07, 0x95, - 0x6f, 0xf3, 0xa0, 0xf2, 0xfe, 0xe1, 0x90, 0xa9, 0x51, 0x9e, 0xd2, 0x1e, 0x4e, 0xc2, 0x57, 0xe6, - 0xa9, 0xf6, 0x28, 0x61, 0x3c, 0x2c, 0x16, 0xeb, 0x89, 0x5d, 0xad, 0xea, 0x53, 0x06, 0x32, 0x5d, - 0x37, 0x9b, 0xf5, 0xe0, 0x77, 0x00, 0x00, 0x00, 0xff, 0xff, 0xd2, 0xf6, 0x0e, 0x47, 0xd8, 0x05, - 0x00, 0x00, -} - -func (m *EventPoolCreated) 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 *EventPoolCreated) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *EventPoolCreated) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.FinalUserPoolShares.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.FinalPool.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - if len(m.Fees) > 0 { - for iNdEx := len(m.Fees) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Fees[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintEvent(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *EventPoolJoined) 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 *EventPoolJoined) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *EventPoolJoined) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.FinalUserPoolShares.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.FinalPool.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - if len(m.RemCoins) > 0 { - for iNdEx := len(m.RemCoins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RemCoins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - { - size, err := m.PoolSharesOut.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.TokensIn) > 0 { - for iNdEx := len(m.TokensIn) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TokensIn[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintEvent(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *EventPoolExited) 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 *EventPoolExited) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *EventPoolExited) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.FinalUserPoolShares.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.FinalPool.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - if len(m.Fees) > 0 { - for iNdEx := len(m.Fees) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Fees[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.TokensOut) > 0 { - for iNdEx := len(m.TokensOut) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TokensOut[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - { - size, err := m.PoolSharesIn.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintEvent(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *EventAssetsSwapped) 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 *EventAssetsSwapped) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *EventAssetsSwapped) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.FinalPool.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.Fee.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.TokenOut.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.TokenIn.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintEvent(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintEvent(dAtA, i, uint64(len(m.Address))) - 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 *EventPoolCreated) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovEvent(uint64(l)) - } - if len(m.Fees) > 0 { - for _, e := range m.Fees { - l = e.Size() - n += 1 + l + sovEvent(uint64(l)) - } - } - l = m.FinalPool.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.FinalUserPoolShares.Size() - n += 1 + l + sovEvent(uint64(l)) - return n -} - -func (m *EventPoolJoined) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovEvent(uint64(l)) - } - if len(m.TokensIn) > 0 { - for _, e := range m.TokensIn { - l = e.Size() - n += 1 + l + sovEvent(uint64(l)) - } - } - l = m.PoolSharesOut.Size() - n += 1 + l + sovEvent(uint64(l)) - if len(m.RemCoins) > 0 { - for _, e := range m.RemCoins { - l = e.Size() - n += 1 + l + sovEvent(uint64(l)) - } - } - l = m.FinalPool.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.FinalUserPoolShares.Size() - n += 1 + l + sovEvent(uint64(l)) - return n -} - -func (m *EventPoolExited) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovEvent(uint64(l)) - } - l = m.PoolSharesIn.Size() - n += 1 + l + sovEvent(uint64(l)) - if len(m.TokensOut) > 0 { - for _, e := range m.TokensOut { - l = e.Size() - n += 1 + l + sovEvent(uint64(l)) - } - } - if len(m.Fees) > 0 { - for _, e := range m.Fees { - l = e.Size() - n += 1 + l + sovEvent(uint64(l)) - } - } - l = m.FinalPool.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.FinalUserPoolShares.Size() - n += 1 + l + sovEvent(uint64(l)) - return n -} - -func (m *EventAssetsSwapped) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovEvent(uint64(l)) - } - l = m.TokenIn.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.TokenOut.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.Fee.Size() - n += 1 + l + sovEvent(uint64(l)) - l = m.FinalPool.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 *EventPoolCreated) 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: EventPoolCreated: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: EventPoolCreated: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Creator", 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.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Fees", 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.Fees = append(m.Fees, types.Coin{}) - if err := m.Fees[len(m.Fees)-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 FinalPool", 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.FinalPool.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FinalUserPoolShares", 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.FinalUserPoolShares.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 *EventPoolJoined) 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: EventPoolJoined: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: EventPoolJoined: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - 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 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.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokensIn", 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.TokensIn = append(m.TokensIn, types.Coin{}) - if err := m.TokensIn[len(m.TokensIn)-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 PoolSharesOut", 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.PoolSharesOut.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RemCoins", 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.RemCoins = append(m.RemCoins, types.Coin{}) - if err := m.RemCoins[len(m.RemCoins)-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 FinalPool", 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.FinalPool.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FinalUserPoolShares", 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.FinalUserPoolShares.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 *EventPoolExited) 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: EventPoolExited: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: EventPoolExited: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - 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 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.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolSharesIn", 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.PoolSharesIn.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokensOut", 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.TokensOut = append(m.TokensOut, types.Coin{}) - if err := m.TokensOut[len(m.TokensOut)-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 Fees", 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.Fees = append(m.Fees, types.Coin{}) - if err := m.Fees[len(m.Fees)-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 FinalPool", 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.FinalPool.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FinalUserPoolShares", 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.FinalUserPoolShares.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 *EventAssetsSwapped) 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: EventAssetsSwapped: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: EventAssetsSwapped: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - 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 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.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenIn", 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.TokenIn.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenOut", 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.TokenOut.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Fee", 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.Fee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FinalPool", 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.FinalPool.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/spot/types/expected_keepers.go b/x/spot/types/expected_keepers.go deleted file mode 100644 index da254c9b2..000000000 --- a/x/spot/types/expected_keepers.go +++ /dev/null @@ -1,53 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" -) - -// AccountKeeper defines the expected account keeper used for simulations (noalias) -type AccountKeeper interface { - IterateAccounts(ctx sdk.Context, process func(authtypes.AccountI) (stop bool)) - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - NewAccount(sdk.Context, authtypes.AccountI) authtypes.AccountI - SetAccount(ctx sdk.Context, acc authtypes.AccountI) - GetModuleAddress(name string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, moduleName string) authtypes.ModuleAccountI - - SetModuleAccount(sdk.Context, authtypes.ModuleAccountI) - // Methods imported from account should be defined here -} - -// BankKeeper defines the expected interface needed to retrieve account balances. -type BankKeeper interface { - // Methods imported from bank should be defined here - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoinsFromModuleToModule(ctx sdk.Context, senderPool, recipientPool string, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error - - MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - BurnCoins(ctx sdk.Context, name string, amt sdk.Coins) error - - SetDenomMetaData(ctx sdk.Context, denomMetaData banktypes.Metadata) - - // Only needed for simulation interface matching - // TODO: Look into golang syntax to make this "Everything in stakingtypes.bankkeeper + extra funcs" - // I think it has to do with listing another interface as the first line here? - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - // SetBalances(ctx sdk.Context, addr sdk.AccAddress, balances sdk.Coins) error - LockedCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - GetSupply(ctx sdk.Context, denom string) sdk.Coin - UndelegateCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - DelegateCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - IterateAllBalances(ctx sdk.Context, callback func(addr sdk.AccAddress, coin sdk.Coin) (stop bool)) -} - -// DistrKeeper defines the contract needed to be fulfilled for distribution keeper. -type DistrKeeper interface { - FundCommunityPool(ctx sdk.Context, amount sdk.Coins, sender sdk.AccAddress) error -} diff --git a/x/spot/types/export.go b/x/spot/types/export.go deleted file mode 100644 index fb4b6e3b6..000000000 --- a/x/spot/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/spot/types/genesis.go b/x/spot/types/genesis.go deleted file mode 100644 index 103b72a0c..000000000 --- a/x/spot/types/genesis.go +++ /dev/null @@ -1,15 +0,0 @@ -package types - -// DefaultGenesis returns the default Capability genesis state -func DefaultGenesis() *GenesisState { - return &GenesisState{ - Params: DefaultParams(), - Pools: []Pool{}, - } -} - -// Validate performs basic genesis state validation returning an error upon any -// failure. -func (gs GenesisState) Validate() error { - return gs.Params.Validate() -} diff --git a/x/spot/types/genesis.pb.go b/x/spot/types/genesis.pb.go deleted file mode 100644 index 0ab2380e2..000000000 --- a/x/spot/types/genesis.pb.go +++ /dev/null @@ -1,387 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: nibiru/spot/v1/genesis.proto - -package types - -import ( - fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" - 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 spot module's genesis state. -type GenesisState struct { - // params defines all the parameters of the module. - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - // pools defines all the pools of the module. - Pools []Pool `protobuf:"bytes,2,rep,name=pools,proto3" json:"pools"` -} - -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_f2772e1e838a47ec, []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) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -func (m *GenesisState) GetPools() []Pool { - if m != nil { - return m.Pools - } - return nil -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "nibiru.spot.v1.GenesisState") -} - -func init() { proto.RegisterFile("nibiru/spot/v1/genesis.proto", fileDescriptor_f2772e1e838a47ec) } - -var fileDescriptor_f2772e1e838a47ec = []byte{ - // 227 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xc9, 0xcb, 0x4c, 0xca, - 0x2c, 0x2a, 0xd5, 0x2f, 0x2e, 0xc8, 0x2f, 0xd1, 0x2f, 0x33, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, - 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x83, 0xc8, 0xea, 0x81, 0x64, 0xf5, - 0xca, 0x0c, 0xa5, 0xa4, 0xd1, 0x54, 0x17, 0x24, 0x16, 0x25, 0xe6, 0x42, 0x15, 0x4b, 0x49, 0xa2, - 0x4b, 0xe6, 0xe7, 0xe7, 0x40, 0xa5, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x4c, 0x7d, 0x10, 0x0b, - 0x22, 0xaa, 0x54, 0xc6, 0xc5, 0xe3, 0x0e, 0xb1, 0x2e, 0xb8, 0x24, 0xb1, 0x24, 0x55, 0xc8, 0x84, - 0x8b, 0x0d, 0x62, 0xa0, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0x98, 0x1e, 0xaa, 0xf5, 0x7a, - 0x01, 0x60, 0x59, 0x27, 0x96, 0x13, 0xf7, 0xe4, 0x19, 0x82, 0xa0, 0x6a, 0x85, 0x0c, 0xb8, 0x58, - 0x41, 0x36, 0x15, 0x4b, 0x30, 0x29, 0x30, 0x6b, 0x70, 0x1b, 0x89, 0x60, 0x68, 0xca, 0xcf, 0xcf, - 0x81, 0x6a, 0x81, 0x28, 0x74, 0x72, 0x39, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, - 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, - 0x28, 0xad, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0x3f, 0xb0, 0x31, - 0xce, 0x19, 0x89, 0x99, 0x79, 0xfa, 0x50, 0x9f, 0x55, 0x40, 0xfc, 0x56, 0x52, 0x59, 0x90, 0x5a, - 0x9c, 0xc4, 0x06, 0xf6, 0x84, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x16, 0xfb, 0x27, 0x7a, 0x42, - 0x01, 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.Pools) > 0 { - for iNdEx := len(m.Pools) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Pools[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - 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 - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.Pools) > 0 { - for _, e := range m.Pools { - l = e.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 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", 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.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pools", 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.Pools = append(m.Pools, Pool{}) - if err := m.Pools[len(m.Pools)-1].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/spot/types/genesis_test.go b/x/spot/types/genesis_test.go deleted file mode 100644 index eae38d740..000000000 --- a/x/spot/types/genesis_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/spot/types" -) - -func TestGenesisState_Validate(t *testing.T) { - for _, tc := range []struct { - desc string - genState *types.GenesisState - valid bool - }{ - { - desc: "default is valid", - genState: types.DefaultGenesis(), - valid: true, - }, - { - desc: "valid genesis state", - genState: &types.GenesisState{}, - valid: true, - }, - } { - t.Run(tc.desc, func(t *testing.T) { - err := tc.genState.Validate() - if tc.valid { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} diff --git a/x/spot/types/keys.go b/x/spot/types/keys.go deleted file mode 100644 index da7fcf46b..000000000 --- a/x/spot/types/keys.go +++ /dev/null @@ -1,54 +0,0 @@ -package types - -import ( - "sort" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // ModuleName defines the module name - ModuleName = "spot" - - // StoreKey defines the primary module store key - StoreKey = ModuleName - - // RouterKey is the message route for slashing - RouterKey = ModuleName - - // QuerierRoute defines the module's query routing key - QuerierRoute = ModuleName - - // MemStoreKey defines the in-memory store key - MemStoreKey = "mem_dex" -) - -func KeyPrefix(p string) []byte { - return []byte(p) -} - -var ( - // KeyNextGlobalPoolNumber defines key to store the next Pool ID to be used - KeyNextGlobalPoolNumber = []byte{0x01} - // KeyPrefixPools defines prefix to store pools - KeyPrefixPools = []byte{0x02} - // KeyTotalLiquidity defines key to store total liquidity - KeyTotalLiquidity = []byte{0x03} - // KeyPrefixPoolIds defines prefix to store pool ids by denoms in the pool - KeyPrefixPoolIds = []byte{0x04} -) - -func GetDenomPrefixPoolIds(denoms ...string) []byte { - sort.Strings(denoms) - concatenation := strings.Join(denoms[:], "") - return append(KeyPrefixPoolIds, []byte(concatenation)...) -} - -func GetKeyPrefixPools(poolId uint64) []byte { - return append(KeyPrefixPools, sdk.Uint64ToBigEndian(poolId)...) -} - -func GetDenomLiquidityPrefix(denom string) []byte { - return append(KeyTotalLiquidity, []byte(denom)...) -} diff --git a/x/spot/types/message.go b/x/spot/types/message.go deleted file mode 100644 index 8724d6b5b..000000000 --- a/x/spot/types/message.go +++ /dev/null @@ -1,226 +0,0 @@ -package types - -import ( - sdkerrors "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" -) - -const ( - TypeMsgExitPool = "exit_pool" - TypeMsgJoinPool = "join_pool" - TypeMsgSwapAssets = "swap_assets" - TypeMsgCreatePool = "create_pool" -) - -var ( - _ sdk.Msg = &MsgExitPool{} - _ sdk.Msg = &MsgJoinPool{} - _ sdk.Msg = &MsgSwapAssets{} - _ sdk.Msg = &MsgCreatePool{} -) - -func NewMsgExitPool(sender string, poolId uint64, poolShares sdk.Coin) *MsgExitPool { - return &MsgExitPool{ - Sender: sender, - PoolId: poolId, - PoolShares: poolShares, - } -} - -func (msg *MsgExitPool) Route() string { - return RouterKey -} - -func (msg *MsgExitPool) Type() string { - return TypeMsgExitPool -} - -func (msg *MsgExitPool) GetSigners() []sdk.AccAddress { - creator, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{creator} -} - -func (msg *MsgExitPool) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) - return sdk.MustSortJSON(bz) -} - -func (msg *MsgExitPool) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return sdkerrors.Wrapf(errors.ErrInvalidAddress, "invalid address (%s)", err) - } - return nil -} - -var _ sdk.Msg = &MsgJoinPool{} - -func NewMsgJoinPool(sender string, poolId uint64, tokensIn sdk.Coins, useAllCoins bool) *MsgJoinPool { - return &MsgJoinPool{ - Sender: sender, - PoolId: poolId, - TokensIn: tokensIn, - UseAllCoins: useAllCoins, - } -} - -func (msg *MsgJoinPool) Route() string { - return RouterKey -} - -func (msg *MsgJoinPool) Type() string { - return TypeMsgJoinPool -} - -func (msg *MsgJoinPool) GetSigners() []sdk.AccAddress { - creator, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{creator} -} - -func (msg *MsgJoinPool) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) - return sdk.MustSortJSON(bz) -} - -func (msg *MsgJoinPool) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return sdkerrors.Wrapf(errors.ErrInvalidAddress, "invalid creator address (%s)", err) - } - return nil -} - -var _ sdk.Msg = &MsgSwapAssets{} - -func NewMsgSwapAssets(sender string, poolId uint64, tokenIn sdk.Coin, tokenOutDenom string) *MsgSwapAssets { - return &MsgSwapAssets{ - Sender: sender, - PoolId: poolId, - TokenIn: tokenIn, - TokenOutDenom: tokenOutDenom, - } -} - -func (msg *MsgSwapAssets) Route() string { - return RouterKey -} - -func (msg *MsgSwapAssets) Type() string { - return TypeMsgSwapAssets -} - -func (msg *MsgSwapAssets) GetSigners() []sdk.AccAddress { - creator, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - panic(err) - } - return []sdk.AccAddress{creator} -} - -func (msg *MsgSwapAssets) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) - return sdk.MustSortJSON(bz) -} - -func (msg *MsgSwapAssets) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return sdkerrors.Wrapf(errors.ErrInvalidAddress, "invalid creator address (%s)", err) - } - - if msg.PoolId == 0 { - return ErrInvalidPoolId.Wrapf("pool id cannot be %d", msg.PoolId) - } - - if msg.TokenIn.Amount.LTE(sdk.ZeroInt()) { - return ErrInvalidTokenIn.Wrapf("invalid argument %s", msg.TokenIn.String()) - } - - if msg.TokenOutDenom == "" { - return ErrInvalidTokenOutDenom.Wrap("cannot be empty") - } - - return nil -} - -var _ sdk.Msg = &MsgCreatePool{} - -func NewMsgCreatePool(creator string, poolAssets []PoolAsset, poolParams *PoolParams) *MsgCreatePool { - return &MsgCreatePool{ - Creator: creator, - PoolAssets: poolAssets, - PoolParams: poolParams, - } -} - -func (msg *MsgCreatePool) Route() string { - return RouterKey -} - -func (msg *MsgCreatePool) Type() string { - return TypeMsgCreatePool -} - -func (msg *MsgCreatePool) GetSigners() []sdk.AccAddress { - creator, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - panic(err) - } - return []sdk.AccAddress{creator} -} - -func (msg *MsgCreatePool) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) - return sdk.MustSortJSON(bz) -} - -func (msg *MsgCreatePool) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - return sdkerrors.Wrapf(errors.ErrInvalidAddress, "invalid creator address (%s)", err) - } - - if len(msg.PoolAssets) < MinPoolAssets { - return ErrTooFewPoolAssets.Wrapf("invalid number of assets (%d)", len(msg.PoolAssets)) - } - if len(msg.PoolAssets) > MaxPoolAssets { - return ErrTooManyPoolAssets.Wrapf("invalid number of assets (%d)", len(msg.PoolAssets)) - } - - for _, asset := range msg.PoolAssets { - if asset.Weight.LTE(sdk.ZeroInt()) { - return ErrInvalidTokenWeight.Wrapf("invalid token weight %d for denom %s", asset.Weight, asset.Token.Denom) - } - } - - if msg.PoolParams.SwapFee.LT(sdk.ZeroDec()) || msg.PoolParams.SwapFee.GT(sdk.OneDec()) { - return ErrInvalidSwapFee.Wrapf("invalid swap fee: %s", msg.PoolParams.SwapFee) - } - - if msg.PoolParams.ExitFee.LT(sdk.ZeroDec()) || msg.PoolParams.ExitFee.GT(sdk.OneDec()) { - return ErrInvalidExitFee.Wrapf("invalid exit fee: %s", msg.PoolParams.ExitFee) - } - - if (msg.PoolParams.PoolType != PoolType_STABLESWAP) && (msg.PoolParams.PoolType != PoolType_BALANCER) { - return ErrInvalidPoolType - } - - if msg.PoolParams.PoolType == PoolType_STABLESWAP { - if msg.PoolParams.A.IsNil() { - return ErrAmplificationMissing - } - - if !msg.PoolParams.A.IsPositive() { - return ErrAmplificationTooLow - } - } - - return nil -} diff --git a/x/spot/types/message_test.go b/x/spot/types/message_test.go deleted file mode 100644 index 3e9f71ce3..000000000 --- a/x/spot/types/message_test.go +++ /dev/null @@ -1,350 +0,0 @@ -package types - -import ( - "testing" - - "github.com/NibiruChain/nibiru/x/common/testutil" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" -) - -func TestValidateBasic(t *testing.T) { - tests := []struct { - name string - msg MsgCreatePool - expectedErr error - }{ - { - name: "invalid address", - msg: MsgCreatePool{ - Creator: "invalid_address", - PoolParams: &PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.003"), - ExitFee: sdk.MustNewDecFromStr("0.003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 1), - Weight: sdk.OneInt(), - }, - }, - }, - expectedErr: sdkerrors.ErrInvalidAddress, - }, - { - name: "invalid swap fee, too small", - msg: MsgCreatePool{ - Creator: testutil.AccAddress().String(), - PoolParams: &PoolParams{ - SwapFee: sdk.MustNewDecFromStr("-0.003"), - ExitFee: sdk.MustNewDecFromStr("0.003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 1), - Weight: sdk.OneInt(), - }, - }, - }, - expectedErr: ErrInvalidSwapFee, - }, - { - name: "invalid swap fee, too large", - msg: MsgCreatePool{ - Creator: testutil.AccAddress().String(), - PoolParams: &PoolParams{ - SwapFee: sdk.MustNewDecFromStr("1.1"), - ExitFee: sdk.MustNewDecFromStr("0.003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 1), - Weight: sdk.OneInt(), - }, - }, - }, - expectedErr: ErrInvalidSwapFee, - }, - { - name: "invalid exit fee, too small", - msg: MsgCreatePool{ - Creator: testutil.AccAddress().String(), - PoolParams: &PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.003"), - ExitFee: sdk.MustNewDecFromStr("-0.003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 1), - Weight: sdk.OneInt(), - }, - }, - }, - expectedErr: ErrInvalidExitFee, - }, - { - name: "invalid exit fee, too large", - msg: MsgCreatePool{ - Creator: testutil.AccAddress().String(), - PoolParams: &PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.003"), - ExitFee: sdk.MustNewDecFromStr("1.1"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 1), - Weight: sdk.OneInt(), - }, - }, - }, - expectedErr: ErrInvalidExitFee, - }, - { - name: "too few assets", - msg: MsgCreatePool{ - Creator: testutil.AccAddress().String(), - PoolParams: &PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.003"), - ExitFee: sdk.MustNewDecFromStr("0.003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1), - Weight: sdk.OneInt(), - }, - }, - }, - expectedErr: ErrTooFewPoolAssets, - }, - { - name: "too many assets", - msg: MsgCreatePool{ - Creator: testutil.AccAddress().String(), - PoolParams: &PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.003"), - ExitFee: sdk.MustNewDecFromStr("0.003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("ccc", 1), - Weight: sdk.OneInt(), - }, - }, - }, - expectedErr: ErrTooManyPoolAssets, - }, - { - name: "invalid token weight", - msg: MsgCreatePool{ - Creator: testutil.AccAddress().String(), - PoolParams: &PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.003"), - ExitFee: sdk.MustNewDecFromStr("0.003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1), - Weight: sdk.ZeroInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 1), - Weight: sdk.ZeroInt(), - }, - }, - }, - expectedErr: ErrInvalidTokenWeight, - }, - { - name: "valid create pool message", - msg: MsgCreatePool{ - Creator: testutil.AccAddress().String(), - PoolParams: &PoolParams{ - SwapFee: sdk.MustNewDecFromStr("0.003"), - ExitFee: sdk.MustNewDecFromStr("0.003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 1), - Weight: sdk.OneInt(), - }, - }, - }, - expectedErr: nil, - }, - } - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.expectedErr != nil { - require.ErrorIs(t, err, tc.expectedErr) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestMsgExitPool_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg MsgExitPool - err error - }{ - { - name: "invalid address", - msg: MsgExitPool{ - Sender: "invalid_address", - }, - err: sdkerrors.ErrInvalidAddress, - }, { - name: "valid address", - msg: MsgExitPool{ - Sender: testutil.AccAddress().String(), - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := tt.msg.ValidateBasic() - if tt.err != nil { - require.ErrorIs(t, err, tt.err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgJoinPool_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg MsgJoinPool - err error - }{ - { - name: "invalid address", - msg: MsgJoinPool{ - Sender: "invalid_address", - }, - err: sdkerrors.ErrInvalidAddress, - }, { - name: "valid address", - msg: MsgJoinPool{ - Sender: testutil.AccAddress().String(), - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := tt.msg.ValidateBasic() - if tt.err != nil { - require.ErrorIs(t, err, tt.err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgSwapAssets_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg MsgSwapAssets - err error - }{ - { - name: "invalid address", - msg: MsgSwapAssets{ - Sender: "invalid_address", - PoolId: 1, - TokenIn: sdk.NewInt64Coin("foo", 1), - TokenOutDenom: "bar", - }, - err: sdkerrors.ErrInvalidAddress, - }, - { - name: "invalid pool id", - msg: MsgSwapAssets{ - Sender: testutil.AccAddress().String(), - PoolId: 0, - TokenIn: sdk.NewInt64Coin("foo", 1), - TokenOutDenom: "bar", - }, - err: ErrInvalidPoolId, - }, - { - name: "invalid tokens in", - msg: MsgSwapAssets{ - Sender: testutil.AccAddress().String(), - PoolId: 1, - TokenIn: sdk.NewInt64Coin("foo", 0), - TokenOutDenom: "bar", - }, - err: ErrInvalidTokenIn, - }, - { - name: "invalid token out denom", - msg: MsgSwapAssets{ - Sender: testutil.AccAddress().String(), - PoolId: 1, - TokenIn: sdk.NewInt64Coin("foo", 1), - TokenOutDenom: "", - }, - err: ErrInvalidTokenOutDenom, - }, - { - name: "valid message", - msg: MsgSwapAssets{ - Sender: testutil.AccAddress().String(), - PoolId: 1, - TokenIn: sdk.NewInt64Coin("foo", 1), - TokenOutDenom: "bar", - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := tt.msg.ValidateBasic() - if tt.err != nil { - require.ErrorIs(t, err, tt.err) - return - } - require.NoError(t, err) - }) - } -} diff --git a/x/spot/types/misc/stabletests.csv b/x/spot/types/misc/stabletests.csv deleted file mode 100644 index c22f81de4..000000000 --- a/x/spot/types/misc/stabletests.csv +++ /dev/null @@ -1,200 +0,0 @@ -"[27775542291595154, 97122479520742482]",3569,1,0,14569132846928708,14558669000207900 -"[99811231953029219, 67867258133352948, 4548504687635641, 22643988721136401]",1866,3,0,74314087998730798,74314370435091235 -"[79490968623278253, 2416473075872119, 16201992876681232, 26563606891100389, 31550918159678239]",1,2,3,20029180402698560,19630034405572792 -"[20390077612988015, 14143931325787607]",2874,0,1,646125170094190,646076474640607 -"[29862292342512526, 67464721015487113, 87029435446288613, 84748092193374166]",1661,1,0,19106998798163720,19105983646625076 -"[26314181423329306, 72232425287195858]",895,1,0,7017055246943759,7008536248313182 -"[50063648172290677, 88478493455845741, 56498015592382508]",434,0,2,56175044123085933,55631680015957697 -"[85974277623017018, 75621698555726081, 29660923586357885]",1769,1,0,56285720871465698,56282169988152274 -"[1448549668833367, 70220925182942167, 42193669609889726]",2702,2,1,30952835910452511,30952209807541944 -"[52760182169704204, 80560578505928626, 38370011571631126, 10523567718382376]",221,0,1,6243981777191623,6244229760683159 -"[21751115335094304, 2269537422422848, 79169137488199321, 62781109611104749, 70868520138484385]",906,1,4,4012347630123592,4013055467856176 -"[33812769090233324, 48275794826844955, 89859018195028312, 27622838635968022]",2623,1,0,29988889904145794,29986866603935209 -"[38550790744242251, 35749808204325994, 93688086287146772, 34503077430670297]",2892,1,0,34838346497693955,34836630239365079 -"[35417314410960968, 4102881661698347, 50055922087158045, 41884105950994686, 21101364706028050]",1186,1,2,3257903809020377,3257972188930204 -"[81129188249394063, 2584813155461682, 44804906888421064, 95264202217524109]",1,0,3,13940226839652919,13942817493440413 -"[72198520015474283, 98969806731775461, 7611649180436155]",3122,1,2,202275634204473,202067889175795 -"[77465114480268386, 78634762228767018, 5358738318039752, 82945484720524193, 30247634941059964]",725,0,4,10590544249402921,10590282436865524 -"[31068776034058944, 39968193528864314, 66360358721109297, 72646270885375562, 49523261462211484]",656,1,2,6857592314650409,6857600057013195 -"[25879450930992734, 73939730379687436, 98429560125131177, 6795064681229696]",1,3,0,13464205242148189,14430167730236281 -"[9340982326865641, 15587877420282456, 19501458580492835]",1007,1,2,9210079999688523,9209722748453901 -"[7872468114108993, 54708259168727746]",1290,0,1,28993075810311349,29008102407452619 -"[16285777537914017, 47446976441183895, 19919924880162336, 74231611041964662]",3763,1,3,40463544061139090,40463479145802453 -"[90591070006013486, 50731623526683063]",867,0,1,20036636364726264,20021021240086739 -"[22375051499480917, 41218751399761200, 12866957746759533, 24558798024917684, 29090029845634340]",2233,3,2,2975889618200377,2975885412523381 -"[62306694955836749, 49854186833579912, 33994657304703837, 28267954219420635]",2410,1,0,41496721619858045,41496504518209157 -"[6070925865583425, 92662876144134456, 95607482675151999, 41971114961613525, 47082597756636923]",3194,4,0,1431992583897632,1431950385301611 -"[80846549083963206, 70906406854076547, 74228318994171188, 2027393953938540, 82811121181051201]",942,2,3,786579769740673,785735057363777 -"[51301342054599088, 77126730028661743, 58751637435206305]",3926,1,0,1891009760636839,1890984993566355 -"[32305358452421359, 60920358540527868, 71857503348686740, 81504571407927530]",1138,2,0,30570323644075886,30557631212637089 -"[74283885983215027, 97376907892131235, 44701059091011433, 75038989483601953]",3572,1,0,61077282754379821,61076374079398594 -"[61809191794567159, 65268210983736695, 13041955921362012]",3334,2,0,1367651454523366,1367875804543958 -"[29305950030977337, 50529747115163700, 87408501924636118]",1893,0,2,57500308755670506,57500367166862904 -"[81555735945943859, 92446513201273467, 26820392358889621]",745,1,0,5649991870092771,5649806044917715 -"[55312357586388897, 85507925667443520]",476,1,0,15461825549485662,15448256102708432 -"[3324774254953230, 7444302682607094, 73818588715037600]",2423,0,1,1036600598831895,1038409415489951 -"[70866111453900446, 987034925133774, 5551501056990013, 33827754450273291]",1,0,2,440991689322851,163173975913946 -"[69260898739623064, 2407120271845792]",2114,1,0,27975191526590264,28031647097048791 -"[78989492850850109, 34085017560697864, 17098872479483990, 82101123756003477, 75942316151386295]",2151,0,2,832459722815124,832455899715611 -"[43105400266091190, 30907212812585241, 99592755261735635, 68038321017851058, 75636781777032787]",3041,1,4,3966410030435909,3966413284798787 -"[72480217367559860, 29633693498020282, 39797991003336311, 23528064722640901]",749,0,3,13344798053600377,13343604186498670 -"[7573870148015712, 96425949453897932, 12213914565225419, 29817160901860679]",3816,1,3,15641214014477820,15640405643999879 -"[39446768558086319, 33060509822102699, 47308413038664680]",3683,2,1,26651994504238407,26649135052115203 -"[59765006200169844, 32729340087571085, 5459283337981383, 72833741419973763]",1958,3,1,15353465961140485,15352657088325650 -"[11687948178407447, 70735263447974241, 19396727197336045, 60339348678984523]",1929,2,3,57279688711334547,57276037997951275 -"[76423498163807014, 61843295785370953, 65130276996772654, 27310582754688037, 18460489944575185]",1763,3,2,55654197258731139,55654084187322882 -"[46510092262672225, 35088848864762949, 85877728950773668]",495,0,2,25241287191968211,25242561667555042 -"[94489200612776920, 12892523631993082]",1703,0,1,6897644195895437,6860662857295104 -"[16624955453576244, 13099675266618686, 9573816005550134, 13670828667375562, 16649951565620241]",2845,2,0,15369216122484917,15369180878123818 -"[4349619225115443, 36739923809792602]",1905,0,1,21733705954783216,21742124926044837 -"[63491607504450131, 6957907101513874, 52641848063164062]",2856,2,0,28866767659336552,28865894138520401 -"[42575766492233533, 75944493215873760, 69477013071683111, 20575071825017380]",1806,2,1,623786338925258,623786837033419 -"[489218592538267, 14662597764290572, 23765886037043450]",2123,0,1,14537721546710050,14517774321461833 -"[13885765464616729, 3550969430265598]",1,1,0,5224753861040049,6500102664148832 -"[79661913387008706, 91524687892670355, 84888699883808398, 56172071485651526]",1,2,0,39201593055227540,38768818852997409 -"[67556033156043755, 5228023594229166, 9567881125457033]",877,0,2,4783368122087361,4765066821372804 -"[74993254895716474, 82141866006727728, 71846419421012636, 91708209715761089]",3726,1,0,28098385920714617,28098320361060157 -"[19637585111522953, 62882034406891290, 94855758426681982, 35490102125455267]",1853,2,1,11169301656973989,11169225571163800 -"[25973997813573493, 68627514110076118, 32245424124395163, 42026703571510752]",3451,1,2,23981507806427169,23981032331783447 -"[1701071625071059, 66138954591081596, 93178803700364461, 18089842293575865]",3070,1,2,48496537290436353,48495556130571719 -"[73507959220182831, 14246726621273775, 57144788495045358]",691,0,1,667236216367843,666656469812813 -"[12976150107437855, 97530586264274771, 76033118824173699, 32784474586516297, 38191053027841122]",3273,0,2,42291896504487313,42291932166701471 -"[91455767533246994, 61860751078374560]",539,0,1,1335308558546835,1334766062174620 -"[48164506381587318, 12397200467071704, 89035296175993046, 93793949252928114, 93874595153952850]",1942,4,2,76359322092558186,76358845763371849 -"[61328513286729704, 89852914158889517, 16905638990485440]",645,2,1,89159278973384881,88902851394992373 -"[68796293159405016, 86982538554379329]",1555,1,0,45511260656708490,45487452422795276 -"[8898007662468760, 92882563089559083]",3079,1,0,6842128161385877,6767336355160415 -"[37572692320844011, 78194216157707620]",3403,1,0,24005344006305440,23994508948323056 -"[63296299392391998, 15393876906431156, 14305587782713097, 68056283702550734]",1931,3,2,11647681896302999,11644441698114468 -"[18495841046767555, 82801749401579506, 61367066674882964]",2401,1,2,50688306115900746,50677407249052123 -"[78569114356943248, 15034128553414328, 96020554733746314]",1906,0,1,10107230131538149,10093317230348115 -"[62995662163319645, 34510490826081701, 65056543656776077, 78725328043591716, 19580263133955812]",3215,2,1,11056603170104980,11056591306192758 -"[46867583551858212, 37361486211856719, 80530344373805838, 35279570203019942, 96169359256080527]",3052,3,1,34823191232863459,34822887767130375 -"[3897337546208566, 61255724506026266, 64124651280978749, 92035336790824045, 78640745983696567]",487,1,0,18865779306098,18859486230683 -"[10449792083323391, 96046536920849986, 13127364880396787, 42121783828388748, 57722048484583211]",1,3,4,21623643670366424,21603788171156399 -"[43569236319830742, 36164620468153152, 75659062096776293, 60290733273448348, 42572681684400149]",967,1,2,37543659747235268,37543662423938384 -"[65111486824188036, 15661462404808721, 90164242572032832]",3666,1,2,14018987270090014,14020290779593297 -"[62061649229886036, 86851118889003425, 88274678251332076, 37389133926544499, 28977216355694804]",2902,0,3,10230551165644378,10230541426013324 -"[41823775070881603, 99225495794483530, 97115572679015653, 11350827886613140]",138,1,0,14693212838718158,14685212817866186 -"[80399317447959105, 19278741788798667, 97066374621342521]",204,0,2,32150528805435421,32145974107469428 -"[42514859695161149, 23779240243607695, 67259951487290892, 88717088575764004, 48834923714106316]",1845,1,2,43338533049253633,43338533336323111 -"[73420340616190429, 13431955718528882, 90085545544663931]",2288,2,1,109354105471013,109307925843683 -"[79173488595533176, 3095237363042198, 21682105737006794]",2929,2,1,1889746623230921,1876010193578316 -"[77704926969639656, 77453655833385927, 41681921151102252, 5223364732082858]",19,0,1,37722403172760587,37658611630002083 -"[20181384943814402, 67648658299439068, 61017188067476311]",3263,0,2,36747715248753532,36747984565464539 -"[59644483751711445, 65368384869406243]",786,0,1,57265510186654588,57143788310280319 -"[11665294459266695, 47481522580086917, 98561920979835682]",1,1,0,2735417209572263,1559400101969246 -"[80343525778891752, 79841930559669422, 49928576688971674, 36481579439455317, 99059687053189357]",1538,1,0,38819021008192692,38818991392060768 -"[25476137267109667, 29779132789637466, 51890576127790626]",3011,2,0,22434291455351709,22426920028781022 -"[21253619500587785, 37083681507189642, 92435363158926560, 48155854277037419, 75395708578308175]",726,4,0,14297986240396403,14297629831923982 -"[56911194864610338, 29983013817364024, 50369147910526390]",2123,0,2,4304286630173394,4304242450001299 -"[62723932673727116, 78212559624222356, 57398895199822767]",1,1,2,55849242356781324,44241962577150562 -"[58811804535401855, 69496955154034174, 20418866425224185]",1768,1,0,35493975483228121,35490931114821848 -"[82718112317463953, 8826850051363447, 92429802699925819, 33974576718302112]",2547,3,1,6383363341197876,6380744896686156 -"[19530792888210565, 548817406053776, 52699645793059384, 53407463938485303, 2925653870295818]",2777,4,1,387981843602306,384220122374564 -"[1645555732508651, 22217428103835650]",3710,0,1,10201715888190194,10206365884637108 -"[60091944007873372, 4825805865875489, 42349758746972729]",1,0,1,2751806457611371,877567379617301 -"[69451152420411631, 21927767292937187, 46613955265624778]",1,2,1,11569573074969161,9100533133080165 -"[80247046112981582, 42946576117522403, 55769140175073498, 2459569987569055]",1199,2,0,42074265990434132,42073217487727570 -"[20419859863985500, 57006432202366351, 45676188739860291]",2053,0,2,26102599708855703,26102529713487053 -"[70799901756274291, 31246070612751444, 51625437793655233, 28002099806049716]",634,2,1,29548979689965134,29533190203501932 -"[74194789012746491, 23111217050480249]",1925,0,1,7678002541916038,7671784007785916 -"[35761839419113165, 43177675271669727, 2793876178502950, 74236746662306530]",3324,3,1,23408516255585964,23407642540826963 -"[2389935293412759, 90722194103360944, 33554657062247059, 75413708292200801]",1412,3,0,348841718471271,347747403470350 -"[81160498135213554, 99142268833380375, 90345012890697159]",2747,2,1,85420679438876243,85410686872367065 -"[32137332442702858, 40678323701569584, 27468385539121105]",1925,2,0,13106400667278981,13106113266529047 -"[60139786451371726, 16377001684986043, 42151498053701624, 15076187330797665]",3865,1,0,50708734466897840,50708584204081401 -"[3621235742757581, 55363775943291536, 85394299419424733, 67699336762421870, 28482776932231394]",1727,4,1,95361111436334,95361674349960 -"[92433040794899419, 17164989863623070]",2536,0,1,7886119318682126,7871771144730641 -"[55214885829406499, 50335319328185454]",849,0,1,3627690833258196,3627341317050072 -"[595195262273315, 23874611527563193]",1643,0,1,6758896817926198,6793532110645690 -"[38638239458495434, 45749377268118255]",1,0,1,41907717755308016,31182448816213348 -"[99558605390903370, 55089900255704010, 21746075552214046, 50722180288720687]",1005,2,3,30507627849563204,30507560771416899 -"[50922729579375163, 96720072430232666, 5131591505294711]",1180,1,0,34397549730425743,34365776712075701 -"[70187425709284979, 78301460518417366, 42914247765978870, 52445731913189562, 54079792593765903]",1044,2,4,20932647044074441,20932637138043229 -"[91796285297293685, 22985387394391223, 68765093669833582, 56015703436774448]",3328,0,2,41396767105996307,41396441439442088 -"[78682156810606273, 60288819532447583, 48606253300325634, 874425726434693, 75169432195480183]",317,2,1,18086202328356698,18085908045182504 -"[6260137618940906, 94592802995981447, 36171078644600848]",3647,2,0,2457151399736167,2453808745051091 -"[90437735388118521, 44941741779181066, 21012424410658660, 37722872677786489, 41294431478651274]",1180,2,4,9339930315177791,9339942012964508 -"[57055247100972084, 97411041131490238, 88049437050618239, 28624004497812491, 66751901520401601]",2842,4,1,40418268224225143,40418264520740681 -"[80129410612599784, 83152019722453770]",1482,0,1,7286711630499487,7286582584842827 -"[96326714879509188, 37150318472078601, 79134390216976776, 60752909349701383, 35545676528189951]",1,2,1,15599990731741671,15536640234327600 -"[72010951167324091, 46352886174585451, 38745205797512237, 991653313080774]",1009,1,2,17799473286977551,17795557440931498 -"[61875212826932831, 72593040558011432, 19011646412279374]",3251,2,1,56205039384725983,56204711457319102 -"[15684112510939275, 96348627053556424]",3255,1,0,6367437054719561,6357124094279745 -"[10577563463353731, 52365820866282587, 29743177535602727, 41464246715654358]",2358,2,1,2125474505652479,2125485704542424 -"[45797231490346310, 19798482141736898]",1559,1,0,17115911409820152,17117702615031928 -"[71563162133678205, 81067597843976089, 70096022688615157, 99605299596835179]",1591,3,1,14585836363953879,14585783933681730 -"[29778208710118849, 64003338911050551, 45683809660143699]",3366,2,1,23470192025837031,23470115661671601 -"[19061029274162701, 88861042867103360]",1838,1,0,10380564887668160,10356328610769880 -"[81787427341393947, 28608408366168903]",3892,0,1,19405170712865413,19391241127797297 -"[5462536427837892, 60313003575039480, 30353510819364908, 80895117588152368, 35609564308819457]",2499,1,2,3096645186275397,3096637399954882 -"[97164432788743194, 9222045657218267, 42669157740877683, 89623221668756758, 13425776184662290]",75,3,4,296290347174338,296144185875546 -"[2525328083241901, 46421200423112829, 49666741712426690, 47352654256329765, 96358952649655268]",2144,1,0,40164958388258,40159395758322 -"[69038980588785024, 79837863579666355]",3973,1,0,43890394893295760,43883134828408922 -"[83515125086460535, 4917642495500753, 87395837591485469]",1862,2,1,2170833162202295,2156365527821558 -"[9994740418341502, 73198573631658376, 56546880956573137, 72102720530614895]",2417,3,1,51015946681524385,51015104737435898 -"[55243677217920709, 77971196695910202, 24757003639492289, 51347097693429737]",2337,2,0,645612721869928,645619377652683 -"[44075484005417502, 99009487706621372, 10206162861896777]",1,0,1,55211367147916370,55174788460612972 -"[77449783951525627, 96622527617405901]",124,1,0,17597919266290529,17564511534571724 -"[31472711499304794, 28537794900047728, 64590509440965888]",2278,1,0,3199818035633924,3199815672426861 -"[85127147804183038, 10907451024955490]",3101,0,1,5172140096670793,5156993162774455 -"[78869112819379136, 65683563674540773, 20450721902044273]",1,0,2,9580067507543145,6681840906321364 -"[76355003527890715, 89423248722724658]",445,0,1,32884188770912793,32874319386910856 -"[58350897179380223, 25320109331183988, 47409765415590316, 45884797510615309, 12771227731243619]",3348,4,3,669497091074848,669498333633530 -"[31629082547321912, 66962487253351599]",984,1,0,23526055061542009,23472331528288205 -"[61339069701175488, 57031595555609106, 27628293955272026]",1959,1,2,12393582463904563,12391970802708548 -"[90723223197964049, 92126516973348926, 25135966310466049, 6468863141559427]",3848,1,3,3502939308201254,3501483276834226 -"[30643815872495940, 99444958907123488, 60753933151148470, 45488579207343040, 36009953155972845]",487,2,3,11864673148291478,11864635854948134 -"[50543316487943597, 40313943101469725]",763,0,1,6352546382595016,6350904205737744 -"[11269790010109139, 65499243416568380, 81108527659964265, 70600446102693155]",114,3,0,10301709506174410,10148535134527868 -"[74554080886007678, 28670405010645704, 85654569480415530, 40968797961996311, 60924679540547467]",245,4,1,13118780250084403,13118494520027400 -"[46737043084360074, 82286149430729857]",2078,0,1,81237921881759889,80892516508534447 -"[8835611916050400, 57628382142431560]",1450,0,1,55989737010935606,55901590251352898 -"[64213443300134140, 64238213023738027]",2293,1,0,49151697148187180,49131920676197744 -"[73853094731189380, 7829335682003209]",2686,1,0,62260051096986523,62266364003095637 -"[5321655983813001, 91317131515757413]",3866,1,0,4160223091286997,4068380917831002 -"[48862501782929970, 55310406286670663, 49464435707234074, 69239111106638847]",1667,3,0,24966900151310959,24966626658169836 -"[30949795165527066, 89836611028918417, 54114214280108296, 51934703618072614]",317,0,1,49248577476488154,49249116887001376 -"[16138777978942730, 91547730741777183]",1443,0,1,12915578092294545,12928501231751342 -"[8218396563534725, 57737575296515419]",3166,0,1,34780030163893337,34786225555935240 -"[20447099011249796, 85406630653105891]",1,1,0,5743132972156642,2840742068206874 -"[91674619594269523, 29729701492058737, 2764287487501530, 10378124496155158]",3685,3,1,15942654438851238,15943004075115926 -"[98644950910472577, 58900491983607430, 36131813150848573]",2043,2,0,93437448520396446,93418264263692998 -"[17900199594434773, 9442670433755745, 27115402511241802, 76251636243027103, 66221708467367021]",2391,2,4,27286261816823239,27286278252910860 -"[99528408031324165, 66063536800192963]",1,0,1,54560755318735428,36277482536949316 -"[53673848541149130, 97714409424635281, 96721723451169947, 58155389654406246]",2326,1,2,60488830579513017,60488441844712628 -"[61976671467845593, 78221250311814832, 4797806429527831]",1273,0,1,40096814654104937,40091787678904902 -"[29132228183822363, 87258711327926155]",1147,0,1,31309221243789011,31317607263211598 -"[88499875721648702, 18532749390880803, 61623274093981801, 48895221084664315]",2461,1,2,24836036948053844,24836210684551946 -"[37918616704488552, 1978275343636407]",1185,1,0,30652228690824828,30682612007314091 -"[39566760046981365, 72165888636327214, 20984355492852881, 69732831981287588, 26644647874223458]",542,0,3,25787314673575233,25787324319619429 -"[33231171828127595, 70031823269237423, 29203587248870731, 46542297859429344]",1,3,1,826924181157457,831903979460410 -"[24168732790973415, 9891884832884577, 95888118345683431, 70447213823396764, 34778290967823452]",3364,2,0,18576443409495213,18576203163745039 -"[43460789793974808, 65358405945975190, 27686557946342977, 3730885400396796]",2477,2,1,52214733323434910,52213910103877138 -"[54867547995683828, 12486378424318257, 86932311741415380, 55718479759640327]",550,1,0,51587976361293124,51580284382596332 -"[95732886232079569, 78704352535502697]",3271,1,0,77725390605163864,77702892480086970 -"[82133674028027480, 62739247902702178]",1,1,0,5361724450167141,5719167931583828 -"[32489426358328931, 36496217877525875, 84851321668505670, 78292922005138858, 791961040552220]",1234,0,1,30737386011478621,30732598969452400 -"[13366363818185899, 30889885647796456, 81467436205101920, 67551454185472331]",742,3,2,29941440958617812,29941207831334242 -"[92918118211171130, 57330341525998584, 75911304280676823, 3890514656626920]",337,0,3,2533367736527389,2501365840465054 -"[76521766164486813, 86354971552504815, 54730979848559086]",1279,1,2,31497989275591945,31493163199716561 -"[49812811743199548, 58186596227649302, 26287660790015157]",933,1,2,8349095818526541,8347329998126068 -"[37933886900413822, 55726202592601111, 46081748926849522]",1786,2,0,12564858311979099,12564332455456866 -"[69867461742160185, 1352814715636538, 7736858741765872, 29311983032987394, 53904387879961111]",3045,3,1,900550488932776,899546826546409 -"[96132482844993548, 20976026519931608, 88455471296293319, 63575262507473881, 15860997286236090]",1,3,4,7634594760238378,7428289578458734 -"[1330441825650699, 35108857365414931]",3682,1,0,35127902021358,34675970003453 -"[10386380277462794, 23652365759781377]",2588,0,1,8543868360422247,8544415115796825 -"[57452763039578501, 25602886812442815, 57161394447653617, 59027345742473696, 28222779128014982]",184,3,0,42555399562147592,42554716657434372 -"[95688279586172992, 81357300020638325]",2875,1,0,44376644563882978,44373443081853912 -"[48086772769243042, 43738509811407018, 95806070340604096, 54383155620608511]",3697,0,3,7745771226916083,7745769878714023 -"[48466550134706494, 62458489539405430, 41001260515711365, 84672518612262309, 66952519627874424]",193,1,0,179130399358799,179129904259862 -"[12467222030895314, 53297354208761319, 9745688825539827, 83158153602115150, 18829217014123659]",3914,1,0,8414326373462587,8414192704810180 -"[87373514757295389, 36776518566996441]",1,0,1,14534609232868448,9396059756397486 -"[20871959848374229, 92008916703325096, 13218142135668071, 89619195637431353, 68632514579833846]",129,4,1,65265537174093928,65263485816100742 -"[98931597104436506, 33132493678017210, 27768934273835381, 92972857848664691, 90429529573619284]",60,4,0,83499627800950500,83491126823768986 -"[86153591584134967, 3499032560766213, 87788771609402210, 95665988072887715]",1756,3,0,18753147219416474,18752788840532866 -"[75038892220520647, 67581506476477568]",3521,1,0,10603995148523590,10603927906542831 -"[71600789539212919, 63529769797209224, 25127151339962766, 70085352502498970, 6565694423980876]",443,0,2,9942752460235186,9942400476625734 -"[19025005827936588, 97753026265519923]",910,0,1,86011328318824956,85981698734805866 -"[72959864838082277, 44748119077116580, 52088565520242482, 6454284556605846, 53320655481448340]",1802,1,0,15221030816245318,15221038933088359 diff --git a/x/spot/types/params.go b/x/spot/types/params.go deleted file mode 100644 index 5028af937..000000000 --- a/x/spot/types/params.go +++ /dev/null @@ -1,98 +0,0 @@ -package types - -import ( - fmt "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "gopkg.in/yaml.v2" - - "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/common/denoms" -) - -var _ paramtypes.ParamSet = (*Params)(nil) - -// ParamKeyTable the param key table for launch module -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// NewParams creates a new Params instance -func NewParams(startingPoolNumber uint64, poolCreationFee sdk.Coins, whitelistedAssets []string) Params { - return Params{ - StartingPoolNumber: startingPoolNumber, - PoolCreationFee: poolCreationFee, - WhitelistedAsset: whitelistedAssets, - } -} - -// DefaultParams returns a default set of parameters -func DefaultParams() Params { - return Params{ - StartingPoolNumber: 1, - PoolCreationFee: sdk.NewCoins(sdk.NewInt64Coin(denoms.NIBI, 1000*common.TO_MICRO)), // 1000 NIBI - WhitelistedAsset: []string{ - denoms.NIBI, - denoms.USDC, - denoms.NUSD, - denoms.USDT, - }, - } -} - -// ParamSetPairs get the params.ParamSet -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair([]byte("StartingPoolNumber"), &p.StartingPoolNumber, validatePoolNumber), - paramtypes.NewParamSetPair([]byte("PoolCreationFee"), &p.PoolCreationFee, validatePoolCreationFee), - paramtypes.NewParamSetPair([]byte("WhitelistedAsset"), &p.WhitelistedAsset, func(value interface{}) error { return nil }), - } -} - -func validatePoolNumber(i interface{}) error { - _, ok := i.(uint64) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - return nil -} - -func validatePoolCreationFee(i interface{}) error { - v, ok := i.(sdk.Coins) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - if v.Validate() != nil { - return fmt.Errorf("invalid pool creation fee: %+v", i) - } - - return nil -} - -// Validate validates the set of params -func (p Params) Validate() error { - if err := validatePoolCreationFee(p.PoolCreationFee); err != nil { - return err - } - - return nil -} - -// String implements the Stringer interface. -func (p Params) String() string { - out, _ := yaml.Marshal(p) - return string(out) -} - -// GetWhitelistedAssetsAsMap returns the whitelisted assets as map, util for -// checking if a value is on the whitelist. -func (p Params) GetWhitelistedAssetsAsMap() map[string]bool { - whitelistedAssets := make(map[string]bool) - for _, a := range p.WhitelistedAsset { - whitelistedAssets[a] = true - } - return whitelistedAssets -} diff --git a/x/spot/types/params.pb.go b/x/spot/types/params.pb.go deleted file mode 100644 index 1327e9702..000000000 --- a/x/spot/types/params.pb.go +++ /dev/null @@ -1,434 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: nibiru/spot/v1/params.proto - -package types - -import ( - fmt "fmt" - _ "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" - 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 - -// Params defines the parameters for the module. -type Params struct { - // The start pool number, i.e. the first pool number that isn't taken yet. - StartingPoolNumber uint64 `protobuf:"varint,1,opt,name=starting_pool_number,json=startingPoolNumber,proto3" json:"starting_pool_number,omitempty"` - // The cost of creating a pool, taken from the pool creator's account. - PoolCreationFee github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=pool_creation_fee,json=poolCreationFee,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"pool_creation_fee" yaml:"pool_creation_fee"` - // The assets that can be used to create liquidity pools - WhitelistedAsset []string `protobuf:"bytes,3,rep,name=whitelisted_asset,json=whitelistedAsset,proto3" json:"whitelisted_asset,omitempty"` -} - -func (m *Params) Reset() { *m = Params{} } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_532c93f2cfe0dc59, []int{0} -} -func (m *Params) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Params.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 *Params) XXX_Merge(src proto.Message) { - xxx_messageInfo_Params.Merge(m, src) -} -func (m *Params) XXX_Size() int { - return m.Size() -} -func (m *Params) XXX_DiscardUnknown() { - xxx_messageInfo_Params.DiscardUnknown(m) -} - -var xxx_messageInfo_Params proto.InternalMessageInfo - -func (m *Params) GetStartingPoolNumber() uint64 { - if m != nil { - return m.StartingPoolNumber - } - return 0 -} - -func (m *Params) GetPoolCreationFee() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.PoolCreationFee - } - return nil -} - -func (m *Params) GetWhitelistedAsset() []string { - if m != nil { - return m.WhitelistedAsset - } - return nil -} - -func init() { - proto.RegisterType((*Params)(nil), "nibiru.spot.v1.Params") -} - -func init() { proto.RegisterFile("nibiru/spot/v1/params.proto", fileDescriptor_532c93f2cfe0dc59) } - -var fileDescriptor_532c93f2cfe0dc59 = []byte{ - // 351 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x64, 0x91, 0x3f, 0x4f, 0xc2, 0x40, - 0x18, 0xc6, 0x5b, 0x20, 0x24, 0xd6, 0x44, 0xa5, 0x61, 0x28, 0x98, 0xb4, 0x84, 0xa9, 0xd1, 0xd8, - 0xb3, 0xba, 0xb1, 0x09, 0xc6, 0xc9, 0x10, 0xc2, 0xe8, 0xd2, 0x5c, 0xcb, 0x59, 0x2e, 0xb6, 0x7d, - 0x9b, 0xde, 0x81, 0x32, 0xfb, 0x05, 0x4c, 0x5c, 0x1c, 0x9d, 0xfd, 0x24, 0x8c, 0x8c, 0x4e, 0x68, - 0xe0, 0x1b, 0xf8, 0x09, 0x4c, 0xef, 0xce, 0x84, 0xc4, 0xe9, 0xfe, 0xfc, 0xde, 0xe7, 0x7d, 0x9f, - 0xbc, 0x8f, 0x71, 0x9c, 0xd1, 0x90, 0x16, 0x33, 0xc4, 0x72, 0xe0, 0x68, 0xee, 0xa3, 0x1c, 0x17, - 0x38, 0x65, 0x5e, 0x5e, 0x00, 0x07, 0xf3, 0x40, 0x42, 0xaf, 0x84, 0xde, 0xdc, 0x6f, 0x37, 0x63, - 0x88, 0x41, 0x20, 0x54, 0xde, 0x64, 0x55, 0xdb, 0x8e, 0x80, 0xa5, 0xc0, 0x50, 0x88, 0x19, 0x41, - 0x73, 0x3f, 0x24, 0x1c, 0xfb, 0x28, 0x02, 0x9a, 0x29, 0xde, 0x92, 0x3c, 0x90, 0x42, 0xf9, 0x90, - 0xa8, 0xfb, 0x5c, 0x31, 0xea, 0x23, 0x31, 0xd1, 0x3c, 0x37, 0x9a, 0x8c, 0xe3, 0x82, 0xd3, 0x2c, - 0x0e, 0x72, 0x80, 0x24, 0xc8, 0x66, 0x69, 0x48, 0x0a, 0x4b, 0xef, 0xe8, 0x6e, 0x6d, 0x6c, 0xfe, - 0xb1, 0x11, 0x40, 0x32, 0x14, 0xc4, 0x7c, 0xd5, 0x8d, 0x86, 0xa8, 0x8c, 0x0a, 0x82, 0x39, 0x85, - 0x2c, 0xb8, 0x27, 0xc4, 0xaa, 0x74, 0xaa, 0xee, 0xfe, 0x45, 0xcb, 0x53, 0x73, 0x4a, 0x53, 0x9e, - 0x32, 0xe5, 0x0d, 0x80, 0x66, 0xfd, 0xdb, 0xe5, 0xda, 0xd1, 0x7e, 0xd6, 0x8e, 0xb5, 0xc0, 0x69, - 0xd2, 0xeb, 0xfe, 0xeb, 0xd0, 0xfd, 0xf8, 0x72, 0xdc, 0x98, 0xf2, 0xe9, 0x2c, 0xf4, 0x22, 0x48, - 0x95, 0x61, 0x75, 0x9c, 0xb1, 0xc9, 0x03, 0xe2, 0x8b, 0x9c, 0x30, 0xd1, 0x8c, 0x8d, 0x0f, 0x4b, - 0xfd, 0x40, 0xc9, 0x6f, 0x08, 0x31, 0x4f, 0x8d, 0xc6, 0xe3, 0x94, 0x72, 0x92, 0x50, 0xc6, 0xc9, - 0x24, 0xc0, 0x8c, 0x11, 0x6e, 0x55, 0x3b, 0x55, 0x77, 0x6f, 0x7c, 0xb4, 0x03, 0xae, 0xca, 0xff, - 0x5e, 0xed, 0xed, 0xdd, 0xd1, 0xfa, 0xd7, 0xcb, 0x8d, 0xad, 0xaf, 0x36, 0xb6, 0xfe, 0xbd, 0xb1, - 0xf5, 0x97, 0xad, 0xad, 0xad, 0xb6, 0xb6, 0xf6, 0xb9, 0xb5, 0xb5, 0xbb, 0x93, 0x1d, 0x1f, 0x43, - 0x91, 0xc5, 0x60, 0x8a, 0x69, 0x86, 0x54, 0x68, 0x4f, 0x32, 0x36, 0xe1, 0x27, 0xac, 0x8b, 0x95, - 0x5e, 0xfe, 0x06, 0x00, 0x00, 0xff, 0xff, 0xe7, 0xf4, 0x89, 0x01, 0xd2, 0x01, 0x00, 0x00, -} - -func (m *Params) 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 *Params) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.WhitelistedAsset) > 0 { - for iNdEx := len(m.WhitelistedAsset) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.WhitelistedAsset[iNdEx]) - copy(dAtA[i:], m.WhitelistedAsset[iNdEx]) - i = encodeVarintParams(dAtA, i, uint64(len(m.WhitelistedAsset[iNdEx]))) - i-- - dAtA[i] = 0x1a - } - } - if len(m.PoolCreationFee) > 0 { - for iNdEx := len(m.PoolCreationFee) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PoolCreationFee[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParams(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if m.StartingPoolNumber != 0 { - i = encodeVarintParams(dAtA, i, uint64(m.StartingPoolNumber)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintParams(dAtA []byte, offset int, v uint64) int { - offset -= sovParams(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.StartingPoolNumber != 0 { - n += 1 + sovParams(uint64(m.StartingPoolNumber)) - } - if len(m.PoolCreationFee) > 0 { - for _, e := range m.PoolCreationFee { - l = e.Size() - n += 1 + l + sovParams(uint64(l)) - } - } - if len(m.WhitelistedAsset) > 0 { - for _, s := range m.WhitelistedAsset { - l = len(s) - n += 1 + l + sovParams(uint64(l)) - } - } - return n -} - -func sovParams(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozParams(x uint64) (n int) { - return sovParams(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Params) 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 ErrIntOverflowParams - } - 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: Params: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field StartingPoolNumber", wireType) - } - m.StartingPoolNumber = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.StartingPoolNumber |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolCreationFee", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParams - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PoolCreationFee = append(m.PoolCreationFee, types.Coin{}) - if err := m.PoolCreationFee[len(m.PoolCreationFee)-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 WhitelistedAsset", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParams - } - 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 ErrInvalidLengthParams - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthParams - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.WhitelistedAsset = append(m.WhitelistedAsset, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParams(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParams - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipParams(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, ErrIntOverflowParams - } - 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, ErrIntOverflowParams - } - 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, ErrIntOverflowParams - } - 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, ErrInvalidLengthParams - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParams - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParams - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParams = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParams = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParams = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/spot/types/pool.go b/x/spot/types/pool.go deleted file mode 100644 index 7144ec620..000000000 --- a/x/spot/types/pool.go +++ /dev/null @@ -1,504 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "math" - - sdkmath "cosmossdk.io/math" - - "github.com/holiman/uint256" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -/* -Returns the *base* denomination of a pool share token for a given poolId. - -args: - - poolId: the pool id number - -ret: - - poolDenom: the pool denomination name of the poolId -*/ -func GetPoolShareBaseDenom(poolId uint64) (poolDenom string) { - return fmt.Sprintf("nibiru/pool/%d", poolId) -} - -/* -Returns the *display* denomination of a pool share token for a given poolId. -Display denom means the denomination showed to the user, which could be many exponents greater than the base denom. -e.g. 1 atom is the display denom, but 10^6 uatom is the base denom. - -In Nibiru, a display denom is 10^18 base denoms. - -args: - - poolId: the pool id number - -ret: - - poolDenom: the pool denomination name of the poolId -*/ -func GetPoolShareDisplayDenom(poolId uint64) (poolDenom string) { - return fmt.Sprintf("NIBIRU-POOL-%d", poolId) -} - -/* -Creates a new pool and sets the initial assets. - -args: - - poolId: the pool numeric id - poolAccountAddr: the pool's account address for holding funds - poolParams: pool configuration options - poolAssets: the initial pool assets and weights - -ret: - - pool: a new pool - err: error if any -*/ -func NewPool( - poolId uint64, - poolAccountAddr sdk.Address, - poolParams PoolParams, - poolAssets []PoolAsset, -) (pool Pool, err error) { - pool = Pool{ - Id: poolId, - Address: poolAccountAddr.String(), - PoolParams: poolParams, - PoolAssets: nil, - TotalWeight: sdk.ZeroInt(), - TotalShares: sdk.NewCoin(GetPoolShareBaseDenom(poolId), InitPoolSharesSupply), - } - - err = pool.setInitialPoolAssets(poolAssets) - if err != nil { - return Pool{}, err - } - - return pool, nil -} - -/* -Ensure the denoms of the tokens in are assets of the pool - -args: - - - tokensIn: the tokens to check - -ret: - - - ok: true if all the denom from tokens in tokens in are in the pool -*/ -func (pool Pool) AreTokensInDenomInPoolAssets(tokensIn sdk.Coins) bool { - for _, asset := range tokensIn { - _, _, err := pool.getPoolAssetAndIndex(asset.Denom) - if err != nil { - return false - } - } - return true -} - -/* -AddTokensToPool Adds tokens to a pool and updates the pool balances (i.e. liquidity). - -args: - - tokensIn: the tokens to add to the pool - -ret: - - numShares: the number of LP shares given to the user for the deposit - - remCoins: the number of coins remaining after the deposit - - err: error if any -*/ -func (pool *Pool) AddTokensToPool(tokensIn sdk.Coins) ( - numShares sdkmath.Int, remCoins sdk.Coins, err error, -) { - if pool.TotalShares.Amount.IsZero() { - // Mint the initial 100.000000000000000000 pool share tokens to the sender - numShares = InitPoolSharesSupply - remCoins = sdk.Coins{} - } else if pool.PoolParams.PoolType == PoolType_STABLESWAP { - numShares, err = pool.numSharesOutFromTokensInStableSwap(tokensIn) - remCoins = sdk.Coins{} - } else { - numShares, remCoins, err = pool.numSharesOutFromTokensIn(tokensIn) - } - if err != nil { - return sdk.ZeroInt(), sdk.Coins{}, err - } - - tokensIn.Sort() - if err := pool.incrementBalances(numShares, tokensIn.Sub(remCoins...)); err != nil { - return sdk.ZeroInt(), sdk.Coins{}, err - } - - return numShares, remCoins, nil -} - -/* -AddAllTokensToPool Adds tokens to a pool optimizing the amount of shares (swap + join) and updates the pool balances (i.e. liquidity). -We maximally join with both tokens first, and then perform a single asset join with the remaining assets. - -This function is only necessary for balancer pool. Stableswap pool already takes all the deposit from the user. - -args: - - tokensIn: the tokens to add to the pool - -ret: - - numShares: the number of LP shares given to the user for the deposit - - remCoins: the number of coins remaining after the deposit - - err: error if any -*/ -func (pool *Pool) AddAllTokensToPool(tokensIn sdk.Coins) ( - numShares sdkmath.Int, remCoins sdk.Coins, err error, -) { - if pool.PoolParams.PoolType == PoolType_STABLESWAP { - err = ErrInvalidPoolType - return - } - - remCoins = tokensIn - if tokensIn.Len() > 1 { - numShares, remCoins, err = pool.AddTokensToPool(tokensIn) - } else { - numShares = sdk.ZeroInt() - } - - if remCoins.Empty() { - return - } - - numShares2nd, _, err := pool.AddTokensToPool(remCoins) - if err != nil { - return - } - - numShares = numShares2nd.Add(numShares) - remCoins = sdk.NewCoins() - return -} - -/* -GetAddress Fetch the pool's address as an sdk.Address. -*/ -func (pool Pool) GetAddress() (addr sdk.AccAddress) { - addr, err := sdk.AccAddressFromBech32(pool.Address) - if err != nil { - panic(fmt.Sprintf("could not bech32 decode address of pool with id: %d", pool.Id)) - } - return addr -} - -/* -ExitPool Given the amount of pool shares to exit, calculates the amount of coins to exit -from the pool and modifies the pool. Accounts for an exit fee, if any, on the pool. - -args: - - exitingShares: the number of pool shares to exit from the pool -*/ -func (pool *Pool) ExitPool(exitingShares sdkmath.Int) ( - exitedCoins sdk.Coins, fees sdk.Coins, err error, -) { - if exitingShares.GT(pool.TotalShares.Amount) { - return sdk.Coins{}, sdk.Coins{}, errors.New("too many shares out") - } - - exitedCoins, fees, err = pool.TokensOutFromPoolSharesIn(exitingShares) - if err != nil { - return sdk.Coins{}, sdk.Coins{}, err - } - - if !exitedCoins.IsValid() { - minShares := pool.MinSharesInForTokensOut() - return sdk.Coins{}, sdk.Coins{}, fmt.Errorf("not enough pool shares to withdraw - please provide at least %v shares", minShares) - } - - // update the pool's balances - for _, exitedCoin := range exitedCoins { - err = pool.SubtractPoolAssetBalance(exitedCoin.Denom, exitedCoin.Amount) - if err != nil { - return sdk.Coins{}, sdk.Coins{}, err - } - } - - pool.TotalShares = sdk.NewCoin(pool.TotalShares.Denom, pool.TotalShares.Amount.Sub(exitingShares)) - return exitedCoins, fees, nil -} - -/* -Updates the pool's asset liquidity using the provided tokens. - -args: - - tokens: the new token liquidity in the pool - -ret: - - err: error if any -*/ -func (pool *Pool) updatePoolAssetBalances(tokens ...sdk.Coin) (err error) { - // Ensures that there are no duplicate denoms, all denom's are valid, - // and amount is > 0 - for _, coin := range tokens { - if coin.Amount.LT(sdk.ZeroInt()) { - return fmt.Errorf("provided coins are invalid, %v", tokens) - } - assetIndex, existingAsset, err := pool.getPoolAssetAndIndex(coin.Denom) - if err != nil { - return err - } - existingAsset.Token = coin - pool.PoolAssets[assetIndex].Token = coin - } - - return nil -} - -// setInitialPoolAssets sets the PoolAssets in the pool. -// It is only designed to be called at the pool's creation. -// If the same denom's PoolAsset exists, will return error. -// The list of PoolAssets must be sorted. This is done to enable fast searching for a PoolAsset by denomination. -func (pool *Pool) setInitialPoolAssets(poolAssets []PoolAsset) (err error) { - exists := make(map[string]bool) - - newTotalWeight := sdk.ZeroInt() - scaledPoolAssets := make([]PoolAsset, 0, len(poolAssets)) - - for _, asset := range poolAssets { - if err = asset.Validate(); err != nil { - return err - } - - if exists[asset.Token.Denom] { - return fmt.Errorf("same PoolAsset already exists") - } - exists[asset.Token.Denom] = true - - // Scale weight from the user provided weight to the correct internal weight - asset.Weight = asset.Weight.MulRaw(GuaranteedWeightPrecision) - scaledPoolAssets = append(scaledPoolAssets, asset) - newTotalWeight = newTotalWeight.Add(asset.Weight) - } - - pool.PoolAssets = scaledPoolAssets - sortPoolAssetsByDenom(pool.PoolAssets) - - pool.TotalWeight = newTotalWeight - - return nil -} - -// For a stableswap pool, compute the D invariant value in non-overflowing integer operations iteratively -// A * sum(x_i) * n**n + D = A * D * n**n + D**(n+1) / (n**n * prod(x_i)) -// Converging solution: -// D[j+1] = (A * n**n * sum(x_i) - D[j]**(n+1) / (n**n prod(x_i))) / (A * n**n - 1) -func (pool Pool) GetD(poolAssets []PoolAsset) (*uint256.Int, error) { - nCoins := uint256.NewInt(uint64(len(poolAssets))) - - S := new(uint256.Int) - - Amp := uint256.NewInt(uint64(pool.PoolParams.A.Int64())) - - Ann := new(uint256.Int) - - nCoinsFloat := float64(len(poolAssets)) - Ann.Mul(Amp, uint256.NewInt(uint64(math.Pow(nCoinsFloat, nCoinsFloat)))) - - var poolAssetsTokens []*uint256.Int - for _, token := range poolAssets { - if token.Token.Amount.IsZero() { - // Pool is borked and one asset is missing. Users can only withdraw funds. - return new(uint256.Int), ErrBorkedPool - } - amount := uint256.NewInt(token.Token.Amount.Uint64()) - poolAssetsTokens = append(poolAssetsTokens, amount) - S.Add(S, amount) - } - - D := new(uint256.Int).Set(S) - - for i := 0; i < 255; i++ { - D_P := new(uint256.Int).Set(D) - for _, token := range poolAssetsTokens { - // We ensure before that token is always != 0 - D_P.Div( - new(uint256.Int).Mul(D_P, D), - new(uint256.Int).Mul(token, nCoins), - ) - } - previousD := new(uint256.Int).Set(D) - - // D = (Ann * S + D_P * N_COINS) * D / ((Ann - 1) * D + (N_COINS + 1) * D_P) - num := new(uint256.Int).Mul( - new(uint256.Int).Add( - new(uint256.Int).Mul(Ann, S), - new(uint256.Int).Mul(D_P, nCoins), - ), - D, - ) - denom := new(uint256.Int).Add( - new(uint256.Int).Mul( - new(uint256.Int).Add( - nCoins, - uint256.NewInt(1), - ), - D_P, - ), - new(uint256.Int).Mul( - new(uint256.Int).Sub(Ann, uint256.NewInt(1)), - D, - ), - ) - - // D = (Ann * S + D_P * N_COINS) * D / ((Ann - 1) * D + (N_COINS + 1) * D_P) - absDifference := new(uint256.Int) - D.Div(num, denom) - - absDifference.Abs(new(uint256.Int).Sub(D, previousD)) - if absDifference.Lt(uint256.NewInt(2)) { // absDifference LTE 1 -> absDifference LT 2 - break - } - } - - return D, nil -} - -// getA returns the amplification factor of the pool -func (pool Pool) getA() (Amp *uint256.Int) { - Amp = uint256.NewInt(uint64(pool.PoolParams.A.Int64())) - return -} - -// Search for the i and j indices for a swap like x[j] if one makes x[i] = x -func (pool Pool) getIJforSwap(denomIn, denomOut string) (i int, j int, err error) { - i, _, err = pool.getPoolAssetAndIndex(denomIn) - if err != nil { - return - } - - j, _, err = pool.getPoolAssetAndIndex(denomOut) - if err != nil { - return - } - - return i, j, nil -} - -func MustSdkIntToUint256(num sdkmath.Int) *uint256.Int { - return uint256.NewInt(uint64(num.Int64())) -} - -// Calculate the amount of token out -func (pool Pool) Exchange(tokenIn sdk.Coin, tokenOutDenom string) (dy sdkmath.Int, err error) { - _, poolAssetIn, err := pool.getPoolAssetAndIndex(tokenIn.Denom) - if err != nil { - return - } - _, poolAssetOut, err := pool.getPoolAssetAndIndex(tokenOutDenom) - if err != nil { - return - } - - dx := poolAssetIn.Token.Add(tokenIn) - - yAmount, err := pool.SolveStableswapInvariant(dx, tokenOutDenom) - if err != nil { - return - } - - y := sdk.NewCoin(tokenOutDenom, yAmount) - dy = poolAssetOut.Token.Sub(y).Amount - return -} - -// Calculate y if one makes x = tokenIn -// Done by solving quadratic equation iteratively. -// x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n+1)/(n ** (2 * n) * prod' * A) -// x_1**2 + b*x_1 = c -// x_1 = (x_1**2 + c) / (2*x_1 + b - D) -func (pool Pool) SolveStableswapInvariant(tokenIn sdk.Coin, tokenOutDenom string) (yAmount sdkmath.Int, err error) { - A := pool.getA() - D, err := pool.GetD(pool.PoolAssets) - if err != nil { - return - } - - Ann := new(uint256.Int) - nCoins := uint256.NewInt(uint64(len(pool.PoolAssets))) - - nCoinsFloat := float64(len(pool.PoolAssets)) - Ann.Mul(A, uint256.NewInt(uint64(math.Pow(nCoinsFloat, nCoinsFloat)))) - - c := new(uint256.Int).Set(D) - S := new(uint256.Int) - var _x *uint256.Int - - i, j, err := pool.getIJforSwap(tokenIn.Denom, tokenOutDenom) - if err != nil { - return - } - - for _i := 0; _i < len(pool.PoolAssets); _i++ { - if _i == i { - _x = MustSdkIntToUint256(tokenIn.Amount) - } else if _i != j { - _x = MustSdkIntToUint256(pool.PoolAssets[_i].Token.Amount) - } else { - continue - } - - S.Add(S, _x) - - c.Div( - new(uint256.Int).Mul(c, D), - new(uint256.Int).Mul(_x, nCoins), - ) - } - - // c = c * D * A_PRECISION / (Ann * N_COINS) - c.Div( - new(uint256.Int).Mul(c, D), - new(uint256.Int).Mul(Ann, nCoins), - ) - - // b = S + D / Ann - b := new(uint256.Int).Add( - S, - new(uint256.Int).Div( - D, - Ann, - ), - ) - - y := new(uint256.Int).Set(D) - y_prev := new(uint256.Int) - - for _i := 0; _i < 255; _i++ { - y_prev.Set(y) - - y.Div( - new(uint256.Int).Add(new(uint256.Int).Mul(y, y), c), - new(uint256.Int).Sub( - new(uint256.Int).Add( - new(uint256.Int).Mul(uint256.NewInt(2), - y, - ), - b, - ), - D, - ), - ) - - absDifference := new(uint256.Int) - absDifference.Abs(new(uint256.Int).Sub(y, y_prev)) - if absDifference.Lt(uint256.NewInt(2)) { // LTE 1 - break - } - } - - return sdk.NewIntFromUint64(y.Uint64()), nil -} diff --git a/x/spot/types/pool.pb.go b/x/spot/types/pool.pb.go deleted file mode 100644 index d921d1738..000000000 --- a/x/spot/types/pool.pb.go +++ /dev/null @@ -1,1123 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: nibiru/spot/v1/pool.proto - -package types - -import ( - fmt "fmt" - _ "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" - 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 - -// - `balancer`: Balancer are pools defined by the equation xy=k, extended by -// the weighs introduced by Balancer. -// - `stableswap`: Stableswap pools are defined by a combination of -// constant-product and constant-sum pool -type PoolType int32 - -const ( - PoolType_BALANCER PoolType = 0 - PoolType_STABLESWAP PoolType = 1 -) - -var PoolType_name = map[int32]string{ - 0: "BALANCER", - 1: "STABLESWAP", -} - -var PoolType_value = map[string]int32{ - "BALANCER": 0, - "STABLESWAP": 1, -} - -func (x PoolType) String() string { - return proto.EnumName(PoolType_name, int32(x)) -} - -func (PoolType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_cf0eee5bfc2c3a2b, []int{0} -} - -// Configuration parameters for the pool. -type PoolParams struct { - SwapFee github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=swap_fee,json=swapFee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"swap_fee" yaml:"swap_fee"` - ExitFee github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=exit_fee,json=exitFee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"exit_fee" yaml:"exit_fee"` - // Amplification Parameter (A): Larger value of A make the curve better - // resemble a straight line in the center (when pool is near balance). Highly - // volatile assets should use a lower value, while assets that are closer - // together may be best with a higher value. This is only used if the - // pool_type is set to 1 (stableswap) - A github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=A,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"A" yaml:"amplification"` - PoolType PoolType `protobuf:"varint,4,opt,name=pool_type,json=poolType,proto3,enum=nibiru.spot.v1.PoolType" json:"pool_type,omitempty" yaml:"pool_type"` -} - -func (m *PoolParams) Reset() { *m = PoolParams{} } -func (m *PoolParams) String() string { return proto.CompactTextString(m) } -func (*PoolParams) ProtoMessage() {} -func (*PoolParams) Descriptor() ([]byte, []int) { - return fileDescriptor_cf0eee5bfc2c3a2b, []int{0} -} -func (m *PoolParams) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PoolParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PoolParams.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 *PoolParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_PoolParams.Merge(m, src) -} -func (m *PoolParams) XXX_Size() int { - return m.Size() -} -func (m *PoolParams) XXX_DiscardUnknown() { - xxx_messageInfo_PoolParams.DiscardUnknown(m) -} - -var xxx_messageInfo_PoolParams proto.InternalMessageInfo - -func (m *PoolParams) GetPoolType() PoolType { - if m != nil { - return m.PoolType - } - return PoolType_BALANCER -} - -// Which assets the pool contains. -type PoolAsset struct { - // Coins we are talking about, - // the denomination must be unique amongst all PoolAssets for this pool. - Token types.Coin `protobuf:"bytes,1,opt,name=token,proto3" json:"token" yaml:"token"` - // Weight that is not normalized. This weight must be less than 2^50 - Weight github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=weight,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"weight" yaml:"weight"` -} - -func (m *PoolAsset) Reset() { *m = PoolAsset{} } -func (m *PoolAsset) String() string { return proto.CompactTextString(m) } -func (*PoolAsset) ProtoMessage() {} -func (*PoolAsset) Descriptor() ([]byte, []int) { - return fileDescriptor_cf0eee5bfc2c3a2b, []int{1} -} -func (m *PoolAsset) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PoolAsset) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PoolAsset.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 *PoolAsset) XXX_Merge(src proto.Message) { - xxx_messageInfo_PoolAsset.Merge(m, src) -} -func (m *PoolAsset) XXX_Size() int { - return m.Size() -} -func (m *PoolAsset) XXX_DiscardUnknown() { - xxx_messageInfo_PoolAsset.DiscardUnknown(m) -} - -var xxx_messageInfo_PoolAsset proto.InternalMessageInfo - -func (m *PoolAsset) GetToken() types.Coin { - if m != nil { - return m.Token - } - return types.Coin{} -} - -type Pool struct { - // The pool id. - Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` - // The pool account address. - Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty" yaml:"address"` - // Fees and other pool-specific parameters. - PoolParams PoolParams `protobuf:"bytes,3,opt,name=pool_params,json=poolParams,proto3" json:"pool_params" yaml:"pool_params"` - // These are assumed to be sorted by denomiation. - // They contain the pool asset and the information about the weight - PoolAssets []PoolAsset `protobuf:"bytes,4,rep,name=pool_assets,json=poolAssets,proto3" json:"pool_assets" yaml:"pool_assets"` - // sum of all non-normalized pool weights - TotalWeight github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,5,opt,name=total_weight,json=totalWeight,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"total_weight" yaml:"total_weight"` - // sum of all LP tokens sent out - TotalShares types.Coin `protobuf:"bytes,6,opt,name=total_shares,json=totalShares,proto3" json:"total_shares" yaml:"total_shares"` -} - -func (m *Pool) Reset() { *m = Pool{} } -func (m *Pool) String() string { return proto.CompactTextString(m) } -func (*Pool) ProtoMessage() {} -func (*Pool) Descriptor() ([]byte, []int) { - return fileDescriptor_cf0eee5bfc2c3a2b, []int{2} -} -func (m *Pool) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Pool) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Pool.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 *Pool) XXX_Merge(src proto.Message) { - xxx_messageInfo_Pool.Merge(m, src) -} -func (m *Pool) XXX_Size() int { - return m.Size() -} -func (m *Pool) XXX_DiscardUnknown() { - xxx_messageInfo_Pool.DiscardUnknown(m) -} - -var xxx_messageInfo_Pool proto.InternalMessageInfo - -func init() { - proto.RegisterEnum("nibiru.spot.v1.PoolType", PoolType_name, PoolType_value) - proto.RegisterType((*PoolParams)(nil), "nibiru.spot.v1.PoolParams") - proto.RegisterType((*PoolAsset)(nil), "nibiru.spot.v1.PoolAsset") - proto.RegisterType((*Pool)(nil), "nibiru.spot.v1.Pool") -} - -func init() { proto.RegisterFile("nibiru/spot/v1/pool.proto", fileDescriptor_cf0eee5bfc2c3a2b) } - -var fileDescriptor_cf0eee5bfc2c3a2b = []byte{ - // 620 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x94, 0xcd, 0x6a, 0xdb, 0x40, - 0x10, 0xc7, 0x25, 0xc7, 0x49, 0x9c, 0x75, 0xea, 0x86, 0xad, 0x0f, 0x8a, 0x0b, 0x52, 0xd8, 0x43, - 0x09, 0xa1, 0x95, 0x70, 0x7a, 0xcb, 0xa5, 0x48, 0x89, 0x03, 0xa5, 0x21, 0x04, 0x25, 0xd4, 0xb4, - 0x14, 0xcc, 0xda, 0xde, 0xd8, 0x4b, 0x6c, 0xad, 0xf0, 0x6e, 0x3e, 0xfc, 0x06, 0x3d, 0xf6, 0x11, - 0x7a, 0xef, 0x4b, 0xf4, 0x98, 0x63, 0x8e, 0xa5, 0x07, 0x51, 0xec, 0x63, 0x6f, 0x7e, 0x82, 0xb2, - 0x1f, 0x6a, 0x12, 0x30, 0x14, 0xd3, 0x93, 0x76, 0xf8, 0xcf, 0xfc, 0xb4, 0xf3, 0x9f, 0x61, 0xc1, - 0x66, 0x42, 0xdb, 0x74, 0x74, 0x19, 0xf0, 0x94, 0x89, 0xe0, 0xaa, 0x1e, 0xa4, 0x8c, 0x0d, 0xfc, - 0x74, 0xc4, 0x04, 0x83, 0x15, 0x2d, 0xf9, 0x52, 0xf2, 0xaf, 0xea, 0xb5, 0x6a, 0x8f, 0xf5, 0x98, - 0x92, 0x02, 0x79, 0xd2, 0x59, 0x35, 0xb7, 0xc3, 0xf8, 0x90, 0xf1, 0xa0, 0x8d, 0x39, 0x09, 0xae, - 0xea, 0x6d, 0x22, 0x70, 0x3d, 0xe8, 0x30, 0x9a, 0x18, 0x7d, 0x53, 0xeb, 0x2d, 0x5d, 0xa8, 0x03, - 0x2d, 0xa1, 0xdf, 0x05, 0x00, 0x4e, 0x18, 0x1b, 0x9c, 0xe0, 0x11, 0x1e, 0x72, 0xf8, 0x09, 0x94, - 0xf8, 0x35, 0x4e, 0x5b, 0xe7, 0x84, 0x38, 0xf6, 0x96, 0xbd, 0xbd, 0x16, 0x85, 0xb7, 0x99, 0x67, - 0xfd, 0xcc, 0xbc, 0x17, 0x3d, 0x2a, 0xfa, 0x97, 0x6d, 0xbf, 0xc3, 0x86, 0x86, 0x60, 0x3e, 0xaf, - 0x78, 0xf7, 0x22, 0x10, 0xe3, 0x94, 0x70, 0xff, 0x80, 0x74, 0x66, 0x99, 0xf7, 0x74, 0x8c, 0x87, - 0x83, 0x3d, 0x94, 0x73, 0x50, 0xbc, 0x2a, 0x8f, 0x87, 0x84, 0x48, 0x3a, 0xb9, 0xa1, 0x42, 0xd1, - 0x0b, 0xff, 0x47, 0xcf, 0x39, 0x28, 0x5e, 0x95, 0x47, 0x49, 0x3f, 0x03, 0x76, 0xe8, 0x2c, 0x29, - 0xec, 0xe1, 0x02, 0xd8, 0xb7, 0x89, 0x98, 0x65, 0x5e, 0x55, 0x63, 0xf1, 0x30, 0x1d, 0xd0, 0x73, - 0xda, 0xc1, 0x82, 0xb2, 0x04, 0xc5, 0x76, 0x08, 0xdf, 0x81, 0x35, 0x39, 0x8f, 0x96, 0x4c, 0x76, - 0x8a, 0x5b, 0xf6, 0x76, 0x65, 0xd7, 0xf1, 0x1f, 0x4f, 0xc5, 0x97, 0x06, 0x9e, 0x8d, 0x53, 0x12, - 0x55, 0x67, 0x99, 0xb7, 0xa1, 0x49, 0x7f, 0x8b, 0x50, 0x5c, 0x4a, 0x8d, 0x8e, 0xbe, 0xd9, 0x60, - 0x4d, 0x26, 0x87, 0x9c, 0x13, 0x01, 0x1b, 0x60, 0x59, 0xb0, 0x0b, 0x92, 0x28, 0xa7, 0xcb, 0xbb, - 0x9b, 0xbe, 0x99, 0x8c, 0x1c, 0xa3, 0x6f, 0xc6, 0xe8, 0xef, 0x33, 0x9a, 0x44, 0x55, 0xd9, 0xcf, - 0x2c, 0xf3, 0xd6, 0x35, 0x5b, 0x55, 0xa1, 0x58, 0x57, 0xc3, 0x26, 0x58, 0xb9, 0x26, 0xb4, 0xd7, - 0x17, 0xc6, 0xd3, 0x37, 0x0b, 0x37, 0xff, 0x44, 0x63, 0x35, 0x05, 0xc5, 0x06, 0x87, 0xbe, 0x2f, - 0x81, 0xa2, 0xbc, 0x2d, 0xac, 0x80, 0x02, 0xed, 0xaa, 0x5b, 0x16, 0xe3, 0x02, 0xed, 0xc2, 0x97, - 0x60, 0x15, 0x77, 0xbb, 0x23, 0xc2, 0xb9, 0xf9, 0x25, 0x9c, 0x65, 0x5e, 0xc5, 0x38, 0xa8, 0x05, - 0x14, 0xe7, 0x29, 0xb0, 0x09, 0xca, 0xca, 0x8c, 0x54, 0xad, 0x98, 0x9a, 0x50, 0x79, 0xb7, 0x36, - 0xcf, 0x43, 0xbd, 0x84, 0x51, 0xcd, 0x74, 0x0b, 0x1f, 0x38, 0xa9, 0x8b, 0x51, 0x0c, 0xd2, 0xfb, - 0x65, 0x7d, 0x6f, 0xc0, 0x58, 0xba, 0xc9, 0x9d, 0xe2, 0xd6, 0x92, 0x72, 0x71, 0x0e, 0x58, 0xf9, - 0x3d, 0x97, 0xab, 0x6b, 0x0d, 0x57, 0xa5, 0x71, 0xd8, 0x07, 0xeb, 0x82, 0x09, 0x3c, 0x68, 0x19, - 0x5b, 0x97, 0x55, 0x8f, 0x8d, 0x85, 0x6d, 0x7d, 0x96, 0x4f, 0xeb, 0x9e, 0x85, 0xe2, 0xb2, 0x0a, - 0x9b, 0x2a, 0x82, 0x1f, 0xf2, 0x3f, 0xf1, 0x3e, 0x1e, 0x11, 0xee, 0xac, 0xfc, 0x6b, 0x11, 0x9e, - 0x9b, 0x16, 0x1e, 0xa1, 0x75, 0x71, 0x8e, 0x3e, 0x55, 0xd1, 0x5e, 0xf1, 0xf3, 0x57, 0xcf, 0xda, - 0xd9, 0x06, 0xa5, 0x7c, 0x39, 0xe1, 0x3a, 0x28, 0x45, 0xe1, 0x51, 0x78, 0xbc, 0xdf, 0x88, 0x37, - 0x2c, 0x58, 0x01, 0xe0, 0xf4, 0x2c, 0x8c, 0x8e, 0x1a, 0xa7, 0xcd, 0xf0, 0x64, 0xc3, 0x8e, 0x0e, - 0x6e, 0x27, 0xae, 0x7d, 0x37, 0x71, 0xed, 0x5f, 0x13, 0xd7, 0xfe, 0x32, 0x75, 0xad, 0xbb, 0xa9, - 0x6b, 0xfd, 0x98, 0xba, 0xd6, 0xc7, 0x9d, 0x07, 0x0d, 0x1f, 0x2b, 0x6f, 0xf7, 0xfb, 0x98, 0x26, - 0x81, 0x79, 0xb5, 0x6e, 0xf4, 0xbb, 0xa5, 0x1a, 0x6f, 0xaf, 0xa8, 0x57, 0xe5, 0xf5, 0x9f, 0x00, - 0x00, 0x00, 0xff, 0xff, 0x0e, 0x8e, 0x88, 0xaa, 0xd3, 0x04, 0x00, 0x00, -} - -func (m *PoolParams) 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 *PoolParams) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PoolParams) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.PoolType != 0 { - i = encodeVarintPool(dAtA, i, uint64(m.PoolType)) - i-- - dAtA[i] = 0x20 - } - { - size := m.A.Size() - i -= size - if _, err := m.A.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintPool(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.ExitFee.Size() - i -= size - if _, err := m.ExitFee.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintPool(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.SwapFee.Size() - i -= size - if _, err := m.SwapFee.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintPool(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *PoolAsset) 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 *PoolAsset) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PoolAsset) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Weight.Size() - i -= size - if _, err := m.Weight.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintPool(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.Token.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintPool(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *Pool) 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 *Pool) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Pool) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.TotalShares.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintPool(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size := m.TotalWeight.Size() - i -= size - if _, err := m.TotalWeight.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintPool(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - if len(m.PoolAssets) > 0 { - for iNdEx := len(m.PoolAssets) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PoolAssets[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintPool(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - { - size, err := m.PoolParams.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintPool(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintPool(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0x12 - } - if m.Id != 0 { - i = encodeVarintPool(dAtA, i, uint64(m.Id)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintPool(dAtA []byte, offset int, v uint64) int { - offset -= sovPool(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *PoolParams) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.SwapFee.Size() - n += 1 + l + sovPool(uint64(l)) - l = m.ExitFee.Size() - n += 1 + l + sovPool(uint64(l)) - l = m.A.Size() - n += 1 + l + sovPool(uint64(l)) - if m.PoolType != 0 { - n += 1 + sovPool(uint64(m.PoolType)) - } - return n -} - -func (m *PoolAsset) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Token.Size() - n += 1 + l + sovPool(uint64(l)) - l = m.Weight.Size() - n += 1 + l + sovPool(uint64(l)) - return n -} - -func (m *Pool) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Id != 0 { - n += 1 + sovPool(uint64(m.Id)) - } - l = len(m.Address) - if l > 0 { - n += 1 + l + sovPool(uint64(l)) - } - l = m.PoolParams.Size() - n += 1 + l + sovPool(uint64(l)) - if len(m.PoolAssets) > 0 { - for _, e := range m.PoolAssets { - l = e.Size() - n += 1 + l + sovPool(uint64(l)) - } - } - l = m.TotalWeight.Size() - n += 1 + l + sovPool(uint64(l)) - l = m.TotalShares.Size() - n += 1 + l + sovPool(uint64(l)) - return n -} - -func sovPool(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozPool(x uint64) (n int) { - return sovPool(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *PoolParams) 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 ErrIntOverflowPool - } - 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: PoolParams: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PoolParams: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SwapFee", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPool - } - 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 ErrInvalidLengthPool - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthPool - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SwapFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExitFee", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPool - } - 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 ErrInvalidLengthPool - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthPool - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExitFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field A", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPool - } - 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 ErrInvalidLengthPool - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthPool - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.A.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolType", wireType) - } - m.PoolType = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPool - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolType |= PoolType(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipPool(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthPool - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PoolAsset) 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 ErrIntOverflowPool - } - 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: PoolAsset: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PoolAsset: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Token", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPool - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthPool - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthPool - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Token.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Weight", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPool - } - 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 ErrInvalidLengthPool - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthPool - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Weight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipPool(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthPool - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Pool) 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 ErrIntOverflowPool - } - 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: Pool: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Pool: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - m.Id = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPool - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Id |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - 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 ErrIntOverflowPool - } - 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 ErrInvalidLengthPool - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthPool - } - 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 PoolParams", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPool - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthPool - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthPool - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.PoolParams.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolAssets", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPool - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthPool - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthPool - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PoolAssets = append(m.PoolAssets, PoolAsset{}) - if err := m.PoolAssets[len(m.PoolAssets)-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 TotalWeight", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPool - } - 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 ErrInvalidLengthPool - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthPool - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalWeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalShares", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPool - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthPool - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthPool - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TotalShares.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipPool(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthPool - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipPool(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, ErrIntOverflowPool - } - 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, ErrIntOverflowPool - } - 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, ErrIntOverflowPool - } - 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, ErrInvalidLengthPool - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupPool - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthPool - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthPool = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowPool = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupPool = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/spot/types/pool_asset.go b/x/spot/types/pool_asset.go deleted file mode 100644 index d81673cda..000000000 --- a/x/spot/types/pool_asset.go +++ /dev/null @@ -1,50 +0,0 @@ -package types - -import ( - "errors" - fmt "fmt" - - sdkmath "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// Validates a PoolAsset amount and weights. -func (poolAsset PoolAsset) Validate() error { - if poolAsset.Token.Amount.LTE(sdk.ZeroInt()) { - return fmt.Errorf("can't add the zero or negative balance of token") - } - - if poolAsset.Weight.LTE(sdk.ZeroInt()) { - return fmt.Errorf("a token's weight in the pool must be greater than 0") - } - - if poolAsset.Weight.GTE(MaxUserSpecifiedWeight.MulRaw(GuaranteedWeightPrecision)) { - return fmt.Errorf("a token's weight in the pool must be less than 1^50") - } - - return nil -} - -/* -Subtracts an amount of coins from a pool's assets. -Throws an error if the final amount is less than zero. -*/ -func (pool *Pool) SubtractPoolAssetBalance(assetDenom string, subAmt sdkmath.Int) (err error) { - if subAmt.LT(sdk.ZeroInt()) { - return errors.New("can't subtract a negative amount") - } - - index, poolAsset, err := pool.getPoolAssetAndIndex(assetDenom) - if err != nil { - return err - } - - // Update the supply of the asset - poolAsset.Token.Amount = poolAsset.Token.Amount.Sub(subAmt) - if poolAsset.Token.Amount.LT(sdk.ZeroInt()) { - return errors.New("can't set the pool's balance of a token to be zero or negative") - } - pool.PoolAssets[index] = poolAsset - return nil -} diff --git a/x/spot/types/pool_asset_test.go b/x/spot/types/pool_asset_test.go deleted file mode 100644 index 780656d21..000000000 --- a/x/spot/types/pool_asset_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package types - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common" -) - -func TestPoolAssetValidateError(t *testing.T) { - tests := []struct { - name string - pa PoolAsset - errMsg string - }{ - { - name: "coin amount too little", - pa: PoolAsset{ - Token: sdk.NewInt64Coin("foo", 0), - Weight: sdk.OneInt(), - }, - errMsg: "can't add the zero or negative balance of token", - }, - { - name: "weight too little", - pa: PoolAsset{ - Token: sdk.NewInt64Coin("foo", 1), - Weight: sdk.ZeroInt(), - }, - errMsg: "can't add the zero or negative balance of token", - }, - { - name: "weight too high", - pa: PoolAsset{ - Token: sdk.NewInt64Coin("foo", 1), - Weight: sdk.NewInt(1 << 50), - }, - errMsg: "a token's weight in the pool must be less than 1^50", - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - require.Errorf(t, tc.pa.Validate(), tc.errMsg) - }) - } -} - -func TestPoolAssetValidateSuccess(t *testing.T) { - tests := []struct { - name string - pa PoolAsset - }{ - { - name: "successful validation", - pa: PoolAsset{ - Token: sdk.NewInt64Coin("foo", 1), - Weight: sdk.OneInt(), - }, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - require.NoError(t, tc.pa.Validate()) - }) - } -} - -func TestSubtractPoolAssetBalance(t *testing.T) { - for _, tc := range []struct { - name string - pool Pool - tokenDenom string - subAmt sdkmath.Int - expectedCoins sdk.Coins - }{ - { - name: "subtract liquidity", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1*common.TO_MICRO), - }, - }, - }, - tokenDenom: "aaa", - subAmt: sdk.NewInt(1_000), - expectedCoins: sdk.NewCoins(sdk.NewInt64Coin("aaa", 999_000)), - }, - { - name: "subtract all liquidity", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1*common.TO_MICRO), - }, - }, - }, - tokenDenom: "aaa", - subAmt: sdk.NewInt(1 * common.TO_MICRO), - expectedCoins: sdk.NewCoins(), - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - require.NoError(t, tc.pool.SubtractPoolAssetBalance(tc.tokenDenom, tc.subAmt)) - actualCoins := tc.pool.PoolBalances() - require.Equal(t, tc.expectedCoins, actualCoins) - }) - } -} diff --git a/x/spot/types/pool_test.go b/x/spot/types/pool_test.go deleted file mode 100644 index a8b54b3e0..000000000 --- a/x/spot/types/pool_test.go +++ /dev/null @@ -1,987 +0,0 @@ -package types - -import ( - "encoding/csv" - "encoding/json" - fmt "fmt" - "log" - "os" - "strconv" - "testing" - - sdkmath "cosmossdk.io/math" - - "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/common/testutil" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestGetPoolShareBaseDenom(t *testing.T) { - require.Equal(t, "nibiru/pool/123", GetPoolShareBaseDenom(123)) -} - -func TestGetPoolShareDisplayDenom(t *testing.T) { - require.Equal(t, "NIBIRU-POOL-123", GetPoolShareDisplayDenom(123)) -} - -func TestGetAddress(t *testing.T) { - tests := []struct { - name string - pool Pool - expectPanic bool - }{ - { - name: "empty address", - pool: Pool{ - Address: "", - }, - expectPanic: true, - }, - { - name: "invalid address", - pool: Pool{ - Address: "asdf", - }, - expectPanic: true, - }, - { - name: "valid address", - pool: Pool{ - Address: testutil.AccAddress().String(), - }, - expectPanic: false, - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - if tc.expectPanic { - require.Panics(t, func() { - tc.pool.GetAddress() - }) - } else { - require.NotPanics(t, func() { - tc.pool.GetAddress() - }) - } - }) - } -} - -func TestMinSharesInForTokensOut(t *testing.T) { - poolAccountAddr := testutil.AccAddress() - poolParams := PoolParams{ - PoolType: PoolType_BALANCER, - SwapFee: sdk.NewDecWithPrec(3, 2), - ExitFee: sdk.NewDecWithPrec(3, 2), - } - poolAssets := []PoolAsset{ - { - Token: sdk.NewInt64Coin("foo", 123124124124), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bar", 13224112312124124), - Weight: sdk.OneInt(), - }, - } - - pool, err := NewPool(1 /*=poold*/, poolAccountAddr, poolParams, poolAssets) - require.NoError(t, err) - - tokenOut, _, err := pool.TokensOutFromPoolSharesIn(pool.MinSharesInForTokensOut()) - require.NoError(t, err) - require.True(t, tokenOut.IsValid()) -} - -func TestNewPool(t *testing.T) { - poolAccountAddr := testutil.AccAddress() - poolParams := PoolParams{ - PoolType: PoolType_BALANCER, - SwapFee: sdk.NewDecWithPrec(3, 2), - ExitFee: sdk.NewDecWithPrec(3, 2), - } - poolAssets := []PoolAsset{ - { - Token: sdk.NewInt64Coin("foo", 100), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.OneInt(), - }, - } - - pool, err := NewPool(1 /*=poold*/, poolAccountAddr, poolParams, poolAssets) - require.NoError(t, err) - require.Equal(t, Pool{ - Id: 1, - Address: poolAccountAddr.String(), - PoolParams: poolParams, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.NewInt(1 << 30), - }, - { - Token: sdk.NewInt64Coin("foo", 100), - Weight: sdk.NewInt(1 << 30), - }, - }, - TotalWeight: sdk.NewInt(2 << 30), - TotalShares: sdk.NewCoin("nibiru/pool/1", sdkmath.NewIntWithDecimal(100, 18)), - }, pool) -} - -func TestJoinPoolHappyPath(t *testing.T) { - for _, tc := range []struct { - name string - pool Pool - tokensIn sdk.Coins - expectedNumShares sdkmath.Int - expectedRemCoins sdk.Coins - expectedPool Pool - }{ - { - name: "all coins deposited", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - PoolParams: PoolParams{A: sdk.NewInt(100), PoolType: PoolType_BALANCER}, - }, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 10), - sdk.NewInt64Coin("bbb", 20), - ), - expectedNumShares: sdk.NewInt(10), - expectedRemCoins: sdk.NewCoins(), - expectedPool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 110), - }, - { - Token: sdk.NewInt64Coin("bbb", 220), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 110), - PoolParams: PoolParams{A: sdk.NewInt(100), PoolType: PoolType_BALANCER}, - }, - }, - { - name: "all coins deposited - stableswap", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - PoolParams: PoolParams{A: sdk.NewInt(100), PoolType: PoolType_STABLESWAP}, - }, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 10), - sdk.NewInt64Coin("bbb", 20), - ), - expectedNumShares: sdk.NewInt(10), - expectedRemCoins: sdk.NewCoins(), - expectedPool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 110), - }, - { - Token: sdk.NewInt64Coin("bbb", 220), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 110), - PoolParams: PoolParams{A: sdk.NewInt(100), PoolType: PoolType_STABLESWAP}, - }, - }, - { - name: "partial coins deposited", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - PoolParams: PoolParams{A: sdk.NewInt(100), PoolType: PoolType_BALANCER}, - }, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 10), - sdk.NewInt64Coin("bbb", 10), - ), - expectedNumShares: sdk.NewInt(5), - expectedRemCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 5), - ), - expectedPool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 105), - }, - { - Token: sdk.NewInt64Coin("bbb", 210), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 105), - PoolParams: PoolParams{A: sdk.NewInt(100), PoolType: PoolType_BALANCER}, - }, - }, - { - name: "difficult numbers", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 3_498_579), - }, - { - Token: sdk.NewInt64Coin("bbb", 1_403_945), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 1*common.TO_MICRO), - PoolParams: PoolParams{A: sdk.NewInt(100), PoolType: PoolType_BALANCER}, - }, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 4859), // 0.138885 % of pool - sdk.NewInt64Coin("bbb", 1345), // 0.09580147 % of pool - ), - expectedNumShares: sdk.NewInt(958), - expectedRemCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 1507), - ), - expectedPool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 3_501_931), - }, - { - Token: sdk.NewInt64Coin("bbb", 1_405_290), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 1_000_958), - PoolParams: PoolParams{A: sdk.NewInt(100), PoolType: PoolType_BALANCER}, - }, - }, - { - name: "difficult numbers ~ stableswap", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 3_498_579), - }, - { - Token: sdk.NewInt64Coin("bbb", 1_403_945), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 1*common.TO_MICRO), - PoolParams: PoolParams{A: sdk.NewInt(100), PoolType: PoolType_STABLESWAP}, - }, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 4859), // 0.138885 % of pool - sdk.NewInt64Coin("bbb", 1345), // 0.09580147 % of pool - ), - expectedRemCoins: sdk.NewCoins(), - expectedNumShares: sdk.NewInt(1264), - expectedPool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 3_503_438), - }, - { - Token: sdk.NewInt64Coin("bbb", 1_405_290), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 1_001_264), - PoolParams: PoolParams{A: sdk.NewInt(100), PoolType: PoolType_STABLESWAP}, - }, - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - numShares, remCoins, err := tc.pool.AddTokensToPool(tc.tokensIn) - require.NoError(t, err) - require.Equal(t, tc.expectedNumShares.String(), numShares.String()) - require.Equal(t, tc.expectedRemCoins.String(), remCoins.String()) - require.Equal(t, tc.expectedPool.String(), tc.pool.String()) - }) - } -} - -func TestJoinPoolAllTokens(t *testing.T) { - for _, tc := range []struct { - name string - pool Pool - tokensIn sdk.Coins - expectedNumShares sdkmath.Int - expectedRemCoins sdk.Coins - expectedPool Pool - }{ - { - name: "all coins deposited", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - Weight: sdk.NewInt(1 << 30), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - Weight: sdk.NewInt(1 << 30), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - TotalWeight: sdk.NewInt(2 << 30), - PoolParams: PoolParams{PoolType: PoolType_BALANCER, SwapFee: sdk.ZeroDec()}, - }, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 10), - sdk.NewInt64Coin("bbb", 20), - ), - expectedNumShares: sdk.NewInt(10), - expectedRemCoins: sdk.NewCoins(), - expectedPool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 110), - Weight: sdk.NewInt(1 << 30), - }, - { - Token: sdk.NewInt64Coin("bbb", 220), - Weight: sdk.NewInt(1 << 30), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 110), - TotalWeight: sdk.NewInt(2 << 30), - PoolParams: PoolParams{PoolType: PoolType_BALANCER, SwapFee: sdk.ZeroDec()}, - }, - }, - { - name: "partial coins deposited", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - Weight: sdk.NewInt(1 << 30), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - Weight: sdk.NewInt(1 << 30), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - TotalWeight: sdk.NewInt(2 << 30), - PoolParams: PoolParams{PoolType: PoolType_BALANCER, SwapFee: sdk.ZeroDec()}, - }, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 10), - sdk.NewInt64Coin("bbb", 10), - ), - expectedNumShares: sdk.NewInt(7), - expectedRemCoins: sdk.NewCoins(), - expectedPool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 110), - Weight: sdk.NewInt(1 << 30), - }, - { - Token: sdk.NewInt64Coin("bbb", 210), - Weight: sdk.NewInt(1 << 30), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 107), - TotalWeight: sdk.NewInt(2 << 30), - PoolParams: PoolParams{PoolType: PoolType_BALANCER, SwapFee: sdk.ZeroDec()}, - }, - }, - { - name: "difficult numbers", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 3_498_579), - Weight: sdk.NewInt(1 << 30), - }, - { - Token: sdk.NewInt64Coin("bbb", 1_403_945), - Weight: sdk.NewInt(1 << 30), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 1*common.TO_MICRO), - TotalWeight: sdk.NewInt(2 << 30), - PoolParams: PoolParams{PoolType: PoolType_BALANCER, SwapFee: sdk.ZeroDec()}, - }, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 4_859), // 0.138885 % of pool - sdk.NewInt64Coin("bbb", 1_345), // 0.09580147 % of pool - ), - expectedNumShares: sdk.NewInt(1173), - expectedRemCoins: sdk.NewCoins(), - expectedPool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 3_503_438), - Weight: sdk.NewInt(1 << 30), - }, - { - Token: sdk.NewInt64Coin("bbb", 1_405_290), - Weight: sdk.NewInt(1 << 30), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 1_001_173), - TotalWeight: sdk.NewInt(2 << 30), - PoolParams: PoolParams{PoolType: PoolType_BALANCER, SwapFee: sdk.ZeroDec()}, - }, - }, - { - name: "difficult numbers - single asset join", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 3_498_579), - Weight: sdk.NewInt(1 << 30), - }, - { - Token: sdk.NewInt64Coin("bbb", 1_403_945), - Weight: sdk.NewInt(1 << 30), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 1*common.TO_MICRO), - TotalWeight: sdk.NewInt(2 << 30), - PoolParams: PoolParams{PoolType: PoolType_BALANCER, SwapFee: sdk.ZeroDec()}, - }, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 4_859), // 0.138885 % of pool - ), - expectedNumShares: sdk.NewInt(694), - expectedRemCoins: sdk.NewCoins(), - expectedPool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 3_503_438), - Weight: sdk.NewInt(1 << 30), - }, - { - Token: sdk.NewInt64Coin("bbb", 1_403_945), - Weight: sdk.NewInt(1 << 30), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 1_000_694), - TotalWeight: sdk.NewInt(2 << 30), - PoolParams: PoolParams{PoolType: PoolType_BALANCER, SwapFee: sdk.ZeroDec()}, - }, - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - numShares, remCoins, err := tc.pool.AddAllTokensToPool(tc.tokensIn) - require.NoError(t, err) - require.Equal(t, tc.expectedNumShares, numShares) - require.Equal(t, tc.expectedRemCoins, remCoins) - require.Equal(t, tc.expectedPool, tc.pool) - }) - } -} - -func TestExitPoolError(t *testing.T) { - for _, tc := range []struct { - name string - pool Pool - exitingShares sdk.Coin - expectedCoins sdk.Coins - expectedRemainingShares sdk.Coin - expectedExitedCoins sdk.Coins - }{ - { - name: "all coins withdrawn, no exit fee", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1000000), - }, - { - Token: sdk.NewInt64Coin("bbb", 2000000), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 10000000000000), - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - ExitFee: sdk.ZeroDec(), - }, - }, - exitingShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - expectedRemainingShares: sdk.NewInt64Coin("nibiru/pool/1", 0), - expectedCoins: nil, - expectedExitedCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 100), - sdk.NewInt64Coin("bbb", 200), - ), - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - _, _, err := tc.pool.ExitPool(sdk.OneInt()) - require.Error(t, err) - expectedErrorMsg := fmt.Sprintf("not enough pool shares to withdraw - please provide at least %v shares", tc.pool.MinSharesInForTokensOut()) - require.Contains(t, err.Error(), expectedErrorMsg) - - _, _, err = tc.pool.ExitPool(tc.pool.MinSharesInForTokensOut()) - require.NoError(t, err) - }) - } -} - -func TestExitPoolHappyPath(t *testing.T) { - for _, tc := range []struct { - name string - pool Pool - exitingShares sdk.Coin - expectedCoins sdk.Coins - expectedRemainingShares sdk.Coin - expectedExitedCoins sdk.Coins - expectedFees sdk.Coins - }{ - { - name: "all coins withdrawn, no exit fee", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - ExitFee: sdk.ZeroDec(), - }, - }, - exitingShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - expectedRemainingShares: sdk.NewInt64Coin("nibiru/pool/1", 0), - expectedCoins: sdk.NewCoins(), - expectedExitedCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 100), - sdk.NewInt64Coin("bbb", 200), - ), - expectedFees: sdk.NewCoins( - sdk.NewCoin("aaa", sdk.ZeroInt()), - sdk.NewCoin("bbb", sdk.ZeroInt()), - ), - }, - { - name: "all coins withdrawn, exit fee", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - ExitFee: sdk.MustNewDecFromStr("0.5"), - }, - }, - exitingShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - expectedRemainingShares: sdk.NewInt64Coin("nibiru/pool/1", 0), - expectedCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 50), - sdk.NewInt64Coin("bbb", 100), - ), - expectedExitedCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 50), - sdk.NewInt64Coin("bbb", 100), - ), - expectedFees: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 50), - sdk.NewInt64Coin("bbb", 100), - ), - }, - { - name: "some coins withdrawn, no exit fee", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - ExitFee: sdk.ZeroDec(), - }, - }, - exitingShares: sdk.NewInt64Coin("nibiru/pool/1", 50), - expectedRemainingShares: sdk.NewInt64Coin("nibiru/pool/1", 50), - expectedCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 50), - sdk.NewInt64Coin("bbb", 100), - ), - expectedExitedCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 50), - sdk.NewInt64Coin("bbb", 100), - ), - expectedFees: sdk.NewCoins( - sdk.NewCoin("aaa", sdk.ZeroInt()), - sdk.NewCoin("bbb", sdk.ZeroInt()), - ), - }, - { - name: "some coins withdrawn, exit fee", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - ExitFee: sdk.MustNewDecFromStr("0.5"), - }, - }, - exitingShares: sdk.NewInt64Coin("nibiru/pool/1", 50), - expectedRemainingShares: sdk.NewInt64Coin("nibiru/pool/1", 50), - expectedCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 75), - sdk.NewInt64Coin("bbb", 150), - ), - expectedExitedCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 25), - sdk.NewInt64Coin("bbb", 50), - ), - expectedFees: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 25), - sdk.NewInt64Coin("bbb", 50), - ), - }, - { - name: "real numbers", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 34_586_245), - }, - { - Token: sdk.NewInt64Coin("bbb", 65_469_884), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 2_347_652), - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - ExitFee: sdk.MustNewDecFromStr("0.003"), - }, - }, - exitingShares: sdk.NewInt64Coin("nibiru/pool/1", 74_747), - expectedRemainingShares: sdk.NewInt64Coin("nibiru/pool/1", 2_272_905), - expectedCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 33_488_356), - sdk.NewInt64Coin("bbb", 63_391_639), - ), - expectedExitedCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 1_097_889), - sdk.NewInt64Coin("bbb", 2_078_245), - ), - expectedFees: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 3304), - sdk.NewInt64Coin("bbb", 6253), - ), - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - exitedCoins, fees, err := tc.pool.ExitPool(tc.exitingShares.Amount) - require.NoError(t, err) - require.Equal(t, tc.expectedCoins, tc.pool.PoolBalances()) - // Comparing zero initialized sdk.Int with zero value sdk.Int leads to different results - if tc.expectedRemainingShares.IsZero() { - require.True(t, tc.pool.TotalShares.IsZero()) - } else { - require.Equal(t, tc.expectedRemainingShares, tc.pool.TotalShares) - } - require.Equal(t, tc.expectedExitedCoins, exitedCoins) - require.Equal(t, tc.expectedFees, fees) - }) - } -} - -// helper function to create dummy test pools -func MockPool(assets []PoolAsset) Pool { - return Pool{ - Id: 1, - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - SwapFee: sdk.SmallestDec(), - ExitFee: sdk.SmallestDec(), - }, - PoolAssets: assets, - TotalShares: sdk.NewInt64Coin(GetPoolShareBaseDenom(1), 100), - TotalWeight: sdk.NewInt(2), - } -} - -func TestUpdatePoolAssetTokens(t *testing.T) { - for _, tc := range []struct { - name string - poolAssets []PoolAsset - newAssets []sdk.Coin - expectedPoolAssets []PoolAsset - }{ - { - name: "update pool asset balances", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - }, - }, - newAssets: []sdk.Coin{ - sdk.NewInt64Coin("aaa", 150), - sdk.NewInt64Coin("bbb", 125), - }, - expectedPoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 150), - }, - { - Token: sdk.NewInt64Coin("bbb", 125), - }, - }, - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - pool := MockPool(tc.poolAssets) - require.NoError(t, pool.updatePoolAssetBalances(tc.newAssets...)) - require.Equal(t, tc.expectedPoolAssets, pool.PoolAssets) - }) - } -} - -func TestGetD(t *testing.T) { - for _, tc := range []struct { - name string - poolAssets []PoolAsset - amplificationParameter sdkmath.Int - expectedErr error - expectedD uint64 - }{ - { - name: "Compute D - 3 assets - tested against Curve contracts code..", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 200), - }, - { - Token: sdk.NewInt64Coin("bbb", 100), - }, - { - Token: sdk.NewInt64Coin("ccc", 100), - }, - }, - amplificationParameter: sdk.OneInt(), - expectedErr: nil, - expectedD: 397, - }, - { - name: "Compute D - 2 assets - tested against Curve contracts code..", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 200), - }, - { - Token: sdk.NewInt64Coin("bbb", 100), - }, - }, - amplificationParameter: sdk.OneInt(), - expectedErr: nil, - expectedD: 294, - }, - { - name: "Compute D - 2 assets, A big - tested against Curve contracts code..", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 200), - }, - { - Token: sdk.NewInt64Coin("bbb", 100), - }, - }, - amplificationParameter: sdk.NewInt(4000), - expectedErr: nil, - expectedD: 299, - }, - { - name: "Compute D - 2 assets, A big, high values - tested against Curve contracts code..", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 200*common.TO_MICRO), - }, - { - Token: sdk.NewInt64Coin("bbb", 100*common.TO_MICRO), - }, - }, - amplificationParameter: sdk.NewInt(4000), - expectedErr: nil, - expectedD: 299997656, - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - pool := Pool{ - PoolAssets: tc.poolAssets, - PoolParams: PoolParams{A: tc.amplificationParameter}, - } - - D, err := pool.GetD(pool.PoolAssets) - require.NoError(t, err) - require.EqualValues(t, fmt.Sprint(tc.expectedD), fmt.Sprint(D.Uint64())) - }) - } -} - -type TestCaseDy struct { - balance []uint64 - amplification sdkmath.Int - send int - receive int - dx sdkmath.Int - expectedDy sdkmath.Int -} - -/* -createTestCases reads the data from the csv file generated with the python curve model and load them into a TestCaseDy -object. - -Columns schema of the file: - - balances: the balance of the pool - - amplification: the amplification parameter for the pool - - send: the id of the token sent to the pool for the swap - - recv: the id of the token expected out of the pool - - dx: the number of token sent for the swap - - dy: the expected number of token from the curve python model. -*/ -func createTestCases(data [][]string) (testCases []TestCaseDy, err error) { - for i, line := range data { - if i > 0 { // omit header line - var rec TestCaseDy - - err := json.Unmarshal([]byte(line[0]), &rec.balance) - if err != nil { - return testCases, err - } - - amplification, err := strconv.ParseInt(line[1], 10, 64) - if err != nil { - return testCases, err - } - - rec.amplification = sdk.NewInt(amplification) - - rec.send, _ = strconv.Atoi(line[2]) - rec.receive, _ = strconv.Atoi(line[3]) - - dx, err := strconv.ParseInt(line[4], 10, 64) - if err != nil { - return testCases, err - } - - expectedDy, err := strconv.ParseInt(line[5], 10, 64) - if err != nil { - return testCases, err - } - - rec.dx = sdk.NewInt(dx) - rec.expectedDy = sdk.NewInt(expectedDy) - - testCases = append(testCases, rec) - } - } - return testCases, nil -} - -func TestSolveStableswapInvariant(t *testing.T) { - t.Run("Test csv file", func(t *testing.T) { - f, err := os.Open("misc/stabletests.csv") - if err != nil { - log.Fatal(err) - } - defer f.Close() - - // read csv values using csv.Reader - csvReader := csv.NewReader(f) - data, err := csvReader.ReadAll() - if err != nil { - log.Fatal(err) - } - - testCases, err := createTestCases(data) - if err != nil { - log.Fatal(err) - } - - for _, tc := range testCases { - tc := tc - - var poolAssets []PoolAsset - - for i, balance := range tc.balance { - poolAssets = append(poolAssets, PoolAsset{Token: sdk.NewCoin("token"+strconv.Itoa(i), sdk.NewIntFromUint64(balance))}) - } - - pool := Pool{ - PoolAssets: poolAssets, - PoolParams: PoolParams{A: tc.amplification}, - } - denomIn := "token" + strconv.Itoa(tc.send) - denomOut := "token" + strconv.Itoa(tc.receive) - - _, poolAssetIn, err := pool.getPoolAssetAndIndex(denomIn) - require.NoError(t, err) - - dy, err := pool.SolveStableswapInvariant( - /* tokenIn = */ sdk.NewCoin(denomIn, tc.dx).Add(poolAssetIn.Token), - /* tokenOutDenom = */ denomOut, - ) - require.NoError(t, err) - - _, poolAssetOut, err := pool.getPoolAssetAndIndex(denomOut) - require.NoError(t, err) - - require.NoError(t, err) - require.Equal(t, tc.expectedDy, poolAssetOut.Token.Amount.Sub(dy)) - } - }) -} diff --git a/x/spot/types/price.go b/x/spot/types/price.go deleted file mode 100644 index e07cbcab5..000000000 --- a/x/spot/types/price.go +++ /dev/null @@ -1,22 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -// CalcSpotPrice calculates the spot price based on weight. -// spotPrice = (BalanceIn / WeightIn) / (BalanceOut / WeightOut) -func (pool Pool) CalcSpotPrice(tokenIn, tokenOut string) (sdk.Dec, error) { - _, poolAssetIn, err := pool.getPoolAssetAndIndex(tokenIn) - if err != nil { - return sdk.Dec{}, err - } - - _, poolAssetOut, err := pool.getPoolAssetAndIndex(tokenOut) - if err != nil { - return sdk.Dec{}, err - } - - weightedBalanceIn := sdk.NewDecFromInt(poolAssetIn.Token.Amount).Quo(sdk.NewDecFromInt(poolAssetIn.Weight)) - weightedBalanceOut := sdk.NewDecFromInt(poolAssetOut.Token.Amount).Quo(sdk.NewDecFromInt(poolAssetOut.Weight)) - - return weightedBalanceIn.Quo(weightedBalanceOut), nil -} diff --git a/x/spot/types/price_test.go b/x/spot/types/price_test.go deleted file mode 100644 index f64d20a7f..000000000 --- a/x/spot/types/price_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package types - -import ( - "testing" - - "github.com/NibiruChain/nibiru/x/common" - "github.com/NibiruChain/nibiru/x/common/testutil" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestCalSpotPrice(t *testing.T) { - tests := []struct { - name string - poolAssets []PoolAsset - expectedPrice sdk.Dec - }{ - { - "equal weight: 2 tokens", - []PoolAsset{ - { - Token: sdk.NewInt64Coin("foo", 2*common.TO_MICRO), - Weight: sdk.NewInt(100), - }, - { - Token: sdk.NewInt64Coin("bar", 1*common.TO_MICRO), - Weight: sdk.NewInt(100), - }, - }, - sdk.MustNewDecFromStr("2"), - }, - { - "different weight: 2 tokens", - []PoolAsset{ - { - Token: sdk.NewInt64Coin("foo", 2*common.TO_MICRO), - Weight: sdk.NewInt(80), - }, - { - Token: sdk.NewInt64Coin("bar", 1*common.TO_MICRO), - Weight: sdk.NewInt(20), - }, - }, - sdk.MustNewDecFromStr("0.5"), - }, - { - "equal weight: 3 tokens", - []PoolAsset{ - { - Token: sdk.NewInt64Coin("foo", 2*common.TO_MICRO), - Weight: sdk.NewInt(100), - }, - { - Token: sdk.NewInt64Coin("goo", 1*common.TO_MICRO), - Weight: sdk.NewInt(100), - }, - { - Token: sdk.NewInt64Coin("bar", 1*common.TO_MICRO), - Weight: sdk.NewInt(100), - }, - }, - sdk.MustNewDecFromStr("2"), - }, - { - "different weight: 3 tokens", - []PoolAsset{ - { - Token: sdk.NewInt64Coin("foo", 2*common.TO_MICRO), - Weight: sdk.NewInt(60), - }, - { - Token: sdk.NewInt64Coin("bar", 1*common.TO_MICRO), - Weight: sdk.NewInt(20), - }, - { - Token: sdk.NewInt64Coin("foobar", 1*common.TO_MICRO), - Weight: sdk.NewInt(20), - }, - }, - sdk.MustNewDecFromStr("0.666666666666666667"), - }, - } - - for _, tc := range tests { - tc := tc - t.Run(tc.name, func(t *testing.T) { - poolAccountAddr := testutil.AccAddress() - poolParams := PoolParams{ - SwapFee: sdk.NewDecWithPrec(3, 2), - ExitFee: sdk.NewDecWithPrec(3, 2), - PoolType: PoolType_BALANCER, - } - - pool, err := NewPool(1, poolAccountAddr, poolParams, tc.poolAssets) - require.NoError(t, err) - - actualPrice, err := pool.CalcSpotPrice(tc.poolAssets[0].Token.Denom, tc.poolAssets[1].Token.Denom) - require.NoError(t, err) - - require.Equal(t, tc.expectedPrice, actualPrice) - }) - } -} diff --git a/x/spot/types/query.pb.go b/x/spot/types/query.pb.go deleted file mode 100644 index e7e5041ce..000000000 --- a/x/spot/types/query.pb.go +++ /dev/null @@ -1,6584 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: nibiru/spot/v1/query.proto - -package types - -import ( - context "context" - fmt "fmt" - 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 - -// QueryParamsRequest is request type for the Query/Params RPC method. -type QueryParamsRequest struct { -} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{0} -} -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.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 *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse is response type for the Query/Params RPC method. -type QueryParamsResponse struct { - // params holds all the parameters of this module. - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{1} -} -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.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 *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -func (m *QueryParamsResponse) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -type QueryPoolNumberRequest struct { -} - -func (m *QueryPoolNumberRequest) Reset() { *m = QueryPoolNumberRequest{} } -func (m *QueryPoolNumberRequest) String() string { return proto.CompactTextString(m) } -func (*QueryPoolNumberRequest) ProtoMessage() {} -func (*QueryPoolNumberRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{2} -} -func (m *QueryPoolNumberRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPoolNumberRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPoolNumberRequest.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 *QueryPoolNumberRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPoolNumberRequest.Merge(m, src) -} -func (m *QueryPoolNumberRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryPoolNumberRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPoolNumberRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPoolNumberRequest proto.InternalMessageInfo - -type QueryPoolNumberResponse struct { - PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` -} - -func (m *QueryPoolNumberResponse) Reset() { *m = QueryPoolNumberResponse{} } -func (m *QueryPoolNumberResponse) String() string { return proto.CompactTextString(m) } -func (*QueryPoolNumberResponse) ProtoMessage() {} -func (*QueryPoolNumberResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{3} -} -func (m *QueryPoolNumberResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPoolNumberResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPoolNumberResponse.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 *QueryPoolNumberResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPoolNumberResponse.Merge(m, src) -} -func (m *QueryPoolNumberResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryPoolNumberResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPoolNumberResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPoolNumberResponse proto.InternalMessageInfo - -func (m *QueryPoolNumberResponse) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -type QueryPoolRequest struct { - PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` -} - -func (m *QueryPoolRequest) Reset() { *m = QueryPoolRequest{} } -func (m *QueryPoolRequest) String() string { return proto.CompactTextString(m) } -func (*QueryPoolRequest) ProtoMessage() {} -func (*QueryPoolRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{4} -} -func (m *QueryPoolRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPoolRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPoolRequest.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 *QueryPoolRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPoolRequest.Merge(m, src) -} -func (m *QueryPoolRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryPoolRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPoolRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPoolRequest proto.InternalMessageInfo - -func (m *QueryPoolRequest) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -type QueryPoolResponse struct { - Pool *Pool `protobuf:"bytes,1,opt,name=pool,proto3" json:"pool,omitempty"` -} - -func (m *QueryPoolResponse) Reset() { *m = QueryPoolResponse{} } -func (m *QueryPoolResponse) String() string { return proto.CompactTextString(m) } -func (*QueryPoolResponse) ProtoMessage() {} -func (*QueryPoolResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{5} -} -func (m *QueryPoolResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPoolResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPoolResponse.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 *QueryPoolResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPoolResponse.Merge(m, src) -} -func (m *QueryPoolResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryPoolResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPoolResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPoolResponse proto.InternalMessageInfo - -func (m *QueryPoolResponse) GetPool() *Pool { - if m != nil { - return m.Pool - } - return nil -} - -type QueryPoolsRequest struct { - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryPoolsRequest) Reset() { *m = QueryPoolsRequest{} } -func (m *QueryPoolsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryPoolsRequest) ProtoMessage() {} -func (*QueryPoolsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{6} -} -func (m *QueryPoolsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPoolsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPoolsRequest.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 *QueryPoolsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPoolsRequest.Merge(m, src) -} -func (m *QueryPoolsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryPoolsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPoolsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPoolsRequest proto.InternalMessageInfo - -func (m *QueryPoolsRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -type QueryPoolsResponse struct { - Pools []*Pool `protobuf:"bytes,1,rep,name=pools,proto3" json:"pools,omitempty"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryPoolsResponse) Reset() { *m = QueryPoolsResponse{} } -func (m *QueryPoolsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryPoolsResponse) ProtoMessage() {} -func (*QueryPoolsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{7} -} -func (m *QueryPoolsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPoolsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPoolsResponse.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 *QueryPoolsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPoolsResponse.Merge(m, src) -} -func (m *QueryPoolsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryPoolsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPoolsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPoolsResponse proto.InternalMessageInfo - -func (m *QueryPoolsResponse) GetPools() []*Pool { - if m != nil { - return m.Pools - } - return nil -} - -func (m *QueryPoolsResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -type QueryPoolParamsRequest struct { - PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` -} - -func (m *QueryPoolParamsRequest) Reset() { *m = QueryPoolParamsRequest{} } -func (m *QueryPoolParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryPoolParamsRequest) ProtoMessage() {} -func (*QueryPoolParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{8} -} -func (m *QueryPoolParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPoolParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPoolParamsRequest.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 *QueryPoolParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPoolParamsRequest.Merge(m, src) -} -func (m *QueryPoolParamsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryPoolParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPoolParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPoolParamsRequest proto.InternalMessageInfo - -func (m *QueryPoolParamsRequest) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -type QueryPoolParamsResponse struct { - PoolParams *PoolParams `protobuf:"bytes,1,opt,name=pool_params,json=poolParams,proto3" json:"pool_params,omitempty"` -} - -func (m *QueryPoolParamsResponse) Reset() { *m = QueryPoolParamsResponse{} } -func (m *QueryPoolParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryPoolParamsResponse) ProtoMessage() {} -func (*QueryPoolParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{9} -} -func (m *QueryPoolParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryPoolParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPoolParamsResponse.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 *QueryPoolParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPoolParamsResponse.Merge(m, src) -} -func (m *QueryPoolParamsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryPoolParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPoolParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPoolParamsResponse proto.InternalMessageInfo - -func (m *QueryPoolParamsResponse) GetPoolParams() *PoolParams { - if m != nil { - return m.PoolParams - } - return nil -} - -type QueryNumPoolsRequest struct { -} - -func (m *QueryNumPoolsRequest) Reset() { *m = QueryNumPoolsRequest{} } -func (m *QueryNumPoolsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryNumPoolsRequest) ProtoMessage() {} -func (*QueryNumPoolsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{10} -} -func (m *QueryNumPoolsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryNumPoolsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryNumPoolsRequest.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 *QueryNumPoolsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryNumPoolsRequest.Merge(m, src) -} -func (m *QueryNumPoolsRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryNumPoolsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryNumPoolsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryNumPoolsRequest proto.InternalMessageInfo - -type QueryNumPoolsResponse struct { - NumPools uint64 `protobuf:"varint,1,opt,name=num_pools,json=numPools,proto3" json:"num_pools,omitempty"` -} - -func (m *QueryNumPoolsResponse) Reset() { *m = QueryNumPoolsResponse{} } -func (m *QueryNumPoolsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryNumPoolsResponse) ProtoMessage() {} -func (*QueryNumPoolsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{11} -} -func (m *QueryNumPoolsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryNumPoolsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryNumPoolsResponse.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 *QueryNumPoolsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryNumPoolsResponse.Merge(m, src) -} -func (m *QueryNumPoolsResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryNumPoolsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryNumPoolsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryNumPoolsResponse proto.InternalMessageInfo - -func (m *QueryNumPoolsResponse) GetNumPools() uint64 { - if m != nil { - return m.NumPools - } - return 0 -} - -// -------------------------------------------- -// Query total liquidity the protocol -type QueryTotalLiquidityRequest struct { -} - -func (m *QueryTotalLiquidityRequest) Reset() { *m = QueryTotalLiquidityRequest{} } -func (m *QueryTotalLiquidityRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalLiquidityRequest) ProtoMessage() {} -func (*QueryTotalLiquidityRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{12} -} -func (m *QueryTotalLiquidityRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalLiquidityRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalLiquidityRequest.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 *QueryTotalLiquidityRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalLiquidityRequest.Merge(m, src) -} -func (m *QueryTotalLiquidityRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalLiquidityRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalLiquidityRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalLiquidityRequest proto.InternalMessageInfo - -type QueryTotalLiquidityResponse struct { - Liquidity github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=liquidity,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"liquidity" yaml:"liquidity"` -} - -func (m *QueryTotalLiquidityResponse) Reset() { *m = QueryTotalLiquidityResponse{} } -func (m *QueryTotalLiquidityResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalLiquidityResponse) ProtoMessage() {} -func (*QueryTotalLiquidityResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{13} -} -func (m *QueryTotalLiquidityResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalLiquidityResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalLiquidityResponse.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 *QueryTotalLiquidityResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalLiquidityResponse.Merge(m, src) -} -func (m *QueryTotalLiquidityResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalLiquidityResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalLiquidityResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalLiquidityResponse proto.InternalMessageInfo - -func (m *QueryTotalLiquidityResponse) GetLiquidity() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Liquidity - } - return nil -} - -// -------------------------------------------- -// Query total liquidity for a pool -type QueryTotalPoolLiquidityRequest struct { - PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` -} - -func (m *QueryTotalPoolLiquidityRequest) Reset() { *m = QueryTotalPoolLiquidityRequest{} } -func (m *QueryTotalPoolLiquidityRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalPoolLiquidityRequest) ProtoMessage() {} -func (*QueryTotalPoolLiquidityRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{14} -} -func (m *QueryTotalPoolLiquidityRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalPoolLiquidityRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalPoolLiquidityRequest.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 *QueryTotalPoolLiquidityRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalPoolLiquidityRequest.Merge(m, src) -} -func (m *QueryTotalPoolLiquidityRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalPoolLiquidityRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalPoolLiquidityRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalPoolLiquidityRequest proto.InternalMessageInfo - -func (m *QueryTotalPoolLiquidityRequest) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -type QueryTotalPoolLiquidityResponse struct { - Liquidity github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=liquidity,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"liquidity" yaml:"liquidity"` -} - -func (m *QueryTotalPoolLiquidityResponse) Reset() { *m = QueryTotalPoolLiquidityResponse{} } -func (m *QueryTotalPoolLiquidityResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalPoolLiquidityResponse) ProtoMessage() {} -func (*QueryTotalPoolLiquidityResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{15} -} -func (m *QueryTotalPoolLiquidityResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalPoolLiquidityResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalPoolLiquidityResponse.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 *QueryTotalPoolLiquidityResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalPoolLiquidityResponse.Merge(m, src) -} -func (m *QueryTotalPoolLiquidityResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalPoolLiquidityResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalPoolLiquidityResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalPoolLiquidityResponse proto.InternalMessageInfo - -func (m *QueryTotalPoolLiquidityResponse) GetLiquidity() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Liquidity - } - return nil -} - -type QueryTotalSharesRequest struct { - PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` -} - -func (m *QueryTotalSharesRequest) Reset() { *m = QueryTotalSharesRequest{} } -func (m *QueryTotalSharesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSharesRequest) ProtoMessage() {} -func (*QueryTotalSharesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{16} -} -func (m *QueryTotalSharesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSharesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSharesRequest.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 *QueryTotalSharesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSharesRequest.Merge(m, src) -} -func (m *QueryTotalSharesRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSharesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSharesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSharesRequest proto.InternalMessageInfo - -func (m *QueryTotalSharesRequest) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -type QueryTotalSharesResponse struct { - // sum of all LP tokens sent out - TotalShares types.Coin `protobuf:"bytes,1,opt,name=total_shares,json=totalShares,proto3" json:"total_shares" yaml:"total_shares"` -} - -func (m *QueryTotalSharesResponse) Reset() { *m = QueryTotalSharesResponse{} } -func (m *QueryTotalSharesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryTotalSharesResponse) ProtoMessage() {} -func (*QueryTotalSharesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{17} -} -func (m *QueryTotalSharesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryTotalSharesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryTotalSharesResponse.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 *QueryTotalSharesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryTotalSharesResponse.Merge(m, src) -} -func (m *QueryTotalSharesResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryTotalSharesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryTotalSharesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryTotalSharesResponse proto.InternalMessageInfo - -func (m *QueryTotalSharesResponse) GetTotalShares() types.Coin { - if m != nil { - return m.TotalShares - } - return types.Coin{} -} - -// Returns the amount of tokenInDenom to produce 1 tokenOutDenom -// For example, if the price of NIBI = 9.123 NUSD, then setting -// tokenInDenom=NUSD and tokenOutDenom=NIBI would give "9.123". -type QuerySpotPriceRequest struct { - PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - // the denomination of the token you are giving into the pool - TokenInDenom string `protobuf:"bytes,2,opt,name=token_in_denom,json=tokenInDenom,proto3" json:"token_in_denom,omitempty"` - // the denomination of the token you are taking out of the pool - TokenOutDenom string `protobuf:"bytes,3,opt,name=token_out_denom,json=tokenOutDenom,proto3" json:"token_out_denom,omitempty"` -} - -func (m *QuerySpotPriceRequest) Reset() { *m = QuerySpotPriceRequest{} } -func (m *QuerySpotPriceRequest) String() string { return proto.CompactTextString(m) } -func (*QuerySpotPriceRequest) ProtoMessage() {} -func (*QuerySpotPriceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{18} -} -func (m *QuerySpotPriceRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySpotPriceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySpotPriceRequest.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 *QuerySpotPriceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySpotPriceRequest.Merge(m, src) -} -func (m *QuerySpotPriceRequest) XXX_Size() int { - return m.Size() -} -func (m *QuerySpotPriceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySpotPriceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySpotPriceRequest proto.InternalMessageInfo - -func (m *QuerySpotPriceRequest) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -func (m *QuerySpotPriceRequest) GetTokenInDenom() string { - if m != nil { - return m.TokenInDenom - } - return "" -} - -func (m *QuerySpotPriceRequest) GetTokenOutDenom() string { - if m != nil { - return m.TokenOutDenom - } - return "" -} - -type QuerySpotPriceResponse struct { - SpotPrice string `protobuf:"bytes,1,opt,name=spot_price,json=spotPrice,proto3" json:"spot_price,omitempty"` -} - -func (m *QuerySpotPriceResponse) Reset() { *m = QuerySpotPriceResponse{} } -func (m *QuerySpotPriceResponse) String() string { return proto.CompactTextString(m) } -func (*QuerySpotPriceResponse) ProtoMessage() {} -func (*QuerySpotPriceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{19} -} -func (m *QuerySpotPriceResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySpotPriceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySpotPriceResponse.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 *QuerySpotPriceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySpotPriceResponse.Merge(m, src) -} -func (m *QuerySpotPriceResponse) XXX_Size() int { - return m.Size() -} -func (m *QuerySpotPriceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySpotPriceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySpotPriceResponse proto.InternalMessageInfo - -func (m *QuerySpotPriceResponse) GetSpotPrice() string { - if m != nil { - return m.SpotPrice - } - return "" -} - -// Given an exact amount of tokens in and a target tokenOutDenom, calculates -// the expected amount of tokens out received from a swap. -type QuerySwapExactAmountInRequest struct { - PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - TokenIn types.Coin `protobuf:"bytes,2,opt,name=token_in,json=tokenIn,proto3" json:"token_in" yaml:"token_in"` - TokenOutDenom string `protobuf:"bytes,3,opt,name=token_out_denom,json=tokenOutDenom,proto3" json:"token_out_denom,omitempty"` -} - -func (m *QuerySwapExactAmountInRequest) Reset() { *m = QuerySwapExactAmountInRequest{} } -func (m *QuerySwapExactAmountInRequest) String() string { return proto.CompactTextString(m) } -func (*QuerySwapExactAmountInRequest) ProtoMessage() {} -func (*QuerySwapExactAmountInRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{20} -} -func (m *QuerySwapExactAmountInRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySwapExactAmountInRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySwapExactAmountInRequest.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 *QuerySwapExactAmountInRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySwapExactAmountInRequest.Merge(m, src) -} -func (m *QuerySwapExactAmountInRequest) XXX_Size() int { - return m.Size() -} -func (m *QuerySwapExactAmountInRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySwapExactAmountInRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySwapExactAmountInRequest proto.InternalMessageInfo - -func (m *QuerySwapExactAmountInRequest) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -func (m *QuerySwapExactAmountInRequest) GetTokenIn() types.Coin { - if m != nil { - return m.TokenIn - } - return types.Coin{} -} - -func (m *QuerySwapExactAmountInRequest) GetTokenOutDenom() string { - if m != nil { - return m.TokenOutDenom - } - return "" -} - -type QuerySwapExactAmountInResponse struct { - TokenOut types.Coin `protobuf:"bytes,2,opt,name=token_out,json=tokenOut,proto3" json:"token_out" yaml:"token_out"` - Fee types.Coin `protobuf:"bytes,3,opt,name=fee,proto3" json:"fee" yaml:"fee"` -} - -func (m *QuerySwapExactAmountInResponse) Reset() { *m = QuerySwapExactAmountInResponse{} } -func (m *QuerySwapExactAmountInResponse) String() string { return proto.CompactTextString(m) } -func (*QuerySwapExactAmountInResponse) ProtoMessage() {} -func (*QuerySwapExactAmountInResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{21} -} -func (m *QuerySwapExactAmountInResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySwapExactAmountInResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySwapExactAmountInResponse.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 *QuerySwapExactAmountInResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySwapExactAmountInResponse.Merge(m, src) -} -func (m *QuerySwapExactAmountInResponse) XXX_Size() int { - return m.Size() -} -func (m *QuerySwapExactAmountInResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySwapExactAmountInResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySwapExactAmountInResponse proto.InternalMessageInfo - -func (m *QuerySwapExactAmountInResponse) GetTokenOut() types.Coin { - if m != nil { - return m.TokenOut - } - return types.Coin{} -} - -func (m *QuerySwapExactAmountInResponse) GetFee() types.Coin { - if m != nil { - return m.Fee - } - return types.Coin{} -} - -// Given an exact amount of tokens out and a target tokenInDenom, calculates -// the expected amount of tokens in required to do the swap. -type QuerySwapExactAmountOutRequest struct { - PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - TokenOut types.Coin `protobuf:"bytes,2,opt,name=token_out,json=tokenOut,proto3" json:"token_out" yaml:"token_out"` - TokenInDenom string `protobuf:"bytes,3,opt,name=token_in_denom,json=tokenInDenom,proto3" json:"token_in_denom,omitempty"` -} - -func (m *QuerySwapExactAmountOutRequest) Reset() { *m = QuerySwapExactAmountOutRequest{} } -func (m *QuerySwapExactAmountOutRequest) String() string { return proto.CompactTextString(m) } -func (*QuerySwapExactAmountOutRequest) ProtoMessage() {} -func (*QuerySwapExactAmountOutRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{22} -} -func (m *QuerySwapExactAmountOutRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySwapExactAmountOutRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySwapExactAmountOutRequest.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 *QuerySwapExactAmountOutRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySwapExactAmountOutRequest.Merge(m, src) -} -func (m *QuerySwapExactAmountOutRequest) XXX_Size() int { - return m.Size() -} -func (m *QuerySwapExactAmountOutRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySwapExactAmountOutRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySwapExactAmountOutRequest proto.InternalMessageInfo - -func (m *QuerySwapExactAmountOutRequest) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -func (m *QuerySwapExactAmountOutRequest) GetTokenOut() types.Coin { - if m != nil { - return m.TokenOut - } - return types.Coin{} -} - -func (m *QuerySwapExactAmountOutRequest) GetTokenInDenom() string { - if m != nil { - return m.TokenInDenom - } - return "" -} - -type QuerySwapExactAmountOutResponse struct { - TokenIn types.Coin `protobuf:"bytes,2,opt,name=token_in,json=tokenIn,proto3" json:"token_in" yaml:"token_in"` -} - -func (m *QuerySwapExactAmountOutResponse) Reset() { *m = QuerySwapExactAmountOutResponse{} } -func (m *QuerySwapExactAmountOutResponse) String() string { return proto.CompactTextString(m) } -func (*QuerySwapExactAmountOutResponse) ProtoMessage() {} -func (*QuerySwapExactAmountOutResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{23} -} -func (m *QuerySwapExactAmountOutResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QuerySwapExactAmountOutResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySwapExactAmountOutResponse.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 *QuerySwapExactAmountOutResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySwapExactAmountOutResponse.Merge(m, src) -} -func (m *QuerySwapExactAmountOutResponse) XXX_Size() int { - return m.Size() -} -func (m *QuerySwapExactAmountOutResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySwapExactAmountOutResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySwapExactAmountOutResponse proto.InternalMessageInfo - -func (m *QuerySwapExactAmountOutResponse) GetTokenIn() types.Coin { - if m != nil { - return m.TokenIn - } - return types.Coin{} -} - -type QueryJoinExactAmountInRequest struct { - PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - TokensIn github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=tokens_in,json=tokensIn,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"tokens_in" yaml:"tokens_in"` -} - -func (m *QueryJoinExactAmountInRequest) Reset() { *m = QueryJoinExactAmountInRequest{} } -func (m *QueryJoinExactAmountInRequest) String() string { return proto.CompactTextString(m) } -func (*QueryJoinExactAmountInRequest) ProtoMessage() {} -func (*QueryJoinExactAmountInRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{24} -} -func (m *QueryJoinExactAmountInRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryJoinExactAmountInRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryJoinExactAmountInRequest.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 *QueryJoinExactAmountInRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryJoinExactAmountInRequest.Merge(m, src) -} -func (m *QueryJoinExactAmountInRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryJoinExactAmountInRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryJoinExactAmountInRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryJoinExactAmountInRequest proto.InternalMessageInfo - -func (m *QueryJoinExactAmountInRequest) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -func (m *QueryJoinExactAmountInRequest) GetTokensIn() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.TokensIn - } - return nil -} - -type QueryJoinExactAmountInResponse struct { - // amount of pool shares returned to user after join - PoolSharesOut github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,1,opt,name=pool_shares_out,json=poolSharesOut,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"pool_shares_out" yaml:"pool_shares_out"` - // coins remaining after pool join - RemCoins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=rem_coins,json=remCoins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"rem_coins" yaml:"rem_coins"` -} - -func (m *QueryJoinExactAmountInResponse) Reset() { *m = QueryJoinExactAmountInResponse{} } -func (m *QueryJoinExactAmountInResponse) String() string { return proto.CompactTextString(m) } -func (*QueryJoinExactAmountInResponse) ProtoMessage() {} -func (*QueryJoinExactAmountInResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{25} -} -func (m *QueryJoinExactAmountInResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryJoinExactAmountInResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryJoinExactAmountInResponse.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 *QueryJoinExactAmountInResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryJoinExactAmountInResponse.Merge(m, src) -} -func (m *QueryJoinExactAmountInResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryJoinExactAmountInResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryJoinExactAmountInResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryJoinExactAmountInResponse proto.InternalMessageInfo - -func (m *QueryJoinExactAmountInResponse) GetRemCoins() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.RemCoins - } - return nil -} - -type QueryJoinExactAmountOutRequest struct { - PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` -} - -func (m *QueryJoinExactAmountOutRequest) Reset() { *m = QueryJoinExactAmountOutRequest{} } -func (m *QueryJoinExactAmountOutRequest) String() string { return proto.CompactTextString(m) } -func (*QueryJoinExactAmountOutRequest) ProtoMessage() {} -func (*QueryJoinExactAmountOutRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{26} -} -func (m *QueryJoinExactAmountOutRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryJoinExactAmountOutRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryJoinExactAmountOutRequest.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 *QueryJoinExactAmountOutRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryJoinExactAmountOutRequest.Merge(m, src) -} -func (m *QueryJoinExactAmountOutRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryJoinExactAmountOutRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryJoinExactAmountOutRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryJoinExactAmountOutRequest proto.InternalMessageInfo - -func (m *QueryJoinExactAmountOutRequest) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -type QueryJoinExactAmountOutResponse struct { -} - -func (m *QueryJoinExactAmountOutResponse) Reset() { *m = QueryJoinExactAmountOutResponse{} } -func (m *QueryJoinExactAmountOutResponse) String() string { return proto.CompactTextString(m) } -func (*QueryJoinExactAmountOutResponse) ProtoMessage() {} -func (*QueryJoinExactAmountOutResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{27} -} -func (m *QueryJoinExactAmountOutResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryJoinExactAmountOutResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryJoinExactAmountOutResponse.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 *QueryJoinExactAmountOutResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryJoinExactAmountOutResponse.Merge(m, src) -} -func (m *QueryJoinExactAmountOutResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryJoinExactAmountOutResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryJoinExactAmountOutResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryJoinExactAmountOutResponse proto.InternalMessageInfo - -type QueryExitExactAmountInRequest struct { - PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` - // amount of pool shares to return to pool - PoolSharesIn github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=pool_shares_in,json=poolSharesIn,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"pool_shares_in" yaml:"pool_shares_in"` -} - -func (m *QueryExitExactAmountInRequest) Reset() { *m = QueryExitExactAmountInRequest{} } -func (m *QueryExitExactAmountInRequest) String() string { return proto.CompactTextString(m) } -func (*QueryExitExactAmountInRequest) ProtoMessage() {} -func (*QueryExitExactAmountInRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{28} -} -func (m *QueryExitExactAmountInRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryExitExactAmountInRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryExitExactAmountInRequest.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 *QueryExitExactAmountInRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryExitExactAmountInRequest.Merge(m, src) -} -func (m *QueryExitExactAmountInRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryExitExactAmountInRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryExitExactAmountInRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryExitExactAmountInRequest proto.InternalMessageInfo - -func (m *QueryExitExactAmountInRequest) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -type QueryExitExactAmountInResponse struct { - // coins obtained after exiting - TokensOut github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=tokens_out,json=tokensOut,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"tokens_out" yaml:"tokens_out"` - Fees github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=fees,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"fees" yaml:"fees"` -} - -func (m *QueryExitExactAmountInResponse) Reset() { *m = QueryExitExactAmountInResponse{} } -func (m *QueryExitExactAmountInResponse) String() string { return proto.CompactTextString(m) } -func (*QueryExitExactAmountInResponse) ProtoMessage() {} -func (*QueryExitExactAmountInResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{29} -} -func (m *QueryExitExactAmountInResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryExitExactAmountInResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryExitExactAmountInResponse.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 *QueryExitExactAmountInResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryExitExactAmountInResponse.Merge(m, src) -} -func (m *QueryExitExactAmountInResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryExitExactAmountInResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryExitExactAmountInResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryExitExactAmountInResponse proto.InternalMessageInfo - -func (m *QueryExitExactAmountInResponse) GetTokensOut() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.TokensOut - } - return nil -} - -func (m *QueryExitExactAmountInResponse) GetFees() github_com_cosmos_cosmos_sdk_types.Coins { - if m != nil { - return m.Fees - } - return nil -} - -type QueryExitExactAmountOutRequest struct { - PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` -} - -func (m *QueryExitExactAmountOutRequest) Reset() { *m = QueryExitExactAmountOutRequest{} } -func (m *QueryExitExactAmountOutRequest) String() string { return proto.CompactTextString(m) } -func (*QueryExitExactAmountOutRequest) ProtoMessage() {} -func (*QueryExitExactAmountOutRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{30} -} -func (m *QueryExitExactAmountOutRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryExitExactAmountOutRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryExitExactAmountOutRequest.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 *QueryExitExactAmountOutRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryExitExactAmountOutRequest.Merge(m, src) -} -func (m *QueryExitExactAmountOutRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryExitExactAmountOutRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryExitExactAmountOutRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryExitExactAmountOutRequest proto.InternalMessageInfo - -func (m *QueryExitExactAmountOutRequest) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -type QueryExitExactAmountOutResponse struct { -} - -func (m *QueryExitExactAmountOutResponse) Reset() { *m = QueryExitExactAmountOutResponse{} } -func (m *QueryExitExactAmountOutResponse) String() string { return proto.CompactTextString(m) } -func (*QueryExitExactAmountOutResponse) ProtoMessage() {} -func (*QueryExitExactAmountOutResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_15e32191d06b2665, []int{31} -} -func (m *QueryExitExactAmountOutResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryExitExactAmountOutResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryExitExactAmountOutResponse.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 *QueryExitExactAmountOutResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryExitExactAmountOutResponse.Merge(m, src) -} -func (m *QueryExitExactAmountOutResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryExitExactAmountOutResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryExitExactAmountOutResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryExitExactAmountOutResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "nibiru.spot.v1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "nibiru.spot.v1.QueryParamsResponse") - proto.RegisterType((*QueryPoolNumberRequest)(nil), "nibiru.spot.v1.QueryPoolNumberRequest") - proto.RegisterType((*QueryPoolNumberResponse)(nil), "nibiru.spot.v1.QueryPoolNumberResponse") - proto.RegisterType((*QueryPoolRequest)(nil), "nibiru.spot.v1.QueryPoolRequest") - proto.RegisterType((*QueryPoolResponse)(nil), "nibiru.spot.v1.QueryPoolResponse") - proto.RegisterType((*QueryPoolsRequest)(nil), "nibiru.spot.v1.QueryPoolsRequest") - proto.RegisterType((*QueryPoolsResponse)(nil), "nibiru.spot.v1.QueryPoolsResponse") - proto.RegisterType((*QueryPoolParamsRequest)(nil), "nibiru.spot.v1.QueryPoolParamsRequest") - proto.RegisterType((*QueryPoolParamsResponse)(nil), "nibiru.spot.v1.QueryPoolParamsResponse") - proto.RegisterType((*QueryNumPoolsRequest)(nil), "nibiru.spot.v1.QueryNumPoolsRequest") - proto.RegisterType((*QueryNumPoolsResponse)(nil), "nibiru.spot.v1.QueryNumPoolsResponse") - proto.RegisterType((*QueryTotalLiquidityRequest)(nil), "nibiru.spot.v1.QueryTotalLiquidityRequest") - proto.RegisterType((*QueryTotalLiquidityResponse)(nil), "nibiru.spot.v1.QueryTotalLiquidityResponse") - proto.RegisterType((*QueryTotalPoolLiquidityRequest)(nil), "nibiru.spot.v1.QueryTotalPoolLiquidityRequest") - proto.RegisterType((*QueryTotalPoolLiquidityResponse)(nil), "nibiru.spot.v1.QueryTotalPoolLiquidityResponse") - proto.RegisterType((*QueryTotalSharesRequest)(nil), "nibiru.spot.v1.QueryTotalSharesRequest") - proto.RegisterType((*QueryTotalSharesResponse)(nil), "nibiru.spot.v1.QueryTotalSharesResponse") - proto.RegisterType((*QuerySpotPriceRequest)(nil), "nibiru.spot.v1.QuerySpotPriceRequest") - proto.RegisterType((*QuerySpotPriceResponse)(nil), "nibiru.spot.v1.QuerySpotPriceResponse") - proto.RegisterType((*QuerySwapExactAmountInRequest)(nil), "nibiru.spot.v1.QuerySwapExactAmountInRequest") - proto.RegisterType((*QuerySwapExactAmountInResponse)(nil), "nibiru.spot.v1.QuerySwapExactAmountInResponse") - proto.RegisterType((*QuerySwapExactAmountOutRequest)(nil), "nibiru.spot.v1.QuerySwapExactAmountOutRequest") - proto.RegisterType((*QuerySwapExactAmountOutResponse)(nil), "nibiru.spot.v1.QuerySwapExactAmountOutResponse") - proto.RegisterType((*QueryJoinExactAmountInRequest)(nil), "nibiru.spot.v1.QueryJoinExactAmountInRequest") - proto.RegisterType((*QueryJoinExactAmountInResponse)(nil), "nibiru.spot.v1.QueryJoinExactAmountInResponse") - proto.RegisterType((*QueryJoinExactAmountOutRequest)(nil), "nibiru.spot.v1.QueryJoinExactAmountOutRequest") - proto.RegisterType((*QueryJoinExactAmountOutResponse)(nil), "nibiru.spot.v1.QueryJoinExactAmountOutResponse") - proto.RegisterType((*QueryExitExactAmountInRequest)(nil), "nibiru.spot.v1.QueryExitExactAmountInRequest") - proto.RegisterType((*QueryExitExactAmountInResponse)(nil), "nibiru.spot.v1.QueryExitExactAmountInResponse") - proto.RegisterType((*QueryExitExactAmountOutRequest)(nil), "nibiru.spot.v1.QueryExitExactAmountOutRequest") - proto.RegisterType((*QueryExitExactAmountOutResponse)(nil), "nibiru.spot.v1.QueryExitExactAmountOutResponse") -} - -func init() { proto.RegisterFile("nibiru/spot/v1/query.proto", fileDescriptor_15e32191d06b2665) } - -var fileDescriptor_15e32191d06b2665 = []byte{ - // 1522 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x58, 0x4d, 0x6f, 0x14, 0xc7, - 0x16, 0x75, 0x63, 0x63, 0x3c, 0x65, 0x30, 0x50, 0x36, 0xc6, 0x6e, 0xc3, 0x18, 0x0a, 0xb0, 0xfd, - 0x6c, 0x31, 0xad, 0x01, 0xde, 0x43, 0xbc, 0x04, 0xa1, 0x18, 0x1c, 0xe2, 0x7c, 0x80, 0x33, 0x44, - 0x91, 0x92, 0x2c, 0x46, 0x6d, 0xbb, 0x3c, 0x34, 0xb8, 0xbb, 0x9a, 0xe9, 0x6a, 0xb0, 0x15, 0x48, - 0xa4, 0x6c, 0xa2, 0x64, 0x13, 0x22, 0xb6, 0x59, 0x64, 0x13, 0x45, 0xca, 0x26, 0x89, 0x22, 0x45, - 0x59, 0xe4, 0x07, 0xb0, 0x44, 0xca, 0x26, 0xca, 0xc2, 0x89, 0x20, 0xbf, 0x80, 0x5f, 0x10, 0x55, - 0xd5, 0xed, 0x9e, 0xfe, 0x9c, 0xee, 0x91, 0x58, 0x64, 0xc5, 0xb8, 0xea, 0xde, 0x7b, 0xce, 0x3d, - 0x75, 0xba, 0xfb, 0x16, 0x48, 0x77, 0xac, 0x55, 0xab, 0xed, 0x1b, 0x9e, 0xcb, 0xb8, 0x71, 0xb7, - 0x6e, 0xdc, 0xf1, 0x69, 0x7b, 0xbb, 0xe6, 0xb6, 0x19, 0x67, 0x78, 0x44, 0xed, 0xd5, 0xc4, 0x5e, - 0xed, 0x6e, 0x5d, 0x1f, 0x6b, 0xb1, 0x16, 0x93, 0x5b, 0x86, 0xf8, 0xa5, 0xa2, 0xf4, 0x23, 0x2d, - 0xc6, 0x5a, 0x9b, 0xd4, 0x30, 0x5d, 0xcb, 0x30, 0x1d, 0x87, 0x71, 0x93, 0x5b, 0xcc, 0xf1, 0x60, - 0x77, 0x7e, 0x8d, 0x79, 0x36, 0xf3, 0x8c, 0x55, 0xd3, 0xa3, 0xaa, 0xb8, 0x71, 0xb7, 0xbe, 0x4a, - 0xb9, 0x59, 0x37, 0x5c, 0xb3, 0x65, 0x39, 0x32, 0x18, 0x62, 0xa7, 0x12, 0x5c, 0x5c, 0xb3, 0x6d, - 0xda, 0x41, 0xa1, 0xc9, 0xe4, 0x26, 0x63, 0x9b, 0xb0, 0x55, 0x8d, 0x62, 0x04, 0xd5, 0xd7, 0x98, - 0x05, 0x75, 0xc9, 0x18, 0xc2, 0x6f, 0x0b, 0xe4, 0x15, 0x59, 0xaf, 0x41, 0xef, 0xf8, 0xd4, 0xe3, - 0xe4, 0x0d, 0x34, 0x1a, 0x5b, 0xf5, 0x5c, 0xe6, 0x78, 0x14, 0x9f, 0x43, 0x83, 0x0a, 0x77, 0x42, - 0x3b, 0xa6, 0xcd, 0x0d, 0x9f, 0x19, 0xaf, 0xc5, 0x55, 0xa8, 0xa9, 0xf8, 0xc5, 0x81, 0xc7, 0x3b, - 0xd3, 0x7d, 0x0d, 0x88, 0x25, 0x13, 0x68, 0x5c, 0x15, 0x63, 0x6c, 0xf3, 0x9a, 0x6f, 0xaf, 0xd2, - 0x76, 0x00, 0x73, 0x06, 0x1d, 0x4e, 0xed, 0x00, 0xd4, 0x61, 0xb4, 0x47, 0x74, 0xd1, 0xb4, 0xd6, - 0x25, 0xd6, 0x40, 0x63, 0x50, 0xfc, 0xb9, 0xbc, 0x4e, 0x16, 0xd0, 0x81, 0x30, 0x07, 0xea, 0xe4, - 0x07, 0x5f, 0x44, 0x07, 0x23, 0xc1, 0x50, 0x7a, 0x0e, 0x0d, 0x88, 0x6d, 0xe8, 0x61, 0x2c, 0xd5, - 0x83, 0x88, 0x95, 0x11, 0xe4, 0x83, 0x48, 0x7a, 0xa0, 0x0d, 0x7e, 0x15, 0xa1, 0xce, 0xe9, 0x40, - 0x91, 0x99, 0x9a, 0x92, 0xb9, 0x26, 0x64, 0xae, 0x29, 0x9f, 0x80, 0xd8, 0xb5, 0x15, 0xb3, 0x45, - 0x21, 0xb7, 0x11, 0xc9, 0x24, 0x9f, 0x69, 0x81, 0xf4, 0xaa, 0x3a, 0xb0, 0x9b, 0x47, 0xbb, 0x05, - 0xb6, 0x90, 0xb8, 0x3f, 0x97, 0x9e, 0x0a, 0xc1, 0x57, 0x63, 0x54, 0x76, 0x49, 0x2a, 0xb3, 0x85, - 0x54, 0x14, 0x50, 0x8c, 0x4b, 0x3d, 0x72, 0x44, 0x31, 0x27, 0xe4, 0x4b, 0xfb, 0x6e, 0xe4, 0xec, - 0x12, 0x36, 0x79, 0x09, 0x0d, 0xcb, 0x9c, 0x98, 0x57, 0xf4, 0xac, 0x46, 0x20, 0x11, 0xb9, 0xe1, - 0x6f, 0x32, 0x8e, 0xc6, 0x64, 0xdd, 0x6b, 0xbe, 0x1d, 0x95, 0x9d, 0x9c, 0x43, 0x87, 0x12, 0xeb, - 0x80, 0x36, 0x85, 0x2a, 0x8e, 0x6f, 0x37, 0x03, 0xd1, 0x04, 0xc7, 0x21, 0x07, 0x82, 0xc8, 0x11, - 0xa4, 0xcb, 0xac, 0x77, 0x18, 0x37, 0x37, 0xdf, 0xb4, 0xee, 0xf8, 0xd6, 0xba, 0xc5, 0xb7, 0x83, - 0x9a, 0x5f, 0x69, 0x68, 0x2a, 0x73, 0x1b, 0x4a, 0x3f, 0x40, 0x95, 0xcd, 0x60, 0x11, 0xce, 0x63, - 0x32, 0x26, 0x6f, 0x20, 0xec, 0x65, 0x66, 0x39, 0x8b, 0x57, 0x84, 0xeb, 0x9f, 0xef, 0x4c, 0x1f, - 0xd8, 0x36, 0xed, 0xcd, 0xff, 0x93, 0x30, 0x93, 0x7c, 0xf7, 0xe7, 0xf4, 0x5c, 0xcb, 0xe2, 0x37, - 0xfd, 0xd5, 0xda, 0x1a, 0xb3, 0x0d, 0x78, 0x22, 0xd5, 0x3f, 0xa7, 0xbd, 0xf5, 0xdb, 0x06, 0xdf, - 0x76, 0xa9, 0x27, 0x8b, 0x78, 0x8d, 0x0e, 0x22, 0xb9, 0x80, 0xaa, 0x1d, 0x76, 0xa2, 0x9f, 0x64, - 0x03, 0xf9, 0xa7, 0xf3, 0xb5, 0x86, 0xa6, 0x73, 0x73, 0xff, 0x1d, 0xdd, 0x05, 0x0f, 0xbf, 0x64, - 0x78, 0xe3, 0xa6, 0xd9, 0xa6, 0xc5, 0xa6, 0xf3, 0xd1, 0x44, 0x3a, 0x07, 0xda, 0x79, 0x0f, 0xed, - 0xe5, 0x62, 0xb9, 0xe9, 0xc9, 0x75, 0xb0, 0x5d, 0x97, 0x8e, 0xa6, 0xa0, 0xa3, 0x51, 0xd5, 0x51, - 0x34, 0x99, 0x34, 0x86, 0x79, 0x07, 0x82, 0x7c, 0x04, 0xde, 0xbb, 0xe1, 0x32, 0xbe, 0xd2, 0xb6, - 0xd6, 0x68, 0x11, 0x51, 0x7c, 0x12, 0x8d, 0x70, 0x76, 0x9b, 0x3a, 0x4d, 0xcb, 0x69, 0xae, 0x53, - 0x87, 0xd9, 0xf2, 0xe9, 0xac, 0x34, 0xf6, 0xca, 0xd5, 0x65, 0xe7, 0x8a, 0x58, 0xc3, 0x33, 0x68, - 0xbf, 0x8a, 0x62, 0x3e, 0x87, 0xb0, 0x7e, 0x19, 0xb6, 0x4f, 0x2e, 0x5f, 0xf7, 0xb9, 0x8c, 0x23, - 0xe7, 0xe1, 0xf1, 0x8c, 0xe0, 0x43, 0xd3, 0x47, 0x11, 0x12, 0xcf, 0x53, 0xd3, 0x15, 0xab, 0x92, - 0x43, 0xa5, 0x51, 0xf1, 0x82, 0x30, 0xf2, 0xbd, 0x86, 0x8e, 0xaa, 0xcc, 0x7b, 0xa6, 0xbb, 0xb4, - 0x65, 0xae, 0xf1, 0x57, 0x6c, 0xe6, 0x3b, 0x7c, 0xd9, 0x29, 0xec, 0xe0, 0x2d, 0x34, 0x14, 0x74, - 0x00, 0x6f, 0x96, 0x2e, 0x52, 0x1e, 0x06, 0x29, 0xf7, 0x07, 0x52, 0xaa, 0x44, 0xd2, 0xd8, 0x03, - 0xfd, 0x96, 0x6e, 0xf5, 0x27, 0x0d, 0x4c, 0x9f, 0xc1, 0x18, 0x7a, 0x5e, 0x41, 0x95, 0xb0, 0x54, - 0x31, 0xb5, 0x89, 0xb8, 0x6f, 0xc3, 0x4c, 0xd2, 0x18, 0x0a, 0x90, 0xf1, 0x25, 0xd4, 0xbf, 0x41, - 0xa9, 0x24, 0xd4, 0xb5, 0x16, 0x86, 0x5a, 0x48, 0xd5, 0xda, 0xa0, 0x94, 0x34, 0x44, 0x26, 0xf9, - 0x31, 0x87, 0xf5, 0x75, 0x9f, 0x17, 0x0a, 0xfd, 0xe2, 0xdb, 0x49, 0x9b, 0xaf, 0x3f, 0x6d, 0x3e, - 0xe2, 0xc2, 0x1b, 0x22, 0x8b, 0x32, 0x28, 0xfd, 0x62, 0x3d, 0x40, 0x7e, 0x0e, 0xdc, 0xf8, 0x3a, - 0xb3, 0x9c, 0xde, 0xdc, 0x78, 0x1f, 0x44, 0xf2, 0x14, 0x95, 0xde, 0xde, 0x55, 0x61, 0x66, 0x6f, - 0xef, 0x2a, 0xd5, 0xbb, 0xb7, 0xec, 0x90, 0x87, 0xbb, 0xe0, 0x78, 0x33, 0x88, 0x83, 0x54, 0x2e, - 0xda, 0x2f, 0x99, 0xab, 0xf7, 0x87, 0x3c, 0x4b, 0xf9, 0x34, 0x2e, 0xbe, 0x26, 0xb8, 0xfc, 0xb1, - 0x33, 0x3d, 0x53, 0x02, 0x77, 0xd9, 0xe1, 0xcf, 0x77, 0xa6, 0xc7, 0x15, 0xeb, 0x44, 0x39, 0xd2, - 0xd8, 0x27, 0x56, 0xd4, 0x1b, 0x49, 0x9c, 0xf2, 0x7d, 0x54, 0x69, 0x53, 0xbb, 0x29, 0x66, 0x39, - 0xaf, 0x67, 0x49, 0xc2, 0xcc, 0x1e, 0x25, 0x69, 0x53, 0x5b, 0xfe, 0x0a, 0xbf, 0x4d, 0x09, 0x45, - 0x4a, 0x18, 0x9e, 0x1c, 0x07, 0xe3, 0x65, 0xa5, 0x2a, 0x35, 0xc9, 0xb7, 0x81, 0x53, 0x96, 0xb6, - 0x2c, 0xde, 0x9b, 0x53, 0x6c, 0x34, 0x12, 0x55, 0x0e, 0x9c, 0x5b, 0x59, 0xbc, 0xda, 0xf3, 0x39, - 0x1c, 0x4a, 0x9f, 0x83, 0xb0, 0xf3, 0xde, 0xce, 0x31, 0x2c, 0x3b, 0xe4, 0xcb, 0xc0, 0x1a, 0x19, - 0x4c, 0xc1, 0x1a, 0x1f, 0x23, 0x04, 0x0e, 0x54, 0xae, 0x28, 0x38, 0xa9, 0x25, 0x38, 0xa9, 0x83, - 0x31, 0xf3, 0x0a, 0x07, 0xf4, 0xf6, 0xa5, 0x55, 0x89, 0xc2, 0x29, 0x0e, 0x1a, 0xd8, 0xa0, 0xb4, - 0x84, 0x49, 0x2e, 0x01, 0xf4, 0x70, 0xf8, 0x7e, 0xeb, 0xd1, 0x1f, 0x12, 0x27, 0xf4, 0x46, 0x42, - 0x92, 0x5e, 0xbc, 0x91, 0x95, 0xaa, 0xe4, 0x3c, 0xf3, 0xcd, 0x28, 0xda, 0x2d, 0x63, 0xb0, 0x83, - 0x06, 0xd5, 0xd0, 0x88, 0x49, 0x72, 0xb8, 0x4c, 0xdf, 0x69, 0xf4, 0x13, 0x5d, 0x63, 0xc0, 0x78, - 0x53, 0x9f, 0xfc, 0xf6, 0xf7, 0xa3, 0x5d, 0x87, 0xf0, 0xa8, 0x11, 0xbd, 0x52, 0xa9, 0x41, 0x56, - 0x1c, 0x64, 0xe7, 0xa6, 0x82, 0x67, 0xb2, 0xeb, 0x25, 0x2f, 0x39, 0xfa, 0x6c, 0x61, 0x1c, 0x60, - 0x1f, 0x93, 0xd8, 0x3a, 0x9e, 0x88, 0x63, 0x0b, 0x9d, 0x1c, 0x05, 0xb9, 0x81, 0x06, 0x44, 0x1e, - 0x3e, 0x96, 0x5b, 0x32, 0x00, 0x3d, 0xde, 0x25, 0x02, 0xe0, 0x26, 0x25, 0xdc, 0x28, 0x3e, 0x98, - 0x82, 0xc3, 0xb7, 0xd0, 0x6e, 0x39, 0x3e, 0xe3, 0xfc, 0x32, 0xa1, 0xac, 0xa4, 0x5b, 0x08, 0x40, - 0xe9, 0x12, 0x6a, 0x0c, 0xe3, 0x14, 0x94, 0x87, 0x3f, 0xd7, 0x94, 0xaa, 0x70, 0x92, 0xf9, 0xaa, - 0xc6, 0x4f, 0x73, 0xb6, 0x30, 0x0e, 0xb0, 0x17, 0x24, 0xf6, 0x29, 0x7c, 0x22, 0x8d, 0x6d, 0x7c, - 0x08, 0x26, 0x7c, 0x10, 0x9c, 0xf0, 0x3d, 0x34, 0x14, 0xdc, 0x2f, 0xf0, 0xc9, 0x4c, 0x84, 0xc4, - 0xb5, 0x44, 0x3f, 0x55, 0x10, 0x05, 0x2c, 0xaa, 0x92, 0xc5, 0x04, 0x1e, 0x8f, 0xb1, 0x08, 0xef, - 0x2d, 0xf8, 0x0b, 0x0d, 0x8d, 0xc4, 0x2f, 0x21, 0x78, 0x3e, 0xb3, 0x72, 0xe6, 0x45, 0x46, 0x5f, - 0x28, 0x15, 0x0b, 0x5c, 0x4e, 0x4a, 0x2e, 0x55, 0x7c, 0x24, 0xc6, 0x45, 0x8d, 0xbf, 0xe1, 0x78, - 0x8e, 0x7f, 0xd0, 0x10, 0x4e, 0x5f, 0x1e, 0x70, 0x2d, 0x1f, 0x29, 0xeb, 0x86, 0xa2, 0x1b, 0xa5, - 0xe3, 0x81, 0xdd, 0x05, 0xc9, 0xee, 0x2c, 0xae, 0x77, 0x3d, 0x2f, 0xc5, 0x56, 0xfe, 0xd9, 0xa1, - 0xfc, 0x48, 0x43, 0xc3, 0x91, 0x9b, 0x01, 0x9e, 0xcd, 0xc7, 0x8e, 0xdd, 0x37, 0xf4, 0xb9, 0xe2, - 0x40, 0x60, 0x57, 0x97, 0xec, 0x16, 0xf0, 0x7f, 0x4a, 0xb0, 0x53, 0xdf, 0x0c, 0xfc, 0xa9, 0x86, - 0x2a, 0xe1, 0xe0, 0x8e, 0xb3, 0xfd, 0x92, 0xbc, 0x58, 0xe8, 0x33, 0x45, 0x61, 0xbd, 0xb9, 0x5b, - 0xe4, 0x78, 0xf8, 0x17, 0x0d, 0x4d, 0x2e, 0x79, 0xdc, 0xb2, 0x4d, 0x4e, 0x53, 0xe3, 0x35, 0x3e, - 0x9d, 0x0d, 0x99, 0x73, 0x71, 0xd0, 0x6b, 0x65, 0xc3, 0x81, 0xe9, 0xcb, 0x92, 0xe9, 0xff, 0xf0, - 0xb9, 0x18, 0xd3, 0x0e, 0x47, 0x0a, 0xc4, 0x0c, 0xef, 0x9e, 0xe9, 0x36, 0xa9, 0xa8, 0xd1, 0x34, - 0x65, 0x91, 0xa6, 0xe5, 0xe0, 0x5f, 0x35, 0xa4, 0xe7, 0x50, 0x17, 0x5f, 0xb8, 0x52, 0x64, 0x3a, - 0xdf, 0x9f, 0x1c, 0x57, 0xe6, 0x4f, 0xc2, 0xe4, 0xa2, 0x64, 0x7f, 0x1e, 0xff, 0xb7, 0x77, 0xf6, - 0xcc, 0xe7, 0x31, 0xe5, 0x53, 0x33, 0x64, 0x8e, 0xf2, 0x79, 0x43, 0x72, 0x8e, 0xf2, 0xb9, 0xa3, - 0x69, 0x79, 0xe5, 0x6f, 0x31, 0xcb, 0xe9, 0xaa, 0x7c, 0x7a, 0x62, 0xc3, 0xa5, 0xc8, 0x14, 0x2a, - 0xdf, 0x65, 0x14, 0x2c, 0xad, 0x7c, 0x9a, 0x7d, 0x52, 0xf9, 0xd4, 0x88, 0x96, 0xa3, 0x7c, 0xde, - 0xd0, 0x99, 0xa3, 0x7c, 0xee, 0xe4, 0x57, 0x5e, 0x79, 0xba, 0x65, 0xf1, 0xae, 0xca, 0xa7, 0xe7, - 0x21, 0x5c, 0x8a, 0x4c, 0xa1, 0xf2, 0xf9, 0x83, 0x56, 0x79, 0xe5, 0xd3, 0xec, 0x99, 0xcf, 0x17, - 0xaf, 0x3c, 0x7e, 0x5a, 0xd5, 0x9e, 0x3c, 0xad, 0x6a, 0x7f, 0x3d, 0xad, 0x6a, 0x0f, 0x9f, 0x55, - 0xfb, 0x9e, 0x3c, 0xab, 0xf6, 0xfd, 0xfe, 0xac, 0xda, 0xf7, 0xfe, 0x7c, 0x64, 0x9e, 0xbc, 0x26, - 0x4b, 0x5f, 0xbe, 0x69, 0x5a, 0x4e, 0x00, 0xb3, 0x05, 0x1f, 0x24, 0x31, 0x57, 0xae, 0x0e, 0xca, - 0xff, 0xa6, 0x3e, 0xfb, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xe6, 0x32, 0xfc, 0x09, 0x8c, 0x17, - 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 { - // Parameters of the spot module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Next available pool id number. - PoolNumber(ctx context.Context, in *QueryPoolNumberRequest, opts ...grpc.CallOption) (*QueryPoolNumberResponse, error) - // Fetch a pool by id. - Pool(ctx context.Context, in *QueryPoolRequest, opts ...grpc.CallOption) (*QueryPoolResponse, error) - // Returns all pools. - Pools(ctx context.Context, in *QueryPoolsRequest, opts ...grpc.CallOption) (*QueryPoolsResponse, error) - // Parameters of a single pool. - PoolParams(ctx context.Context, in *QueryPoolParamsRequest, opts ...grpc.CallOption) (*QueryPoolParamsResponse, error) - // Number of pools. - NumPools(ctx context.Context, in *QueryNumPoolsRequest, opts ...grpc.CallOption) (*QueryNumPoolsResponse, error) - // Total liquidity across all pools. - TotalLiquidity(ctx context.Context, in *QueryTotalLiquidityRequest, opts ...grpc.CallOption) (*QueryTotalLiquidityResponse, error) - // Total liquidity in a single pool. - TotalPoolLiquidity(ctx context.Context, in *QueryTotalPoolLiquidityRequest, opts ...grpc.CallOption) (*QueryTotalPoolLiquidityResponse, error) - // Total shares in a single pool. - TotalShares(ctx context.Context, in *QueryTotalSharesRequest, opts ...grpc.CallOption) (*QueryTotalSharesResponse, error) - // Instantaneous price of an asset in a pool. - SpotPrice(ctx context.Context, in *QuerySpotPriceRequest, opts ...grpc.CallOption) (*QuerySpotPriceResponse, error) - // Estimates the amount of assets returned given an exact amount of tokens to - // swap. - EstimateSwapExactAmountIn(ctx context.Context, in *QuerySwapExactAmountInRequest, opts ...grpc.CallOption) (*QuerySwapExactAmountInResponse, error) - // Estimates the amount of tokens required to return the exact amount of - // assets requested. - EstimateSwapExactAmountOut(ctx context.Context, in *QuerySwapExactAmountOutRequest, opts ...grpc.CallOption) (*QuerySwapExactAmountOutResponse, error) - // Estimates the amount of pool shares returned given an amount of tokens to - // join. - EstimateJoinExactAmountIn(ctx context.Context, in *QueryJoinExactAmountInRequest, opts ...grpc.CallOption) (*QueryJoinExactAmountInResponse, error) - // Estimates the amount of tokens required to obtain an exact amount of pool - // shares. - EstimateJoinExactAmountOut(ctx context.Context, in *QueryJoinExactAmountOutRequest, opts ...grpc.CallOption) (*QueryJoinExactAmountOutResponse, error) - // Estimates the amount of tokens returned to the user given an exact amount - // of pool shares. - EstimateExitExactAmountIn(ctx context.Context, in *QueryExitExactAmountInRequest, opts ...grpc.CallOption) (*QueryExitExactAmountInResponse, error) - // Estimates the amount of pool shares required to extract an exact amount of - // tokens from the pool. - EstimateExitExactAmountOut(ctx context.Context, in *QueryExitExactAmountOutRequest, opts ...grpc.CallOption) (*QueryExitExactAmountOutResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) PoolNumber(ctx context.Context, in *QueryPoolNumberRequest, opts ...grpc.CallOption) (*QueryPoolNumberResponse, error) { - out := new(QueryPoolNumberResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/PoolNumber", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Pool(ctx context.Context, in *QueryPoolRequest, opts ...grpc.CallOption) (*QueryPoolResponse, error) { - out := new(QueryPoolResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/Pool", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Pools(ctx context.Context, in *QueryPoolsRequest, opts ...grpc.CallOption) (*QueryPoolsResponse, error) { - out := new(QueryPoolsResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/Pools", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) PoolParams(ctx context.Context, in *QueryPoolParamsRequest, opts ...grpc.CallOption) (*QueryPoolParamsResponse, error) { - out := new(QueryPoolParamsResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/PoolParams", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) NumPools(ctx context.Context, in *QueryNumPoolsRequest, opts ...grpc.CallOption) (*QueryNumPoolsResponse, error) { - out := new(QueryNumPoolsResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/NumPools", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalLiquidity(ctx context.Context, in *QueryTotalLiquidityRequest, opts ...grpc.CallOption) (*QueryTotalLiquidityResponse, error) { - out := new(QueryTotalLiquidityResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/TotalLiquidity", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalPoolLiquidity(ctx context.Context, in *QueryTotalPoolLiquidityRequest, opts ...grpc.CallOption) (*QueryTotalPoolLiquidityResponse, error) { - out := new(QueryTotalPoolLiquidityResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/TotalPoolLiquidity", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TotalShares(ctx context.Context, in *QueryTotalSharesRequest, opts ...grpc.CallOption) (*QueryTotalSharesResponse, error) { - out := new(QueryTotalSharesResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/TotalShares", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) SpotPrice(ctx context.Context, in *QuerySpotPriceRequest, opts ...grpc.CallOption) (*QuerySpotPriceResponse, error) { - out := new(QuerySpotPriceResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/SpotPrice", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) EstimateSwapExactAmountIn(ctx context.Context, in *QuerySwapExactAmountInRequest, opts ...grpc.CallOption) (*QuerySwapExactAmountInResponse, error) { - out := new(QuerySwapExactAmountInResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/EstimateSwapExactAmountIn", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) EstimateSwapExactAmountOut(ctx context.Context, in *QuerySwapExactAmountOutRequest, opts ...grpc.CallOption) (*QuerySwapExactAmountOutResponse, error) { - out := new(QuerySwapExactAmountOutResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/EstimateSwapExactAmountOut", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) EstimateJoinExactAmountIn(ctx context.Context, in *QueryJoinExactAmountInRequest, opts ...grpc.CallOption) (*QueryJoinExactAmountInResponse, error) { - out := new(QueryJoinExactAmountInResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/EstimateJoinExactAmountIn", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) EstimateJoinExactAmountOut(ctx context.Context, in *QueryJoinExactAmountOutRequest, opts ...grpc.CallOption) (*QueryJoinExactAmountOutResponse, error) { - out := new(QueryJoinExactAmountOutResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/EstimateJoinExactAmountOut", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) EstimateExitExactAmountIn(ctx context.Context, in *QueryExitExactAmountInRequest, opts ...grpc.CallOption) (*QueryExitExactAmountInResponse, error) { - out := new(QueryExitExactAmountInResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/EstimateExitExactAmountIn", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) EstimateExitExactAmountOut(ctx context.Context, in *QueryExitExactAmountOutRequest, opts ...grpc.CallOption) (*QueryExitExactAmountOutResponse, error) { - out := new(QueryExitExactAmountOutResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Query/EstimateExitExactAmountOut", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Parameters of the spot module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Next available pool id number. - PoolNumber(context.Context, *QueryPoolNumberRequest) (*QueryPoolNumberResponse, error) - // Fetch a pool by id. - Pool(context.Context, *QueryPoolRequest) (*QueryPoolResponse, error) - // Returns all pools. - Pools(context.Context, *QueryPoolsRequest) (*QueryPoolsResponse, error) - // Parameters of a single pool. - PoolParams(context.Context, *QueryPoolParamsRequest) (*QueryPoolParamsResponse, error) - // Number of pools. - NumPools(context.Context, *QueryNumPoolsRequest) (*QueryNumPoolsResponse, error) - // Total liquidity across all pools. - TotalLiquidity(context.Context, *QueryTotalLiquidityRequest) (*QueryTotalLiquidityResponse, error) - // Total liquidity in a single pool. - TotalPoolLiquidity(context.Context, *QueryTotalPoolLiquidityRequest) (*QueryTotalPoolLiquidityResponse, error) - // Total shares in a single pool. - TotalShares(context.Context, *QueryTotalSharesRequest) (*QueryTotalSharesResponse, error) - // Instantaneous price of an asset in a pool. - SpotPrice(context.Context, *QuerySpotPriceRequest) (*QuerySpotPriceResponse, error) - // Estimates the amount of assets returned given an exact amount of tokens to - // swap. - EstimateSwapExactAmountIn(context.Context, *QuerySwapExactAmountInRequest) (*QuerySwapExactAmountInResponse, error) - // Estimates the amount of tokens required to return the exact amount of - // assets requested. - EstimateSwapExactAmountOut(context.Context, *QuerySwapExactAmountOutRequest) (*QuerySwapExactAmountOutResponse, error) - // Estimates the amount of pool shares returned given an amount of tokens to - // join. - EstimateJoinExactAmountIn(context.Context, *QueryJoinExactAmountInRequest) (*QueryJoinExactAmountInResponse, error) - // Estimates the amount of tokens required to obtain an exact amount of pool - // shares. - EstimateJoinExactAmountOut(context.Context, *QueryJoinExactAmountOutRequest) (*QueryJoinExactAmountOutResponse, error) - // Estimates the amount of tokens returned to the user given an exact amount - // of pool shares. - EstimateExitExactAmountIn(context.Context, *QueryExitExactAmountInRequest) (*QueryExitExactAmountInResponse, error) - // Estimates the amount of pool shares required to extract an exact amount of - // tokens from the pool. - EstimateExitExactAmountOut(context.Context, *QueryExitExactAmountOutRequest) (*QueryExitExactAmountOutResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} -func (*UnimplementedQueryServer) PoolNumber(ctx context.Context, req *QueryPoolNumberRequest) (*QueryPoolNumberResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method PoolNumber not implemented") -} -func (*UnimplementedQueryServer) Pool(ctx context.Context, req *QueryPoolRequest) (*QueryPoolResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Pool not implemented") -} -func (*UnimplementedQueryServer) Pools(ctx context.Context, req *QueryPoolsRequest) (*QueryPoolsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Pools not implemented") -} -func (*UnimplementedQueryServer) PoolParams(ctx context.Context, req *QueryPoolParamsRequest) (*QueryPoolParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method PoolParams not implemented") -} -func (*UnimplementedQueryServer) NumPools(ctx context.Context, req *QueryNumPoolsRequest) (*QueryNumPoolsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method NumPools not implemented") -} -func (*UnimplementedQueryServer) TotalLiquidity(ctx context.Context, req *QueryTotalLiquidityRequest) (*QueryTotalLiquidityResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalLiquidity not implemented") -} -func (*UnimplementedQueryServer) TotalPoolLiquidity(ctx context.Context, req *QueryTotalPoolLiquidityRequest) (*QueryTotalPoolLiquidityResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalPoolLiquidity not implemented") -} -func (*UnimplementedQueryServer) TotalShares(ctx context.Context, req *QueryTotalSharesRequest) (*QueryTotalSharesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TotalShares not implemented") -} -func (*UnimplementedQueryServer) SpotPrice(ctx context.Context, req *QuerySpotPriceRequest) (*QuerySpotPriceResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SpotPrice not implemented") -} -func (*UnimplementedQueryServer) EstimateSwapExactAmountIn(ctx context.Context, req *QuerySwapExactAmountInRequest) (*QuerySwapExactAmountInResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method EstimateSwapExactAmountIn not implemented") -} -func (*UnimplementedQueryServer) EstimateSwapExactAmountOut(ctx context.Context, req *QuerySwapExactAmountOutRequest) (*QuerySwapExactAmountOutResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method EstimateSwapExactAmountOut not implemented") -} -func (*UnimplementedQueryServer) EstimateJoinExactAmountIn(ctx context.Context, req *QueryJoinExactAmountInRequest) (*QueryJoinExactAmountInResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method EstimateJoinExactAmountIn not implemented") -} -func (*UnimplementedQueryServer) EstimateJoinExactAmountOut(ctx context.Context, req *QueryJoinExactAmountOutRequest) (*QueryJoinExactAmountOutResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method EstimateJoinExactAmountOut not implemented") -} -func (*UnimplementedQueryServer) EstimateExitExactAmountIn(ctx context.Context, req *QueryExitExactAmountInRequest) (*QueryExitExactAmountInResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method EstimateExitExactAmountIn not implemented") -} -func (*UnimplementedQueryServer) EstimateExitExactAmountOut(ctx context.Context, req *QueryExitExactAmountOutRequest) (*QueryExitExactAmountOutResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method EstimateExitExactAmountOut not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_PoolNumber_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryPoolNumberRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).PoolNumber(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/PoolNumber", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).PoolNumber(ctx, req.(*QueryPoolNumberRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Pool_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryPoolRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Pool(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/Pool", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Pool(ctx, req.(*QueryPoolRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Pools_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryPoolsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Pools(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/Pools", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Pools(ctx, req.(*QueryPoolsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_PoolParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryPoolParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).PoolParams(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/PoolParams", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).PoolParams(ctx, req.(*QueryPoolParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_NumPools_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryNumPoolsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).NumPools(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/NumPools", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).NumPools(ctx, req.(*QueryNumPoolsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalLiquidity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalLiquidityRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalLiquidity(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/TotalLiquidity", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalLiquidity(ctx, req.(*QueryTotalLiquidityRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalPoolLiquidity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalPoolLiquidityRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalPoolLiquidity(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/TotalPoolLiquidity", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalPoolLiquidity(ctx, req.(*QueryTotalPoolLiquidityRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TotalShares_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryTotalSharesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TotalShares(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/TotalShares", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TotalShares(ctx, req.(*QueryTotalSharesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_SpotPrice_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QuerySpotPriceRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).SpotPrice(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/SpotPrice", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).SpotPrice(ctx, req.(*QuerySpotPriceRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_EstimateSwapExactAmountIn_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QuerySwapExactAmountInRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).EstimateSwapExactAmountIn(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/EstimateSwapExactAmountIn", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).EstimateSwapExactAmountIn(ctx, req.(*QuerySwapExactAmountInRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_EstimateSwapExactAmountOut_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QuerySwapExactAmountOutRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).EstimateSwapExactAmountOut(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/EstimateSwapExactAmountOut", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).EstimateSwapExactAmountOut(ctx, req.(*QuerySwapExactAmountOutRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_EstimateJoinExactAmountIn_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryJoinExactAmountInRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).EstimateJoinExactAmountIn(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/EstimateJoinExactAmountIn", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).EstimateJoinExactAmountIn(ctx, req.(*QueryJoinExactAmountInRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_EstimateJoinExactAmountOut_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryJoinExactAmountOutRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).EstimateJoinExactAmountOut(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/EstimateJoinExactAmountOut", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).EstimateJoinExactAmountOut(ctx, req.(*QueryJoinExactAmountOutRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_EstimateExitExactAmountIn_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryExitExactAmountInRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).EstimateExitExactAmountIn(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/EstimateExitExactAmountIn", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).EstimateExitExactAmountIn(ctx, req.(*QueryExitExactAmountInRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_EstimateExitExactAmountOut_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryExitExactAmountOutRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).EstimateExitExactAmountOut(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Query/EstimateExitExactAmountOut", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).EstimateExitExactAmountOut(ctx, req.(*QueryExitExactAmountOutRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "nibiru.spot.v1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "PoolNumber", - Handler: _Query_PoolNumber_Handler, - }, - { - MethodName: "Pool", - Handler: _Query_Pool_Handler, - }, - { - MethodName: "Pools", - Handler: _Query_Pools_Handler, - }, - { - MethodName: "PoolParams", - Handler: _Query_PoolParams_Handler, - }, - { - MethodName: "NumPools", - Handler: _Query_NumPools_Handler, - }, - { - MethodName: "TotalLiquidity", - Handler: _Query_TotalLiquidity_Handler, - }, - { - MethodName: "TotalPoolLiquidity", - Handler: _Query_TotalPoolLiquidity_Handler, - }, - { - MethodName: "TotalShares", - Handler: _Query_TotalShares_Handler, - }, - { - MethodName: "SpotPrice", - Handler: _Query_SpotPrice_Handler, - }, - { - MethodName: "EstimateSwapExactAmountIn", - Handler: _Query_EstimateSwapExactAmountIn_Handler, - }, - { - MethodName: "EstimateSwapExactAmountOut", - Handler: _Query_EstimateSwapExactAmountOut_Handler, - }, - { - MethodName: "EstimateJoinExactAmountIn", - Handler: _Query_EstimateJoinExactAmountIn_Handler, - }, - { - MethodName: "EstimateJoinExactAmountOut", - Handler: _Query_EstimateJoinExactAmountOut_Handler, - }, - { - MethodName: "EstimateExitExactAmountIn", - Handler: _Query_EstimateExitExactAmountIn_Handler, - }, - { - MethodName: "EstimateExitExactAmountOut", - Handler: _Query_EstimateExitExactAmountOut_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "nibiru/spot/v1/query.proto", -} - -func (m *QueryParamsRequest) 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 *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) 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 *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.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 *QueryPoolNumberRequest) 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 *QueryPoolNumberRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPoolNumberRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryPoolNumberResponse) 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 *QueryPoolNumberResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPoolNumberResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.PoolId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryPoolRequest) 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 *QueryPoolRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPoolRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.PoolId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryPoolResponse) 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 *QueryPoolResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pool != nil { - { - size, err := m.Pool.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 *QueryPoolsRequest) 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 *QueryPoolsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPoolsRequest) 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 *QueryPoolsResponse) 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 *QueryPoolsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPoolsResponse) 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.Pools) > 0 { - for iNdEx := len(m.Pools) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Pools[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 *QueryPoolParamsRequest) 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 *QueryPoolParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPoolParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.PoolId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryPoolParamsResponse) 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 *QueryPoolParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPoolParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.PoolParams != nil { - { - size, err := m.PoolParams.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 *QueryNumPoolsRequest) 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 *QueryNumPoolsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryNumPoolsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryNumPoolsResponse) 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 *QueryNumPoolsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryNumPoolsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.NumPools != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.NumPools)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalLiquidityRequest) 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 *QueryTotalLiquidityRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalLiquidityRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryTotalLiquidityResponse) 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 *QueryTotalLiquidityResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalLiquidityResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Liquidity) > 0 { - for iNdEx := len(m.Liquidity) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Liquidity[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 *QueryTotalPoolLiquidityRequest) 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 *QueryTotalPoolLiquidityRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalPoolLiquidityRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.PoolId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalPoolLiquidityResponse) 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 *QueryTotalPoolLiquidityResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalPoolLiquidityResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Liquidity) > 0 { - for iNdEx := len(m.Liquidity) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Liquidity[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 *QueryTotalSharesRequest) 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 *QueryTotalSharesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSharesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.PoolId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryTotalSharesResponse) 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 *QueryTotalSharesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryTotalSharesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.TotalShares.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 *QuerySpotPriceRequest) 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 *QuerySpotPriceRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySpotPriceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TokenOutDenom) > 0 { - i -= len(m.TokenOutDenom) - copy(dAtA[i:], m.TokenOutDenom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.TokenOutDenom))) - i-- - dAtA[i] = 0x1a - } - if len(m.TokenInDenom) > 0 { - i -= len(m.TokenInDenom) - copy(dAtA[i:], m.TokenInDenom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.TokenInDenom))) - i-- - dAtA[i] = 0x12 - } - if m.PoolId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QuerySpotPriceResponse) 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 *QuerySpotPriceResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySpotPriceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.SpotPrice) > 0 { - i -= len(m.SpotPrice) - copy(dAtA[i:], m.SpotPrice) - i = encodeVarintQuery(dAtA, i, uint64(len(m.SpotPrice))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QuerySwapExactAmountInRequest) 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 *QuerySwapExactAmountInRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySwapExactAmountInRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TokenOutDenom) > 0 { - i -= len(m.TokenOutDenom) - copy(dAtA[i:], m.TokenOutDenom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.TokenOutDenom))) - i-- - dAtA[i] = 0x1a - } - { - size, err := m.TokenIn.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.PoolId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QuerySwapExactAmountInResponse) 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 *QuerySwapExactAmountInResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySwapExactAmountInResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Fee.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.TokenOut.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - return len(dAtA) - i, nil -} - -func (m *QuerySwapExactAmountOutRequest) 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 *QuerySwapExactAmountOutRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySwapExactAmountOutRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TokenInDenom) > 0 { - i -= len(m.TokenInDenom) - copy(dAtA[i:], m.TokenInDenom) - i = encodeVarintQuery(dAtA, i, uint64(len(m.TokenInDenom))) - i-- - dAtA[i] = 0x1a - } - { - size, err := m.TokenOut.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.PoolId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QuerySwapExactAmountOutResponse) 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 *QuerySwapExactAmountOutResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySwapExactAmountOutResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.TokenIn.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - return len(dAtA) - i, nil -} - -func (m *QueryJoinExactAmountInRequest) 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 *QueryJoinExactAmountInRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryJoinExactAmountInRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TokensIn) > 0 { - for iNdEx := len(m.TokensIn) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TokensIn[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if m.PoolId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryJoinExactAmountInResponse) 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 *QueryJoinExactAmountInResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryJoinExactAmountInResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RemCoins) > 0 { - for iNdEx := len(m.RemCoins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RemCoins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size := m.PoolSharesOut.Size() - i -= size - if _, err := m.PoolSharesOut.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 *QueryJoinExactAmountOutRequest) 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 *QueryJoinExactAmountOutRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryJoinExactAmountOutRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.PoolId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryJoinExactAmountOutResponse) 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 *QueryJoinExactAmountOutResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryJoinExactAmountOutResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryExitExactAmountInRequest) 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 *QueryExitExactAmountInRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryExitExactAmountInRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.PoolSharesIn.Size() - i -= size - if _, err := m.PoolSharesIn.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.PoolId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryExitExactAmountInResponse) 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 *QueryExitExactAmountInResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryExitExactAmountInResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Fees) > 0 { - for iNdEx := len(m.Fees) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Fees[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.TokensOut) > 0 { - for iNdEx := len(m.TokensOut) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TokensOut[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 *QueryExitExactAmountOutRequest) 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 *QueryExitExactAmountOutRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryExitExactAmountOutRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.PoolId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryExitExactAmountOutResponse) 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 *QueryExitExactAmountOutResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryExitExactAmountOutResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - 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 *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryPoolNumberRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryPoolNumberResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PoolId != 0 { - n += 1 + sovQuery(uint64(m.PoolId)) - } - return n -} - -func (m *QueryPoolRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PoolId != 0 { - n += 1 + sovQuery(uint64(m.PoolId)) - } - return n -} - -func (m *QueryPoolResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Pool != nil { - l = m.Pool.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryPoolsRequest) 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 *QueryPoolsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Pools) > 0 { - for _, e := range m.Pools { - 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 *QueryPoolParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PoolId != 0 { - n += 1 + sovQuery(uint64(m.PoolId)) - } - return n -} - -func (m *QueryPoolParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PoolParams != nil { - l = m.PoolParams.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryNumPoolsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryNumPoolsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.NumPools != 0 { - n += 1 + sovQuery(uint64(m.NumPools)) - } - return n -} - -func (m *QueryTotalLiquidityRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryTotalLiquidityResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Liquidity) > 0 { - for _, e := range m.Liquidity { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryTotalPoolLiquidityRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PoolId != 0 { - n += 1 + sovQuery(uint64(m.PoolId)) - } - return n -} - -func (m *QueryTotalPoolLiquidityResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Liquidity) > 0 { - for _, e := range m.Liquidity { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryTotalSharesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PoolId != 0 { - n += 1 + sovQuery(uint64(m.PoolId)) - } - return n -} - -func (m *QueryTotalSharesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.TotalShares.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QuerySpotPriceRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PoolId != 0 { - n += 1 + sovQuery(uint64(m.PoolId)) - } - l = len(m.TokenInDenom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.TokenOutDenom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySpotPriceResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.SpotPrice) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySwapExactAmountInRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PoolId != 0 { - n += 1 + sovQuery(uint64(m.PoolId)) - } - l = m.TokenIn.Size() - n += 1 + l + sovQuery(uint64(l)) - l = len(m.TokenOutDenom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySwapExactAmountInResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.TokenOut.Size() - n += 1 + l + sovQuery(uint64(l)) - l = m.Fee.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QuerySwapExactAmountOutRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PoolId != 0 { - n += 1 + sovQuery(uint64(m.PoolId)) - } - l = m.TokenOut.Size() - n += 1 + l + sovQuery(uint64(l)) - l = len(m.TokenInDenom) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySwapExactAmountOutResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.TokenIn.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryJoinExactAmountInRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PoolId != 0 { - n += 1 + sovQuery(uint64(m.PoolId)) - } - if len(m.TokensIn) > 0 { - for _, e := range m.TokensIn { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryJoinExactAmountInResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.PoolSharesOut.Size() - n += 1 + l + sovQuery(uint64(l)) - if len(m.RemCoins) > 0 { - for _, e := range m.RemCoins { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryJoinExactAmountOutRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PoolId != 0 { - n += 1 + sovQuery(uint64(m.PoolId)) - } - return n -} - -func (m *QueryJoinExactAmountOutResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryExitExactAmountInRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PoolId != 0 { - n += 1 + sovQuery(uint64(m.PoolId)) - } - l = m.PoolSharesIn.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryExitExactAmountInResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.TokensOut) > 0 { - for _, e := range m.TokensOut { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if len(m.Fees) > 0 { - for _, e := range m.Fees { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func (m *QueryExitExactAmountOutRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PoolId != 0 { - n += 1 + sovQuery(uint64(m.PoolId)) - } - return n -} - -func (m *QueryExitExactAmountOutResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = 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 *QueryParamsRequest) 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: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: 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 *QueryParamsResponse) 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: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", 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.Params.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 *QueryPoolNumberRequest) 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: QueryPoolNumberRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPoolNumberRequest: 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 *QueryPoolNumberResponse) 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: QueryPoolNumberResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPoolNumberResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - 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 *QueryPoolRequest) 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: QueryPoolRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPoolRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - 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 *QueryPoolResponse) 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: QueryPoolResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pool", 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.Pool == nil { - m.Pool = &Pool{} - } - if err := m.Pool.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 *QueryPoolsRequest) 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: QueryPoolsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPoolsRequest: 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 *QueryPoolsResponse) 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: QueryPoolsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPoolsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pools", 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.Pools = append(m.Pools, &Pool{}) - if err := m.Pools[len(m.Pools)-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 *QueryPoolParamsRequest) 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: QueryPoolParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPoolParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - 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 *QueryPoolParamsResponse) 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: QueryPoolParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPoolParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolParams", 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.PoolParams == nil { - m.PoolParams = &PoolParams{} - } - if err := m.PoolParams.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 *QueryNumPoolsRequest) 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: QueryNumPoolsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryNumPoolsRequest: 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 *QueryNumPoolsResponse) 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: QueryNumPoolsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryNumPoolsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field NumPools", wireType) - } - m.NumPools = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.NumPools |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - 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 *QueryTotalLiquidityRequest) 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: QueryTotalLiquidityRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalLiquidityRequest: 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 *QueryTotalLiquidityResponse) 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: QueryTotalLiquidityResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalLiquidityResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Liquidity", 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.Liquidity = append(m.Liquidity, types.Coin{}) - if err := m.Liquidity[len(m.Liquidity)-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 *QueryTotalPoolLiquidityRequest) 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: QueryTotalPoolLiquidityRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalPoolLiquidityRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - 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 *QueryTotalPoolLiquidityResponse) 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: QueryTotalPoolLiquidityResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalPoolLiquidityResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Liquidity", 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.Liquidity = append(m.Liquidity, types.Coin{}) - if err := m.Liquidity[len(m.Liquidity)-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 *QueryTotalSharesRequest) 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: QueryTotalSharesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSharesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - 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 *QueryTotalSharesResponse) 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: QueryTotalSharesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryTotalSharesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalShares", 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.TotalShares.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 *QuerySpotPriceRequest) 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: QuerySpotPriceRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySpotPriceRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenInDenom", 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.TokenInDenom = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenOutDenom", 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.TokenOutDenom = 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 *QuerySpotPriceResponse) 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: QuerySpotPriceResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySpotPriceResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SpotPrice", 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.SpotPrice = 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 *QuerySwapExactAmountInRequest) 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: QuerySwapExactAmountInRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySwapExactAmountInRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenIn", 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.TokenIn.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenOutDenom", 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.TokenOutDenom = 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 *QuerySwapExactAmountInResponse) 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: QuerySwapExactAmountInResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySwapExactAmountInResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenOut", 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.TokenOut.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Fee", 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.Fee.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 *QuerySwapExactAmountOutRequest) 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: QuerySwapExactAmountOutRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySwapExactAmountOutRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenOut", 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.TokenOut.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenInDenom", 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.TokenInDenom = 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 *QuerySwapExactAmountOutResponse) 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: QuerySwapExactAmountOutResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySwapExactAmountOutResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenIn", 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.TokenIn.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 *QueryJoinExactAmountInRequest) 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: QueryJoinExactAmountInRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryJoinExactAmountInRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokensIn", 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.TokensIn = append(m.TokensIn, types.Coin{}) - if err := m.TokensIn[len(m.TokensIn)-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 *QueryJoinExactAmountInResponse) 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: QueryJoinExactAmountInResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryJoinExactAmountInResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolSharesOut", 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.PoolSharesOut.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RemCoins", 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.RemCoins = append(m.RemCoins, types.Coin{}) - if err := m.RemCoins[len(m.RemCoins)-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 *QueryJoinExactAmountOutRequest) 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: QueryJoinExactAmountOutRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryJoinExactAmountOutRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - 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 *QueryJoinExactAmountOutResponse) 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: QueryJoinExactAmountOutResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryJoinExactAmountOutResponse: 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 *QueryExitExactAmountInRequest) 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: QueryExitExactAmountInRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryExitExactAmountInRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolSharesIn", 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.PoolSharesIn.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 *QueryExitExactAmountInResponse) 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: QueryExitExactAmountInResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryExitExactAmountInResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokensOut", 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.TokensOut = append(m.TokensOut, types.Coin{}) - if err := m.TokensOut[len(m.TokensOut)-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 Fees", 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.Fees = append(m.Fees, types.Coin{}) - if err := m.Fees[len(m.Fees)-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 *QueryExitExactAmountOutRequest) 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: QueryExitExactAmountOutRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryExitExactAmountOutRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - 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 *QueryExitExactAmountOutResponse) 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: QueryExitExactAmountOutResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryExitExactAmountOutResponse: 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 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/spot/types/query.pb.gw.go b/x/spot/types/query.pb.gw.go deleted file mode 100644 index 7669c197a..000000000 --- a/x/spot/types/query.pb.gw.go +++ /dev/null @@ -1,1614 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: nibiru/spot/v1/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 - -func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_PoolNumber_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPoolNumberRequest - var metadata runtime.ServerMetadata - - msg, err := client.PoolNumber(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_PoolNumber_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPoolNumberRequest - var metadata runtime.ServerMetadata - - msg, err := server.PoolNumber(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Pool_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Pool_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPoolRequest - 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_Pool_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Pool(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Pool_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPoolRequest - 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_Pool_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Pool(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_Pools_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Pools_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPoolsRequest - 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_Pools_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Pools(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Pools_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPoolsRequest - 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_Pools_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Pools(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_PoolParams_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPoolParamsRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - msg, err := client.PoolParams(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_PoolParams_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPoolParamsRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - msg, err := server.PoolParams(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_NumPools_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryNumPoolsRequest - var metadata runtime.ServerMetadata - - msg, err := client.NumPools(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_NumPools_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryNumPoolsRequest - var metadata runtime.ServerMetadata - - msg, err := server.NumPools(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_TotalLiquidity_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalLiquidityRequest - var metadata runtime.ServerMetadata - - msg, err := client.TotalLiquidity(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalLiquidity_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalLiquidityRequest - var metadata runtime.ServerMetadata - - msg, err := server.TotalLiquidity(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_TotalPoolLiquidity_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalPoolLiquidityRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - msg, err := client.TotalPoolLiquidity(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalPoolLiquidity_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalPoolLiquidityRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - msg, err := server.TotalPoolLiquidity(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_TotalShares_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSharesRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - msg, err := client.TotalShares(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_TotalShares_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryTotalSharesRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - msg, err := server.TotalShares(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_SpotPrice_0 = &utilities.DoubleArray{Encoding: map[string]int{"pool_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Query_SpotPrice_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySpotPriceRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SpotPrice_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.SpotPrice(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_SpotPrice_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySpotPriceRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SpotPrice_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.SpotPrice(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_EstimateSwapExactAmountIn_0 = &utilities.DoubleArray{Encoding: map[string]int{"pool_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Query_EstimateSwapExactAmountIn_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySwapExactAmountInRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_EstimateSwapExactAmountIn_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.EstimateSwapExactAmountIn(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_EstimateSwapExactAmountIn_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySwapExactAmountInRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_EstimateSwapExactAmountIn_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.EstimateSwapExactAmountIn(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_EstimateSwapExactAmountOut_0 = &utilities.DoubleArray{Encoding: map[string]int{"pool_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Query_EstimateSwapExactAmountOut_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySwapExactAmountOutRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_EstimateSwapExactAmountOut_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.EstimateSwapExactAmountOut(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_EstimateSwapExactAmountOut_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySwapExactAmountOutRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_EstimateSwapExactAmountOut_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.EstimateSwapExactAmountOut(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_EstimateJoinExactAmountIn_0 = &utilities.DoubleArray{Encoding: map[string]int{"pool_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Query_EstimateJoinExactAmountIn_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryJoinExactAmountInRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_EstimateJoinExactAmountIn_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.EstimateJoinExactAmountIn(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_EstimateJoinExactAmountIn_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryJoinExactAmountInRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_EstimateJoinExactAmountIn_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.EstimateJoinExactAmountIn(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_EstimateJoinExactAmountOut_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryJoinExactAmountOutRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - msg, err := client.EstimateJoinExactAmountOut(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_EstimateJoinExactAmountOut_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryJoinExactAmountOutRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - msg, err := server.EstimateJoinExactAmountOut(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Query_EstimateExitExactAmountIn_0 = &utilities.DoubleArray{Encoding: map[string]int{"pool_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Query_EstimateExitExactAmountIn_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryExitExactAmountInRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_EstimateExitExactAmountIn_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.EstimateExitExactAmountIn(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_EstimateExitExactAmountIn_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryExitExactAmountInRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_EstimateExitExactAmountIn_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.EstimateExitExactAmountIn(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Query_EstimateExitExactAmountOut_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryExitExactAmountOutRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - msg, err := client.EstimateExitExactAmountOut(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_EstimateExitExactAmountOut_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryExitExactAmountOutRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - msg, err := server.EstimateExitExactAmountOut(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_Params_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_Params_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_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_PoolNumber_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_PoolNumber_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_PoolNumber_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Pool_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_Pool_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_Pool_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Pools_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_Pools_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_Pools_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_PoolParams_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_PoolParams_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_PoolParams_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_NumPools_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_NumPools_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_NumPools_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalLiquidity_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_TotalLiquidity_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_TotalLiquidity_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalPoolLiquidity_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_TotalPoolLiquidity_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_TotalPoolLiquidity_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalShares_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_TotalShares_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_TotalShares_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_SpotPrice_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_SpotPrice_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_SpotPrice_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_EstimateSwapExactAmountIn_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_EstimateSwapExactAmountIn_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_EstimateSwapExactAmountIn_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_EstimateSwapExactAmountOut_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_EstimateSwapExactAmountOut_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_EstimateSwapExactAmountOut_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_EstimateJoinExactAmountIn_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_EstimateJoinExactAmountIn_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_EstimateJoinExactAmountIn_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_EstimateJoinExactAmountOut_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_EstimateJoinExactAmountOut_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_EstimateJoinExactAmountOut_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_EstimateExitExactAmountIn_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_EstimateExitExactAmountIn_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_EstimateExitExactAmountIn_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_EstimateExitExactAmountOut_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_EstimateExitExactAmountOut_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_EstimateExitExactAmountOut_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_Params_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_Params_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_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_PoolNumber_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_PoolNumber_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_PoolNumber_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Pool_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_Pool_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_Pool_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_Pools_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_Pools_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_Pools_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_PoolParams_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_PoolParams_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_PoolParams_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_NumPools_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_NumPools_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_NumPools_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalLiquidity_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_TotalLiquidity_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_TotalLiquidity_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalPoolLiquidity_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_TotalPoolLiquidity_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_TotalPoolLiquidity_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_TotalShares_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_TotalShares_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_TotalShares_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_SpotPrice_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_SpotPrice_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_SpotPrice_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_EstimateSwapExactAmountIn_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_EstimateSwapExactAmountIn_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_EstimateSwapExactAmountIn_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_EstimateSwapExactAmountOut_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_EstimateSwapExactAmountOut_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_EstimateSwapExactAmountOut_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_EstimateJoinExactAmountIn_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_EstimateJoinExactAmountIn_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_EstimateJoinExactAmountIn_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_EstimateJoinExactAmountOut_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_EstimateJoinExactAmountOut_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_EstimateJoinExactAmountOut_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_EstimateExitExactAmountIn_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_EstimateExitExactAmountIn_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_EstimateExitExactAmountIn_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_Query_EstimateExitExactAmountOut_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_EstimateExitExactAmountOut_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_EstimateExitExactAmountOut_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"nibiru", "spot", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_PoolNumber_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"nibiru", "spot", "pool_number"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Pool_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"nibiru", "spot", "pool"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Pools_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"nibiru", "spot", "pools"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_PoolParams_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4}, []string{"nibiru", "spot", "pools", "pool_id", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_NumPools_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"nibiru", "spot", "num_pools"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalLiquidity_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"nibiru", "spot", "total_liquidity"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalPoolLiquidity_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4}, []string{"nibiru", "spot", "pools", "pool_id", "total_pool_liquidity"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_TotalShares_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4}, []string{"nibiru", "spot", "pools", "pool_id", "total_shares"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_SpotPrice_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4}, []string{"nibiru", "spot", "pools", "pool_id", "prices"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_EstimateSwapExactAmountIn_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 2, 4}, []string{"nibiru", "spot", "pool_id", "estimate", "swap_exact_amount_in"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_EstimateSwapExactAmountOut_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 2, 4}, []string{"nibiru", "spot", "pool_id", "estimate", "swap_exact_amount_out"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_EstimateJoinExactAmountIn_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 2, 4}, []string{"nibiru", "spot", "pool_id", "estimate", "join_exact_amount_in"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_EstimateJoinExactAmountOut_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 2, 4}, []string{"nibiru", "spot", "pool_id", "estimate", "join_exact_amount_out"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_EstimateExitExactAmountIn_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 2, 4}, []string{"nibiru", "spot", "pool_id", "estimate", "exit_exact_amount_in"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_EstimateExitExactAmountOut_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 2, 4}, []string{"nibiru", "spot", "pool_id", "estimate", "exit_exact_amount_out"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_PoolNumber_0 = runtime.ForwardResponseMessage - - forward_Query_Pool_0 = runtime.ForwardResponseMessage - - forward_Query_Pools_0 = runtime.ForwardResponseMessage - - forward_Query_PoolParams_0 = runtime.ForwardResponseMessage - - forward_Query_NumPools_0 = runtime.ForwardResponseMessage - - forward_Query_TotalLiquidity_0 = runtime.ForwardResponseMessage - - forward_Query_TotalPoolLiquidity_0 = runtime.ForwardResponseMessage - - forward_Query_TotalShares_0 = runtime.ForwardResponseMessage - - forward_Query_SpotPrice_0 = runtime.ForwardResponseMessage - - forward_Query_EstimateSwapExactAmountIn_0 = runtime.ForwardResponseMessage - - forward_Query_EstimateSwapExactAmountOut_0 = runtime.ForwardResponseMessage - - forward_Query_EstimateJoinExactAmountIn_0 = runtime.ForwardResponseMessage - - forward_Query_EstimateJoinExactAmountOut_0 = runtime.ForwardResponseMessage - - forward_Query_EstimateExitExactAmountIn_0 = runtime.ForwardResponseMessage - - forward_Query_EstimateExitExactAmountOut_0 = runtime.ForwardResponseMessage -) diff --git a/x/spot/types/shares.go b/x/spot/types/shares.go deleted file mode 100644 index b6a958b70..000000000 --- a/x/spot/types/shares.go +++ /dev/null @@ -1,242 +0,0 @@ -package types - -import ( - "errors" - - sdkmath "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -/* -Takes a pool and the amount of tokens desired to add to the pool, -and calculates the number of pool shares and remaining coins after theoretically -adding the tokensIn to the pool. - -Note that this function is pure/read-only. It only calculates the theoretical amoount -and doesn't modify the actual state. - -args: - - tokensIn: a slice of coins to add to the pool - -ret: - - numShares: the number of LP shares representing the maximal number of tokens added to the pool - - remCoins: the remaining number of coins after adding the tokens - - err: error if any -*/ -func (pool Pool) numSharesOutFromTokensIn(tokensIn sdk.Coins) ( - numShares sdkmath.Int, remCoins sdk.Coins, err error, -) { - coinShareRatios := make([]sdk.Dec, len(tokensIn)) - minShareRatio := sdk.MaxSortableDec - maxShareRatio := sdk.ZeroDec() - - poolLiquidity := pool.PoolBalances() - if len(tokensIn) == 1 { - // From balancer whitepaper, for 2 assets with the same weight, the shares issued are: - // P_{supply} * (sqrt(1+((1-f/2) * x_{in})/X)-1) - - one := sdk.OneDec() - - joinShare := sdk.NewDecFromInt(tokensIn[0].Amount).Mul(one.Sub(pool.PoolParams.SwapFee.Quo(sdk.NewDec(2)))).QuoInt( - poolLiquidity.AmountOfNoDenomValidation(tokensIn[0].Denom), - ).Add(one) - - joinShare, err = joinShare.ApproxSqrt() - if err != nil { - return - } - - numShares = joinShare.Sub(one).MulInt(pool.TotalShares.Amount).TruncateInt() - return - } - - for i, coin := range tokensIn { - shareRatio := sdk.NewDecFromInt(coin.Amount).QuoInt( - poolLiquidity.AmountOfNoDenomValidation(coin.Denom), - ) - if shareRatio.LT(minShareRatio) { - minShareRatio = shareRatio - } - if shareRatio.GT(maxShareRatio) { - maxShareRatio = shareRatio - } - coinShareRatios[i] = shareRatio - } - - if minShareRatio.Equal(sdk.MaxSortableDec) { - return sdk.ZeroInt(), sdk.NewCoins(), errors.New("unexpected error in balancer maximalExactRatioJoin") - } - - if minShareRatio.IsZero() { - return sdk.ZeroInt(), tokensIn, nil - } - - numShares = minShareRatio.MulInt(pool.TotalShares.Amount).TruncateInt() - remCoins = sdk.Coins{} - - // if we have multiple shares, calculate remCoins - if !minShareRatio.Equal(maxShareRatio) { - // we have to calculate remCoins - for i, coin := range tokensIn { - if !coinShareRatios[i].Equal(minShareRatio) { - usedAmount := minShareRatio.MulInt( - poolLiquidity.AmountOfNoDenomValidation(coin.Denom)).Ceil().TruncateInt() - remainingAmount := coin.Amount.Sub(usedAmount) - // add to RemCoins - if !remainingAmount.IsZero() { - remCoins = remCoins.Add(sdk.Coin{Denom: coin.Denom, Amount: remainingAmount}) - } - } - } - } - - return numShares, remCoins, nil -} - -/* -For a stableswap pool, takes the amount of tokens desired to add to the pool, -and calculates the number of pool shares and remaining coins after theoretically -adding the tokensIn to the pool. All tokens are used in this function. - -The delta in number of share follows the evolution of the constant of the pool. E.g. if someone bring tokens -to increase the value D of the pool by 10%, he will receive 10% of the existing token share. - -Note that this function is pure/read-only. It only calculates the theoretical amoount -and doesn't modify the actual state. - -args: - - tokensIn: a slice of coins to add to the pool - -ret: - - numShares: the number of LP shares representing the maximal number of tokens added to the pool - - remCoins: the remaining number of coins after adding the tokens - - err: error if any -*/ -func (pool Pool) numSharesOutFromTokensInStableSwap(tokensIn sdk.Coins) ( - numShares sdkmath.Int, err error, -) { - tokenSupply := pool.TotalShares.Amount - - D, err := pool.GetD(pool.PoolAssets) - if err != nil { - return - } - D0 := sdk.NewInt(int64(D.Uint64())) - - var newPoolAssets []PoolAsset - - for assetIndex, poolAsset := range pool.PoolAssets { - inAmount := tokensIn.AmountOf(poolAsset.Token.Denom) - - if !inAmount.IsZero() { - newAmount := pool.PoolAssets[assetIndex].Token.Amount.Add(inAmount) - - newPoolAssets = append(newPoolAssets, PoolAsset{Token: sdk.NewCoin(poolAsset.Token.Denom, newAmount)}) - } else { - newPoolAssets = append(newPoolAssets, poolAsset) - } - } - - newD, err := pool.GetD(newPoolAssets) - if err != nil { - return - } - D1 := sdk.NewInt(int64(newD.Uint64())) - if D1.LT(D0) { - // Should not happen - err = ErrInvariantLowerAfterJoining - return - } - - // Calculate, how much pool tokens to mint - numShares = tokenSupply.Mul(D1.Sub(D0)).Quo(D0) - - return -} - -/* -TokensOutFromPoolSharesIn Calculates the number of tokens to remove from liquidity given LP shares returned to the pool. - -Note that this function is pure/read-only. It only calculates the theoretical amoount -and doesn't modify the actual state. - -args: - - numSharesIn: number of LP shares to return to the pool - -ret: - - tokensOut: the tokens withdrawn from the pool - - fees: the fees collected - - err: error if any -*/ -func (pool Pool) TokensOutFromPoolSharesIn(numSharesIn sdkmath.Int) ( - tokensOut sdk.Coins, fees sdk.Coins, err error, -) { - if numSharesIn.IsZero() { - return nil, nil, errors.New("num shares in must be greater than zero") - } - - shareRatio := sdk.NewDecFromInt(numSharesIn).QuoInt(pool.TotalShares.Amount) - if shareRatio.IsZero() { - return nil, nil, errors.New("share ratio must be greater than zero") - } - if shareRatio.GT(sdk.OneDec()) { - return nil, nil, errors.New("share ratio cannot be greater than one") - } - - poolLiquidity := pool.PoolBalances() - tokensOut = make(sdk.Coins, len(poolLiquidity)) - fees = make(sdk.Coins, len(poolLiquidity)) - for i, coin := range poolLiquidity { - // tokenOut = shareRatio * poolTokenAmt * (1 - exitFee) - tokenAmount := shareRatio.MulInt(coin.Amount) - tokenOutAmt := tokenAmount.Mul( - sdk.OneDec().Sub(pool.PoolParams.ExitFee), - ).TruncateInt() - tokensOut[i] = sdk.NewCoin(coin.Denom, tokenOutAmt) - fees[i] = sdk.NewCoin(coin.Denom, tokenAmount.TruncateInt().Sub(tokenOutAmt)) - } - - return tokensOut, sdk.NewCoins(fees...), nil -} - -/* -Compute the minimum number of shares a user need to provide to get at least one u-token -*/ -func (pool Pool) MinSharesInForTokensOut() (minShares sdkmath.Int) { - poolLiquidity := pool.PoolBalances() - - minShares = sdk.ZeroInt() - - for _, coin := range poolLiquidity { - shareRatio := sdk.MustNewDecFromStr("2").Quo(sdk.NewDecFromInt(coin.Amount).Quo(sdk.OneDec().Sub(pool.PoolParams.ExitFee))) - - shares := shareRatio.MulInt(pool.TotalShares.Amount).TruncateInt() - - if minShares.IsZero() || minShares.LT(shares) { - minShares = shares - } - } - return -} - -/* -Adds new liquidity to the pool and increments the total number of shares. - -args: - - numShares: the number of LP shares to increment - - newLiquidity: the new tokens to deposit into the pool -*/ -func (pool *Pool) incrementBalances(numShares sdkmath.Int, newLiquidity sdk.Coins) ( - err error, -) { - for _, coin := range newLiquidity { - i, poolAsset, err := pool.getPoolAssetAndIndex(coin.Denom) - if err != nil { - return err - } - poolAsset.Token.Amount = poolAsset.Token.Amount.Add(coin.Amount) - pool.PoolAssets[i] = poolAsset - } - pool.TotalShares.Amount = pool.TotalShares.Amount.Add(numShares) - return nil -} diff --git a/x/spot/types/shares_test.go b/x/spot/types/shares_test.go deleted file mode 100644 index 8ca4e98f4..000000000 --- a/x/spot/types/shares_test.go +++ /dev/null @@ -1,499 +0,0 @@ -package types - -import ( - "testing" - - sdkmath "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestMaximalSharesFromExactRatioJoin(t *testing.T) { - for _, tc := range []struct { - name string - poolAssets []PoolAsset - existingShares int64 - tokensIn sdk.Coins - expectedNumShares sdkmath.Int - expectedRemCoins sdk.Coins - }{ - { - name: "all coins deposited", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 100), - }, - }, - existingShares: 100, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 100), - sdk.NewInt64Coin("bbb", 100), - ), - expectedNumShares: sdk.NewInt(100), - expectedRemCoins: sdk.NewCoins(), - }, - { - name: "some coins deposited", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 100), - }, - }, - existingShares: 100, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 100), - sdk.NewInt64Coin("bbb", 50), - ), - expectedNumShares: sdk.NewInt(50), - expectedRemCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 50), - ), - }, - { - name: "limited by smallest amount", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 100), - }, - }, - existingShares: 100, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 1), - sdk.NewInt64Coin("bbb", 50), - ), - expectedNumShares: sdk.OneInt(), - expectedRemCoins: sdk.NewCoins( - sdk.NewInt64Coin("bbb", 49), - ), - }, - { - name: "limited by smallest amount - 2", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - }, - }, - existingShares: 100, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 10), - sdk.NewInt64Coin("bbb", 10), - ), - expectedNumShares: sdk.NewInt(5), - expectedRemCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 5), - ), - }, - { - name: "right number of LP shares", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 50), - }, - { - Token: sdk.NewInt64Coin("bbb", 100), - }, - }, - existingShares: 150, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 50), - sdk.NewInt64Coin("bbb", 50), - ), - expectedNumShares: sdk.NewInt(75), - expectedRemCoins: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 25), - ), - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - pool := Pool{ - Id: 1, - Address: "some_address", - PoolParams: PoolParams{}, - PoolAssets: tc.poolAssets, - TotalWeight: sdk.OneInt(), - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", tc.existingShares), - } - numShares, remCoins, _ := pool.numSharesOutFromTokensIn(tc.tokensIn) - require.Equal(t, tc.expectedNumShares, numShares) - require.Equal(t, tc.expectedRemCoins, remCoins) - }) - } -} - -func TestTokensOutFromExactSharesHappyPath(t *testing.T) { - for _, tc := range []struct { - name string - pool Pool - numSharesIn sdkmath.Int - expectedTokensOut sdk.Coins - expectedFees sdk.Coins - }{ - { - name: "all coins withdrawn, no exit fee", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - }, - { - Token: sdk.NewInt64Coin("foo", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 50), - PoolParams: PoolParams{ - ExitFee: sdk.ZeroDec(), - }, - }, - numSharesIn: sdk.NewInt(50), - expectedTokensOut: sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 200), - ), - expectedFees: sdk.Coins{}, - }, - { - name: "partial coins withdrawn, no exit fee", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - }, - { - Token: sdk.NewInt64Coin("foo", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 50), - PoolParams: PoolParams{ - ExitFee: sdk.ZeroDec(), - }, - }, - numSharesIn: sdk.NewInt(25), - expectedTokensOut: sdk.NewCoins( - sdk.NewInt64Coin("bar", 50), - sdk.NewInt64Coin("foo", 100), - ), - expectedFees: sdk.Coins{}, - }, - { - name: "fractional coins withdrawn truncates to int, no exit fee", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - }, - { - Token: sdk.NewInt64Coin("foo", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 1000), - PoolParams: PoolParams{ - ExitFee: sdk.ZeroDec(), - }, - }, - numSharesIn: sdk.NewInt(25), - expectedTokensOut: sdk.NewCoins( - sdk.NewInt64Coin("bar", 2), - sdk.NewInt64Coin("foo", 5), - ), - expectedFees: sdk.Coins{}, - }, - { - name: "all coins withdrawn, with exit fee", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - }, - { - Token: sdk.NewInt64Coin("foo", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 50), - PoolParams: PoolParams{ - ExitFee: sdk.MustNewDecFromStr("0.5"), - }, - }, - numSharesIn: sdk.NewInt(50), - expectedTokensOut: sdk.NewCoins( - sdk.NewInt64Coin("bar", 50), - sdk.NewInt64Coin("foo", 100), - ), - expectedFees: sdk.NewCoins( - sdk.NewInt64Coin("bar", 50), - sdk.NewInt64Coin("foo", 100), - ), - }, - { - name: "partial coins withdrawn, with exit fee", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - }, - { - Token: sdk.NewInt64Coin("foo", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 50), - PoolParams: PoolParams{ - ExitFee: sdk.MustNewDecFromStr("0.5"), - }, - }, - numSharesIn: sdk.NewInt(25), - expectedTokensOut: sdk.NewCoins( - sdk.NewInt64Coin("bar", 25), - sdk.NewInt64Coin("foo", 50), - ), - expectedFees: sdk.NewCoins( - sdk.NewInt64Coin("bar", 25), - sdk.NewInt64Coin("foo", 50), - ), - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - tokensOut, fees, err := tc.pool.TokensOutFromPoolSharesIn(tc.numSharesIn) - require.NoError(t, err) - require.Equal(t, tc.expectedTokensOut, tokensOut) - require.Equal(t, tc.expectedFees, fees) - }) - } -} - -func TestTokensOutFromExactSharesErrors(t *testing.T) { - for _, tc := range []struct { - name string - pool Pool - numSharesIn sdkmath.Int - }{ - { - name: "zero pool shares", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - }, - { - Token: sdk.NewInt64Coin("foo", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 50), - }, - numSharesIn: sdk.ZeroInt(), - }, - { - name: "too many pool shares", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - }, - { - Token: sdk.NewInt64Coin("foo", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 50), - }, - numSharesIn: sdk.NewInt(51), - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - _, _, err := tc.pool.TokensOutFromPoolSharesIn(tc.numSharesIn) - require.Error(t, err) - }) - } -} - -func TestUpdateLiquidityHappyPath(t *testing.T) { - for _, tc := range []struct { - name string - pool Pool - numShares sdkmath.Int - newLiquidity sdk.Coins - expectedNumShares sdkmath.Int - expectedNewPoolAssets []PoolAsset - }{ - { - name: "all coins deposited", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - }, - numShares: sdk.NewInt(10), - newLiquidity: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 10), - sdk.NewInt64Coin("bbb", 20), - ), - expectedNumShares: sdk.NewInt(110), - expectedNewPoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 110), - }, - { - Token: sdk.NewInt64Coin("bbb", 220), - }, - }, - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - err := tc.pool.incrementBalances(tc.numShares, tc.newLiquidity) - require.NoError(t, err) - require.Equal(t, tc.expectedNumShares, tc.pool.TotalShares.Amount) - require.Equal(t, tc.expectedNewPoolAssets, tc.pool.PoolAssets) - }) - } -} - -func TestUpdateLiquidityInvalidInput(t *testing.T) { - for _, tc := range []struct { - name string - pool Pool - numShares sdkmath.Int - newLiquidity sdk.Coins - }{ - { - name: "add non-existent coin", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - }, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - }, - numShares: sdk.NewInt(10), - newLiquidity: sdk.NewCoins( - sdk.NewInt64Coin("bbb", 20), - ), - }, - { - name: "no existing liquidity", - pool: Pool{ - PoolAssets: []PoolAsset{}, - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", 100), - }, - numShares: sdk.NewInt(10), - newLiquidity: sdk.NewCoins( - sdk.NewInt64Coin("bbb", 20), - ), - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - err := tc.pool.incrementBalances(tc.numShares, tc.newLiquidity) - require.Error(t, err) - }) - } -} - -func TestNumSharesOutStableswap(t *testing.T) { - for _, tc := range []struct { - name string - poolAssets []PoolAsset - existingShares int64 - tokensIn sdk.Coins - expectedNumShares sdkmath.Int - A sdkmath.Int - expectedError error - }{ - { - name: "all coins deposited", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 100), - }, - }, - A: sdk.NewInt(2000), - existingShares: 50, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 100), - sdk.NewInt64Coin("bbb", 100), - ), - expectedNumShares: sdk.NewInt(50), - }, - { - name: "all coins deposited - 3pool", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 100), - }, - { - Token: sdk.NewInt64Coin("ccc", 100), - }, - }, - A: sdk.NewInt(2000), - existingShares: 50, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 100), - sdk.NewInt64Coin("bbb", 100), - ), - expectedNumShares: sdk.NewInt(33), - }, - { - name: "all coins deposited - imbalance", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 100), - }, - }, - A: sdk.NewInt(2000), - existingShares: 50, - tokensIn: sdk.NewCoins( - sdk.NewInt64Coin("aaa", 50), - sdk.NewInt64Coin("bbb", 100), - ), - expectedNumShares: sdk.NewInt(37), - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - pool := Pool{ - Id: 1, - Address: "some_address", - PoolParams: PoolParams{A: tc.A}, - PoolAssets: tc.poolAssets, - TotalWeight: sdk.OneInt(), - TotalShares: sdk.NewInt64Coin("nibiru/pool/1", tc.existingShares), - } - numShares, err := pool.numSharesOutFromTokensInStableSwap(tc.tokensIn) - if tc.expectedError != nil { - require.ErrorIs(t, err, tc.expectedError) - } else { - require.NoError(t, err) - require.Equal(t, tc.expectedNumShares, numShares) - } - }) - } -} diff --git a/x/spot/types/swap.go b/x/spot/types/swap.go deleted file mode 100644 index a73172b7f..000000000 --- a/x/spot/types/swap.go +++ /dev/null @@ -1,193 +0,0 @@ -package types - -import ( - "fmt" - - sdkmath "cosmossdk.io/math" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/NibiruChain/nibiru/x/spot/math" -) - -/* -CalcOutAmtGivenIn Calculates the amount of tokenOut given tokenIn, deducting the swap fee. -Solved using the SolveConstantProductInvariant AMM curve. -Only supports single asset swaps. - -args: - - tokenIn: the amount of tokens to swap - - tokenOutDenom: the target token denom - - noFee: whether we want to bypass swap fee (for single asset join) - -ret: - - tokenOut: the tokens received from the swap - - fee: the fee deducted from the swap - - err: error if any -*/ -func (pool Pool) CalcOutAmtGivenIn(tokenIn sdk.Coin, tokenOutDenom string, noFee bool) ( - tokenOut sdk.Coin, fee sdk.Coin, err error, -) { - _, poolAssetIn, err := pool.getPoolAssetAndIndex(tokenIn.Denom) - if err != nil { - return tokenOut, fee, err - } - - _, poolAssetOut, err := pool.getPoolAssetAndIndex(tokenOutDenom) - if err != nil { - return tokenOut, fee, err - } - - var tokenAmountInAfterFee sdk.Dec - if noFee { - tokenAmountInAfterFee = sdk.NewDecFromInt(tokenIn.Amount) - } else { - tokenAmountInAfterFee = sdk.NewDecFromInt(tokenIn.Amount).Mul(sdk.OneDec().Sub(pool.PoolParams.SwapFee)) - } - feeAmount := sdk.NewDecFromInt(tokenIn.Amount).Sub(tokenAmountInAfterFee) - fee = sdk.NewCoin(tokenIn.Denom, feeAmount.TruncateInt()) - - poolTokenInBalance := sdk.NewDecFromInt(poolAssetIn.Token.Amount) - poolTokenInBalancePostSwap := poolTokenInBalance.Add(tokenAmountInAfterFee) - - // deduct swapfee on the in asset - // delta balanceOut is positive(tokens inside the pool decreases) - var tokenAmountOut sdkmath.Int - if pool.PoolParams.PoolType == PoolType_STABLESWAP { - tokenAmountOut, err = pool.Exchange(sdk.NewCoin(tokenIn.Denom, tokenAmountInAfterFee.TruncateInt()), tokenOutDenom) - - if err != nil { - return - } - } else if pool.PoolParams.PoolType == PoolType_BALANCER { - tokenAmountOut = math.SolveConstantProductInvariant( - /*xPrior=*/ poolTokenInBalance, - /*xAfter=*/ poolTokenInBalancePostSwap, - /*xWeight=*/ sdk.NewDecFromInt(poolAssetIn.Weight), - /*yPrior=*/ sdk.NewDecFromInt(poolAssetOut.Token.Amount), - /*yWeight=*/ sdk.NewDecFromInt(poolAssetOut.Weight), - ).TruncateInt() - } - - if tokenAmountOut.IsZero() { - return tokenOut, fee, fmt.Errorf("tokenIn (%s) must be higher to perform a swap", tokenIn.Denom) - } - - return sdk.NewCoin(tokenOutDenom, tokenAmountOut), fee, nil -} - -/* -Calculates the amount of tokenIn required to obtain tokenOut coins from a swap, -accounting for additional fees. -Only supports single asset swaps. -This function is the inverse of CalcOutAmtGivenIn. - -args: - - tokenOut: the amount of tokens to swap - - tokenInDenom: the target token denom - -ret: - - tokenIn: the tokens received from the swap - - err: error if any -*/ -func (pool Pool) CalcInAmtGivenOut(tokenOut sdk.Coin, tokenInDenom string) ( - tokenIn sdk.Coin, err error, -) { - if pool.PoolParams.PoolType == PoolType_BALANCER { - return pool.CalcInAmtGivenOutBalancer(tokenOut, tokenInDenom) - } else if pool.PoolParams.PoolType == PoolType_STABLESWAP { - return pool.CalcInAmtGivenOutStableswap(tokenOut, tokenInDenom) - } - return sdk.Coin{}, ErrInvalidPoolType -} - -/* -Calculates the amount of tokenIn required to obtain tokenOut coins from a swap, -accounting for additional fees. This is not implemented yet in curve and in Nibiru. -*/ -func (pool Pool) CalcInAmtGivenOutStableswap(tokenOut sdk.Coin, tokenInDenom string) ( - tokenIn sdk.Coin, err error, -) { - return sdk.Coin{}, ErrNotImplemented -} - -/* -Calculates the amount of tokenIn required to obtain tokenOut coins from a swap, -accounting for additional fees. -Only supports single asset swaps. -This function is the inverse of CalcOutAmtGivenIn. - -args: - - tokenOut: the amount of tokens to swap - - tokenInDenom: the target token denom - -ret: - - tokenIn: the tokens received from the swap - - err: error if any -*/ -func (pool Pool) CalcInAmtGivenOutBalancer(tokenOut sdk.Coin, tokenInDenom string) ( - tokenIn sdk.Coin, err error, -) { - _, poolAssetOut, err := pool.getPoolAssetAndIndex(tokenOut.Denom) - if err != nil { - return tokenIn, err - } - - _, poolAssetIn, err := pool.getPoolAssetAndIndex(tokenInDenom) - if err != nil { - return tokenIn, err - } - - // assuming the user wishes to withdraw 'tokenOut', the balance of 'tokenOut' post swap will be lower - poolTokenOutBalance := sdk.NewDecFromInt(poolAssetOut.Token.Amount) - poolTokenOutBalancePostSwap := poolTokenOutBalance.Sub(sdk.NewDecFromInt(tokenOut.Amount)) - // (x_0)(y_0) = (x_0 + in)(y_0 - out) - tokenAmountIn := math.SolveConstantProductInvariant( - /*xPrior=*/ poolTokenOutBalance, - /*xAfter=*/ poolTokenOutBalancePostSwap, - /*xWeight=*/ sdk.NewDecFromInt(poolAssetOut.Weight), - /*yPrior=*/ sdk.NewDecFromInt(poolAssetIn.Token.Amount), - /*yWeight=*/ sdk.NewDecFromInt(poolAssetIn.Weight), - ).Neg() - - // We deduct a swap fee on the input asset. The swap happens by following the invariant curve on the input * (1 - swap fee) - // and then the swap fee is added to the pool. - // Thus in order to give X amount out, we solve the invariant for the invariant input. However invariant input = (1 - swapfee) * trade input. - // Therefore we divide by (1 - swapfee) here - tokenAmountInBeforeFee := tokenAmountIn.Quo(sdk.OneDec().Sub(pool.PoolParams.SwapFee)).Ceil().TruncateInt() - return sdk.NewCoin(tokenInDenom, tokenAmountInBeforeFee), nil -} - -/* -Applies a swap to the pool by adding tokenIn and removing tokenOut from pool asset balances. - -args: - - tokenIn: the amount of token to deposit - - tokenOut: the amount of token to withdraw - -ret: - - err: error if any -*/ -func (pool *Pool) ApplySwap(tokenIn sdk.Coin, tokenOut sdk.Coin) (err error) { - if tokenIn.Amount.LTE(sdk.ZeroInt()) { - return fmt.Errorf("tokenIn (%s) cannot be zero", tokenIn.Denom) - } - if tokenOut.Amount.LTE(sdk.ZeroInt()) { - return fmt.Errorf("tokenOut (%s) cannot be zero", tokenOut.Denom) - } - - _, poolAssetIn, err := pool.getPoolAssetAndIndex(tokenIn.Denom) - if err != nil { - return err - } - - _, poolAssetOut, err := pool.getPoolAssetAndIndex(tokenOut.Denom) - if err != nil { - return err - } - - poolAssetIn.Token.Amount = poolAssetIn.Token.Amount.Add(tokenIn.Amount) - poolAssetOut.Token.Amount = poolAssetOut.Token.Amount.Sub(tokenOut.Amount) - - return pool.updatePoolAssetBalances(poolAssetIn.Token, poolAssetOut.Token) -} diff --git a/x/spot/types/swap_test.go b/x/spot/types/swap_test.go deleted file mode 100644 index 29ea241a2..000000000 --- a/x/spot/types/swap_test.go +++ /dev/null @@ -1,362 +0,0 @@ -package types - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/NibiruChain/nibiru/x/common" -) - -func TestCalcOutAmtGivenIn(t *testing.T) { - for _, tc := range []struct { - name string - pool Pool - tokenIn sdk.Coin - tokenOutDenom string - expectedTokenOut sdk.Coin - expectedFee sdk.Coin - shouldError bool - }{ - { - name: "simple swap", - pool: Pool{ - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - SwapFee: sdk.MustNewDecFromStr("0.0003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 100), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - }, - tokenIn: sdk.NewInt64Coin("aaa", 10), - tokenOutDenom: "bbb", - expectedTokenOut: sdk.NewInt64Coin("bbb", 9), - expectedFee: sdk.NewInt64Coin("aaa", 0), // 0.0003 * 10 = 0.003, truncated to 0 - }, - { - name: "big simple numbers", - pool: Pool{ - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - SwapFee: sdk.MustNewDecFromStr("0.0003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100*common.TO_MICRO), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 100*common.TO_MICRO), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - }, - tokenIn: sdk.NewInt64Coin("aaa", 10), - tokenOutDenom: "bbb", - expectedTokenOut: sdk.NewInt64Coin("bbb", 9), - expectedFee: sdk.NewInt64Coin("aaa", 0), // 0.0003 * 10 = 0.003, truncated to 0 - }, - { - name: "big simple numbers, huge swap fee", - pool: Pool{ - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - SwapFee: sdk.MustNewDecFromStr("0.5"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1*common.TO_MICRO), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 1*common.TO_MICRO), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - }, - tokenIn: sdk.NewInt64Coin("aaa", 10), - tokenOutDenom: "bbb", - expectedTokenOut: sdk.NewInt64Coin("bbb", 4), - expectedFee: sdk.NewInt64Coin("aaa", 5), // 0.5 * 10 = 5 - }, - { - name: "real numbers", - pool: Pool{ - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - SwapFee: sdk.MustNewDecFromStr("0.0003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 3498723457), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 23318504), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - }, - tokenIn: sdk.NewInt64Coin("aaa", 5844683), - tokenOutDenom: "bbb", - // solved with wolfram alpha (https://www.wolframalpha.com/input?i=23318504+-+%283498723457*23318504%29%2F+%283498723457%2B5844683*%281-0.0003%29%29) - expectedTokenOut: sdk.NewInt64Coin("bbb", 38877), - expectedFee: sdk.NewInt64Coin("aaa", 1753), // 0.0003 * 5844683 = 1753.4049, truncated to 1753 - }, - { - name: "swap with very low output token amount", - pool: Pool{ - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - SwapFee: sdk.MustNewDecFromStr("0.0003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 100), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - }, - tokenIn: sdk.NewInt64Coin("aaa", 1), - tokenOutDenom: "bbb", - shouldError: true, - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - tokenOut, fee, err := tc.pool.CalcOutAmtGivenIn(tc.tokenIn, tc.tokenOutDenom, false) - if tc.shouldError { - require.Error(t, err) - } else { - require.NoError(t, err) - require.Equal(t, tc.expectedTokenOut, tokenOut) - require.True(t, tc.expectedFee.Equal(fee)) - } - }) - } -} - -func TestCalcInAmtGivenOut(t *testing.T) { - for _, tc := range []struct { - name string - pool Pool - tokenOut sdk.Coin - tokenInDenom string - expectedTokenIn sdk.Coin - }{ - { - name: "simple swap", - pool: Pool{ - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - SwapFee: sdk.MustNewDecFromStr("0.0003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 100), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - }, - tokenOut: sdk.NewInt64Coin("bbb", 9), - tokenInDenom: "aaa", - expectedTokenIn: sdk.NewInt64Coin("aaa", 10), - }, - { - name: "big simple numbers", - pool: Pool{ - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - SwapFee: sdk.MustNewDecFromStr("0.0003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100*common.TO_MICRO), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 100*common.TO_MICRO), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - }, - tokenOut: sdk.NewInt64Coin("bbb", 9), - tokenInDenom: "aaa", - expectedTokenIn: sdk.NewInt64Coin("aaa", 10), - }, - { - name: "big simple numbers, huge swap fee", - pool: Pool{ - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - SwapFee: sdk.MustNewDecFromStr("0.5"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 1*common.TO_MICRO), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 1*common.TO_MICRO), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - }, - tokenOut: sdk.NewInt64Coin("bbb", 4), - tokenInDenom: "aaa", - expectedTokenIn: sdk.NewInt64Coin("aaa", 9), - }, - { - name: "real numbers", - pool: Pool{ - PoolParams: PoolParams{ - PoolType: PoolType_BALANCER, - SwapFee: sdk.MustNewDecFromStr("0.0003"), - }, - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 3498723457), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bbb", 23318504), - Weight: sdk.OneInt(), - }, - }, - TotalWeight: sdk.NewInt(2), - }, - // solved with wolfram alpha (https://www.wolframalpha.com/input?i=%28%283498723457*23318504%29%2F+%2823318504-38877%29+-+3498723457%29%2F%281-0.0003%29) - tokenOut: sdk.NewInt64Coin("bbb", 38877), - tokenInDenom: "aaa", - expectedTokenIn: sdk.NewInt64Coin("aaa", 5844626), - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - // CalcInAmtGivenOut is the inverse, so we can use the same test inputs/outputs - tokenIn, err := tc.pool.CalcInAmtGivenOut(tc.tokenOut, tc.tokenInDenom) - require.NoError(t, err) - require.Equal(t, tc.expectedTokenIn, tokenIn) - }) - } -} - -func TestApplySwap(t *testing.T) { - for _, tc := range []struct { - name string - pool Pool - tokenIn sdk.Coin - tokenOut sdk.Coin - expectedPoolAssets []PoolAsset - shouldError bool - }{ - { - name: "apply simple swap", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - }, - }, - }, - tokenIn: sdk.NewInt64Coin("aaa", 50), - tokenOut: sdk.NewInt64Coin("bbb", 75), - expectedPoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 150), - }, - { - Token: sdk.NewInt64Coin("bbb", 125), - }, - }, - shouldError: false, - }, - { - name: "swap fails due to too large numbers", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - }, - }, - }, - tokenIn: sdk.NewInt64Coin("aaa", 1), - tokenOut: sdk.NewInt64Coin("bbb", 201), - shouldError: true, - }, - { - name: "swap fails due to zero tokenIn", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - }, - }, - }, - tokenIn: sdk.NewInt64Coin("aaa", 0), - tokenOut: sdk.NewInt64Coin("bbb", 100), - shouldError: true, - }, - { - name: "swap fails due to zero tokenOut", - pool: Pool{ - PoolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("aaa", 100), - }, - { - Token: sdk.NewInt64Coin("bbb", 200), - }, - }, - }, - tokenIn: sdk.NewInt64Coin("aaa", 100), - tokenOut: sdk.NewInt64Coin("bbb", 0), - shouldError: true, - }, - } { - tc := tc - t.Run(tc.name, func(t *testing.T) { - err := tc.pool.ApplySwap(tc.tokenIn, tc.tokenOut) - if tc.shouldError { - require.Error(t, err) - } else { - require.NoError(t, err) - require.Equal(t, tc.expectedPoolAssets, tc.pool.PoolAssets) - } - }) - } -} diff --git a/x/spot/types/tx.pb.go b/x/spot/types/tx.pb.go deleted file mode 100644 index 1b992e1ac..000000000 --- a/x/spot/types/tx.pb.go +++ /dev/null @@ -1,2363 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: nibiru/spot/v1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - 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 - -type MsgCreatePool struct { - Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` - PoolParams *PoolParams `protobuf:"bytes,2,opt,name=pool_params,json=poolParams,proto3" json:"pool_params,omitempty" yaml:"pool_params"` - PoolAssets []PoolAsset `protobuf:"bytes,3,rep,name=pool_assets,json=poolAssets,proto3" json:"pool_assets"` -} - -func (m *MsgCreatePool) Reset() { *m = MsgCreatePool{} } -func (m *MsgCreatePool) String() string { return proto.CompactTextString(m) } -func (*MsgCreatePool) ProtoMessage() {} -func (*MsgCreatePool) Descriptor() ([]byte, []int) { - return fileDescriptor_2ac7099e2729ab26, []int{0} -} -func (m *MsgCreatePool) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgCreatePool) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCreatePool.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 *MsgCreatePool) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCreatePool.Merge(m, src) -} -func (m *MsgCreatePool) XXX_Size() int { - return m.Size() -} -func (m *MsgCreatePool) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCreatePool.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCreatePool proto.InternalMessageInfo - -func (m *MsgCreatePool) GetCreator() string { - if m != nil { - return m.Creator - } - return "" -} - -func (m *MsgCreatePool) GetPoolParams() *PoolParams { - if m != nil { - return m.PoolParams - } - return nil -} - -func (m *MsgCreatePool) GetPoolAssets() []PoolAsset { - if m != nil { - return m.PoolAssets - } - return nil -} - -type MsgCreatePoolResponse struct { - PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` -} - -func (m *MsgCreatePoolResponse) Reset() { *m = MsgCreatePoolResponse{} } -func (m *MsgCreatePoolResponse) String() string { return proto.CompactTextString(m) } -func (*MsgCreatePoolResponse) ProtoMessage() {} -func (*MsgCreatePoolResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2ac7099e2729ab26, []int{1} -} -func (m *MsgCreatePoolResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgCreatePoolResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCreatePoolResponse.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 *MsgCreatePoolResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCreatePoolResponse.Merge(m, src) -} -func (m *MsgCreatePoolResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgCreatePoolResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCreatePoolResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCreatePoolResponse proto.InternalMessageInfo - -func (m *MsgCreatePoolResponse) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -// Message to join a pool (identified by poolId) with a set of tokens to deposit. -type MsgJoinPool struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` - PoolId uint64 `protobuf:"varint,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty" yaml:"pool_id"` - TokensIn []types.Coin `protobuf:"bytes,3,rep,name=tokens_in,json=tokensIn,proto3" json:"tokens_in" yaml:"tokens_in"` - UseAllCoins bool `protobuf:"varint,4,opt,name=use_all_coins,json=useAllCoins,proto3" json:"use_all_coins,omitempty" yaml:"use_all_coins"` -} - -func (m *MsgJoinPool) Reset() { *m = MsgJoinPool{} } -func (m *MsgJoinPool) String() string { return proto.CompactTextString(m) } -func (*MsgJoinPool) ProtoMessage() {} -func (*MsgJoinPool) Descriptor() ([]byte, []int) { - return fileDescriptor_2ac7099e2729ab26, []int{2} -} -func (m *MsgJoinPool) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgJoinPool) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgJoinPool.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 *MsgJoinPool) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgJoinPool.Merge(m, src) -} -func (m *MsgJoinPool) XXX_Size() int { - return m.Size() -} -func (m *MsgJoinPool) XXX_DiscardUnknown() { - xxx_messageInfo_MsgJoinPool.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgJoinPool proto.InternalMessageInfo - -func (m *MsgJoinPool) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgJoinPool) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -func (m *MsgJoinPool) GetTokensIn() []types.Coin { - if m != nil { - return m.TokensIn - } - return nil -} - -func (m *MsgJoinPool) GetUseAllCoins() bool { - if m != nil { - return m.UseAllCoins - } - return false -} - -// Response when a user joins a pool. -type MsgJoinPoolResponse struct { - // the final state of the pool after a join - Pool *Pool `protobuf:"bytes,1,opt,name=pool,proto3" json:"pool,omitempty"` - // sum of LP tokens minted from the join - NumPoolSharesOut types.Coin `protobuf:"bytes,2,opt,name=num_pool_shares_out,json=numPoolSharesOut,proto3" json:"num_pool_shares_out" yaml:"num_pool_shares_out"` - // remaining tokens from attempting to join the pool - RemainingCoins []types.Coin `protobuf:"bytes,3,rep,name=remaining_coins,json=remainingCoins,proto3" json:"remaining_coins" yaml:"tokens_in"` -} - -func (m *MsgJoinPoolResponse) Reset() { *m = MsgJoinPoolResponse{} } -func (m *MsgJoinPoolResponse) String() string { return proto.CompactTextString(m) } -func (*MsgJoinPoolResponse) ProtoMessage() {} -func (*MsgJoinPoolResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2ac7099e2729ab26, []int{3} -} -func (m *MsgJoinPoolResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgJoinPoolResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgJoinPoolResponse.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 *MsgJoinPoolResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgJoinPoolResponse.Merge(m, src) -} -func (m *MsgJoinPoolResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgJoinPoolResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgJoinPoolResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgJoinPoolResponse proto.InternalMessageInfo - -func (m *MsgJoinPoolResponse) GetPool() *Pool { - if m != nil { - return m.Pool - } - return nil -} - -func (m *MsgJoinPoolResponse) GetNumPoolSharesOut() types.Coin { - if m != nil { - return m.NumPoolSharesOut - } - return types.Coin{} -} - -func (m *MsgJoinPoolResponse) GetRemainingCoins() []types.Coin { - if m != nil { - return m.RemainingCoins - } - return nil -} - -type MsgExitPool struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` - PoolId uint64 `protobuf:"varint,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty" yaml:"pool_id"` - PoolShares types.Coin `protobuf:"bytes,3,opt,name=pool_shares,json=poolShares,proto3" json:"pool_shares" yaml:"pool_shares"` -} - -func (m *MsgExitPool) Reset() { *m = MsgExitPool{} } -func (m *MsgExitPool) String() string { return proto.CompactTextString(m) } -func (*MsgExitPool) ProtoMessage() {} -func (*MsgExitPool) Descriptor() ([]byte, []int) { - return fileDescriptor_2ac7099e2729ab26, []int{4} -} -func (m *MsgExitPool) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgExitPool) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgExitPool.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 *MsgExitPool) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgExitPool.Merge(m, src) -} -func (m *MsgExitPool) XXX_Size() int { - return m.Size() -} -func (m *MsgExitPool) XXX_DiscardUnknown() { - xxx_messageInfo_MsgExitPool.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgExitPool proto.InternalMessageInfo - -func (m *MsgExitPool) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgExitPool) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -func (m *MsgExitPool) GetPoolShares() types.Coin { - if m != nil { - return m.PoolShares - } - return types.Coin{} -} - -type MsgExitPoolResponse struct { - TokensOut []types.Coin `protobuf:"bytes,3,rep,name=tokens_out,json=tokensOut,proto3" json:"tokens_out" yaml:"tokens_out"` -} - -func (m *MsgExitPoolResponse) Reset() { *m = MsgExitPoolResponse{} } -func (m *MsgExitPoolResponse) String() string { return proto.CompactTextString(m) } -func (*MsgExitPoolResponse) ProtoMessage() {} -func (*MsgExitPoolResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2ac7099e2729ab26, []int{5} -} -func (m *MsgExitPoolResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgExitPoolResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgExitPoolResponse.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 *MsgExitPoolResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgExitPoolResponse.Merge(m, src) -} -func (m *MsgExitPoolResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgExitPoolResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgExitPoolResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgExitPoolResponse proto.InternalMessageInfo - -func (m *MsgExitPoolResponse) GetTokensOut() []types.Coin { - if m != nil { - return m.TokensOut - } - return nil -} - -type MsgSwapAssets struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` - PoolId uint64 `protobuf:"varint,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty" yaml:"pool_id"` - TokenIn types.Coin `protobuf:"bytes,3,opt,name=token_in,json=tokenIn,proto3" json:"token_in" yaml:"token_in"` - TokenOutDenom string `protobuf:"bytes,4,opt,name=token_out_denom,json=tokenOutDenom,proto3" json:"token_out_denom,omitempty" yaml:"token_out_denom"` -} - -func (m *MsgSwapAssets) Reset() { *m = MsgSwapAssets{} } -func (m *MsgSwapAssets) String() string { return proto.CompactTextString(m) } -func (*MsgSwapAssets) ProtoMessage() {} -func (*MsgSwapAssets) Descriptor() ([]byte, []int) { - return fileDescriptor_2ac7099e2729ab26, []int{6} -} -func (m *MsgSwapAssets) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSwapAssets) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSwapAssets.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 *MsgSwapAssets) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSwapAssets.Merge(m, src) -} -func (m *MsgSwapAssets) XXX_Size() int { - return m.Size() -} -func (m *MsgSwapAssets) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSwapAssets.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSwapAssets proto.InternalMessageInfo - -func (m *MsgSwapAssets) GetSender() string { - if m != nil { - return m.Sender - } - return "" -} - -func (m *MsgSwapAssets) GetPoolId() uint64 { - if m != nil { - return m.PoolId - } - return 0 -} - -func (m *MsgSwapAssets) GetTokenIn() types.Coin { - if m != nil { - return m.TokenIn - } - return types.Coin{} -} - -func (m *MsgSwapAssets) GetTokenOutDenom() string { - if m != nil { - return m.TokenOutDenom - } - return "" -} - -type MsgSwapAssetsResponse struct { - TokenOut types.Coin `protobuf:"bytes,3,opt,name=token_out,json=tokenOut,proto3" json:"token_out" yaml:"token_out"` -} - -func (m *MsgSwapAssetsResponse) Reset() { *m = MsgSwapAssetsResponse{} } -func (m *MsgSwapAssetsResponse) String() string { return proto.CompactTextString(m) } -func (*MsgSwapAssetsResponse) ProtoMessage() {} -func (*MsgSwapAssetsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_2ac7099e2729ab26, []int{7} -} -func (m *MsgSwapAssetsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MsgSwapAssetsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSwapAssetsResponse.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 *MsgSwapAssetsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSwapAssetsResponse.Merge(m, src) -} -func (m *MsgSwapAssetsResponse) XXX_Size() int { - return m.Size() -} -func (m *MsgSwapAssetsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSwapAssetsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSwapAssetsResponse proto.InternalMessageInfo - -func (m *MsgSwapAssetsResponse) GetTokenOut() types.Coin { - if m != nil { - return m.TokenOut - } - return types.Coin{} -} - -func init() { - proto.RegisterType((*MsgCreatePool)(nil), "nibiru.spot.v1.MsgCreatePool") - proto.RegisterType((*MsgCreatePoolResponse)(nil), "nibiru.spot.v1.MsgCreatePoolResponse") - proto.RegisterType((*MsgJoinPool)(nil), "nibiru.spot.v1.MsgJoinPool") - proto.RegisterType((*MsgJoinPoolResponse)(nil), "nibiru.spot.v1.MsgJoinPoolResponse") - proto.RegisterType((*MsgExitPool)(nil), "nibiru.spot.v1.MsgExitPool") - proto.RegisterType((*MsgExitPoolResponse)(nil), "nibiru.spot.v1.MsgExitPoolResponse") - proto.RegisterType((*MsgSwapAssets)(nil), "nibiru.spot.v1.MsgSwapAssets") - proto.RegisterType((*MsgSwapAssetsResponse)(nil), "nibiru.spot.v1.MsgSwapAssetsResponse") -} - -func init() { proto.RegisterFile("nibiru/spot/v1/tx.proto", fileDescriptor_2ac7099e2729ab26) } - -var fileDescriptor_2ac7099e2729ab26 = []byte{ - // 832 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x55, 0x41, 0x6f, 0xe3, 0x44, - 0x14, 0xae, 0x9b, 0xa8, 0x4d, 0x27, 0x4a, 0xbb, 0x75, 0xcb, 0xd6, 0xf1, 0xb2, 0x49, 0x34, 0x2b, - 0xa4, 0x00, 0x92, 0x4d, 0xc2, 0x0d, 0x71, 0x60, 0x9d, 0xe5, 0x50, 0xa4, 0xd0, 0xca, 0x91, 0x38, - 0x20, 0xa4, 0x68, 0x92, 0x8c, 0xdc, 0x59, 0xec, 0x19, 0x93, 0x19, 0xb7, 0x59, 0x21, 0x2e, 0x5c, - 0xb9, 0x20, 0xf1, 0x7b, 0x90, 0x38, 0xee, 0x71, 0xa5, 0xbd, 0x70, 0x8a, 0x50, 0xcb, 0x2f, 0x88, - 0xc4, 0x85, 0x13, 0xf2, 0xcc, 0xd8, 0x75, 0x8a, 0xd5, 0x08, 0xa1, 0xde, 0x3c, 0xef, 0xbd, 0xf9, - 0xde, 0xfb, 0xbe, 0xf7, 0xde, 0x18, 0x9c, 0x50, 0x32, 0x21, 0xf3, 0xc4, 0xe5, 0x31, 0x13, 0xee, - 0x65, 0xcf, 0x15, 0x0b, 0x27, 0x9e, 0x33, 0xc1, 0xcc, 0x7d, 0xe5, 0x70, 0x52, 0x87, 0x73, 0xd9, - 0xb3, 0x9b, 0x77, 0x02, 0x63, 0xc6, 0x42, 0x15, 0x6a, 0x1f, 0x07, 0x2c, 0x60, 0xf2, 0xd3, 0x4d, - 0xbf, 0xb4, 0xb5, 0x35, 0x65, 0x3c, 0x62, 0xdc, 0x9d, 0x20, 0x8e, 0xdd, 0xcb, 0xde, 0x04, 0x0b, - 0xd4, 0x73, 0xa7, 0x8c, 0x50, 0xed, 0x7f, 0x37, 0x60, 0x2c, 0x08, 0xb1, 0x8b, 0x62, 0xe2, 0x22, - 0x4a, 0x99, 0x40, 0x82, 0x30, 0xca, 0x95, 0x17, 0xfe, 0x66, 0x80, 0xc6, 0x90, 0x07, 0x83, 0x39, - 0x46, 0x02, 0x9f, 0x33, 0x16, 0x9a, 0x16, 0xd8, 0x9d, 0xa6, 0x27, 0x36, 0xb7, 0x8c, 0x8e, 0xd1, - 0xdd, 0xf3, 0xb3, 0xa3, 0x39, 0x02, 0xf5, 0xb4, 0x9a, 0x71, 0x8c, 0xe6, 0x28, 0xe2, 0xd6, 0x76, - 0xc7, 0xe8, 0xd6, 0xfb, 0xb6, 0xb3, 0x4e, 0xc0, 0x49, 0x41, 0xce, 0x65, 0x84, 0xf7, 0x78, 0xb5, - 0x6c, 0x9b, 0xaf, 0x50, 0x14, 0x7e, 0x02, 0x0b, 0x17, 0xa1, 0x0f, 0xe2, 0x3c, 0xc6, 0xfc, 0x4c, - 0x83, 0x22, 0xce, 0xb1, 0xe0, 0x56, 0xa5, 0x53, 0xe9, 0xd6, 0xfb, 0xcd, 0x32, 0xd0, 0xe7, 0x69, - 0x84, 0x57, 0x7d, 0xbd, 0x6c, 0x6f, 0x29, 0x04, 0x69, 0xe0, 0xf0, 0x23, 0xf0, 0xce, 0x1a, 0x03, - 0x1f, 0xf3, 0x98, 0x51, 0x8e, 0xcd, 0x13, 0xb0, 0x2b, 0xa1, 0xc9, 0x4c, 0x32, 0xa9, 0xfa, 0x3b, - 0xe9, 0xf1, 0x74, 0x06, 0xff, 0x32, 0x40, 0x7d, 0xc8, 0x83, 0x2f, 0x18, 0xa1, 0x92, 0xf2, 0xfb, - 0x60, 0x87, 0x63, 0x3a, 0xc3, 0x9a, 0xb1, 0x77, 0xb8, 0x5a, 0xb6, 0x1b, 0xaa, 0x6e, 0x65, 0x87, - 0xbe, 0x0e, 0x30, 0x3f, 0xbc, 0xc5, 0x4c, 0xf9, 0x57, 0x3d, 0x73, 0xb5, 0x6c, 0xef, 0x17, 0x38, - 0x92, 0x19, 0xcc, 0xf2, 0x98, 0xe7, 0x60, 0x4f, 0xb0, 0x6f, 0x31, 0xe5, 0x63, 0x42, 0x73, 0x66, - 0xaa, 0x5d, 0x4e, 0xda, 0x2e, 0x47, 0xb7, 0xcb, 0x19, 0x30, 0x42, 0x3d, 0x2b, 0x65, 0xb6, 0x5a, - 0xb6, 0x1f, 0x29, 0xb4, 0xfc, 0x26, 0xf4, 0x6b, 0xea, 0xfb, 0x94, 0x9a, 0x9f, 0x82, 0x46, 0xc2, - 0xf1, 0x18, 0x85, 0xe1, 0x38, 0x6d, 0x31, 0xb7, 0xaa, 0x1d, 0xa3, 0x5b, 0xf3, 0xac, 0xd5, 0xb2, - 0x7d, 0xac, 0xae, 0xad, 0xb9, 0xa1, 0x5f, 0x4f, 0x38, 0x7e, 0x1e, 0x86, 0x03, 0x79, 0xfa, 0x69, - 0x1b, 0x1c, 0x15, 0x78, 0xe7, 0x42, 0x75, 0x41, 0x35, 0xad, 0x58, 0xb2, 0xaf, 0xf7, 0x8f, 0xcb, - 0xc4, 0xf7, 0x65, 0x84, 0x19, 0x82, 0x23, 0x9a, 0x44, 0x63, 0xc9, 0x94, 0x5f, 0xa0, 0x39, 0xe6, - 0x63, 0x96, 0x08, 0x3d, 0x0a, 0xf7, 0x70, 0x83, 0x9a, 0x9b, 0xad, 0x8a, 0x2c, 0xc1, 0x80, 0xfe, - 0x23, 0x9a, 0x44, 0x69, 0xaa, 0x91, 0xb4, 0x9d, 0x25, 0xc2, 0xfc, 0x06, 0x1c, 0xcc, 0x71, 0x84, - 0x08, 0x25, 0x34, 0xd0, 0x7c, 0xff, 0x87, 0x8a, 0xfb, 0x39, 0x96, 0x52, 0xe3, 0x57, 0x35, 0x05, - 0x9f, 0x2f, 0x88, 0x78, 0xd0, 0x29, 0xf8, 0x4a, 0x4f, 0xb8, 0xe2, 0x6a, 0x55, 0x36, 0x69, 0x65, - 0x6b, 0x06, 0xc5, 0xcd, 0x51, 0x77, 0xf5, 0xe6, 0x28, 0x81, 0xe0, 0x4b, 0xd9, 0xcc, 0xac, 0xfc, - 0xbc, 0x99, 0x23, 0x00, 0x34, 0xe9, 0xb4, 0x33, 0x1b, 0xf5, 0x6a, 0xea, 0x6c, 0x87, 0x6b, 0x7a, - 0xc9, 0x86, 0xe8, 0xe1, 0x3d, 0x4b, 0x04, 0xfc, 0x5b, 0x3d, 0x13, 0xa3, 0x2b, 0x14, 0xab, 0xad, - 0x7b, 0x30, 0xb5, 0x86, 0x40, 0x4d, 0xbb, 0x5a, 0x99, 0x0d, 0x52, 0x9d, 0xe8, 0xe2, 0x0f, 0x0a, - 0xc5, 0xcb, 0x5e, 0xef, 0xca, 0xcf, 0x53, 0x6a, 0x7a, 0xe0, 0x40, 0x59, 0x59, 0x22, 0xc6, 0x33, - 0x4c, 0x59, 0x24, 0x57, 0x66, 0xcf, 0xb3, 0x57, 0xcb, 0xf6, 0xe3, 0xe2, 0xb5, 0x3c, 0x00, 0xfa, - 0x0d, 0x69, 0x39, 0x4b, 0xc4, 0x0b, 0x79, 0x26, 0xf2, 0x81, 0xb9, 0xe5, 0x9e, 0x4b, 0x9d, 0xed, - 0xb7, 0x56, 0xda, 0xf8, 0xef, 0x93, 0xa9, 0x84, 0xae, 0x65, 0xf9, 0xfa, 0x6f, 0x2b, 0xa0, 0x32, - 0xe4, 0x81, 0x19, 0x01, 0x50, 0x78, 0x92, 0x9f, 0xde, 0xdd, 0xc8, 0xb5, 0xf7, 0xce, 0x7e, 0xef, - 0x5e, 0x77, 0x56, 0x2d, 0x6c, 0xfe, 0xf8, 0xf6, 0xcf, 0x5f, 0xb6, 0x8f, 0xe0, 0xa1, 0x5b, 0xfc, - 0xc5, 0xc8, 0xb5, 0xfe, 0x0e, 0xd4, 0xf2, 0xc7, 0xf0, 0x49, 0x09, 0x5a, 0xe6, 0xb4, 0x9f, 0xdd, - 0xe3, 0xcc, 0x13, 0x3d, 0x93, 0x89, 0x9e, 0xc2, 0x27, 0x6b, 0x89, 0xbe, 0xd7, 0xad, 0xfe, 0xc1, - 0x7d, 0xc9, 0x08, 0x4d, 0x53, 0xe6, 0x9b, 0x57, 0x96, 0x32, 0x73, 0x96, 0xa6, 0xbc, 0x3b, 0xf4, - 0x1b, 0x53, 0xe2, 0x05, 0x11, 0xe6, 0x15, 0x00, 0x85, 0x01, 0x2e, 0x13, 0xf5, 0xd6, 0x5d, 0x2a, - 0xea, 0xbf, 0x47, 0x60, 0x63, 0x62, 0x7e, 0x85, 0x62, 0xef, 0xc5, 0xeb, 0xeb, 0x96, 0xf1, 0xe6, - 0xba, 0x65, 0xfc, 0x71, 0xdd, 0x32, 0x7e, 0xbe, 0x69, 0x6d, 0xbd, 0xb9, 0x69, 0x6d, 0xfd, 0x7e, - 0xd3, 0xda, 0xfa, 0xfa, 0x83, 0x80, 0x88, 0x8b, 0x64, 0xe2, 0x4c, 0x59, 0xe4, 0x7e, 0x29, 0x01, - 0x06, 0x17, 0x88, 0xd0, 0x0c, 0x6c, 0xa1, 0xe0, 0xc4, 0xab, 0x18, 0xf3, 0xc9, 0x8e, 0xfc, 0x63, - 0x7f, 0xfc, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x79, 0xa8, 0xd2, 0xbd, 0x4b, 0x08, 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 { - // Used to create a pool. - CreatePool(ctx context.Context, in *MsgCreatePool, opts ...grpc.CallOption) (*MsgCreatePoolResponse, error) - // Join a pool as a liquidity provider. - JoinPool(ctx context.Context, in *MsgJoinPool, opts ...grpc.CallOption) (*MsgJoinPoolResponse, error) - // Exit a pool position by returning LP shares - ExitPool(ctx context.Context, in *MsgExitPool, opts ...grpc.CallOption) (*MsgExitPoolResponse, error) - // Swap assets in a pool - SwapAssets(ctx context.Context, in *MsgSwapAssets, opts ...grpc.CallOption) (*MsgSwapAssetsResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) CreatePool(ctx context.Context, in *MsgCreatePool, opts ...grpc.CallOption) (*MsgCreatePoolResponse, error) { - out := new(MsgCreatePoolResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Msg/CreatePool", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) JoinPool(ctx context.Context, in *MsgJoinPool, opts ...grpc.CallOption) (*MsgJoinPoolResponse, error) { - out := new(MsgJoinPoolResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Msg/JoinPool", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ExitPool(ctx context.Context, in *MsgExitPool, opts ...grpc.CallOption) (*MsgExitPoolResponse, error) { - out := new(MsgExitPoolResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Msg/ExitPool", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) SwapAssets(ctx context.Context, in *MsgSwapAssets, opts ...grpc.CallOption) (*MsgSwapAssetsResponse, error) { - out := new(MsgSwapAssetsResponse) - err := c.cc.Invoke(ctx, "/nibiru.spot.v1.Msg/SwapAssets", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // Used to create a pool. - CreatePool(context.Context, *MsgCreatePool) (*MsgCreatePoolResponse, error) - // Join a pool as a liquidity provider. - JoinPool(context.Context, *MsgJoinPool) (*MsgJoinPoolResponse, error) - // Exit a pool position by returning LP shares - ExitPool(context.Context, *MsgExitPool) (*MsgExitPoolResponse, error) - // Swap assets in a pool - SwapAssets(context.Context, *MsgSwapAssets) (*MsgSwapAssetsResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) CreatePool(ctx context.Context, req *MsgCreatePool) (*MsgCreatePoolResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CreatePool not implemented") -} -func (*UnimplementedMsgServer) JoinPool(ctx context.Context, req *MsgJoinPool) (*MsgJoinPoolResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method JoinPool not implemented") -} -func (*UnimplementedMsgServer) ExitPool(ctx context.Context, req *MsgExitPool) (*MsgExitPoolResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ExitPool not implemented") -} -func (*UnimplementedMsgServer) SwapAssets(ctx context.Context, req *MsgSwapAssets) (*MsgSwapAssetsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SwapAssets not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_CreatePool_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgCreatePool) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).CreatePool(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Msg/CreatePool", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).CreatePool(ctx, req.(*MsgCreatePool)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_JoinPool_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgJoinPool) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).JoinPool(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Msg/JoinPool", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).JoinPool(ctx, req.(*MsgJoinPool)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ExitPool_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgExitPool) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ExitPool(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Msg/ExitPool", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ExitPool(ctx, req.(*MsgExitPool)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_SwapAssets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgSwapAssets) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).SwapAssets(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/nibiru.spot.v1.Msg/SwapAssets", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).SwapAssets(ctx, req.(*MsgSwapAssets)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "nibiru.spot.v1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "CreatePool", - Handler: _Msg_CreatePool_Handler, - }, - { - MethodName: "JoinPool", - Handler: _Msg_JoinPool_Handler, - }, - { - MethodName: "ExitPool", - Handler: _Msg_ExitPool_Handler, - }, - { - MethodName: "SwapAssets", - Handler: _Msg_SwapAssets_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "nibiru/spot/v1/tx.proto", -} - -func (m *MsgCreatePool) 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 *MsgCreatePool) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCreatePool) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.PoolAssets) > 0 { - for iNdEx := len(m.PoolAssets) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PoolAssets[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if m.PoolParams != nil { - { - size, err := m.PoolParams.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgCreatePoolResponse) 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 *MsgCreatePoolResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCreatePoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.PoolId != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MsgJoinPool) 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 *MsgJoinPool) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgJoinPool) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.UseAllCoins { - i-- - if m.UseAllCoins { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x20 - } - if len(m.TokensIn) > 0 { - for iNdEx := len(m.TokensIn) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TokensIn[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if m.PoolId != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x10 - } - 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 *MsgJoinPoolResponse) 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 *MsgJoinPoolResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgJoinPoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.RemainingCoins) > 0 { - for iNdEx := len(m.RemainingCoins) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.RemainingCoins[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - { - size, err := m.NumPoolSharesOut.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.Pool != nil { - { - size, err := m.Pool.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 *MsgExitPool) 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 *MsgExitPool) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgExitPool) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.PoolShares.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if m.PoolId != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x10 - } - 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 *MsgExitPoolResponse) 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 *MsgExitPoolResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgExitPoolResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TokensOut) > 0 { - for iNdEx := len(m.TokensOut) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TokensOut[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - return len(dAtA) - i, nil -} - -func (m *MsgSwapAssets) 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 *MsgSwapAssets) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSwapAssets) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.TokenOutDenom) > 0 { - i -= len(m.TokenOutDenom) - copy(dAtA[i:], m.TokenOutDenom) - i = encodeVarintTx(dAtA, i, uint64(len(m.TokenOutDenom))) - i-- - dAtA[i] = 0x22 - } - { - size, err := m.TokenIn.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if m.PoolId != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.PoolId)) - i-- - dAtA[i] = 0x10 - } - 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 *MsgSwapAssetsResponse) 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 *MsgSwapAssetsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSwapAssetsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.TokenOut.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - 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 *MsgCreatePool) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.PoolParams != nil { - l = m.PoolParams.Size() - n += 1 + l + sovTx(uint64(l)) - } - if len(m.PoolAssets) > 0 { - for _, e := range m.PoolAssets { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgCreatePoolResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PoolId != 0 { - n += 1 + sovTx(uint64(m.PoolId)) - } - return n -} - -func (m *MsgJoinPool) 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 m.PoolId != 0 { - n += 1 + sovTx(uint64(m.PoolId)) - } - if len(m.TokensIn) > 0 { - for _, e := range m.TokensIn { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - if m.UseAllCoins { - n += 2 - } - return n -} - -func (m *MsgJoinPoolResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Pool != nil { - l = m.Pool.Size() - n += 1 + l + sovTx(uint64(l)) - } - l = m.NumPoolSharesOut.Size() - n += 1 + l + sovTx(uint64(l)) - if len(m.RemainingCoins) > 0 { - for _, e := range m.RemainingCoins { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgExitPool) 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 m.PoolId != 0 { - n += 1 + sovTx(uint64(m.PoolId)) - } - l = m.PoolShares.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgExitPoolResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.TokensOut) > 0 { - for _, e := range m.TokensOut { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgSwapAssets) 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 m.PoolId != 0 { - n += 1 + sovTx(uint64(m.PoolId)) - } - l = m.TokenIn.Size() - n += 1 + l + sovTx(uint64(l)) - l = len(m.TokenOutDenom) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgSwapAssetsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.TokenOut.Size() - n += 1 + l + sovTx(uint64(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 *MsgCreatePool) 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: MsgCreatePool: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCreatePool: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Creator", 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.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolParams", 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.PoolParams == nil { - m.PoolParams = &PoolParams{} - } - if err := m.PoolParams.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolAssets", 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.PoolAssets = append(m.PoolAssets, PoolAsset{}) - if err := m.PoolAssets[len(m.PoolAssets)-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 *MsgCreatePoolResponse) 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: MsgCreatePoolResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCreatePoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= 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 *MsgJoinPool) 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: MsgJoinPool: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgJoinPool: 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 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokensIn", 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.TokensIn = append(m.TokensIn, types.Coin{}) - if err := m.TokensIn[len(m.TokensIn)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field UseAllCoins", 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.UseAllCoins = bool(v != 0) - 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 *MsgJoinPoolResponse) 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: MsgJoinPoolResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgJoinPoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pool", 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.Pool == nil { - m.Pool = &Pool{} - } - if err := m.Pool.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NumPoolSharesOut", 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.NumPoolSharesOut.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RemainingCoins", 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.RemainingCoins = append(m.RemainingCoins, types.Coin{}) - if err := m.RemainingCoins[len(m.RemainingCoins)-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 *MsgExitPool) 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: MsgExitPool: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgExitPool: 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 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolShares", 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.PoolShares.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 *MsgExitPoolResponse) 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: MsgExitPoolResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgExitPoolResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokensOut", 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.TokensOut = append(m.TokensOut, types.Coin{}) - if err := m.TokensOut[len(m.TokensOut)-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 *MsgSwapAssets) 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: MsgSwapAssets: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSwapAssets: 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 { - return fmt.Errorf("proto: wrong wireType = %d for field PoolId", wireType) - } - m.PoolId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PoolId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenIn", 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.TokenIn.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenOutDenom", 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.TokenOutDenom = 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 *MsgSwapAssetsResponse) 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: MsgSwapAssetsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSwapAssetsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TokenOut", 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.TokenOut.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 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/spot/types/tx.pb.gw.go b/x/spot/types/tx.pb.gw.go deleted file mode 100644 index c20b4b91f..000000000 --- a/x/spot/types/tx.pb.gw.go +++ /dev/null @@ -1,528 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: nibiru/spot/v1/tx.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_Msg_CreatePool_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Msg_CreatePool_0(ctx context.Context, marshaler runtime.Marshaler, client MsgClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq MsgCreatePool - 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_Msg_CreatePool_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.CreatePool(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Msg_CreatePool_0(ctx context.Context, marshaler runtime.Marshaler, server MsgServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq MsgCreatePool - 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_Msg_CreatePool_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.CreatePool(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Msg_JoinPool_0 = &utilities.DoubleArray{Encoding: map[string]int{"pool_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Msg_JoinPool_0(ctx context.Context, marshaler runtime.Marshaler, client MsgClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq MsgJoinPool - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Msg_JoinPool_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.JoinPool(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Msg_JoinPool_0(ctx context.Context, marshaler runtime.Marshaler, server MsgServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq MsgJoinPool - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Msg_JoinPool_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.JoinPool(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Msg_ExitPool_0 = &utilities.DoubleArray{Encoding: map[string]int{"pool_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Msg_ExitPool_0(ctx context.Context, marshaler runtime.Marshaler, client MsgClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq MsgExitPool - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Msg_ExitPool_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.ExitPool(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Msg_ExitPool_0(ctx context.Context, marshaler runtime.Marshaler, server MsgServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq MsgExitPool - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Msg_ExitPool_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.ExitPool(ctx, &protoReq) - return msg, metadata, err - -} - -var ( - filter_Msg_SwapAssets_0 = &utilities.DoubleArray{Encoding: map[string]int{"pool_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_Msg_SwapAssets_0(ctx context.Context, marshaler runtime.Marshaler, client MsgClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq MsgSwapAssets - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Msg_SwapAssets_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.SwapAssets(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Msg_SwapAssets_0(ctx context.Context, marshaler runtime.Marshaler, server MsgServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq MsgSwapAssets - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["pool_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "pool_id") - } - - protoReq.PoolId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Msg_SwapAssets_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.SwapAssets(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterMsgHandlerServer registers the http handlers for service Msg to "mux". -// UnaryRPC :call MsgServer 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 RegisterMsgHandlerFromEndpoint instead. -func RegisterMsgHandlerServer(ctx context.Context, mux *runtime.ServeMux, server MsgServer) error { - - mux.Handle("POST", pattern_Msg_CreatePool_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_Msg_CreatePool_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_Msg_CreatePool_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Msg_JoinPool_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_Msg_JoinPool_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_Msg_JoinPool_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Msg_ExitPool_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_Msg_ExitPool_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_Msg_ExitPool_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Msg_SwapAssets_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_Msg_SwapAssets_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_Msg_SwapAssets_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterMsgHandlerFromEndpoint is same as RegisterMsgHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterMsgHandlerFromEndpoint(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 RegisterMsgHandler(ctx, mux, conn) -} - -// RegisterMsgHandler registers the http handlers for service Msg to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterMsgHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterMsgHandlerClient(ctx, mux, NewMsgClient(conn)) -} - -// RegisterMsgHandlerClient registers the http handlers for service Msg -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "MsgClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "MsgClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "MsgClient" to call the correct interceptors. -func RegisterMsgHandlerClient(ctx context.Context, mux *runtime.ServeMux, client MsgClient) error { - - mux.Handle("POST", pattern_Msg_CreatePool_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_Msg_CreatePool_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Msg_CreatePool_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Msg_JoinPool_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_Msg_JoinPool_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Msg_JoinPool_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Msg_ExitPool_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_Msg_ExitPool_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Msg_ExitPool_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Msg_SwapAssets_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_Msg_SwapAssets_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Msg_SwapAssets_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Msg_CreatePool_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"nibiru", "spot", "pool"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Msg_JoinPool_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"nibiru", "spot", "pool_id", "join"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Msg_ExitPool_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"nibiru", "spot", "pool_id", "exit"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Msg_SwapAssets_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"nibiru", "spot", "pool_id", "swap"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Msg_CreatePool_0 = runtime.ForwardResponseMessage - - forward_Msg_JoinPool_0 = runtime.ForwardResponseMessage - - forward_Msg_ExitPool_0 = runtime.ForwardResponseMessage - - forward_Msg_SwapAssets_0 = runtime.ForwardResponseMessage -) diff --git a/x/spot/types/utils.go b/x/spot/types/utils.go deleted file mode 100644 index 555bb71c8..000000000 --- a/x/spot/types/utils.go +++ /dev/null @@ -1,74 +0,0 @@ -package types - -import ( - fmt "fmt" - "sort" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -/* -given a pool, find the poolAsset with a given denom. - -args: - - poolAssets: all of the pool's assets. Must be sorted. - - denom: the denom string to search for - -ret: - - index: the index of the denom in the pool assets - - poolAsset: the pool asset itself - - err: error if any -*/ -func (pool Pool) getPoolAssetAndIndex(denom string) ( - index int, poolAsset PoolAsset, err error, -) { - if denom == "" { - return -1, PoolAsset{}, fmt.Errorf("empty denom") - } - - if len(pool.PoolAssets) == 0 { - return -1, PoolAsset{}, fmt.Errorf("empty pool assets") - } - - // binary search for the asset. poolAssets must be sorted. - i := sort.Search(len(pool.PoolAssets), func(i int) bool { - compare := strings.Compare(pool.PoolAssets[i].Token.Denom, denom) - return compare >= 0 - }) - - if i < 0 || i >= len(pool.PoolAssets) || pool.PoolAssets[i].Token.Denom != denom { - return -1, PoolAsset{}, ErrTokenDenomNotFound.Wrapf("could not find denom %s in pool id %d", denom, pool.Id) - } - - return i, pool.PoolAssets[i], nil -} - -/* -Maps poolAssets to its underlying coins. - -ret: - - coins: all the coins in the pool assets - -args: - - poolAssets: the slice of pool assets -*/ -func (pool Pool) PoolBalances() sdk.Coins { - coins := sdk.NewCoins() - for _, asset := range pool.PoolAssets { - coins = coins.Add(asset.Token) - } - return coins -} - -/* -Sorts poolAssets in place by denom, lexicographically increasing. - -args: - - poolAssets: the pool assets to sort -*/ -func sortPoolAssetsByDenom(poolAssets []PoolAsset) { - sort.Slice(poolAssets, func(i, j int) bool { - return strings.Compare(poolAssets[i].Token.Denom, poolAssets[j].Token.Denom) == -1 - }) -} diff --git a/x/spot/types/utils_test.go b/x/spot/types/utils_test.go deleted file mode 100644 index ce690ee3f..000000000 --- a/x/spot/types/utils_test.go +++ /dev/null @@ -1,250 +0,0 @@ -package types - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestGetPoolAssetAndIndexHappyPath(t *testing.T) { - tests := []struct { - name string - poolAssets []PoolAsset - denom string - expectedPoolAsset PoolAsset - expectedIndex int - }{ - { - name: "single asset", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("foo", 100), - Weight: sdk.OneInt(), - }, - }, - denom: "foo", - expectedPoolAsset: PoolAsset{ - Token: sdk.NewInt64Coin("foo", 100), - Weight: sdk.OneInt(), - }, - expectedIndex: 0, - }, - { - name: "middle asset", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("foo", 100), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("zee", 100), - Weight: sdk.OneInt(), - }, - }, - denom: "foo", - expectedPoolAsset: PoolAsset{ - Token: sdk.NewInt64Coin("foo", 100), - Weight: sdk.OneInt(), - }, - expectedIndex: 1, - }, - { - name: "asset to the left", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("foo", 200), - Weight: sdk.OneInt(), - }, - }, - denom: "bar", - expectedPoolAsset: PoolAsset{ - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.OneInt(), - }, - expectedIndex: 0, - }, - } - - for _, testcase := range tests { - tc := testcase - t.Run(tc.name, func(t *testing.T) { - pool := Pool{ - PoolAssets: tc.poolAssets, - } - index, poolAsset, err := pool.getPoolAssetAndIndex(tc.denom) - require.NoError(t, err) - require.Equal(t, tc.expectedIndex, index) - require.Equal(t, tc.expectedPoolAsset, poolAsset) - }) - } -} - -func TestGetPoolAssetAndIndexErrors(t *testing.T) { - tests := []struct { - name string - poolAssets []PoolAsset - denom string - expectedError string - }{ - { - name: "empty pool assets", - poolAssets: []PoolAsset{}, - denom: "foo", - expectedError: "Empty pool assets.", - }, - { - name: "empty denom", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("foo", 100), - Weight: sdk.OneInt(), - }, - }, - denom: "", - expectedError: "Empty denom.", - }, - { - name: "denom not found - input denom lexicographically higher", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.OneInt(), - }, - }, - denom: "foo", - expectedError: "Did not find the PoolAsset (foo)", - }, - { - name: "denom not found - input denom lexicographically lower", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("foo", 100), - Weight: sdk.OneInt(), - }, - }, - denom: "bar", - expectedError: "Did not find the PoolAsset (bar)", - }, - } - - for _, testcase := range tests { - tc := testcase - t.Run(tc.name, func(t *testing.T) { - pool := Pool{ - PoolAssets: tc.poolAssets, - } - _, _, err := pool.getPoolAssetAndIndex(tc.denom) - require.Errorf(t, err, tc.expectedError) - }) - } -} - -func TestPoolBalances(t *testing.T) { - tests := []struct { - name string - poolAssets []PoolAsset - expectedCoins sdk.Coins - }{ - { - name: "happy path single asset", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("foo", 100), - Weight: sdk.OneInt(), - }, - }, - expectedCoins: sdk.NewCoins(sdk.NewInt64Coin("foo", 100)), - }, - { - name: "happy path multiple asset", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 100), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("foo", 200), - Weight: sdk.OneInt(), - }, - }, - expectedCoins: sdk.NewCoins( - sdk.NewInt64Coin("bar", 100), - sdk.NewInt64Coin("foo", 200), - ), - }, - } - - for _, testcase := range tests { - tc := testcase - t.Run(tc.name, func(t *testing.T) { - pool := Pool{ - PoolAssets: tc.poolAssets, - } - require.Equal(t, tc.expectedCoins, pool.PoolBalances()) - }) - } -} - -func TestSortPoolAssets(t *testing.T) { - tests := []struct { - name string - poolAssets []PoolAsset - expectedPoolAsset []PoolAsset - }{ - { - name: "single asset", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("foo", 100), - Weight: sdk.OneInt(), - }, - }, - expectedPoolAsset: []PoolAsset{ - { - Token: sdk.NewInt64Coin("foo", 100), - Weight: sdk.OneInt(), - }, - }, - }, - { - name: "happy path multiple asset", - poolAssets: []PoolAsset{ - { - Token: sdk.NewInt64Coin("foo", 100), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("bar", 200), - Weight: sdk.OneInt(), - }, - }, - expectedPoolAsset: []PoolAsset{ - { - Token: sdk.NewInt64Coin("bar", 200), - Weight: sdk.OneInt(), - }, - { - Token: sdk.NewInt64Coin("foo", 100), - Weight: sdk.OneInt(), - }, - }, - }, - } - - for _, testcase := range tests { - tc := testcase - t.Run(tc.name, func(t *testing.T) { - sortPoolAssetsByDenom(tc.poolAssets) - require.Equal(t, tc.expectedPoolAsset, tc.poolAssets) - }) - } -}