From 7e3560c0017fd5142e1e95b6eba2e193f5ec82e4 Mon Sep 17 00:00:00 2001 From: codelover <62229912+DedicatedDev@users.noreply.github.com> Date: Thu, 14 Sep 2023 22:18:00 +0300 Subject: [PATCH] Dex (#17) * refactor: :art: change domain and binary * chore: lint issue fix * feat: define proto and generate types * feat: define poolmanager * feat: create pool/add liquidity scaffold and types * feat: :sparkles: create pool * feat: implement swap function * feat: integration toolsuit setup * fix: :art: lint issue fix * ci: :test_tube: add ci/cd for golint and group testing * test: :test_tube: add message validation testcases * chore: lint fix * chore: decrease testgroup * chore: decrease testgroup * chore: remove docker image build * chore: add release ci/cd * chore: build yml * chore: remove arm archietecture * chore: add integration testcases * chore: lint issue fix * chore: stable swap * feat: :sparkles: add stable swap algorithm * chore: fix lint issue * chore: fix testcase issue * chore: address problems * chore: add slippage confirmation in swap * chore: fix lint issue * chore: fix testcase issues * chore: fix lint issue * test: :art: update create/add liquidity testcases * test: :art: add swap tests about stable pool * chore: add all testcases * chore: add pool queries --- .editorconfig | 17 + .github/workflows/build.yml | 37 + .github/workflows/docker-image.yml | 35 - .github/workflows/lint.yml | 38 + .github/workflows/release.yml | 26 + .github/workflows/tests.yml | 33 + JOIN_TESTNEWORK.md | 48 - Makefile | 139 +- app/app.go | 37 +- app/encoding.go | 2 +- app/export.go | 2 +- app/simulation_test.go | 2 +- app/test_helper.go | 178 ++ app/upgrades/v0/constants.go | 4 +- app/upgrades/v0/upgrades.go | 2 +- cmd/sided/cmd/config.go | 2 +- cmd/sided/cmd/root.go | 10 +- cmd/sided/main.go | 4 +- docs/docs.go | 7 +- docs/static/openapi.yml | 383 +++ go.mod | 45 +- go.sum | 69 +- proto/side/gmm/genesis.proto | 12 + proto/side/gmm/params.proto | 14 + proto/side/gmm/pool.proto | 23 + proto/side/gmm/pool_asset.proto | 17 + proto/side/gmm/pool_params.proto | 30 + proto/side/gmm/query.proto | 63 + proto/side/gmm/tx.proto | 67 + testutil/keeper/gmm.go | 54 + testutil/network/network.go | 2 +- x/gmm/client/cli/query.go | 32 + x/gmm/client/cli/query_params.go | 36 + x/gmm/client/cli/tx.go | 33 + x/gmm/client/cli/tx_add_liquidity.go | 47 + x/gmm/client/cli/tx_create_pool.go | 129 + x/gmm/client/cli/tx_swap.go | 51 + x/gmm/client/cli/tx_withdraw.go | 48 + x/gmm/genesis.go | 23 + x/gmm/genesis_test.go | 29 + x/gmm/keeper/bank.go | 56 + x/gmm/keeper/event.go | 37 + x/gmm/keeper/keeper.go | 51 + x/gmm/keeper/keeper_test.go | 180 ++ x/gmm/keeper/msg_server.go | 17 + x/gmm/keeper/msg_server_add_liquidity.go | 53 + x/gmm/keeper/msg_server_add_liquidity_test.go | 136 + x/gmm/keeper/msg_server_create_pool.go | 35 + x/gmm/keeper/msg_server_create_pool_test.go | 249 ++ x/gmm/keeper/msg_server_swap.go | 64 + x/gmm/keeper/msg_server_swap_test.go | 134 + x/gmm/keeper/msg_server_test.go | 23 + x/gmm/keeper/msg_server_withdraw.go | 54 + x/gmm/keeper/msg_server_withdraw_test.go | 114 + x/gmm/keeper/params.go | 17 + x/gmm/keeper/params_test.go | 18 + x/gmm/keeper/pool.go | 206 ++ x/gmm/keeper/query.go | 7 + x/gmm/keeper/query_params.go | 19 + x/gmm/keeper/query_params_test.go | 21 + x/gmm/keeper/query_pools.go | 112 + x/gmm/keeper/share.go | 24 + x/gmm/module.go | 152 ++ x/gmm/module_simulation.go | 169 ++ x/gmm/simulation/add_liquidity.go | 31 + x/gmm/simulation/create_pool.go | 32 + x/gmm/simulation/helpers.go | 15 + x/gmm/simulation/swap.go | 31 + x/gmm/simulation/withdraw.go | 31 + x/gmm/types/codec.go | 40 + x/gmm/types/consts.go | 7 + x/gmm/types/errors.go | 33 + x/gmm/types/events.go | 25 + x/gmm/types/expected_keepers.go | 35 + x/gmm/types/genesis.go | 24 + x/gmm/types/genesis.pb.go | 320 +++ x/gmm/types/genesis_test.go | 41 + x/gmm/types/keys.go | 36 + x/gmm/types/message_add_liquidity.go | 64 + x/gmm/types/message_add_liquidity_test.go | 89 + x/gmm/types/message_create_pool.go | 123 + x/gmm/types/message_create_pool_test.go | 95 + x/gmm/types/message_swap.go | 71 + x/gmm/types/message_swap_test.go | 64 + x/gmm/types/message_withdraw.go | 66 + x/gmm/types/message_withdraw_test.go | 77 + x/gmm/types/params.go | 39 + x/gmm/types/params.pb.go | 300 +++ x/gmm/types/pool.go | 153 ++ x/gmm/types/pool.pb.go | 661 +++++ x/gmm/types/pool_asset.pb.go | 427 +++ x/gmm/types/pool_params.pb.go | 526 ++++ x/gmm/types/pool_stable.go | 239 ++ x/gmm/types/pool_weight.go | 116 + x/gmm/types/query.pb.go | 1482 ++++++++++ x/gmm/types/query.pb.gw.go | 456 ++++ x/gmm/types/swap_route.pb.go | 562 ++++ x/gmm/types/tx.pb.go | 2376 +++++++++++++++++ x/gmm/types/types.go | 1 + x/gmm/types/utils.go | 38 + 100 files changed, 12279 insertions(+), 225 deletions(-) create mode 100644 .editorconfig create mode 100644 .github/workflows/build.yml delete mode 100644 .github/workflows/docker-image.yml create mode 100644 .github/workflows/lint.yml create mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/tests.yml delete mode 100644 JOIN_TESTNEWORK.md create mode 100644 app/test_helper.go create mode 100644 proto/side/gmm/genesis.proto create mode 100644 proto/side/gmm/params.proto create mode 100644 proto/side/gmm/pool.proto create mode 100644 proto/side/gmm/pool_asset.proto create mode 100644 proto/side/gmm/pool_params.proto create mode 100644 proto/side/gmm/query.proto create mode 100644 proto/side/gmm/tx.proto create mode 100644 testutil/keeper/gmm.go create mode 100644 x/gmm/client/cli/query.go create mode 100644 x/gmm/client/cli/query_params.go create mode 100644 x/gmm/client/cli/tx.go create mode 100644 x/gmm/client/cli/tx_add_liquidity.go create mode 100644 x/gmm/client/cli/tx_create_pool.go create mode 100644 x/gmm/client/cli/tx_swap.go create mode 100644 x/gmm/client/cli/tx_withdraw.go create mode 100644 x/gmm/genesis.go create mode 100644 x/gmm/genesis_test.go create mode 100644 x/gmm/keeper/bank.go create mode 100644 x/gmm/keeper/event.go create mode 100644 x/gmm/keeper/keeper.go create mode 100644 x/gmm/keeper/keeper_test.go create mode 100644 x/gmm/keeper/msg_server.go create mode 100644 x/gmm/keeper/msg_server_add_liquidity.go create mode 100644 x/gmm/keeper/msg_server_add_liquidity_test.go create mode 100644 x/gmm/keeper/msg_server_create_pool.go create mode 100644 x/gmm/keeper/msg_server_create_pool_test.go create mode 100644 x/gmm/keeper/msg_server_swap.go create mode 100644 x/gmm/keeper/msg_server_swap_test.go create mode 100644 x/gmm/keeper/msg_server_test.go create mode 100644 x/gmm/keeper/msg_server_withdraw.go create mode 100644 x/gmm/keeper/msg_server_withdraw_test.go create mode 100644 x/gmm/keeper/params.go create mode 100644 x/gmm/keeper/params_test.go create mode 100644 x/gmm/keeper/pool.go create mode 100644 x/gmm/keeper/query.go create mode 100644 x/gmm/keeper/query_params.go create mode 100644 x/gmm/keeper/query_params_test.go create mode 100644 x/gmm/keeper/query_pools.go create mode 100644 x/gmm/keeper/share.go create mode 100644 x/gmm/module.go create mode 100644 x/gmm/module_simulation.go create mode 100644 x/gmm/simulation/add_liquidity.go create mode 100644 x/gmm/simulation/create_pool.go create mode 100644 x/gmm/simulation/helpers.go create mode 100644 x/gmm/simulation/swap.go create mode 100644 x/gmm/simulation/withdraw.go create mode 100644 x/gmm/types/codec.go create mode 100644 x/gmm/types/consts.go create mode 100644 x/gmm/types/errors.go create mode 100644 x/gmm/types/events.go create mode 100644 x/gmm/types/expected_keepers.go create mode 100644 x/gmm/types/genesis.go create mode 100644 x/gmm/types/genesis.pb.go create mode 100644 x/gmm/types/genesis_test.go create mode 100644 x/gmm/types/keys.go create mode 100644 x/gmm/types/message_add_liquidity.go create mode 100644 x/gmm/types/message_add_liquidity_test.go create mode 100644 x/gmm/types/message_create_pool.go create mode 100644 x/gmm/types/message_create_pool_test.go create mode 100644 x/gmm/types/message_swap.go create mode 100644 x/gmm/types/message_swap_test.go create mode 100644 x/gmm/types/message_withdraw.go create mode 100644 x/gmm/types/message_withdraw_test.go create mode 100644 x/gmm/types/params.go create mode 100644 x/gmm/types/params.pb.go create mode 100644 x/gmm/types/pool.go create mode 100644 x/gmm/types/pool.pb.go create mode 100644 x/gmm/types/pool_asset.pb.go create mode 100644 x/gmm/types/pool_params.pb.go create mode 100644 x/gmm/types/pool_stable.go create mode 100644 x/gmm/types/pool_weight.go create mode 100644 x/gmm/types/query.pb.go create mode 100644 x/gmm/types/query.pb.gw.go create mode 100644 x/gmm/types/swap_route.pb.go create mode 100644 x/gmm/types/tx.pb.go create mode 100644 x/gmm/types/types.go create mode 100644 x/gmm/types/utils.go diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..23c62d98 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,17 @@ +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{sh,Makefile}] +indent_style = tab + +[*.proto] +indent_style = space +indent_size = 2 + diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 00000000..08e48076 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,37 @@ +name: Build +# Tests runs different tests (test_abci_apps, test_abci_cli, test_apps) +# This workflow runs on every push to main or release branch and every pull requests +# All jobs will pass without running if no *{.go, .mod, .sum} files have been modified +on: + pull_request: + push: + branches: + - develop + +jobs: + build: + name: Build + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + goarch: ["amd64"] + goos: ["linux"] + timeout-minutes: 5 + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v4 + with: + go-version: "1.20" + - uses: technote-space/get-diff-action@v6 + with: + PATTERNS: | + **/*.go + "!test/" + go.mod + go.sum + Makefile + + - name: install + run: GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} make build + if: "env.GIT_DIFF != ''" diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml deleted file mode 100644 index 81e4532b..00000000 --- a/.github/workflows/docker-image.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Build and Deploy - -on: - push: - branches: ["dev"] - pull_request: - branches: ["dev"] - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v1 - - - name: Login to GitHub Container Registry - uses: docker/login-action@v1 - with: - registry: ghcr.io - username: ${{ github.repository_owner }} - password: ${{ secrets.GHCR_TOKEN }} - - - name: Get current timestamp - id: timestamp - run: echo "::set-output name=timestamp::$(date +%s)" - - - name: Build and push Docker image - uses: docker/build-push-action@v2 - with: - context: . - push: true - tags: ghcr.io/sideprotocol/sidechain:${{ steps.timestamp.outputs.timestamp }} diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000..a660a943 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,38 @@ +name: Golang Linter +# Lint runs golangci-lint over the entire WMBFT repository. +# +# This workflow is run on every pull request and push to main. +# +# The `golangci` job will pass without running if no *.{go, mod, sum} +# files have been modified. +# +# To run this locally, simply run `make lint` from the root of the repo. + +on: + pull_request: + push: + branches: + - develop + +jobs: + golangci: + name: golangci-lint + runs-on: ubuntu-latest + timeout-minutes: 8 + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v4 + with: + go-version: '1.20' + - uses: technote-space/get-diff-action@v6 + with: + PATTERNS: | + **/**.go + go.mod + go.sum + - uses: golangci/golangci-lint-action@v3 + with: + version: v1.51 + args: --timeout 10m + github-token: ${{ secrets.github_token }} + if: env.GIT_DIFF diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..cc588dac --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,26 @@ +# This workflow creates a release using goreleaser +# via the 'make release' command. + +name: Create release +on: + push: + tags: + - v* +permissions: + contents: write +jobs: + release: + name: Create release + runs-on: ubuntu-latest + steps: + - name: Check out repository code + uses: actions/checkout@v3 + with: + fetch-depth: 0 + ref: ${{ github.event.inputs.release_tag }} + - name: Make release + run: | + sudo rm -rf dist + make release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 00000000..6969ed3f --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,33 @@ +name: Test +on: + pull_request: + push: + paths: + - "**.go" + branches: + - develop + +jobs: + tests: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + part: ["00", "01", "02"] + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v4 + with: + go-version: "1.20" + - uses: technote-space/get-diff-action@v6 + with: + PATTERNS: | + **/**.go + "!test/" + go.mod + go.sum + Makefile + - name: Run Go Tests + run: | + make test-group-${{ matrix.part }} NUM_SPLIT=6 + if: env.GIT_DIFF diff --git a/JOIN_TESTNEWORK.md b/JOIN_TESTNEWORK.md deleted file mode 100644 index 086be8e7..00000000 --- a/JOIN_TESTNEWORK.md +++ /dev/null @@ -1,48 +0,0 @@ -# Join a network - -## Initialize node configuration files -```shell -export TESTNET_PATH=${PWD}/testnet -cd build/ -./sidechaind init outsider --home ${TESTNET_PATH}/outsider -``` - -## Get the genesis file for the existing network - -```shell -cp ${TESTNET_PATH}/node0/config/genesis.json ${TESTNET_PATH}/outsider/config/ -``` - -## Add at least one seed peer - -### Add seed peer (you need a seed peer online for this to work) - -```shell -# export SEEDER_IP=$(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps | grep docker_seeder | awk '{print $1}')) -sed -i "s/seeds = \"\"/seeds = \"6a4fa5865eda7c4f3e9d257190f4635008a3c8d6@13.212.61.41:26656\"/g" ${TESTNET_PATH}/outsider/config/config.toml -``` - -### Set node to look for peers constantly - -```shell -sed -i 's/seed_mode = false/seed_mode = true/g' ${TESTNET_PATH}/outsider/config/config.toml -``` - -### On local networks, change addr_book_strict flag to false - -```shell -sed -i 's/addr_book_strict = true/addr_book_strict = false/g' ${TESTNET_PATH}/outsider/config/config.toml -``` - -## Build docker image - -```shell -cd ../.. -docker build -f .docker/Dockerfile-outsider . -t docker_outsider -``` - -## Start the node - -```shell -docker run --name=outsider --network=docker_default -d docker_outsider -``` \ No newline at end of file diff --git a/Makefile b/Makefile index 1a9e1ea3..19d1889c 100755 --- a/Makefile +++ b/Makefile @@ -279,7 +279,7 @@ vulncheck: $(BUILDDIR)/ $(BUILDDIR)/govulncheck ./... godocs: - @echo "--> Wait a few seconds and visit http://localhost:6060/pkg/github.com/sideprotocol/github.com/sideprotocol/sidechain/types" + @echo "--> Wait a few seconds and visit http://localhost:6060/pkg/github.com/sideprotocol/github.com/sideprotocol/github.com/sideprotocol/side/types" godoc -http=:6060 # Start docs site at localhost:8080 @@ -371,83 +371,48 @@ benchmark: ### Linting ### ############################################################################### -lint: - golangci-lint run --out-format=tab - solhint contracts/**/*.sol +golangci_version=v1.52.2 -lint-contracts: - @cd contracts && \ - npm i && \ - npm run lint +lint: + @echo "--> Running linter" + @go run --mod=mod github.com/golangci/golangci-lint/cmd/golangci-lint@$(golangci_version) run --timeout=15m lint-fix: - golangci-lint run --fix --out-format=tab --issues-exit-code=0 - -lint-fix-contracts: - @cd contracts && \ - npm i && \ - npm run lint-fix - solhint --fix contracts/**/*.sol + @echo "--> Running linter" + @go run --mod=mod github.com/golangci/golangci-lint/cmd/golangci-lint@$(golangci_version) run --fix .PHONY: lint lint-fix -format: - find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/docs/statik/statik.go" -not -name '*.pb.go' | xargs gofumpt -w -l - -.PHONY: format ############################################################################### ### Protobuf ### ############################################################################### -# ------ -# NOTE: Link to the tendermintdev/sdk-proto-gen docker images: -# https://hub.docker.com/r/tendermintdev/sdk-proto-gen/tags -# -protoVer=v0.7 -protoImageName=tendermintdev/sdk-proto-gen:$(protoVer) -protoImage=$(DOCKER) run --network host --rm -v $(CURDIR):/workspace --workdir /workspace $(protoImageName) -# ------ -# NOTE: cosmos/proto-builder image is needed because clang-format is not installed -# on the tendermintdev/sdk-proto-gen docker image. -# Link to the cosmos/proto-builder docker images: -# https://github.com/cosmos/cosmos-sdk/pkgs/container/proto-builder -# -protoCosmosVer=0.11.2 -protoCosmosName=ghcr.io/cosmos/proto-builder:$(protoCosmosVer) -protoCosmosImage=$(DOCKER) run --network host --rm -v $(CURDIR):/workspace --workdir /workspace $(protoCosmosName) -# ------ -# NOTE: Link to the yoheimuta/protolint docker images: -# https://hub.docker.com/r/yoheimuta/protolint/tags -# -protolintVer=0.42.2 -protolintName=yoheimuta/protolint:$(protolintVer) -protolintImage=$(DOCKER) run --network host --rm -v $(CURDIR):/workspace --workdir /workspace $(protolintName) - +check-proto-deps: +ifeq (,$(shell which protoc-gen-gogofaster)) + @go install github.com/cosmos/gogoproto/protoc-gen-gogofaster@latest +endif +.PHONY: check-proto-deps -# ------ -# NOTE: If you are experiencing problems running these commands, try deleting -# the docker images and execute the desired command again. -# -proto-all: proto-format proto-lint proto-gen -proto-gen: +proto-gen: check-proto-deps @echo "Generating Protobuf files" - $(protoImage) sh ./scripts/protocgen.sh - -# TODO: Rethink API docs generation -# proto-swagger-gen: -# @echo "Generating Protobuf Swagger" -# $(protoImage) sh ./scripts/protoc-swagger-gen.sh + @go run github.com/bufbuild/buf/cmd/buf generate + @mv ./proto/tendermint/abci/types.pb.go ./abci/types/ + @cp ./proto/tendermint/rpc/grpc/types.pb.go ./rpc/grpc +.PHONY: proto-gen + +# These targets are provided for convenience and are intended for local +# execution only. +proto-lint: check-proto-deps + @echo "Linting Protobuf files" + @go run github.com/bufbuild/buf/cmd/buf lint +.PHONY: proto-lint -proto-format: +proto-format: check-proto-format-deps @echo "Formatting Protobuf files" - $(protoCosmosImage) find ./ -name *.proto -exec clang-format -i {} \; - -# NOTE: The linter configuration lives in .protolint.yaml -proto-lint: - @echo "Linting Protobuf files" - $(protolintImage) lint ./proto + @find . -name '*.proto' -path "./proto/*" -exec clang-format -i {} \; +.PHONY: proto-format proto-check-breaking: @echo "Checking Protobuf files for breaking changes" @@ -502,7 +467,7 @@ localnet-build: # Start a 4-node testnet locally localnet-start: localnet-stop localnet-build - @if ! [ -f build/node0/$(SIDECHAIN_BINARY)/config/genesis.json ]; then docker run --rm -v $(CURDIR)/build:/sidechain:Z github.com/sideprotocol/sidechain/node "./sided testnet init-files --v 4 -o /sidechain --keyring-backend=test --starting-ip-address 192.167.10.2"; fi + @if ! [ -f build/node0/$(SIDECHAIN_BINARY)/config/genesis.json ]; then docker run --rm -v $(CURDIR)/build:/sidechain:Z github.com/sideprotocol/github.com/sideprotocol/side/node "./sided testnet init-files --v 4 -o /sidechain --keyring-backend=test --starting-ip-address 192.167.10.2"; fi docker-compose up -d # Stop testnet @@ -518,15 +483,15 @@ localnet-clean: localnet-unsafe-reset: docker-compose down ifeq ($(OS),Windows_NT) - @docker run --rm -v $(CURDIR)\build\node0\sided:/sidechain\Z github.com/sideprotocol/sidechain/node "./sided tendermint unsafe-reset-all --home=/sidechain" - @docker run --rm -v $(CURDIR)\build\node1\sided:/sidechain\Z github.com/sideprotocol/sidechain/node "./sided tendermint unsafe-reset-all --home=/sidechain" - @docker run --rm -v $(CURDIR)\build\node2\sided:/sidechain\Z github.com/sideprotocol/sidechain/node "./sided tendermint unsafe-reset-all --home=/sidechain" - @docker run --rm -v $(CURDIR)\build\node3\sided:/sidechain\Z github.com/sideprotocol/sidechain/node "./sided tendermint unsafe-reset-all --home=/sidechain" + @docker run --rm -v $(CURDIR)\build\node0\sided:/sidechain\Z github.com/sideprotocol/github.com/sideprotocol/side/node "./sided tendermint unsafe-reset-all --home=/sidechain" + @docker run --rm -v $(CURDIR)\build\node1\sided:/sidechain\Z github.com/sideprotocol/github.com/sideprotocol/side/node "./sided tendermint unsafe-reset-all --home=/sidechain" + @docker run --rm -v $(CURDIR)\build\node2\sided:/sidechain\Z github.com/sideprotocol/github.com/sideprotocol/side/node "./sided tendermint unsafe-reset-all --home=/sidechain" + @docker run --rm -v $(CURDIR)\build\node3\sided:/sidechain\Z github.com/sideprotocol/github.com/sideprotocol/side/node "./sided tendermint unsafe-reset-all --home=/sidechain" else - @docker run --rm -v $(CURDIR)/build/node0/sided:/sidechain:Z github.com/sideprotocol/sidechain/node "./sided tendermint unsafe-reset-all --home=/sidechain" - @docker run --rm -v $(CURDIR)/build/node1/sided:/sidechain:Z github.com/sideprotocol/sidechain/node "./sided tendermint unsafe-reset-all --home=/sidechain" - @docker run --rm -v $(CURDIR)/build/node2/sided:/sidechain:Z github.com/sideprotocol/sidechain/node "./sided tendermint unsafe-reset-all --home=/sidechain" - @docker run --rm -v $(CURDIR)/build/node3/sided:/sidechain:Z github.com/sideprotocol/sidechain/node "./sided tendermint unsafe-reset-all --home=/sidechain" + @docker run --rm -v $(CURDIR)/build/node0/sided:/sidechain:Z github.com/sideprotocol/github.com/sideprotocol/side/node "./sided tendermint unsafe-reset-all --home=/sidechain" + @docker run --rm -v $(CURDIR)/build/node1/sided:/sidechain:Z github.com/sideprotocol/github.com/sideprotocol/side/node "./sided tendermint unsafe-reset-all --home=/sidechain" + @docker run --rm -v $(CURDIR)/build/node2/sided:/sidechain:Z github.com/sideprotocol/github.com/sideprotocol/side/node "./sided tendermint unsafe-reset-all --home=/sidechain" + @docker run --rm -v $(CURDIR)/build/node3/sided:/sidechain:Z github.com/sideprotocol/github.com/sideprotocol/side/node "./sided tendermint unsafe-reset-all --home=/sidechain" endif # Clean testnet @@ -627,3 +592,35 @@ create-contracts-json: mv $(TMP_JSON) $(COMPILED_DIR)/$${c}.json ;\ done @rm -rf tmp + + +# Implements test splitting and running. This is pulled directly from +# the github action workflows for better local reproducibility. + +GO_TEST_FILES != find $(CURDIR) -name "*_test.go" + +# default to four splits by default +NUM_SPLIT ?= 3 + +UNAME_S := $(shell uname -s) + +ifeq ($(UNAME_S),Darwin) # macOS + SPLIT_CMD = gsplit +else + SPLIT_CMD = split +endif + +$(BUILDDIR): + mkdir -p $@ + +# The format statement filters out all packages that don't have tests. +# Note we need to check for both in-package tests (.TestGoFiles) and +# out-of-package tests (.XTestGoFiles). +$(BUILDDIR)/packages.txt:$(GO_TEST_FILES) $(BUILDDIR) + go list -f "{{ if (or .TestGoFiles .XTestGoFiles) }}{{ .ImportPath }}{{ end }}" ./... | sort > $@ + +split-test-packages:$(BUILDDIR)/packages.txt + $(SPLIT_CMD) -d -n l/$(NUM_SPLIT) $< $<. + +test-group-%:split-test-packages + cat $(BUILDDIR)/packages.txt.$* | xargs go test -mod=readonly -timeout=10m -race -coverprofile=$(BUILDDIR)/$*.profile.out \ No newline at end of file diff --git a/app/app.go b/app/app.go index 4ac22bf8..317ff779 100644 --- a/app/app.go +++ b/app/app.go @@ -117,10 +117,14 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/spf13/cast" + gmmmodule "github.com/sideprotocol/side/x/gmm" + gmmmodulekeeper "github.com/sideprotocol/side/x/gmm/keeper" + gmmmoduletypes "github.com/sideprotocol/side/x/gmm/types" + // this line is used by starport scaffolding # stargate/app/moduleImport - appparams "sidechain/app/params" - "sidechain/docs" + appparams "github.com/sideprotocol/side/app/params" + "github.com/sideprotocol/side/docs" // wasmd module integrate "github.com/CosmWasm/wasmd/x/wasm" @@ -185,6 +189,7 @@ var ( ibcfee.AppModuleBasic{}, wasm.AppModuleBasic{}, + gmmmodule.AppModuleBasic{}, // this line is used by starport scaffolding # stargate/app/moduleBasic ) @@ -200,6 +205,7 @@ var ( ibcfeetypes.ModuleName: nil, ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, wasm.ModuleName: {authtypes.Burner}, + gmmmoduletypes.ModuleName: {authtypes.Minter, authtypes.Burner, authtypes.Staking}, // this line is used by starport scaffolding # stargate/app/maccPerms } ) @@ -268,6 +274,8 @@ type App struct { scopedWasmKeeper capabilitykeeper.ScopedKeeper + GmmKeeper gmmmodulekeeper.Keeper + // this line is used by starport scaffolding # stargate/app/keeperDeclaration // mm is the module manager @@ -314,6 +322,7 @@ func New( govtypes.StoreKey, paramstypes.StoreKey, ibcexported.StoreKey, upgradetypes.StoreKey, feegrant.StoreKey, evidencetypes.StoreKey, ibctransfertypes.StoreKey, icahosttypes.StoreKey, capabilitytypes.StoreKey, group.StoreKey, icacontrollertypes.StoreKey, consensusparamtypes.StoreKey, wasmTypes.StoreKey, ibcfeetypes.StoreKey, + gmmmoduletypes.StoreKey, // this line is used by starport scaffolding # stargate/app/storeKey ) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) @@ -509,7 +518,7 @@ func New( icaModule := ica.NewAppModule(&icaControllerKeeper, &app.ICAHostKeeper) icaHostIBCModule := icahost.NewIBCModule(app.ICAHostKeeper) - // Create evidence Keeper for to register the IBC light client misbehaviour evidence route + // Create evidence Keeper for to register the IBC light client misbehavior evidence route evidenceKeeper := evidencekeeper.NewKeeper( appCodec, keys[evidencetypes.StoreKey], @@ -575,6 +584,16 @@ func New( wasmOpts..., ) + app.GmmKeeper = *gmmmodulekeeper.NewKeeper( + appCodec, + keys[gmmmoduletypes.StoreKey], + keys[gmmmoduletypes.MemStoreKey], + app.GetSubspace(gmmmoduletypes.ModuleName), + app.AccountKeeper, + app.BankKeeper, + ) + gmmModule := gmmmodule.NewAppModule(appCodec, app.GmmKeeper, app.AccountKeeper, app.BankKeeper) + // this line is used by starport scaffolding # stargate/app/keeperDefinition /**** IBC Routing ****/ @@ -641,6 +660,7 @@ func New( params.NewAppModule(app.ParamsKeeper), icaModule, + gmmModule, // this line is used by starport scaffolding # stargate/app/appModule crisis.NewAppModule(app.CrisisKeeper, skipGenesisInvariants, app.GetSubspace(crisistypes.ModuleName)), // always be last to make sure that it checks for all invariants and not only part of them @@ -675,6 +695,7 @@ func New( consensusparamtypes.ModuleName, ibcfeetypes.ModuleName, wasmTypes.ModuleName, + gmmmoduletypes.ModuleName, // this line is used by starport scaffolding # stargate/app/beginBlockers ) @@ -702,6 +723,7 @@ func New( consensusparamtypes.ModuleName, ibcfeetypes.ModuleName, wasmTypes.ModuleName, + gmmmoduletypes.ModuleName, // this line is used by starport scaffolding # stargate/app/endBlockers ) @@ -734,6 +756,7 @@ func New( vestingtypes.ModuleName, consensusparamtypes.ModuleName, wasmTypes.ModuleName, + gmmmoduletypes.ModuleName, // this line is used by starport scaffolding # stargate/app/initGenesis } app.mm.SetOrderInitGenesis(genesisModuleOrder...) @@ -918,9 +941,10 @@ func (app *App) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig // Register grpc-gateway routes for all modules. ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) - - // register app's OpenAPI routes. - docs.RegisterOpenAPIService(Name, apiSvr.Router) + if apiConfig.Enable { + // register app's OpenAPI routes. + docs.RegisterOpenAPIService(Name, apiSvr.Router) + } } // RegisterTxService implements the Application.RegisterTxService method. @@ -959,6 +983,7 @@ func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino paramsKeeper.Subspace(ibcexported.ModuleName) paramsKeeper.Subspace(icacontrollertypes.SubModuleName) paramsKeeper.Subspace(icahosttypes.SubModuleName) + paramsKeeper.Subspace(gmmmoduletypes.ModuleName) // this line is used by starport scaffolding # stargate/app/paramSubspace return paramsKeeper diff --git a/app/encoding.go b/app/encoding.go index 290b8486..91f5666f 100644 --- a/app/encoding.go +++ b/app/encoding.go @@ -6,7 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/std" "github.com/cosmos/cosmos-sdk/x/auth/tx" - "sidechain/app/params" + "github.com/sideprotocol/side/app/params" ) // makeEncodingConfig creates an EncodingConfig for an amino based test configuration. diff --git a/app/export.go b/app/export.go index db240d2b..728dfe0e 100644 --- a/app/export.go +++ b/app/export.go @@ -49,7 +49,7 @@ func (app *App) ExportAppStateAndValidators( // prepForZeroHeightGenesis prepares for a fresh genesis // // NOTE zero height genesis is a temporary feature which will be deprecated -// in favour of export at a block height +// in favor of export at a block height func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { applyAllowedAddrs := false diff --git a/app/simulation_test.go b/app/simulation_test.go index 64b2b752..94c587c0 100644 --- a/app/simulation_test.go +++ b/app/simulation_test.go @@ -36,7 +36,7 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/require" - "sidechain/app" + "github.com/sideprotocol/side/app" ) type storeKeysPrefixes struct { diff --git a/app/test_helper.go b/app/test_helper.go new file mode 100644 index 00000000..17c10674 --- /dev/null +++ b/app/test_helper.go @@ -0,0 +1,178 @@ +package app + +import ( + "encoding/json" + "testing" + "time" + + "github.com/cometbft/cometbft/crypto/secp256k1" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + tmtypes "github.com/cometbft/cometbft/types" + "github.com/cosmos/cosmos-sdk/testutil/mock" + "github.com/stretchr/testify/require" + + 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" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + dbm "github.com/cometbft/cometbft-db" + abci "github.com/cometbft/cometbft/abci/types" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + + "github.com/cometbft/cometbft/libs/log" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" +) + +const ( + DefaultBondDenom = "uside" + USDC = "uusdc" + WBTC = "wbtc" + WDAI = "wdai" + WUSDT = "wusdt" +) + +// Setup initializes a new App. A Nop logger is set in App. +func Setup(t *testing.T) *App { + t.Helper() + + privVal := mock.NewPV() + pubKey, err := privVal.GetPubKey() + require.NoError(t, err) + + // create validator set with single validator + validator := tmtypes.NewValidator(pubKey, 1) + valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) + + // generate genesis account + senderPrivKey := secp256k1.GenPrivKey() + acc := authtypes.NewBaseAccountWithAddress(senderPrivKey.PubKey().Address().Bytes()) + balance := banktypes.Balance{ + Address: acc.GetAddress().String(), + Coins: sdk.NewCoins( + sdk.NewCoin(DefaultBondDenom, sdk.NewInt(100000000000000)), + sdk.NewCoin(USDC, sdk.NewInt(100000000000000)), + ), + } + + app := SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, balance) + + return app +} + +func genesisStateWithValSet(t *testing.T, + app *App, genesisState GenesisState, + valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, + balances ...banktypes.Balance, +) GenesisState { + // set genesis accounts + + authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) + genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) + + validators := make([]stakingtypes.Validator, 0, len(valSet.Validators)) + delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators)) + + bondAmt := sdk.DefaultPowerReduction + + for _, val := range valSet.Validators { + pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey) + require.NoError(t, err) + pkAny, err := codectypes.NewAnyWithValue(pk) + require.NoError(t, err) + validator := stakingtypes.Validator{ + OperatorAddress: sdk.ValAddress(val.Address).String(), + ConsensusPubkey: pkAny, + Jailed: false, + Status: stakingtypes.Bonded, + Tokens: bondAmt, + DelegatorShares: sdk.OneDec(), + Description: stakingtypes.Description{}, + UnbondingHeight: int64(0), + UnbondingTime: time.Unix(0, 0).UTC(), + Commission: stakingtypes.NewCommission(sdk.OneDec(), sdk.OneDec(), sdk.OneDec()), + MinSelfDelegation: sdk.ZeroInt(), + } + validators = append(validators, validator) + delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec())) + + } + // set validators and delegations + stakingParams := stakingtypes.DefaultParams() + stakingParams.BondDenom = DefaultBondDenom + stakingParams.MinCommissionRate = sdk.OneDec() + stakingGenesis := stakingtypes.NewGenesisState(stakingParams, validators, delegations) + genesisState[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGenesis) + + totalSupply := sdk.NewCoins() + for _, b := range balances { + // add genesis acc tokens to total supply + totalSupply = totalSupply.Add(b.Coins...) + } + + for range delegations { + // add delegated tokens to total supply + totalSupply = totalSupply.Add(sdk.NewCoin(DefaultBondDenom, bondAmt)) + } + + // add bonded amount to bonded pool module account + balances = append(balances, banktypes.Balance{ + Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), + Coins: sdk.Coins{sdk.NewCoin(DefaultBondDenom, bondAmt)}, + }) + + // update total supply + bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}, []banktypes.SendEnabled{}) + genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) + + return genesisState +} + +// SetupWithGenesisValSet initializes a new App with a validator set and genesis accounts +// that also act as delegators. For simplicity, each validator is bonded with a delegation +// of one consensus engine unit (10^6) in the default token of the simapp from first genesis +// account. A Nop logger is set in App. +func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *App { + t.Helper() + + app, genesisState := setup(true, 5) + genesisState = genesisStateWithValSet(t, app, genesisState, valSet, genAccs, balances...) + + stateBytes, err := json.MarshalIndent(genesisState, "", " ") + require.NoError(t, err) + + // init chain will set the validator set and initialize the genesis accounts + app.InitChain( + abci.RequestInitChain{ + Validators: []abci.ValidatorUpdate{}, + ConsensusParams: simtestutil.DefaultConsensusParams, + AppStateBytes: stateBytes, + }, + ) + + // commit genesis changes + app.Commit() + app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{ + Height: app.LastBlockHeight() + 1, + AppHash: app.LastCommitID().Hash, + ValidatorsHash: valSet.Hash(), + NextValidatorsHash: valSet.Hash(), + }}) + + return app +} + +func setup(withGenesis bool, invCheckPeriod uint) (*App, GenesisState) { + db := dbm.NewMemDB() + encCdc := MakeEncodingConfig() + appOptions := make(simtestutil.AppOptionsMap, 0) + app := New( + log.NewNopLogger(), + db, + nil, true, map[int64]bool{}, DefaultNodeHome, invCheckPeriod, encCdc, appOptions) + if withGenesis { + return app, NewDefaultGenesisState(encCdc.Marshaler) + } + return app, GenesisState{} +} diff --git a/app/upgrades/v0/constants.go b/app/upgrades/v0/constants.go index 6e8f4313..4696f556 100644 --- a/app/upgrades/v0/constants.go +++ b/app/upgrades/v0/constants.go @@ -13,7 +13,7 @@ // // You should have received a copy of the GNU Lesser General Public License -package v0_1_1 +package v011 const ( // UpgradeName is the shared upgrade plan name for mainnet and testnet @@ -22,5 +22,5 @@ const ( // UpgradeHeight = 130_0000 // UpgradeInfo defines the binaries that will be used for the upgrade - // UpgradeInfo = `'{"binaries":{"darwin/arm64":"https://github.com/SideProtocol/sidechain/v_8.0.0_Darwin_arm64.tar.gz"}}'` + // UpgradeInfo = `'{"binaries":{"darwin/arm64":"https://github.com/SideProtocol/github.com/sideprotocol/side/v_8.0.0_Darwin_arm64.tar.gz"}}'` ) diff --git a/app/upgrades/v0/upgrades.go b/app/upgrades/v0/upgrades.go index 66debd72..f3ae612b 100644 --- a/app/upgrades/v0/upgrades.go +++ b/app/upgrades/v0/upgrades.go @@ -1,4 +1,4 @@ -package v0_1_1 +package v011 import ( sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/cmd/sided/cmd/config.go b/cmd/sided/cmd/config.go index 93273437..855e220d 100644 --- a/cmd/sided/cmd/config.go +++ b/cmd/sided/cmd/config.go @@ -3,7 +3,7 @@ package cmd import ( sdk "github.com/cosmos/cosmos-sdk/types" - "sidechain/app" + "github.com/sideprotocol/side/app" ) func initSDKConfig() { diff --git a/cmd/sided/cmd/root.go b/cmd/sided/cmd/root.go index 89ed8345..73cc35fb 100644 --- a/cmd/sided/cmd/root.go +++ b/cmd/sided/cmd/root.go @@ -2,6 +2,7 @@ package cmd import ( "errors" + "fmt" "io" "os" "path/filepath" @@ -36,10 +37,11 @@ import ( "github.com/spf13/cast" "github.com/spf13/cobra" "github.com/spf13/pflag" + // this line is used by starport scaffolding # root/moduleImport - "sidechain/app" - appparams "sidechain/app/params" + "github.com/sideprotocol/side/app" + appparams "github.com/sideprotocol/side/app/params" ) // NewRootCmd creates a new root command for a Cosmos SDK application @@ -208,7 +210,9 @@ func overwriteFlagDefaults(c *cobra.Command, defaults map[string]string) { set := func(s *pflag.FlagSet, key, val string) { if f := s.Lookup(key); f != nil { f.DefValue = val - f.Value.Set(val) + if err := f.Value.Set(val); err != nil { + fmt.Println(err) + } } } for key, val := range defaults { diff --git a/cmd/sided/main.go b/cmd/sided/main.go index 2b696e62..8d6ebc8a 100644 --- a/cmd/sided/main.go +++ b/cmd/sided/main.go @@ -6,8 +6,8 @@ import ( "github.com/cosmos/cosmos-sdk/server" svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" - "sidechain/app" - "sidechain/cmd/sided/cmd" + "github.com/sideprotocol/side/app" + "github.com/sideprotocol/side/cmd/sided/cmd" ) func main() { diff --git a/docs/docs.go b/docs/docs.go index 1ba96c79..ed8d1ce9 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -2,6 +2,7 @@ package docs import ( "embed" + "fmt" httptemplate "html/template" "net/http" @@ -29,12 +30,14 @@ func handler(title string) http.HandlerFunc { t, _ := httptemplate.ParseFS(template, indexFile) return func(w http.ResponseWriter, req *http.Request) { - t.Execute(w, struct { + if err := t.Execute(w, struct { Title string URL string }{ title, apiFile, - }) + }); err != nil { + fmt.Println(err) + } } } diff --git a/docs/static/openapi.yml b/docs/static/openapi.yml index c9aef345..248935d5 100644 --- a/docs/static/openapi.yml +++ b/docs/static/openapi.yml @@ -52201,6 +52201,150 @@ paths: } tags: - Query + /sideprotocol/side/gmm/params: + get: + summary: Parameters queries the parameters of the module. + operationId: SideGmmParams + responses: + '200': + description: A successful response. + schema: + type: object + properties: + params: + description: params holds all the parameters of this module. + type: object + properties: + poolCreationFee: + type: string + format: uint64 + description: >- + QueryParamsResponse is response type for the Query/Params RPC + method. + default: + description: An unexpected error response. + schema: + type: object + properties: + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + '@type': + type: string + additionalProperties: {} + tags: + - Query + /sideprotocol/side/gmm/{pool_id}: + get: + operationId: SideGmmPool + responses: + '200': + description: A successful response. + schema: + type: object + properties: + pool: + type: object + properties: + pool_id: + type: string + sender: + type: string + poolParams: + type: object + properties: + type: + type: string + enum: + - WEIGHT + - STABLE + default: WEIGHT + swapFee: + type: string + description: swapFee is ranged from 0 to 10000. + exitFee: + type: string + useOracle: + type: boolean + amp: + type: string + description: Amplifier parameters for stable pool. + assets: + type: object + additionalProperties: + type: object + properties: + token: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. + + + NOTE: The amount field is an Int which implements + the custom method + + signatures required by gogoproto. + weight: + type: string + decimal: + type: string + total_shares: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. + title: sum of all LP tokens sent out + title: >- + QueryLiquidityPoolResponse is response type for the + Query/Liquidity RPC method + default: + description: An unexpected error response. + schema: + type: object + properties: + code: + type: integer + format: int32 + message: + type: string + details: + type: array + items: + type: object + properties: + '@type': + type: string + additionalProperties: {} + parameters: + - name: pool_id + in: path + required: true + type: string + tags: + - Query definitions: cosmos.auth.v1beta1.AddressBytesToStringResponse: type: object @@ -82591,3 +82735,242 @@ definitions: description: |- Version defines the versioning scheme used to negotiate the IBC verison in the connection handshake. + side.gmm.MsgAddLiquidityResponse: + type: object + properties: + pool_id: + type: string + side.gmm.MsgCreatePoolResponse: + type: object + properties: + pool_id: + type: string + side.gmm.MsgSwapResponse: + type: object + properties: + pool_id: + type: string + tokenIn: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + side.gmm.MsgWithdrawResponse: + type: object + properties: + share: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + side.gmm.Params: + type: object + properties: + poolCreationFee: + type: string + format: uint64 + description: Params defines the parameters for the module. + side.gmm.Pool: + type: object + properties: + pool_id: + type: string + sender: + type: string + poolParams: + type: object + properties: + type: + type: string + enum: + - WEIGHT + - STABLE + default: WEIGHT + swapFee: + type: string + description: swapFee is ranged from 0 to 10000. + exitFee: + type: string + useOracle: + type: boolean + amp: + type: string + description: Amplifier parameters for stable pool. + assets: + type: object + additionalProperties: + type: object + properties: + token: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + weight: + type: string + decimal: + type: string + total_shares: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + title: sum of all LP tokens sent out + side.gmm.PoolAsset: + type: object + properties: + token: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. + weight: + type: string + decimal: + type: string + side.gmm.PoolParams: + type: object + properties: + type: + type: string + enum: + - WEIGHT + - STABLE + default: WEIGHT + swapFee: + type: string + description: swapFee is ranged from 0 to 10000. + exitFee: + type: string + useOracle: + type: boolean + amp: + type: string + description: Amplifier parameters for stable pool. + side.gmm.PoolType: + type: string + enum: + - WEIGHT + - STABLE + default: WEIGHT + side.gmm.QueryParamsResponse: + type: object + properties: + params: + description: params holds all the parameters of this module. + type: object + properties: + poolCreationFee: + type: string + format: uint64 + description: QueryParamsResponse is response type for the Query/Params RPC method. + side.gmm.QueryPoolResponse: + type: object + properties: + pool: + type: object + properties: + pool_id: + type: string + sender: + type: string + poolParams: + type: object + properties: + type: + type: string + enum: + - WEIGHT + - STABLE + default: WEIGHT + swapFee: + type: string + description: swapFee is ranged from 0 to 10000. + exitFee: + type: string + useOracle: + type: boolean + amp: + type: string + description: Amplifier parameters for stable pool. + assets: + type: object + additionalProperties: + type: object + properties: + token: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + weight: + type: string + decimal: + type: string + total_shares: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. + title: sum of all LP tokens sent out + title: >- + QueryLiquidityPoolResponse is response type for the Query/Liquidity RPC + method diff --git a/go.mod b/go.mod index c186d77e..3494e78a 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ -module sidechain +module github.com/sideprotocol/side -go 1.19 +go 1.20 require ( cosmossdk.io/api v0.3.1 @@ -14,9 +14,9 @@ require ( github.com/grpc-ecosystem/grpc-gateway v1.16.0 github.com/grpc-ecosystem/grpc-gateway/v2 v2.15.2 github.com/spf13/cast v1.5.1 - github.com/spf13/cobra v1.6.1 + github.com/spf13/cobra v1.7.0 github.com/spf13/pflag v1.0.5 - github.com/stretchr/testify v1.8.3 + github.com/stretchr/testify v1.8.4 ) require ( @@ -27,21 +27,22 @@ require ( cloud.google.com/go/storage v1.29.0 // indirect cosmossdk.io/core v0.5.1 // indirect cosmossdk.io/depinject v1.0.0-alpha.3 // indirect - cosmossdk.io/errors v1.0.0-beta.7 // indirect cosmossdk.io/log v1.1.0 // indirect - cosmossdk.io/math v1.0.1 // indirect cosmossdk.io/tools/rosetta v0.2.1 // indirect filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.1 // indirect + github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d // indirect github.com/CosmWasm/wasmvm v1.2.4 // indirect + github.com/Microsoft/go-winio v0.6.1 // indirect github.com/armon/go-metrics v0.4.1 // indirect github.com/aws/aws-sdk-go v1.44.203 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 // indirect github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect + github.com/bufbuild/protocompile v0.6.0 // indirect github.com/cenkalti/backoff/v4 v4.1.3 // indirect github.com/cespare/xxhash v1.1.0 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect @@ -50,7 +51,6 @@ require ( github.com/coinbase/rosetta-sdk-go/types v1.0.0 // indirect github.com/confio/ics23/go v0.9.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect - github.com/cosmos/cosmos-proto v1.0.0-beta.2 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/iavl v0.20.0 // indirect @@ -107,7 +107,7 @@ require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/jmhodges/levigo v1.0.0 // indirect - github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/compress v1.16.7 // indirect github.com/lib/pq v1.10.7 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect github.com/magiconair/properties v1.8.7 // indirect @@ -122,6 +122,7 @@ require ( github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/mtibben/percent v0.2.1 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect + github.com/opencontainers/image-spec v1.1.0-rc4 // indirect github.com/pelletier/go-toml/v2 v2.0.7 // indirect github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect github.com/pkg/errors v0.9.1 // indirect @@ -131,9 +132,11 @@ require ( github.com/prometheus/procfs v0.9.0 // indirect github.com/rakyll/statik v0.1.7 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rs/cors v1.8.3 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect + github.com/rs/cors v1.9.0 // indirect github.com/rs/zerolog v1.29.1 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect + github.com/sirupsen/logrus v1.9.3 // indirect github.com/spf13/afero v1.9.3 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/viper v1.15.0 // indirect @@ -147,21 +150,19 @@ require ( github.com/zondax/ledger-go v0.14.1 // indirect go.etcd.io/bbolt v1.3.7 // indirect go.opencensus.io v0.24.0 // indirect - golang.org/x/crypto v0.8.0 // indirect - golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc // indirect - golang.org/x/net v0.9.0 // indirect + golang.org/x/crypto v0.12.0 // indirect + golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 // indirect + golang.org/x/net v0.14.0 // indirect golang.org/x/oauth2 v0.6.0 // indirect - golang.org/x/sys v0.7.0 // indirect - golang.org/x/term v0.7.0 // indirect - golang.org/x/text v0.9.0 // indirect + golang.org/x/sys v0.11.0 // indirect + golang.org/x/term v0.11.0 // indirect + golang.org/x/text v0.12.0 // indirect + golang.org/x/tools v0.12.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect google.golang.org/api v0.110.0 // indirect google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4 // indirect - google.golang.org/grpc v1.55.0 // indirect - google.golang.org/protobuf v1.30.0 // indirect + google.golang.org/protobuf v1.31.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect nhooyr.io/websocket v1.8.6 // indirect pgregory.net/rapid v0.5.5 // indirect @@ -169,8 +170,14 @@ require ( ) require ( + cosmossdk.io/errors v1.0.0-beta.7 + cosmossdk.io/math v1.0.1 github.com/CosmWasm/wasmd v0.40.1 + github.com/cosmos/cosmos-proto v1.0.0-beta.2 github.com/prometheus/client_golang v1.15.0 + google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4 + google.golang.org/grpc v1.55.0 + gopkg.in/yaml.v2 v2.4.0 ) replace github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 diff --git a/go.sum b/go.sum index bae8ae2e..fc930c52 100644 --- a/go.sum +++ b/go.sum @@ -209,7 +209,8 @@ github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMb github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN7oaIRCjzsZ2dE+yG5k+rsdt3qcwykqK6HVGcKwsw4= github.com/99designs/keyring v1.2.1 h1:tYLp1ULvO7i3fI5vE21ReQuj99QFSs7lGm0xWyJo87o= github.com/99designs/keyring v1.2.1/go.mod h1:fc+wB5KTk9wQ9sDx0kFXB3A0MaeGHM9AwRStKOQ5vOA= -github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= +github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= +github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d h1:nalkkPQcITbvhmL4+C4cKA87NW0tfm3Kl9VXRoPywFg= @@ -220,7 +221,8 @@ github.com/CosmWasm/wasmvm v1.2.4 h1:6OfeZuEcEH/9iqwrg2pkeVtDCkMoj9U6PpKtcrCyVrQ github.com/CosmWasm/wasmvm v1.2.4/go.mod h1:vW/E3h8j9xBQs9bCoijDuawKo9kCtxOaS8N8J7KFtkc= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= -github.com/Microsoft/go-winio v0.6.0 h1:slsWYD/zyx7lCXoZVlvQrj0hPTM1HI4+v1sIda2yDvg= +github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= +github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 h1:TngWCqHvy9oXAN6lEVMRuU21PR1EtLVZJmdB18Gu3Rw= github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= @@ -265,7 +267,8 @@ github.com/btcsuite/btcd/btcec/v2 v2.3.2 h1:5n0X6hX0Zk+6omWcihdYvdAlGf2DfasC0GMf github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= github.com/btcsuite/btcd/btcutil v1.1.2 h1:XLMbX8JQEiwMcYft2EGi8zPUkoa0abKIU6/BJSRsjzQ= github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 h1:q0rUy8C/TYNBQS1+CGKw68tLOFYSNEs0TFnxxnS9+4U= -github.com/bufbuild/protocompile v0.4.0 h1:LbFKd2XowZvQ/kajzguUp2DC9UEIQhIq77fZZlaQsNA= +github.com/bufbuild/protocompile v0.6.0 h1:Uu7WiSQ6Yj9DbkdnOe7U4mNKp58y9WDMKDn28/ZlunY= +github.com/bufbuild/protocompile v0.6.0/go.mod h1:YNP35qEYoYGme7QMtz5SBCoN4kL4g12jTtjuzRNdjpE= github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4= github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= @@ -654,7 +657,6 @@ github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1: github.com/improbable-eng/grpc-web v0.15.0 h1:BN+7z6uNXZ1tQGcNAuaU1YjsLTApzkjt2tzCixLaUPQ= github.com/improbable-eng/grpc-web v0.15.0/go.mod h1:1sy9HKV4Jt9aEs9JSnkWlRJPuPtwNr0l57L4f878wP8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= @@ -687,8 +689,8 @@ github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYs github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.15.11/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM= -github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= -github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I= +github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= @@ -784,7 +786,8 @@ github.com/onsi/gomega v1.20.0 h1:8W0cWlwFkflGPLltQvLRB7ZVD5HuP6ng320w2IS245Q= github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= -github.com/opencontainers/image-spec v1.1.0-rc2 h1:2zx/Stx4Wc5pIPDvIxHXvXtQFW/7XWJGmnM7r3wg034= +github.com/opencontainers/image-spec v1.1.0-rc4 h1:oOxKUJWnFC4YGHCCMNql1x4YaDfYBTS5Y4x/Cgeo1E0= +github.com/opencontainers/image-spec v1.1.0-rc4/go.mod h1:X4pATf0uXsnn3g5aiGIsVnJBR4mxhKzfwmvK/B2NTm8= github.com/opencontainers/runc v1.1.3 h1:vIXrkId+0/J2Ymu2m7VjGvbSlAId9XNRPhn2p4b+d8w= github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492/go.mod h1:Ngi6UdF0k5OKD5t5wlmGhe/EDKPoUM3BXZSSfIuJbis= github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74= @@ -859,10 +862,11 @@ github.com/regen-network/gocuke v0.6.2 h1:pHviZ0kKAq2U2hN2q3smKNxct6hS0mGByFMHGn github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= -github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= -github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= +github.com/rs/cors v1.9.0 h1:l9HGsTsHJcvW14Nk7J9KFz8bzeAWXn3CG6bgt7LsrAE= +github.com/rs/cors v1.9.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= @@ -879,7 +883,8 @@ github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPx github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= @@ -895,8 +900,8 @@ github.com/spf13/cast v1.5.1 h1:R+kOtfhWQE6TVQzY+4D7wJLBgkdVasCEFxSUBYBYIlA= github.com/spf13/cast v1.5.1/go.mod h1:b9PdjNptOpzXr7Rq1q9gJML/2cdGQAo69NKzQ10KN48= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= -github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -924,8 +929,8 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= -github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/subosito/gotenv v1.4.2 h1:X1TuBLAMDFbaTAChgCBLu3DU3UPyELpnF2jjJ2cz/S8= github.com/subosito/gotenv v1.4.2/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70Z7CTTCmYQn2CKbY8j86K7/FAIr141uY= @@ -998,8 +1003,8 @@ golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= -golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= +golang.org/x/crypto v0.12.0 h1:tFM/ta59kqch6LlvYnPa0yx5a83cL2nHflFhYKvv9Yk= +golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -1011,8 +1016,8 @@ golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/exp v0.0.0-20200331195152-e8c3332aa8e5/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= -golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc h1:mCRnTeVUjcrhlRmO0VK8a6k6Rrf6TF9htwo2pJVSjIU= -golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w= +golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 h1:MGwJjxBy0HJshjDNfLsYO8xppfqWlA5ZT9OhtUUhTNw= +golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= @@ -1039,7 +1044,7 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8= +golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1100,8 +1105,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.0.0-20220909164309-bea034e7d591/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.0.0-20221014081412-f15817d10f9b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= -golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= -golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= +golang.org/x/net v0.14.0 h1:BONx9s002vGdD9umnlX1Po8vOZmrgH34qlHcD1MfK14= +golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1234,6 +1239,7 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220624220833-87e55d714810/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -1241,13 +1247,13 @@ golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= -golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM= +golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= -golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= +golang.org/x/term v0.11.0 h1:F9tnn/DA/Im8nCwm+fX+1/eBwi4qFjRT++MhtVC4ZX0= +golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1258,8 +1264,8 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= -golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.12.0 h1:k+n5B8goJNdU7hSvEtMUz3d1Q6D/XW4COJSJR6fN0mc= +golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1326,7 +1332,8 @@ golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM= +golang.org/x/tools v0.12.0 h1:YW6HUoUmYBpwSgyaGaZq1fHjrBjX1rlpZ54T6mu2kss= +golang.org/x/tools v0.12.0/go.mod h1:Sc0INKfu04TlqNoRA1hgpFZbhYXHPr4V5DzpSBTPqQM= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -1565,8 +1572,8 @@ google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQ google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= -google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= -google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= +google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/proto/side/gmm/genesis.proto b/proto/side/gmm/genesis.proto new file mode 100644 index 00000000..c9bdbaae --- /dev/null +++ b/proto/side/gmm/genesis.proto @@ -0,0 +1,12 @@ +syntax = "proto3"; +package side.gmm; + +import "gogoproto/gogo.proto"; +import "side/gmm/params.proto"; + +option go_package = "github.com/sideprotocol/side/x/gmm/types"; + +// GenesisState defines the gmm module's genesis state. +message GenesisState { + Params params = 1 [(gogoproto.nullable) = false]; +} diff --git a/proto/side/gmm/params.proto b/proto/side/gmm/params.proto new file mode 100644 index 00000000..5691ed5c --- /dev/null +++ b/proto/side/gmm/params.proto @@ -0,0 +1,14 @@ +syntax = "proto3"; +package side.gmm; + +import "gogoproto/gogo.proto"; + +option go_package = "github.com/sideprotocol/side/x/gmm/types"; + +// Params defines the parameters for the module. +message Params { + option (gogoproto.goproto_stringer) = false; + uint64 poolCreationFee = 1; +} + + diff --git a/proto/side/gmm/pool.proto b/proto/side/gmm/pool.proto new file mode 100644 index 00000000..fa260084 --- /dev/null +++ b/proto/side/gmm/pool.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; +package side.gmm; + +option go_package = "github.com/sideprotocol/side/x/gmm/types"; +import "side/gmm/pool_params.proto"; +import "side/gmm/pool_asset.proto"; +import "gogoproto/gogo.proto"; +import "cosmos/base/v1beta1/coin.proto"; +import "cosmos_proto/cosmos.proto"; + +message Pool { + option (cosmos_proto.implements_interface) = "PoolI"; + string pool_id = 1; + string sender = 2; + PoolParams poolParams = 3 [(gogoproto.nullable) = false]; + map assets = 4 [(gogoproto.nullable) = false]; + // sum of all LP tokens sent out + cosmos.base.v1beta1.Coin total_shares = 5 [ + (gogoproto.moretags) = "yaml:\"total_shares\"", + (gogoproto.nullable) = false + ]; +} + diff --git a/proto/side/gmm/pool_asset.proto b/proto/side/gmm/pool_asset.proto new file mode 100644 index 00000000..be4bfb5c --- /dev/null +++ b/proto/side/gmm/pool_asset.proto @@ -0,0 +1,17 @@ +syntax = "proto3"; +package side.gmm; +option go_package = "github.com/sideprotocol/side/x/gmm/types"; + +import "gogoproto/gogo.proto"; +import "cosmos/base/v1beta1/coin.proto"; + +message PoolAsset { + cosmos.base.v1beta1.Coin token = 1 [(gogoproto.nullable) = false]; + string weight = 2 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int" + ]; + string decimal = 3 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", + (gogoproto.nullable) = false + ]; +} diff --git a/proto/side/gmm/pool_params.proto b/proto/side/gmm/pool_params.proto new file mode 100644 index 00000000..126505a3 --- /dev/null +++ b/proto/side/gmm/pool_params.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; +package side.gmm; + +import "gogoproto/gogo.proto"; + +option go_package = "github.com/sideprotocol/side/x/gmm/types"; + +enum PoolType { + WEIGHT = 0; + STABLE = 1; +} + +message PoolParams { + PoolType type = 1; + // swapFee is ranged from 0 to 10000. + string swapFee = 2 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + string exitFee = 3 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + bool useOracle = 4; + + // Amplifier parameters for stable pool. + string amp = 5 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int" + ]; +} diff --git a/proto/side/gmm/query.proto b/proto/side/gmm/query.proto new file mode 100644 index 00000000..aee74d19 --- /dev/null +++ b/proto/side/gmm/query.proto @@ -0,0 +1,63 @@ +syntax = "proto3"; +package side.gmm; + +import "gogoproto/gogo.proto"; +import "google/api/annotations.proto"; +import "cosmos/base/query/v1beta1/pagination.proto"; +import "side/gmm/params.proto"; +import "side/gmm/pool.proto"; + +option go_package = "github.com/sideprotocol/side/x/gmm/types"; + +// Query defines the gRPC querier service. +service Query { + // Parameters queries the parameters of the module. + rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { + option (google.api.http).get = "/sideprotocol/side/gmm/params"; + } + + rpc Pool (QueryPoolRequest) returns (QueryPoolResponse) { + option (google.api.http).get = "/sideprotocol/side/gmm/{pool_id}"; + } + + rpc Pools (QueryPoolsRequest) returns (QueryPoolsResponse) { + option (google.api.http).get = "/sideprotocol/side/gmm/all"; + } + + rpc MyPools (QueryPoolsRequest) returns (QueryPoolsResponse) { + option (google.api.http).get = "/sideprotocol/side/gmm/{creator}"; + } +} + +// 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. + Params params = 1 [(gogoproto.nullable) = false]; +} + +// QueryLiquidityPoolRequest is request type for the Query/Liquidity RPC method. +message QueryPoolRequest { + string pool_id = 1; +} + +// QueryLiquidityPoolResponse is response type for the Query/Liquidity RPC method +message QueryPoolResponse { + Pool pool = 1; +} + + +// QueryPoolsRequest is request type for the Query/Liquidities RPC method. +message QueryPoolsRequest { + string creator = 1; + cosmos.base.query.v1beta1.PageRequest pagination = 2; +} + +// QueryPoolsResponse is response type for the Query/Pools RPC method +message QueryPoolsResponse { + repeated Pool pools = 1 [(gogoproto.nullable) = false]; + cosmos.base.query.v1beta1.PageResponse pagination = 2; +} + diff --git a/proto/side/gmm/tx.proto b/proto/side/gmm/tx.proto new file mode 100644 index 00000000..8eed5eae --- /dev/null +++ b/proto/side/gmm/tx.proto @@ -0,0 +1,67 @@ +syntax = "proto3"; + +package side.gmm; + +option go_package = "github.com/sideprotocol/side/x/gmm/types"; + +import "gogoproto/gogo.proto"; +import "cosmos/base/v1beta1/coin.proto"; +import "side/gmm/pool_params.proto"; +import "side/gmm/pool_asset.proto"; + +// Msg defines the Msg service. +service Msg { + rpc CreatePool (MsgCreatePool ) returns (MsgCreatePoolResponse ); + rpc AddLiquidity (MsgAddLiquidity) returns (MsgAddLiquidityResponse); + rpc Withdraw (MsgWithdraw ) returns (MsgWithdrawResponse ); + rpc Swap (MsgSwap ) returns (MsgSwapResponse ); + +} +message MsgCreatePool { + string sender = 1; + PoolParams params = 2; + repeated PoolAsset liquidity = 3 [(gogoproto.nullable) = false]; +} + +message MsgCreatePoolResponse { + string pool_id = 1; +} + +message MsgAddLiquidity { + string sender = 1; + string pool_id = 2; + repeated cosmos.base.v1beta1.Coin liquidity = 3 [(gogoproto.nullable) = false]; +} + +message MsgAddLiquidityResponse { + string pool_id = 1; +} + +message MsgWithdraw { + string sender = 1; + string receiver = 2; + string pool_id = 3; + cosmos.base.v1beta1.Coin share = 4 [(gogoproto.nullable) = false]; +} + +message MsgWithdrawResponse { + cosmos.base.v1beta1.Coin share = 1 [(gogoproto.nullable) = false]; +} + +message MsgSwap { + string sender = 1; + string pool_id = 2; + cosmos.base.v1beta1.Coin tokenIn = 3 [(gogoproto.nullable) = false]; + cosmos.base.v1beta1.Coin tokenOut = 4 [(gogoproto.nullable) = false]; + string slippage = 5 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", + (gogoproto.nullable) = false + ]; +} + +message MsgSwapResponse { + string pool_id = 1; + cosmos.base.v1beta1.Coin tokenIn = 2 [(gogoproto.nullable) = false]; + +} + diff --git a/testutil/keeper/gmm.go b/testutil/keeper/gmm.go new file mode 100644 index 00000000..23e7b67c --- /dev/null +++ b/testutil/keeper/gmm.go @@ -0,0 +1,54 @@ +package keeper + +import ( + "testing" + + tmdb "github.com/cometbft/cometbft-db" + "github.com/cometbft/cometbft/libs/log" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/store" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + typesparams "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/sideprotocol/side/x/gmm/keeper" + "github.com/sideprotocol/side/x/gmm/types" + "github.com/stretchr/testify/require" +) + +func GmmKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) { + storeKey := sdk.NewKVStoreKey(types.StoreKey) + memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey) + + db := tmdb.NewMemDB() + stateStore := store.NewCommitMultiStore(db) + stateStore.MountStoreWithDB(storeKey, storetypes.StoreTypeIAVL, db) + stateStore.MountStoreWithDB(memStoreKey, storetypes.StoreTypeMemory, nil) + require.NoError(t, stateStore.LoadLatestVersion()) + + registry := codectypes.NewInterfaceRegistry() + cdc := codec.NewProtoCodec(registry) + + paramsSubspace := typesparams.NewSubspace(cdc, + types.Amino, + storeKey, + memStoreKey, + "GmmParams", + ) + k := keeper.NewKeeper( + cdc, + storeKey, + memStoreKey, + paramsSubspace, + nil, + nil, + ) + + ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger()) + + // Initialize params + k.SetParams(ctx, types.DefaultParams()) + + return k, ctx +} diff --git a/testutil/network/network.go b/testutil/network/network.go index 968f7220..832c52fb 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -18,7 +18,7 @@ import ( authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/stretchr/testify/require" - "sidechain/app" + "github.com/sideprotocol/side/app" ) type ( diff --git a/x/gmm/client/cli/query.go b/x/gmm/client/cli/query.go new file mode 100644 index 00000000..8c9001a1 --- /dev/null +++ b/x/gmm/client/cli/query.go @@ -0,0 +1,32 @@ +package cli + +import ( + "fmt" + // "strings" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" + // "github.com/cosmos/cosmos-sdk/client/flags" + // sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sideprotocol/side/x/gmm/types" +) + +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd(queryRoute string) *cobra.Command { + // Group gmm queries under a subcommand + _ = queryRoute + cmd := &cobra.Command{ + Use: types.ModuleName, + Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand(CmdQueryParams()) + // this line is used by starport scaffolding # 1 + + return cmd +} diff --git a/x/gmm/client/cli/query_params.go b/x/gmm/client/cli/query_params.go new file mode 100644 index 00000000..d41edf89 --- /dev/null +++ b/x/gmm/client/cli/query_params.go @@ -0,0 +1,36 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/spf13/cobra" + + "github.com/sideprotocol/side/x/gmm/types" +) + +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, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.Params(cmd.Context(), &types.QueryParamsRequest{}) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/gmm/client/cli/tx.go b/x/gmm/client/cli/tx.go new file mode 100644 index 00000000..986f806f --- /dev/null +++ b/x/gmm/client/cli/tx.go @@ -0,0 +1,33 @@ +package cli + +import ( + "fmt" + "time" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" + // "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/sideprotocol/side/x/gmm/types" +) + +var DefaultRelativePacketTimeoutTimestamp = uint64((time.Duration(10) * time.Minute).Nanoseconds()) + +// 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(CmdAddLiquidity()) + cmd.AddCommand(CmdCreatePool()) + cmd.AddCommand(CmdWithdraw()) + cmd.AddCommand(CmdSwap()) + // this line is used by starport scaffolding # 1 + + return cmd +} diff --git a/x/gmm/client/cli/tx_add_liquidity.go b/x/gmm/client/cli/tx_add_liquidity.go new file mode 100644 index 00000000..90dc674a --- /dev/null +++ b/x/gmm/client/cli/tx_add_liquidity.go @@ -0,0 +1,47 @@ +package cli + +import ( + "strconv" + + "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/sideprotocol/side/x/gmm/types" + "github.com/spf13/cobra" +) + +var _ = strconv.Itoa(0) + +func CmdAddLiquidity() *cobra.Command { + cmd := &cobra.Command{ + Use: "add-liquidity [pool-id] [liquidity]", + Short: "Broadcast message add-liquidity", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) (err error) { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + liquidity, err := sdk.ParseCoinsNormalized(args[1]) + if err != nil { + return err + } + + msg := types.NewMsgAddLiquidity( + clientCtx.GetFromAddress().String(), + args[0], + liquidity, + ) + if err := msg.ValidateBasic(); err != nil { + return err + } + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} diff --git a/x/gmm/client/cli/tx_create_pool.go b/x/gmm/client/cli/tx_create_pool.go new file mode 100644 index 00000000..ab66a174 --- /dev/null +++ b/x/gmm/client/cli/tx_create_pool.go @@ -0,0 +1,129 @@ +package cli + +import ( + "fmt" + "strconv" + "strings" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/x/gmm/types" + "github.com/spf13/cobra" +) + +var _ = strconv.Itoa(0) + +func CmdCreatePool() *cobra.Command { + cmd := &cobra.Command{ + Use: "create-pool [tokens] [decimals] [weights] [swap-fee] ", + Short: "Broadcast message create-pool", + Args: cobra.ExactArgs(4), + RunE: func(cmd *cobra.Command, args []string) (err error) { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + tokens, err := sdk.ParseCoinsNormalized(args[0]) + if err != nil { + return err + } + + weights, err := parseWeights(args[2]) + if err != nil { + return err + } + + decimals, err := parseDecimals(args[3]) + if err != nil { + return err + } + + swapFee, err := strconv.Atoi(args[4]) + if err != nil { + return err + } + + // swapFee is ranged from 0 to 10000. + if swapFee > 10000 { + return fmt.Errorf("swap fee must be less than 10000") + } + + liquidity := []types.PoolAsset{} + for i := 0; i < len(weights); i++ { + if len(weights) != len(decimals) { + return fmt.Errorf("weights and decimals must have the same length") + } + if len(tokens) != len(decimals) { + return fmt.Errorf("liquidity and weights must have the same length") + } + weight := sdk.NewInt(int64(weights[i])) + liquidity = append(liquidity, types.PoolAsset{ + Token: tokens[i], + Weight: &weight, + Decimal: sdk.NewInt(int64(decimals[i])), + }) + } + + msg := types.NewMsgCreatePool( + clientCtx.GetFromAddress().String(), + types.PoolParams{ + SwapFee: sdk.NewDec(int64(swapFee)), + }, + liquidity, + ) + if err := msg.ValidateBasic(); err != nil { + return err + } + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} + +func parseDecimals(decimalsStr string) ([]uint32, error) { + decimalList := strings.Split(decimalsStr, ",") + decimals := make([]uint32, 0, len(decimalList)) + + for _, decimalStr := range decimalList { + decimal, err := strconv.Atoi(decimalStr) + if err != nil { + return nil, fmt.Errorf("invalid decimal %s", decimalStr) + } + decimals = append(decimals, uint32(decimal)) + } + + if len(decimals) != 2 { + return nil, fmt.Errorf("invalid decimals length %v", decimals) + } + + return decimals, nil +} + +func parseWeights(weightsStr string) ([]uint32, error) { + weights := strings.Split(weightsStr, ",") + if len(weights) != 2 { + return nil, fmt.Errorf("invalid weights length %v", weights) + } + + totalWeight := 0 + weightsAsInt := []uint32{} + for _, weight := range weights { + weightAsInt, err := strconv.Atoi(weight) + if err != nil || weightAsInt <= 0 { + return nil, fmt.Errorf("can't parse weight value %v", err) + } + totalWeight += weightAsInt + weightsAsInt = append(weightsAsInt, uint32(weightAsInt)) + } + + if totalWeight != 100 { + return nil, fmt.Errorf("weight sum has to be equal to 100 %v", totalWeight) + } + return weightsAsInt, nil +} diff --git a/x/gmm/client/cli/tx_swap.go b/x/gmm/client/cli/tx_swap.go new file mode 100644 index 00000000..467a0b2a --- /dev/null +++ b/x/gmm/client/cli/tx_swap.go @@ -0,0 +1,51 @@ +package cli + +import ( + "strconv" + + "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/sideprotocol/side/x/gmm/types" + "github.com/spf13/cobra" +) + +var _ = strconv.Itoa(0) + +func CmdSwap() *cobra.Command { + cmd := &cobra.Command{ + Use: "swap [pool_id] [tokenIn] [tokenOut]", + Short: "Broadcast message swap", + Args: cobra.ExactArgs(0), + RunE: func(cmd *cobra.Command, args []string) (err error) { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + tokenIn, err := sdk.ParseCoinNormalized(args[1]) + if err != nil { + return err + } + + tokenOut, err := sdk.ParseCoinNormalized(args[2]) + if err != nil { + return err + } + msg := types.NewMsgSwap( + clientCtx.GetFromAddress().String(), + args[0], + tokenIn, + tokenOut, + ) + if err := msg.ValidateBasic(); err != nil { + return err + } + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} diff --git a/x/gmm/client/cli/tx_withdraw.go b/x/gmm/client/cli/tx_withdraw.go new file mode 100644 index 00000000..7b726147 --- /dev/null +++ b/x/gmm/client/cli/tx_withdraw.go @@ -0,0 +1,48 @@ +package cli + +import ( + "strconv" + + "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/sideprotocol/side/x/gmm/types" + "github.com/spf13/cobra" +) + +var _ = strconv.Itoa(0) + +func CmdWithdraw() *cobra.Command { + cmd := &cobra.Command{ + Use: "withdraw [pool_id] [receiver] [share]", + Short: "Broadcast message withdraw", + Args: cobra.ExactArgs(3), + RunE: func(cmd *cobra.Command, args []string) (err error) { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + share, err := sdk.ParseCoinNormalized(args[1]) + if err != nil { + return err + } + + msg := types.NewMsgWithdraw( + clientCtx.GetFromAddress().String(), + args[0], + args[1], + share, + ) + if err := msg.ValidateBasic(); err != nil { + return err + } + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} diff --git a/x/gmm/genesis.go b/x/gmm/genesis.go new file mode 100644 index 00000000..eb906c47 --- /dev/null +++ b/x/gmm/genesis.go @@ -0,0 +1,23 @@ +package gmm + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/x/gmm/keeper" + "github.com/sideprotocol/side/x/gmm/types" +) + +// InitGenesis initializes the module's state from a provided genesis state. +func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) { + // this line is used by starport scaffolding # genesis/module/init + k.SetParams(ctx, genState.Params) +} + +// ExportGenesis returns the module's exported genesis +func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { + genesis := types.DefaultGenesis() + genesis.Params = k.GetParams(ctx) + + // this line is used by starport scaffolding # genesis/module/export + + return genesis +} diff --git a/x/gmm/genesis_test.go b/x/gmm/genesis_test.go new file mode 100644 index 00000000..a233d9c7 --- /dev/null +++ b/x/gmm/genesis_test.go @@ -0,0 +1,29 @@ +package gmm_test + +import ( + "testing" + + keepertest "github.com/sideprotocol/side/testutil/keeper" + "github.com/sideprotocol/side/testutil/nullify" + "github.com/sideprotocol/side/x/gmm" + "github.com/sideprotocol/side/x/gmm/types" + "github.com/stretchr/testify/require" +) + +func TestGenesis(t *testing.T) { + genesisState := types.GenesisState{ + Params: types.DefaultParams(), + + // this line is used by starport scaffolding # genesis/test/state + } + + k, ctx := keepertest.GmmKeeper(t) + gmm.InitGenesis(ctx, *k, genesisState) + got := gmm.ExportGenesis(ctx, *k) + require.NotNil(t, got) + + nullify.Fill(&genesisState) + nullify.Fill(got) + + // this line is used by starport scaffolding # genesis/test/assert +} diff --git a/x/gmm/keeper/bank.go b/x/gmm/keeper/bank.go new file mode 100644 index 00000000..c6dbcce1 --- /dev/null +++ b/x/gmm/keeper/bank.go @@ -0,0 +1,56 @@ +package keeper + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/x/gmm/types" +) + +func (k Keeper) LockTokens(ctx sdk.Context, poolID string, sender sdk.AccAddress, tokens sdk.Coins) error { + escrow := types.GetEscrowAddress(poolID) + // escrow source tokens. It fails if balance insufficient + return k.bankKeeper.SendCoins( + ctx, sender, escrow, tokens, + ) +} + +func (k Keeper) UnLockTokens(ctx sdk.Context, poolID string, receiver sdk.AccAddress, tokens sdk.Coins) error { + escrow := types.GetEscrowAddress(poolID) + // escrow source tokens. It fails if balance insufficient + return k.bankKeeper.SendCoins( + ctx, escrow, receiver, sdk.NewCoins(tokens...), + ) +} + +func (k Keeper) BurnTokens(ctx sdk.Context, sender sdk.AccAddress, tokens sdk.Coin) error { + // transfer the coins to the module account and burn them + if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, sdk.NewCoins(tokens)); err != nil { + return err + } + if err := k.bankKeeper.BurnCoins( + ctx, types.ModuleName, sdk.NewCoins(tokens), + ); err != nil { + // NOTE: should not happen as the module account was + // retrieved on the step above and it has enough balance + // to burn. + panic(fmt.Sprintf("cannot burn coins after a successful send to a module account: %v", err)) + } + return nil +} + +func (k Keeper) MintTokens(ctx sdk.Context, receiver sdk.AccAddress, tokens sdk.Coin) error { + // mint new tokens if the source of the transfer is the same chain + if err := k.bankKeeper.MintCoins( + ctx, types.ModuleName, sdk.NewCoins(tokens), + ); err != nil { + return err + } + // send to receiver + if err := k.bankKeeper.SendCoinsFromModuleToAccount( + ctx, types.ModuleName, receiver, sdk.NewCoins(tokens), + ); err != nil { + panic(fmt.Sprintf("unable to send coins from module to account despite previously minting coins to module account: %v", err)) + } + return nil +} diff --git a/x/gmm/keeper/event.go b/x/gmm/keeper/event.go new file mode 100644 index 00000000..31e1b0db --- /dev/null +++ b/x/gmm/keeper/event.go @@ -0,0 +1,37 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/x/gmm/types" +) + +func (k Keeper) EmitEvent(ctx sdk.Context, + action, poolID, sender string, attr ...sdk.Attribute, +) { + headerAttr := []sdk.Attribute{ + { + Key: types.AttributeKeyAction, + Value: action, + }, + { + Key: types.AttributeKeyPoolID, + Value: poolID, + }, + { + Key: types.AttributeKeyName, + Value: types.ModuleName, + }, + { + Key: types.AttributeKeyMsgSender, + Value: sender, + }, + } + + headerAttr = append(headerAttr, attr...) + ctx.EventManager().EmitEvent( + sdk.NewEvent( + types.ModuleName, + headerAttr..., + ), + ) +} diff --git a/x/gmm/keeper/keeper.go b/x/gmm/keeper/keeper.go new file mode 100644 index 00000000..b1a93c13 --- /dev/null +++ b/x/gmm/keeper/keeper.go @@ -0,0 +1,51 @@ +package keeper + +import ( + "fmt" + + "github.com/cometbft/cometbft/libs/log" + "github.com/cosmos/cosmos-sdk/codec" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + + "github.com/sideprotocol/side/x/gmm/types" +) + +type ( + Keeper struct { + cdc codec.BinaryCodec + storeKey storetypes.StoreKey + memKey storetypes.StoreKey + paramstore paramtypes.Subspace + accountKeeper types.AccountKeeper + bankKeeper types.BankKeeper + } +) + +func NewKeeper( + cdc codec.BinaryCodec, + storeKey, + memKey storetypes.StoreKey, + ps paramtypes.Subspace, + accountKeeper types.AccountKeeper, + bankKeeper types.BankKeeper, +) *Keeper { + // set KeyTable if it has not already been set + if !ps.HasKeyTable() { + ps = ps.WithKeyTable(types.ParamKeyTable()) + } + + return &Keeper{ + cdc: cdc, + storeKey: storeKey, + memKey: memKey, + paramstore: ps, + accountKeeper: accountKeeper, + bankKeeper: bankKeeper, + } +} + +func (k Keeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +} diff --git a/x/gmm/keeper/keeper_test.go b/x/gmm/keeper/keeper_test.go new file mode 100644 index 00000000..6c7b013d --- /dev/null +++ b/x/gmm/keeper/keeper_test.go @@ -0,0 +1,180 @@ +package keeper_test + +import ( + "testing" + "time" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + simapp "github.com/sideprotocol/side/app" + "github.com/sideprotocol/side/x/gmm/keeper" + "github.com/sideprotocol/side/x/gmm/types" + "github.com/stretchr/testify/suite" + + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +const ( + initChain = true +) + +const ( + balAlice = 500000000000 + balBob = 200000000000 + balCarol = 100000000000 +) + +type KeeperTestSuite struct { + suite.Suite + + legacyAmino *codec.LegacyAmino + ctx sdk.Context + app *simapp.App + msgServer types.MsgServer + queryClient types.QueryClient +} + +var gmmModuleAddress string + +func (suite *KeeperTestSuite) SetupTest() { + // app := simapp.InitSideTestApp(initChain) + app := simapp.Setup(suite.T()) + ctx := app.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) + + app.AccountKeeper.SetParams(ctx, authtypes.DefaultParams()) + app.BankKeeper.SetParams(ctx, banktypes.DefaultParams()) + stakingParams := stakingtypes.DefaultParams() + stakingParams.MinCommissionRate = sdk.OneDec() + app.StakingKeeper.SetParams(ctx, stakingtypes.DefaultParams()) + + gmmModuleAddress = app.AccountKeeper.GetModuleAddress(types.ModuleName).String() + + queryHelper := baseapp.NewQueryServerTestHelper(ctx, app.InterfaceRegistry()) + types.RegisterQueryServer(queryHelper, app.GmmKeeper) + queryClient := types.NewQueryClient(queryHelper) + + suite.legacyAmino = app.LegacyAmino() + suite.ctx = ctx + suite.app = app + suite.queryClient = queryClient + suite.msgServer = keeper.NewMsgServerImpl(app.GmmKeeper) + + // Set Coins + suite.setupSuiteWithBalances() +} + +func TestKeeperSuite(t *testing.T) { + suite.Run(t, new(KeeperTestSuite)) +} + +func makeBalance(address string, balance int64, denom string) banktypes.Balance { + return banktypes.Balance{ + Address: address, + Coins: sdk.Coins{ + sdk.Coin{ + Denom: denom, + Amount: sdk.NewInt(balance), + }, + }, + } +} + +func getBankGenesis() *banktypes.GenesisState { + coins := []banktypes.Balance{ + makeBalance(types.Alice, balAlice, simapp.DefaultBondDenom), + makeBalance(types.Alice, balAlice, simapp.USDC), + makeBalance(types.Alice, balAlice, simapp.WBTC), + makeBalance(types.Alice, balAlice, simapp.WDAI), + makeBalance(types.Alice, balAlice, simapp.WUSDT), + + makeBalance(types.Bob, balBob, simapp.DefaultBondDenom), + makeBalance(types.Bob, balBob, simapp.USDC), + makeBalance(types.Bob, balAlice, simapp.WBTC), + makeBalance(types.Bob, balAlice, simapp.WDAI), + makeBalance(types.Bob, balAlice, simapp.WUSDT), + + makeBalance(types.Carol, balCarol, simapp.DefaultBondDenom), + makeBalance(types.Carol, balCarol, simapp.USDC), + makeBalance(types.Carol, balAlice, simapp.WBTC), + makeBalance(types.Carol, balAlice, simapp.WDAI), + makeBalance(types.Carol, balAlice, simapp.WUSDT), + } + + params := banktypes.DefaultParams() + params.DefaultSendEnabled = true + state := banktypes.NewGenesisState( + params, + coins, + addAll(coins), + []banktypes.Metadata{}, []banktypes.SendEnabled{ + {Denom: simapp.DefaultBondDenom, Enabled: true}, + {Denom: simapp.USDC, Enabled: true}, + }) + + return state +} + +func addAll(balances []banktypes.Balance) sdk.Coins { + total := sdk.NewCoins() + for _, balance := range balances { + total = total.Add(balance.Coins...) + } + return total +} + +func (suite *KeeperTestSuite) SetupStableCoinPrices() { + // prices set for USDT and USDC + // provider := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()) + // suite.app.OracleKeeper.SetAssetInfo(suite.ctx, oracletypes.AssetInfo{ + // Denom: "uusdc", + // Display: "USDC", + // Decimal: 6, + // }) + // suite.app.OracleKeeper.SetAssetInfo(suite.ctx, oracletypes.AssetInfo{ + // Denom: "uusdt", + // Display: "USDT", + // Decimal: 6, + // }) + // suite.app.OracleKeeper.SetPrice(suite.ctx, oracletypes.Price{ + // Asset: "USDC", + // Price: sdk.NewDec(1), + // Source: "elys", + // Provider: provider.String(), + // Timestamp: uint64(suite.ctx.BlockTime().Unix()), + // }) + // suite.app.OracleKeeper.SetPrice(suite.ctx, oracletypes.Price{ + // Asset: "USDT", + // Price: sdk.NewDec(1), + // Source: "elys", + // Provider: provider.String(), + // Timestamp: uint64(suite.ctx.BlockTime().Unix()), + // }) +} + +// func getStakeGenesis() *stakingtypes.GenesisState { +// state := stakingtypes.DefaultGenesisState() +// state.Params.BondDenom = simapp.DefaultBondDenom +// state.Params.MinCommissionRate = sdk.OneDec() +// return state +// } + +func (suite *KeeperTestSuite) setupSuiteWithBalances() { + // suite.app.StakingKeeper.InitGenesis(suite.ctx, getStakeGenesis()) + suite.app.BankKeeper.InitGenesis(suite.ctx, getBankGenesis()) +} + +// func (suite *KeeperTestSuite) RequireBankBalance(expected int, atAddress string) { +// suite.RequireBankBalanceWithDenom(expected, "aside", atAddress) +// } + +// func (suite *KeeperTestSuite) RequireBankBalanceWithDenom(expected int, denom string, atAddress string) { +// sdkAdd, err := sdk.AccAddressFromBech32(atAddress) +// suite.Require().Nil(err, "Failed to parse address: %s", atAddress) +// suite.Require().Equal( +// int64(expected), +// suite.app.BankKeeper.GetBalance(suite.ctx, sdkAdd, denom).Amount.Int64()) +// } diff --git a/x/gmm/keeper/msg_server.go b/x/gmm/keeper/msg_server.go new file mode 100644 index 00000000..0cf59ea0 --- /dev/null +++ b/x/gmm/keeper/msg_server.go @@ -0,0 +1,17 @@ +package keeper + +import ( + "github.com/sideprotocol/side/x/gmm/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{} diff --git a/x/gmm/keeper/msg_server_add_liquidity.go b/x/gmm/keeper/msg_server_add_liquidity.go new file mode 100644 index 00000000..59e22452 --- /dev/null +++ b/x/gmm/keeper/msg_server_add_liquidity.go @@ -0,0 +1,53 @@ +package keeper + +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/x/gmm/types" +) + +func (k msgServer) AddLiquidity(goCtx context.Context, msg *types.MsgAddLiquidity) (*types.MsgAddLiquidityResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + if err := msg.ValidateBasic(); err != nil { + return nil, err + } + + pool, found := k.GetPool(ctx, msg.PoolId) + if !found { + return nil, types.ErrNotFoundAssetInPool + } + + poolCreator := sdk.MustAccAddressFromBech32(msg.Sender) + + // Move asset from sender to module account + if err := k.LockTokens(ctx, msg.PoolId, poolCreator, msg.Liquidity); err != nil { + return nil, err + } + + // Mint share to creator + share, err := pool.EstimateShare(msg.Liquidity) + if err != nil { + return nil, err + } + if err := k.MintPoolShareToAccount(ctx, poolCreator, share); err != nil { + return nil, err + } + // Update pool status + if err := pool.IncreaseLiquidity(msg.Liquidity); err != nil { + return nil, err + } + pool.IncreaseShare(share.Amount) + + // Save update information + k.SetPool(ctx, pool) + + // Emit events + k.EmitEvent( + ctx, types.EventValueActionDeposit, + msg.PoolId, + msg.Sender, + types.GetEventAttrOfAsset(msg.Liquidity)..., + ) + return &types.MsgAddLiquidityResponse{}, nil +} diff --git a/x/gmm/keeper/msg_server_add_liquidity_test.go b/x/gmm/keeper/msg_server_add_liquidity_test.go new file mode 100644 index 00000000..8ee81af1 --- /dev/null +++ b/x/gmm/keeper/msg_server_add_liquidity_test.go @@ -0,0 +1,136 @@ +package keeper_test + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + simapp "github.com/sideprotocol/side/app" + "github.com/sideprotocol/side/testutil/sample" + "github.com/sideprotocol/side/x/gmm/types" +) + +func (suite *KeeperTestSuite) TestMsgAddLiquidity() { + suite.SetupTest() + + tests := []struct { + name string + poolType types.PoolType + mutator func(*types.MsgAddLiquidity, string) + }{ + { + "add liquidity to weight pool", + types.PoolType_WEIGHT, + func(msg *types.MsgAddLiquidity, poolID string) { + msg.Liquidity = []sdk.Coin{ + sdk.NewCoin(simapp.DefaultBondDenom, sdk.NewInt(100)), + } + }, + }, + { + "add liquidity to stable pool", + types.PoolType_STABLE, + func(msg *types.MsgAddLiquidity, poolID string) { + msg.Liquidity = []sdk.Coin{ + sdk.NewCoin(simapp.WDAI, sdk.NewInt(100)), + sdk.NewCoin(simapp.WUSDT, sdk.NewInt(100)), + } + }, + }, + } + + for _, tc := range tests { + suite.Run(tc.name, func() { + // Create a new pool of the specific type + poolID := suite.CreateNewPool(tc.poolType) + + // Initialize the MsgAddLiquidity + msg := types.MsgAddLiquidity{ + Sender: types.Carol, + PoolId: poolID, + } + + // Use the mutator to set the liquidity for the specific pool type + tc.mutator(&msg, poolID) + + ctx := sdk.WrapSDKContext(suite.ctx) + res, err := suite.msgServer.AddLiquidity(ctx, &msg) + + suite.Require().NoError(err) + suite.Require().NotNil(res) + }) + } +} + +func (suite *KeeperTestSuite) TestMsgAddLiquidityFail() { + var msg *types.MsgAddLiquidity + // Create a new pool + poolID := suite.CreateNewPool(types.PoolType_WEIGHT) + + testCases := []struct { + name string + mallet func(msg *types.MsgAddLiquidity, poolID string) + }{ + { + "invalid sender", + func(msg *types.MsgAddLiquidity, poolID string) {}, + }, + { + "invalid poolID", + func(msg *types.MsgAddLiquidity, poolID string) { + msg = &types.MsgAddLiquidity{ + Sender: sample.AccAddress(), + PoolId: "", + Liquidity: []sdk.Coin{ + sdk.NewCoin( + simapp.DefaultBondDenom, + sdk.NewInt(100), + ), + }, + } + }, + }, + { + "not enough funds", + func(msg *types.MsgAddLiquidity, poolID string) { + msg = &types.MsgAddLiquidity{ + Sender: sample.AccAddress(), + PoolId: poolID, + Liquidity: []sdk.Coin{ + sdk.NewCoin( + simapp.DefaultBondDenom, + sdk.NewInt(100), + ), + }, + } + }, + }, + { + "invalid asset type", + func(msg *types.MsgAddLiquidity, poolID string) { + msg.Liquidity = []sdk.Coin{ + sdk.NewCoin("INVALID_ASSET_TYPE", sdk.NewInt(100)), + } + }, + }, + { + "zero liquidity", + func(msg *types.MsgAddLiquidity, poolID string) { + msg.Liquidity = []sdk.Coin{ + sdk.NewCoin(simapp.DefaultBondDenom, sdk.NewInt(0)), + } + }, + }, + } + + for _, tc := range testCases { + + msg = types.NewMsgAddLiquidity( + "", + poolID, + []sdk.Coin{}, + ) + tc.mallet(msg, poolID) + + res, err := suite.msgServer.AddLiquidity(sdk.WrapSDKContext(suite.ctx), msg) + suite.Require().Error(err) + suite.Require().Nil(res) + } +} diff --git a/x/gmm/keeper/msg_server_create_pool.go b/x/gmm/keeper/msg_server_create_pool.go new file mode 100644 index 00000000..7eecfe2a --- /dev/null +++ b/x/gmm/keeper/msg_server_create_pool.go @@ -0,0 +1,35 @@ +package keeper + +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/x/gmm/types" +) + +func (k msgServer) CreatePool(goCtx context.Context, msg *types.MsgCreatePool) (*types.MsgCreatePoolResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + if err := msg.ValidateBasic(); err != nil { + return nil, err + } + + // Initialize pool + pooID, err := k.initializePool(ctx, msg) + if err != nil { + return nil, err + } + + // Emit events + k.EmitEvent( + ctx, types.EventValueActionCreatePool, *pooID, + msg.Sender, + sdk.Attribute{ + Key: types.AttributeKeyPoolCreator, + Value: msg.Sender, + }, + ) + + return &types.MsgCreatePoolResponse{ + PoolId: *pooID, + }, nil +} diff --git a/x/gmm/keeper/msg_server_create_pool_test.go b/x/gmm/keeper/msg_server_create_pool_test.go new file mode 100644 index 00000000..d8fa7a7d --- /dev/null +++ b/x/gmm/keeper/msg_server_create_pool_test.go @@ -0,0 +1,249 @@ +package keeper_test + +import ( + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" + simapp "github.com/sideprotocol/side/app" + "github.com/sideprotocol/side/testutil/sample" + "github.com/sideprotocol/side/x/gmm/types" +) + +func (suite *KeeperTestSuite) TestMsgCreatePool() { + suite.SetupTest() + + tests := []struct { + name string + mutator func(msg *types.MsgCreatePool) + }{ + { + "weight pool", + func(msg *types.MsgCreatePool) { + msg.Params.Type = types.PoolType_WEIGHT + }, + }, + { + "stable pool", + func(msg *types.MsgCreatePool) { + amp := sdk.NewInt(100) + msg.Params.Type = types.PoolType_STABLE + msg.Params.Amp = & + msg.Liquidity = suite.createStablePoolLiquidity() + }, + }, + } + + for _, tc := range tests { + suite.Run(tc.name, func() { + msg := suite.defaultMsgCreatePool() + tc.mutator(msg) + + ctx := sdk.WrapSDKContext(suite.ctx) + res, err := suite.msgServer.CreatePool(ctx, msg) + + suite.Require().NoError(err) + suite.Require().NotNil(res) + + // Check pool is created or not + pool, err := suite.queryClient.Pool(ctx, &types.QueryPoolRequest{ + PoolId: res.PoolId, + }) + suite.Require().NoError(err) + suite.Require().Equal(pool.Pool.PoolId, res.PoolId) + }) + } +} + +// Helper method to create a default MsgCreatePool for testing +func (suite *KeeperTestSuite) defaultMsgCreatePool() *types.MsgCreatePool { + weight := sdk.NewInt(50) + amp := sdk.NewInt(100) + return types.NewMsgCreatePool( + types.Alice, + types.PoolParams{ + Type: types.PoolType_WEIGHT, + SwapFee: sdkmath.LegacyDec(sdk.NewInt(100)), + Amp: &, + }, + []types.PoolAsset{ + { + Token: sdk.NewCoin(simapp.DefaultBondDenom, sdkmath.NewInt(100)), + Weight: &weight, + Decimal: sdk.NewInt(6), + }, + { + Token: sdk.NewCoin(simapp.USDC, sdkmath.NewInt(100)), + Weight: &weight, + Decimal: sdk.NewInt(6), + }, + }, + ) +} + +// Helper method to create stable pool liquidity for testing +func (suite *KeeperTestSuite) createStablePoolLiquidity() []types.PoolAsset { + weight := sdk.NewInt(50) + return []types.PoolAsset{ + { + Token: sdk.NewCoin(simapp.WDAI, sdkmath.NewInt(100)), + Weight: &weight, + Decimal: sdk.NewInt(6), + }, + { + Token: sdk.NewCoin(simapp.WUSDT, sdkmath.NewInt(100)), + Weight: &weight, + Decimal: sdk.NewInt(6), + }, + } +} + +func (suite *KeeperTestSuite) TestMsgCreatePoolFail() { + var msg *types.MsgCreatePool + suite.SetupTest() + weight := sdk.NewInt(50) + amp := sdk.NewInt(100) + + testCases := []struct { + name string + mallet func() + }{ + { + "invalid sender", + func() {}, + }, + { + "not enough funds", + func() { + msg = types.NewMsgCreatePool( + sample.AccAddress(), + types.PoolParams{ + Type: types.PoolType_WEIGHT, + SwapFee: sdkmath.LegacyDec(sdk.NewInt(100)), + Amp: &, + }, + []types.PoolAsset{ + { + Token: sdk.NewCoin(simapp.DefaultBondDenom, sdkmath.NewInt(100)), + Weight: &weight, + Decimal: sdk.NewInt(6), + }, + { + Token: sdk.NewCoin(simapp.USDC, sdkmath.NewInt(100)), + Weight: &weight, + Decimal: sdk.NewInt(6), + }, + }, + ) + }, + }, + { + "create pool with zero liquidity", + func() { + msg = types.NewMsgCreatePool( + sample.AccAddress(), + types.PoolParams{ + Type: types.PoolType_WEIGHT, + SwapFee: sdkmath.LegacyDec(sdk.NewInt(100)), + Amp: &, + }, + []types.PoolAsset{}, + ) + }, + }, + } + + for _, tc := range testCases { + + msg = types.NewMsgCreatePool( + "", + types.PoolParams{}, + []types.PoolAsset{}, + ) + tc.mallet() + + res, err := suite.msgServer.CreatePool(sdk.WrapSDKContext(suite.ctx), msg) + suite.Require().Error(err) + suite.Require().Nil(res) + } +} + +func (suite *KeeperTestSuite) CreateNewPool(poolType types.PoolType) string { + switch poolType { + case types.PoolType_STABLE: + return suite.createNewStablePool() + default: + return suite.createNewWeightPool() + } +} + +// Helper function to create a new pool +func (suite *KeeperTestSuite) createNewWeightPool() string { + var msg *types.MsgCreatePool + suite.SetupTest() + + weight := sdk.NewInt(50) + amp := sdk.NewInt(100) + + msg = types.NewMsgCreatePool( + types.Alice, + types.PoolParams{ + Type: types.PoolType_WEIGHT, + SwapFee: sdkmath.LegacyDec(sdk.NewInt(100)), + Amp: &, + }, + []types.PoolAsset{ + { + Token: sdk.NewCoin(simapp.DefaultBondDenom, sdkmath.NewInt(100)), + Weight: &weight, + Decimal: sdk.NewInt(6), + }, + { + Token: sdk.NewCoin(simapp.USDC, sdkmath.NewInt(100)), + Weight: &weight, + Decimal: sdk.NewInt(6), + }, + }, + ) + + ctx := sdk.WrapSDKContext(suite.ctx) + res, err := suite.msgServer.CreatePool(ctx, msg) + + suite.Require().NoError(err) + suite.Require().NotNil(res) + return res.PoolId +} + +func (suite *KeeperTestSuite) createNewStablePool() string { + var msg *types.MsgCreatePool + suite.SetupTest() + + weight := sdk.NewInt(50) + amp := sdk.NewInt(1) + + msg = types.NewMsgCreatePool( + types.Alice, + types.PoolParams{ + Type: types.PoolType_STABLE, + SwapFee: sdkmath.LegacyDec(sdk.NewInt(100)), + Amp: &, + }, + []types.PoolAsset{ + { + Token: sdk.NewCoin(simapp.WDAI, sdkmath.NewInt(100)), + Weight: &weight, + Decimal: sdk.NewInt(6), + }, + { + Token: sdk.NewCoin(simapp.WUSDT, sdkmath.NewInt(100)), + Weight: &weight, + Decimal: sdk.NewInt(6), + }, + }, + ) + + ctx := sdk.WrapSDKContext(suite.ctx) + res, err := suite.msgServer.CreatePool(ctx, msg) + + suite.Require().NoError(err) + suite.Require().NotNil(res) + return res.PoolId +} diff --git a/x/gmm/keeper/msg_server_swap.go b/x/gmm/keeper/msg_server_swap.go new file mode 100644 index 00000000..f1427830 --- /dev/null +++ b/x/gmm/keeper/msg_server_swap.go @@ -0,0 +1,64 @@ +package keeper + +import ( + "context" + + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/x/gmm/types" +) + +func (k msgServer) Swap(goCtx context.Context, msg *types.MsgSwap) (*types.MsgSwapResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + if err := msg.ValidateBasic(); err != nil { + return nil, err + } + + pool, found := k.GetPool(ctx, msg.PoolId) + if !found { + return nil, types.ErrNotFoundAssetInPool + } + + out, err := pool.EstimateSwap(msg.TokenIn, msg.TokenOut.Denom) + if err != nil { + return nil, err + } + + // Calculate the absolute difference between the expected and actual token output amounts + differ := msg.TokenOut.Amount.Sub(out.Amount).Abs() + + // Calculate the expected slippage. Make sure msg.Slippage is in the correct unit (e.g., percentage). + // Divide by 100 if msg.Slippage is a percentage. + expectedDiffer := msg.TokenOut.Amount.Mul(msg.Slippage).Quo(sdkmath.NewInt(100)) + + // Check if the actual slippage exceeds the expected slippage + if differ.GT(expectedDiffer) { + return nil, types.ErrNotMeetSlippage + } + + // Move asset from sender to module account + if err := k.LockTokens(ctx, msg.PoolId, sdk.MustAccAddressFromBech32(msg.Sender), sdk.NewCoins( + msg.TokenIn, + )); err != nil { + return nil, err + } + + // Send wanted token from pool to user + if err := k.UnLockTokens(ctx, msg.PoolId, sdk.MustAccAddressFromBech32(msg.Sender), sdk.NewCoins( + out, + )); err != nil { + return nil, err + } + + // Update state. + if err := pool.IncreaseLiquidity([]sdk.Coin{msg.TokenIn}); err != nil { + return nil, err + } + if err := pool.DecreaseLiquidity([]sdk.Coin{out}); err != nil { + return nil, err + } + + // Save pool. + k.SetPool(ctx, pool) + return &types.MsgSwapResponse{}, nil +} diff --git a/x/gmm/keeper/msg_server_swap_test.go b/x/gmm/keeper/msg_server_swap_test.go new file mode 100644 index 00000000..e2a448e1 --- /dev/null +++ b/x/gmm/keeper/msg_server_swap_test.go @@ -0,0 +1,134 @@ +package keeper_test + +import ( + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" + simapp "github.com/sideprotocol/side/app" + "github.com/sideprotocol/side/x/gmm/types" +) + +func (suite *KeeperTestSuite) TestMsgSwap() { + suite.SetupTest() + + tests := []struct { + name string + poolType types.PoolType + mutator func(*types.MsgSwap, string) + }{ + { + "swap in weight pool", + types.PoolType_WEIGHT, + func(msg *types.MsgSwap, poolID string) { + msg.TokenIn = sdk.NewCoin(simapp.DefaultBondDenom, sdk.NewInt(100)) + msg.TokenOut = sdk.NewCoin(simapp.USDC, sdk.NewInt(0)) + }, + }, + { + "swap in stable pool", + types.PoolType_STABLE, + func(msg *types.MsgSwap, poolID string) { + msg.TokenIn = sdk.NewCoin(simapp.WDAI, sdk.NewInt(100)) + msg.TokenOut = sdk.NewCoin(simapp.WUSDT, sdk.NewInt(0)) + }, + }, + } + + for _, tc := range tests { + suite.Run(tc.name, func() { + // Create a new pool of the specific type + poolID := suite.CreateNewPool(tc.poolType) + + // Initialize the MsgSwap + msg := types.MsgSwap{ + Sender: types.Alice, + PoolId: poolID, + Slippage: sdkmath.NewInt(1), + } + + // Use the mutator to set the token in and token out for the specific pool type + tc.mutator(&msg, poolID) + + ctx := sdk.WrapSDKContext(suite.ctx) + + // Query the pool before the swap + queryResBeforeSwap, err := suite.queryClient.Pool(ctx, &types.QueryPoolRequest{ + PoolId: poolID, + }) + suite.Require().NoError(err) + + outAssetBeforeSwap := queryResBeforeSwap.Pool.Assets[msg.TokenOut.Denom] + estimatedOut, err := queryResBeforeSwap.Pool.EstimateSwap(msg.TokenIn, msg.TokenOut.Denom) + msg.TokenOut = estimatedOut + + suite.Require().NoError(err) + + // Perform the swap + res, err := suite.msgServer.Swap(ctx, &msg) + suite.Require().NoError(err) + suite.Require().NotNil(res) + + // Query the pool after the swap + queryResAfterSwap, err := suite.queryClient.Pool(ctx, &types.QueryPoolRequest{ + PoolId: poolID, + }) + suite.Require().NoError(err) + + outAssetAfterSwap := queryResAfterSwap.Pool.Assets[msg.TokenOut.Denom] + out := outAssetBeforeSwap.Token.Sub(outAssetAfterSwap.Token) + suite.Require().Equal(out, estimatedOut) + }) + } +} + +func (suite *KeeperTestSuite) TestMsgSwapFail() { + suite.SetupTest() + + tests := []struct { + name string + poolType types.PoolType + mutator func(*types.MsgSwap, string) + }{ + { + "swap with invalid pool ID", + types.PoolType_WEIGHT, + func(msg *types.MsgSwap, poolID string) { + msg.PoolId = "invalid_pool_id" + }, + }, + { + "swap with invalid sender", + types.PoolType_WEIGHT, + func(msg *types.MsgSwap, poolID string) { + msg.Sender = "invalid_sender_address" + }, + }, + } + + for _, tc := range tests { + suite.Run(tc.name, func() { + // Create a new pool of the specific type, if necessary + poolID := suite.CreateNewPool(tc.poolType) + + // Initialize the MsgSwap + msg := types.MsgSwap{ + Sender: types.Alice, + PoolId: poolID, + Slippage: sdkmath.NewInt(1), + TokenIn: sdk.NewCoin(simapp.WDAI, sdk.NewInt(100)), + TokenOut: sdk.NewCoin(simapp.WUSDT, sdk.NewInt(50)), + } + + // Use the mutator to set the failure conditions + tc.mutator(&msg, poolID) + + ctx := sdk.WrapSDKContext(suite.ctx) + + // Perform the swap + res, err := suite.msgServer.Swap(ctx, &msg) + + // Expect an error and nil result + suite.Require().Error(err) + suite.Require().Nil(res) + }) + } +} diff --git a/x/gmm/keeper/msg_server_test.go b/x/gmm/keeper/msg_server_test.go new file mode 100644 index 00000000..9b39bda8 --- /dev/null +++ b/x/gmm/keeper/msg_server_test.go @@ -0,0 +1,23 @@ +package keeper_test + +import ( + "context" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + keepertest "github.com/sideprotocol/side/testutil/keeper" + "github.com/sideprotocol/side/x/gmm/keeper" + "github.com/sideprotocol/side/x/gmm/types" + "github.com/stretchr/testify/require" +) + +func setupMsgServer(t testing.TB) (types.MsgServer, context.Context) { + k, ctx := keepertest.GmmKeeper(t) + return keeper.NewMsgServerImpl(*k), sdk.WrapSDKContext(ctx) +} + +func TestMsgServer(t *testing.T) { + ms, ctx := setupMsgServer(t) + require.NotNil(t, ms) + require.NotNil(t, ctx) +} diff --git a/x/gmm/keeper/msg_server_withdraw.go b/x/gmm/keeper/msg_server_withdraw.go new file mode 100644 index 00000000..d4e9859a --- /dev/null +++ b/x/gmm/keeper/msg_server_withdraw.go @@ -0,0 +1,54 @@ +package keeper + +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/x/gmm/types" +) + +func (k msgServer) Withdraw(goCtx context.Context, msg *types.MsgWithdraw) (*types.MsgWithdrawResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + if err := msg.ValidateBasic(); err != nil { + return nil, err + } + + pool, found := k.GetPool(ctx, msg.PoolId) + if !found { + return nil, types.ErrNotFoundAssetInPool + } + + outs, err := pool.EstimateWithdrawals(msg.Share) + if err != nil { + return nil, err + } + + // Check creator has enough share or not + bal := k.bankKeeper.GetBalance(ctx, sdk.MustAccAddressFromBech32(msg.Sender), + msg.Share.Denom, + ) + if bal.IsLT(msg.Share) { + return nil, types.ErrInsufficientBalance + } + + // Unlock asset from pool + if err = k.UnLockTokens(ctx, pool.PoolId, sdk.MustAccAddressFromBech32(msg.Receiver), outs); err != nil { + return nil, err + } + + // Burn lp token + if err = k.BurnTokens(ctx, sdk.MustAccAddressFromBech32(msg.Sender), msg.Share); err != nil { + return nil, err + } + + // Update pool statues. + if err := pool.DecreaseLiquidity(outs); err != nil { + return nil, err + } + pool.DecreaseShare(msg.Share.Amount) + + // Save pool + k.SetPool(ctx, pool) + return &types.MsgWithdrawResponse{}, nil +} diff --git a/x/gmm/keeper/msg_server_withdraw_test.go b/x/gmm/keeper/msg_server_withdraw_test.go new file mode 100644 index 00000000..78d83e4b --- /dev/null +++ b/x/gmm/keeper/msg_server_withdraw_test.go @@ -0,0 +1,114 @@ +package keeper_test + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/x/gmm/types" +) + +func (suite *KeeperTestSuite) TestMsgWithdraw() { + suite.SetupTest() + + tests := []struct { + name string + poolType types.PoolType + mutator func(*types.MsgWithdraw, string) + }{ + { + "withdraw from weight pool", + types.PoolType_WEIGHT, + func(msg *types.MsgWithdraw, poolID string) { + msg.Share = sdk.NewCoin(poolID, sdk.NewInt(100)) + }, + }, + { + "withdraw from stable pool", + types.PoolType_STABLE, + func(msg *types.MsgWithdraw, poolID string) { + msg.Share = sdk.NewCoin(poolID, sdk.NewInt(200)) + }, + }, + } + + for _, tc := range tests { + suite.Run(tc.name, func() { + // Create a new pool of the specific type + poolID := suite.CreateNewPool(tc.poolType) + + // Initialize the MsgWithdraw + msg := types.MsgWithdraw{ + Sender: types.Alice, + Receiver: types.Carol, + PoolId: poolID, + } + + // Use the mutator to set the share for the specific pool type + tc.mutator(&msg, poolID) + + ctx := sdk.WrapSDKContext(suite.ctx) + res, err := suite.msgServer.Withdraw(ctx, &msg) + + suite.Require().NoError(err) + suite.Require().NotNil(res) + }) + } +} + +func (suite *KeeperTestSuite) TestMsgWithdrawFail() { + suite.SetupTest() + + tests := []struct { + name string + poolType types.PoolType + mutator func(*types.MsgWithdraw, string) + }{ + { + "withdraw from non-existent pool", + types.PoolType_WEIGHT, + func(msg *types.MsgWithdraw, poolID string) { + msg.PoolId = "invalid_pool_id" + }, + }, + { + "withdraw with invalid sender", + types.PoolType_WEIGHT, + func(msg *types.MsgWithdraw, poolID string) { + msg.Sender = "invalid_sender_address" + }, + }, + { + "withdraw with insufficient balance", + types.PoolType_WEIGHT, + func(msg *types.MsgWithdraw, poolID string) { + msg.Share = sdk.NewCoin(poolID, sdk.NewInt(1000000)) // Some large number + }, + }, + // Add more failure test cases to cover all scenarios + } + + for _, tc := range tests { + suite.Run(tc.name, func() { + // Create a new pool of the specific type if necessary + poolID := suite.CreateNewPool(tc.poolType) + + // Initialize the MsgWithdraw + msg := types.MsgWithdraw{ + Sender: types.Alice, + Receiver: types.Carol, + PoolId: poolID, + Share: sdk.NewCoin(poolID, sdk.NewInt(200)), + } + + // Use the mutator to set the failure condition + tc.mutator(&msg, poolID) + + ctx := sdk.WrapSDKContext(suite.ctx) + + // Perform the withdraw + res, err := suite.msgServer.Withdraw(ctx, &msg) + + // Expect an error and nil result + suite.Require().Error(err) + suite.Require().Nil(res) + }) + } +} diff --git a/x/gmm/keeper/params.go b/x/gmm/keeper/params.go new file mode 100644 index 00000000..a81b304b --- /dev/null +++ b/x/gmm/keeper/params.go @@ -0,0 +1,17 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/x/gmm/types" +) + +// GetParams get all parameters as types.Params +func (k Keeper) GetParams(ctx sdk.Context) types.Params { + _ = ctx + return types.NewParams() +} + +// SetParams set the params +func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { + k.paramstore.SetParamSet(ctx, ¶ms) +} diff --git a/x/gmm/keeper/params_test.go b/x/gmm/keeper/params_test.go new file mode 100644 index 00000000..50b3dc04 --- /dev/null +++ b/x/gmm/keeper/params_test.go @@ -0,0 +1,18 @@ +package keeper_test + +import ( + "testing" + + testkeeper "github.com/sideprotocol/side/testutil/keeper" + "github.com/sideprotocol/side/x/gmm/types" + "github.com/stretchr/testify/require" +) + +func TestGetParams(t *testing.T) { + k, ctx := testkeeper.GmmKeeper(t) + params := types.DefaultParams() + + k.SetParams(ctx, params) + + require.EqualValues(t, params, k.GetParams(ctx)) +} diff --git a/x/gmm/keeper/pool.go b/x/gmm/keeper/pool.go new file mode 100644 index 00000000..543dec9d --- /dev/null +++ b/x/gmm/keeper/pool.go @@ -0,0 +1,206 @@ +package keeper + +import ( + "encoding/binary" + "fmt" + + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/sideprotocol/side/x/gmm/types" +) + +func (k Keeper) initializePool(ctx sdk.Context, msg *types.MsgCreatePool) (*string, error) { + poolCreator := msg.PoolCreator() + pool := msg.CreatePool() + totalShares := sdk.NewInt(0) + + poolShareBaseDenom := pool.PoolId + poolShareDisplayDenom := pool.PoolId + + assets := make(map[string]types.PoolAsset) + for _, liquidity := range msg.Liquidity { + assets[liquidity.Token.Denom] = liquidity + totalShares = totalShares.Add(liquidity.Token.Amount) + } + + // Check pool already created or not + if _, found := k.GetPool(ctx, pool.PoolId); found { + return nil, types.ErrAlreadyCreatedPool + } + + // Check balance. + for _, liquidity := range msg.Liquidity { + balance := k.bankKeeper.GetBalance(ctx, poolCreator, liquidity.Token.Denom) + if balance.Amount.LT(liquidity.Token.Amount) { + return nil, types.ErrInsufficientBalance + } + } + + // Move asset from Sender to module account + + if err := k.LockTokens(ctx, pool.PoolId, msg.PoolCreator(), msg.InitialLiquidity()); err != nil { + return nil, err + } + + // Register metadata to bank keeper + + k.bankKeeper.SetDenomMetaData(ctx, banktypes.Metadata{ + Description: fmt.Sprintf("The share token of the gamm pool %s", pool.GetPoolId()), + DenomUnits: []*banktypes.DenomUnit{ + { + Denom: poolShareBaseDenom, + Exponent: 0, + Aliases: []string{ + "attopoolshare", + }, + }, + { + Denom: poolShareDisplayDenom, + Exponent: types.OneShareExponent, + Aliases: nil, + }, + }, + Base: poolShareBaseDenom, + Display: poolShareDisplayDenom, + }) + + // Mint share to Sender + if err := k.MintPoolShareToAccount(ctx, poolCreator, sdk.NewCoin( + poolShareBaseDenom, + totalShares, + )); err != nil { + return nil, err + } + + // Save pool to chain + k.AppendPool(ctx, pool) + return &pool.PoolId, nil +} + +// RemoveInterchainLiquidityPool removes a interchainLiquidityPool from the store +func (k Keeper) RemoveInterchainLiquidityPool( + ctx sdk.Context, + poolID string, +) { + // Get current pool count + poolCount, found := k.GetCountByPoolID(ctx, poolID) + if !found { + return + } + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPoolsPrefix) + store.Delete(GetPoolKey(poolCount)) +} + +func (k Keeper) GetPoolCount(ctx sdk.Context) uint64 { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPoolsPrefix) + b := store.Get(types.KeyCurrentPoolCountPrefix) + if b == nil { + return 0 + } + return binary.BigEndian.Uint64(b) +} + +func (k Keeper) SetPoolCount(ctx sdk.Context, count uint64) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPoolsPrefix) + b := make([]byte, 8) + binary.BigEndian.PutUint64(b, count) + store.Set(types.KeyCurrentPoolCountPrefix, b) +} + +func GetPoolKey(count uint64) []byte { + return []byte(fmt.Sprintf("%020d", count)) +} + +// GetAllInterchainLiquidityPool returns all interchainLiquidityPool +func (k Keeper) GetAllPool(ctx sdk.Context) (list []types.Pool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(string(types.KeyPoolsPrefix))) + + // Start from the latest pool and move to the oldest + poolCount := k.GetPoolCount(ctx) + for i := poolCount; i >= 1 && (poolCount-i) < types.MaxPoolCount; i-- { + b := store.Get(GetPoolKey(i)) + if b == nil { + continue + } + var val types.Pool + k.cdc.MustUnmarshal(b, &val) + list = append(list, val) + } + return +} + +// Sets the mapping between poolId and its count index +func (k Keeper) SetPoolIDToCountMapping(ctx sdk.Context, poolID string, count uint64) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPoolIDToCountPrefix) + b := make([]byte, 8) + binary.BigEndian.PutUint64(b, count) + store.Set([]byte(poolID), b) +} + +// Gets the count index of the poolId +func (k Keeper) GetCountByPoolID(ctx sdk.Context, poolID string) (count uint64, found bool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPoolIDToCountPrefix) + b := store.Get([]byte(poolID)) + if b == nil { + return 0, false + } + return binary.BigEndian.Uint64(b), true +} + +// Modified SetInterchainLiquidityPool +func (k Keeper) AppendPool(ctx sdk.Context, pool types.Pool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPoolsPrefix) + + // Get current pool count + poolCount := k.GetPoolCount(ctx) + + // Increment the count + poolCount++ + + // Set the new count + k.SetPoolCount(ctx, poolCount) + + // Set the poolId to count mapping + k.SetPoolIDToCountMapping(ctx, pool.PoolId, poolCount) + + // Marshal the pool and set in store + b := k.cdc.MustMarshal(&pool) + store.Set(GetPoolKey(poolCount), b) + + // Check if we exceed max pools + if poolCount > types.MaxPoolCount { + // Remove the oldest pool + store.Delete(GetPoolKey(poolCount - types.MaxPoolCount)) + } +} + +func (k Keeper) SetPool(ctx sdk.Context, pool types.Pool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(string(types.KeyPoolsPrefix))) + // Get current pool count + poolCount, found := k.GetCountByPoolID(ctx, pool.PoolId) + if !found { + return + } + // Marshal the pool and set in store + b := k.cdc.MustMarshal(&pool) + store.Set(GetPoolKey(poolCount), b) +} + +// Modified GetInterchainLiquidityPool +func (k Keeper) GetPool(ctx sdk.Context, poolID string) (val types.Pool, found bool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPoolsPrefix) + + count, found := k.GetCountByPoolID(ctx, poolID) + if !found { + return val, false + } + + b := store.Get(GetPoolKey(count)) + if b == nil { + return val, false + } + + k.cdc.MustUnmarshal(b, &val) + return val, true +} diff --git a/x/gmm/keeper/query.go b/x/gmm/keeper/query.go new file mode 100644 index 00000000..715086d9 --- /dev/null +++ b/x/gmm/keeper/query.go @@ -0,0 +1,7 @@ +package keeper + +import ( + "github.com/sideprotocol/side/x/gmm/types" +) + +var _ types.QueryServer = Keeper{} diff --git a/x/gmm/keeper/query_params.go b/x/gmm/keeper/query_params.go new file mode 100644 index 00000000..12f36aba --- /dev/null +++ b/x/gmm/keeper/query_params.go @@ -0,0 +1,19 @@ +package keeper + +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/x/gmm/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func (k Keeper) Params(goCtx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + ctx := sdk.UnwrapSDKContext(goCtx) + + return &types.QueryParamsResponse{Params: k.GetParams(ctx)}, nil +} diff --git a/x/gmm/keeper/query_params_test.go b/x/gmm/keeper/query_params_test.go new file mode 100644 index 00000000..4929053a --- /dev/null +++ b/x/gmm/keeper/query_params_test.go @@ -0,0 +1,21 @@ +package keeper_test + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + testkeeper "github.com/sideprotocol/side/testutil/keeper" + "github.com/sideprotocol/side/x/gmm/types" + "github.com/stretchr/testify/require" +) + +func TestParamsQuery(t *testing.T) { + keeper, ctx := testkeeper.GmmKeeper(t) + wctx := sdk.WrapSDKContext(ctx) + params := types.DefaultParams() + keeper.SetParams(ctx, params) + + response, err := keeper.Params(wctx, &types.QueryParamsRequest{}) + require.NoError(t, err) + require.Equal(t, &types.QueryParamsResponse{Params: params}, response) +} diff --git a/x/gmm/keeper/query_pools.go b/x/gmm/keeper/query_pools.go new file mode 100644 index 00000000..72768107 --- /dev/null +++ b/x/gmm/keeper/query_pools.go @@ -0,0 +1,112 @@ +package keeper + +import ( + "context" + "encoding/binary" + + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/query" + "github.com/sideprotocol/side/x/gmm/types" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func (k Keeper) Pool(goCtx context.Context, req *types.QueryPoolRequest) (*types.QueryPoolResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + ctx := sdk.UnwrapSDKContext(goCtx) + pool, found := k.GetPool(ctx, req.PoolId) + if !found { + return &types.QueryPoolResponse{}, types.ErrPoolNotFound + } + return &types.QueryPoolResponse{Pool: &pool}, nil +} + +func (k Keeper) Pools(goCtx context.Context, req *types.QueryPoolsRequest) (*types.QueryPoolsResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + + var pools []types.Pool + ctx := sdk.UnwrapSDKContext(goCtx) + + // Use the store with the mapping of poolId to its count + store := ctx.KVStore(k.storeKey) + poolIDToCountStore := prefix.NewStore(store, types.KeyPoolIDToCountPrefix) + + // A counter for pagination + var counter int + + pageRes, err := query.Paginate(poolIDToCountStore, req.Pagination, func(key []byte, value []byte) error { + counter++ + + // Decode the count for the given poolId + count := binary.BigEndian.Uint64(value) + + // Get the actual pool using the count + poolStore := prefix.NewStore(store, types.KeyPrefix(string(types.KeyPoolsPrefix))) + poolBytes := poolStore.Get(GetPoolKey(count)) + if poolBytes == nil { + return nil + } + + var pool types.Pool + if err := k.cdc.Unmarshal(poolBytes, &pool); 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 +} + +func (k Keeper) MyPools(goCtx context.Context, req *types.QueryPoolsRequest) (*types.QueryPoolsResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + + var pools []types.Pool + ctx := sdk.UnwrapSDKContext(goCtx) + + // Use the store with the mapping of poolId to its count + store := ctx.KVStore(k.storeKey) + poolIDToCountStore := prefix.NewStore(store, types.KeyPoolIDToCountPrefix) + + // A counter for pagination + var counter int + + pageRes, err := query.Paginate(poolIDToCountStore, req.Pagination, func(key []byte, value []byte) error { + counter++ + + // Decode the count for the given poolId + count := binary.BigEndian.Uint64(value) + + // Get the actual pool using the count + poolStore := prefix.NewStore(store, types.KeyPrefix(string(types.KeyPoolsPrefix))) + poolBytes := poolStore.Get(GetPoolKey(count)) + if poolBytes == nil { + return nil + } + + var pool types.Pool + if err := k.cdc.Unmarshal(poolBytes, &pool); err != nil { + return err + } + if pool.Sender == req.Creator { + 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 +} diff --git a/x/gmm/keeper/share.go b/x/gmm/keeper/share.go new file mode 100644 index 00000000..200d7161 --- /dev/null +++ b/x/gmm/keeper/share.go @@ -0,0 +1,24 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/x/gmm/types" +) + +// MintPoolShareToAccount attempts to mint shares of a GAMM denomination to the +// specified address returning an error upon failure. Shares are minted using +// the x/gamm module account. +func (k Keeper) MintPoolShareToAccount(ctx sdk.Context, addr sdk.AccAddress, share sdk.Coin) error { + amt := sdk.NewCoins(share) + err := k.bankKeeper.MintCoins(ctx, types.ModuleName, amt) + if err != nil { + return err + } + + err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, amt) + if err != nil { + return err + } + + return nil +} diff --git a/x/gmm/module.go b/x/gmm/module.go new file mode 100644 index 00000000..a27ba435 --- /dev/null +++ b/x/gmm/module.go @@ -0,0 +1,152 @@ +package gmm + +import ( + "context" + "encoding/json" + "fmt" + + // this line is used by starport scaffolding # 1 + + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + + 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" + "github.com/sideprotocol/side/x/gmm/client/cli" + "github.com/sideprotocol/side/x/gmm/keeper" + "github.com/sideprotocol/side/x/gmm/types" +) + +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} +) + +// ---------------------------------------------------------------------------- +// AppModuleBasic +// ---------------------------------------------------------------------------- + +// AppModuleBasic implements the AppModuleBasic interface that defines the independent methods a Cosmos SDK module needs to implement. +type AppModuleBasic struct { + cdc codec.BinaryCodec +} + +func NewAppModuleBasic(cdc codec.BinaryCodec) AppModuleBasic { + return AppModuleBasic{cdc: cdc} +} + +// Name returns the name of the module as a string +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the amino codec for the module, which is used to marshal and unmarshal structs to/from []byte in order to persist them in the module's KVStore +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterCodec(cdc) +} + +// RegisterInterfaces registers a module's interface types and their concrete implementations as proto.Message +func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { + types.RegisterInterfaces(reg) +} + +// DefaultGenesis returns a default GenesisState for the module, marshaled to json.RawMessage. The default GenesisState need to be defined by the module developer and is primarily used for testing +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return cdc.MustMarshalJSON(types.DefaultGenesis()) +} + +// ValidateGenesis used to validate the GenesisState, given in its json.RawMessage form +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, 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) { + err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) + if err != nil { + fmt.Println(err) + } +} + +// GetTxCmd returns the root Tx command for the module. The subcommands of this root command are used by end-users to generate new transactions containing messages defined in the module +func (a AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd() +} + +// GetQueryCmd returns the root query command for the module. The subcommands of this root command are used by end-users to generate new queries to the subset of the state defined by the module +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd(types.StoreKey) +} + +// ---------------------------------------------------------------------------- +// AppModule +// ---------------------------------------------------------------------------- + +// AppModule implements the AppModule interface that defines the inter-dependent methods that modules need to implement +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, + } +} + +// RegisterServices registers a gRPC query service to respond to the module-specific gRPC queries +func (am AppModule) RegisterServices(cfg module.Configurator) { + types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) + types.RegisterQueryServer(cfg.QueryServer(), am.keeper) +} + +// RegisterInvariants registers the invariants of the module. If an invariant deviates from its predicted value, the InvariantRegistry triggers appropriate logic (most often the chain will be halted) +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// InitGenesis performs the 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 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 is a sequence number for state-breaking change of the module. It should be incremented on each consensus-breaking change introduced by the module. To avoid wrong/empty versions, the initial version should be set to 1 +func (AppModule) ConsensusVersion() uint64 { return 1 } + +// BeginBlock contains the logic that is automatically triggered at the beginning of each block +func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} + +// EndBlock contains the logic that is automatically triggered at the end of each block +func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} diff --git a/x/gmm/module_simulation.go b/x/gmm/module_simulation.go new file mode 100644 index 00000000..d2a135bb --- /dev/null +++ b/x/gmm/module_simulation.go @@ -0,0 +1,169 @@ +package gmm + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/sideprotocol/side/testutil/sample" + gmmsimulation "github.com/sideprotocol/side/x/gmm/simulation" + "github.com/sideprotocol/side/x/gmm/types" +) + +// avoid unused import issue +var ( + _ = sample.AccAddress + _ = gmmsimulation.FindAccount + _ = simulation.MsgEntryKind + _ = baseapp.Paramspace + _ = rand.Rand{} +) + +const ( + opWeightMsgAddLiquidity = "op_weight_msg_add_liquidity" // #nosec + // TODO: Determine the simulation weight value + defaultWeightMsgAddLiquidity int = 100 + + opWeightMsgCreatePool = "op_weight_msg_create_pool" // #nosec + // TODO: Determine the simulation weight value + defaultWeightMsgCreatePool int = 100 + + opWeightMsgWithdraw = "op_weight_msg_withdraw" // #nosec + // TODO: Determine the simulation weight value + defaultWeightMsgWithdraw int = 100 + + opWeightMsgSwap = "op_weight_msg_swap" // #nosec + // TODO: Determine the simulation weight value + defaultWeightMsgSwap int = 100 + + opWeightMsgDeletePool = "op_weight_msg_delete_pool" // #nosec + // TODO: Determine the simulation weight value + defaultWeightMsgDeletePool int = 100 + + // this line is used by starport scaffolding # simapp/module/const +) + +// GenerateGenesisState creates a randomized GenState of the module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + accs := make([]string, len(simState.Accounts)) + for i, acc := range simState.Accounts { + accs[i] = acc.Address.String() + } + gmmGenesis := types.GenesisState{ + Params: types.DefaultParams(), + // this line is used by starport scaffolding # simapp/module/genesisState + } + simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&gmmGenesis) +} + +// RegisterStoreDecoder registers a decoder. +func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} + +// ProposalContents doesn't return any content functions for governance proposals. +func (AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedProposalMsg { + return nil +} + +// WeightedOperations returns the all the gov module operations with their respective weights. +func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { + operations := make([]simtypes.WeightedOperation, 0) + _ = simState + var weightMsgAddLiquidity int + simState.AppParams.GetOrGenerate(simState.Cdc, opWeightMsgAddLiquidity, &weightMsgAddLiquidity, nil, + func(_ *rand.Rand) { + weightMsgAddLiquidity = defaultWeightMsgAddLiquidity + }, + ) + operations = append(operations, simulation.NewWeightedOperation( + weightMsgAddLiquidity, + gmmsimulation.SimulateMsgAddLiquidity(am.accountKeeper, am.bankKeeper, am.keeper), + )) + + var weightMsgCreatePool int + simState.AppParams.GetOrGenerate(simState.Cdc, opWeightMsgCreatePool, &weightMsgCreatePool, nil, + func(_ *rand.Rand) { + weightMsgCreatePool = defaultWeightMsgCreatePool + }, + ) + operations = append(operations, simulation.NewWeightedOperation( + weightMsgCreatePool, + gmmsimulation.SimulateMsgCreatePool(am.accountKeeper, am.bankKeeper, am.keeper), + )) + + var weightMsgWithdraw int + simState.AppParams.GetOrGenerate(simState.Cdc, opWeightMsgWithdraw, &weightMsgWithdraw, nil, + func(_ *rand.Rand) { + weightMsgWithdraw = defaultWeightMsgWithdraw + }, + ) + operations = append(operations, simulation.NewWeightedOperation( + weightMsgWithdraw, + gmmsimulation.SimulateMsgWithdraw(am.accountKeeper, am.bankKeeper, am.keeper), + )) + + var weightMsgSwap int + simState.AppParams.GetOrGenerate(simState.Cdc, opWeightMsgSwap, &weightMsgSwap, nil, + func(_ *rand.Rand) { + weightMsgSwap = defaultWeightMsgSwap + }, + ) + operations = append(operations, simulation.NewWeightedOperation( + weightMsgSwap, + gmmsimulation.SimulateMsgSwap(am.accountKeeper, am.bankKeeper, am.keeper), + )) + + var weightMsgDeletePool int + simState.AppParams.GetOrGenerate(simState.Cdc, opWeightMsgDeletePool, &weightMsgDeletePool, nil, + func(_ *rand.Rand) { + weightMsgDeletePool = defaultWeightMsgDeletePool + }, + ) + + // this line is used by starport scaffolding # simapp/module/operation + + return operations +} + +// ProposalMsgs returns msgs used for governance proposals for simulations. +func (am AppModule) ProposalMsgs(simState module.SimulationState) []simtypes.WeightedProposalMsg { + _ = simState + return []simtypes.WeightedProposalMsg{ + simulation.NewWeightedProposalMsg( + opWeightMsgAddLiquidity, + defaultWeightMsgAddLiquidity, + func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { + gmmsimulation.SimulateMsgAddLiquidity(am.accountKeeper, am.bankKeeper, am.keeper) + return nil + }, + ), + simulation.NewWeightedProposalMsg( + opWeightMsgCreatePool, + defaultWeightMsgCreatePool, + func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { + gmmsimulation.SimulateMsgCreatePool(am.accountKeeper, am.bankKeeper, am.keeper) + return nil + }, + ), + simulation.NewWeightedProposalMsg( + opWeightMsgWithdraw, + defaultWeightMsgWithdraw, + func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { + gmmsimulation.SimulateMsgWithdraw(am.accountKeeper, am.bankKeeper, am.keeper) + return nil + }, + ), + simulation.NewWeightedProposalMsg( + opWeightMsgSwap, + defaultWeightMsgSwap, + func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { + gmmsimulation.SimulateMsgSwap(am.accountKeeper, am.bankKeeper, am.keeper) + return nil + }, + ), + + // this line is used by starport scaffolding # simapp/module/OpMsg + } +} diff --git a/x/gmm/simulation/add_liquidity.go b/x/gmm/simulation/add_liquidity.go new file mode 100644 index 00000000..af8b5013 --- /dev/null +++ b/x/gmm/simulation/add_liquidity.go @@ -0,0 +1,31 @@ +package simulation + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/sideprotocol/side/x/gmm/keeper" + "github.com/sideprotocol/side/x/gmm/types" +) + +func SimulateMsgAddLiquidity( + 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) + msg := &types.MsgAddLiquidity{ + Sender: simAccount.Address.String(), + } + + // TODO: Handling the AddLiquidity simulation + _ = k + _ = bk + _ = ak + return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "AddLiquidity simulation not implemented"), nil, nil + } +} diff --git a/x/gmm/simulation/create_pool.go b/x/gmm/simulation/create_pool.go new file mode 100644 index 00000000..5d34cdf3 --- /dev/null +++ b/x/gmm/simulation/create_pool.go @@ -0,0 +1,32 @@ +package simulation + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/sideprotocol/side/x/gmm/keeper" + "github.com/sideprotocol/side/x/gmm/types" +) + +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) + msg := &types.MsgCreatePool{ + Sender: simAccount.Address.String(), + } + + // TODO: Handling the CreatePool simulation + _ = k + _ = bk + _ = ak + + return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "CreatePool simulation not implemented"), nil, nil + } +} diff --git a/x/gmm/simulation/helpers.go b/x/gmm/simulation/helpers.go new file mode 100644 index 00000000..92c437c0 --- /dev/null +++ b/x/gmm/simulation/helpers.go @@ -0,0 +1,15 @@ +package simulation + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" +) + +// FindAccount find a specific address from an account list +func FindAccount(accs []simtypes.Account, address string) (simtypes.Account, bool) { + creator, err := sdk.AccAddressFromBech32(address) + if err != nil { + panic(err) + } + return simtypes.FindAccount(accs, creator) +} diff --git a/x/gmm/simulation/swap.go b/x/gmm/simulation/swap.go new file mode 100644 index 00000000..bdad6683 --- /dev/null +++ b/x/gmm/simulation/swap.go @@ -0,0 +1,31 @@ +package simulation + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/sideprotocol/side/x/gmm/keeper" + "github.com/sideprotocol/side/x/gmm/types" +) + +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) { + simAccount, _ := simtypes.RandomAcc(r, accs) + msg := &types.MsgSwap{ + Sender: simAccount.Address.String(), + } + + // TODO: Handling the Swap simulation + _ = k + _ = bk + _ = ak + return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "Swap simulation not implemented"), nil, nil + } +} diff --git a/x/gmm/simulation/withdraw.go b/x/gmm/simulation/withdraw.go new file mode 100644 index 00000000..58fffd4f --- /dev/null +++ b/x/gmm/simulation/withdraw.go @@ -0,0 +1,31 @@ +package simulation + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/sideprotocol/side/x/gmm/keeper" + "github.com/sideprotocol/side/x/gmm/types" +) + +func SimulateMsgWithdraw( + 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) + msg := &types.MsgWithdraw{ + Sender: simAccount.Address.String(), + } + + // TODO: Handling the Withdraw simulation + _ = k + _ = bk + _ = ak + return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "Withdraw simulation not implemented"), nil, nil + } +} diff --git a/x/gmm/types/codec.go b/x/gmm/types/codec.go new file mode 100644 index 00000000..915b09f4 --- /dev/null +++ b/x/gmm/types/codec.go @@ -0,0 +1,40 @@ +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 RegisterCodec(cdc *codec.LegacyAmino) { + cdc.RegisterConcrete(&MsgAddLiquidity{}, "gmm/AddLiquidity", nil) + cdc.RegisterConcrete(&MsgCreatePool{}, "gmm/CreatePool", nil) + cdc.RegisterConcrete(&MsgWithdraw{}, "gmm/Withdraw", nil) + cdc.RegisterConcrete(&MsgSwap{}, "gmm/Swap", nil) + // this line is used by starport scaffolding # 2 +} + +func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { + registry.RegisterImplementations((*sdk.Msg)(nil), + &MsgAddLiquidity{}, + ) + registry.RegisterImplementations((*sdk.Msg)(nil), + &MsgCreatePool{}, + ) + registry.RegisterImplementations((*sdk.Msg)(nil), + &MsgWithdraw{}, + ) + registry.RegisterImplementations((*sdk.Msg)(nil), + &MsgSwap{}, + ) + // this line is used by starport scaffolding # 3 + + msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +} + +var ( + Amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) +) diff --git a/x/gmm/types/consts.go b/x/gmm/types/consts.go new file mode 100644 index 00000000..4ffabe1c --- /dev/null +++ b/x/gmm/types/consts.go @@ -0,0 +1,7 @@ +package types + +const ( + OneShareExponent = 6 + MaxPoolCount = 1e11 + Multiplier = 1e18 +) diff --git a/x/gmm/types/errors.go b/x/gmm/types/errors.go new file mode 100644 index 00000000..fb0748f7 --- /dev/null +++ b/x/gmm/types/errors.go @@ -0,0 +1,33 @@ +package types + +// DONTCOVER + +import ( + sdkerrors "cosmossdk.io/errors" +) + +// x/gmm module sentinel errors +var ( + ErrSample = sdkerrors.Register(ModuleName, 1100, "sample error") + ErrAlreadyCreatedPool = sdkerrors.Register(ModuleName, 1101, "already exist pool in the system") + ErrNotEnoughBalance = sdkerrors.Register(ModuleName, 1102, "not enough balance") + ErrInvalidPoolType = sdkerrors.Register(ModuleName, 1103, "invalid pool type") + ErrInvalidNumOfAssets = sdkerrors.Register(ModuleName, 1104, "invalid number of assets") + ErrNotFoundAssetInPool = sdkerrors.Register(ModuleName, 1105, "did not find asset") + ErrNotFoundAPool = sdkerrors.Register(ModuleName, 1106, "did not find pool") + ErrOverflowShareAmount = sdkerrors.Register(ModuleName, 1107, "share amount is over than pool total supply") + ErrInvalidAddress = sdkerrors.Register(ModuleName, 1109, "invalid betch32 address") + ErrInvalidPoolParams = sdkerrors.Register(ModuleName, 1110, "invalid pool params") + ErrEmptyLiquidity = sdkerrors.Register(ModuleName, 1111, "empty pool liquidity") + ErrInvalidLiquidityInLength = sdkerrors.Register(ModuleName, 1112, "invalid pool liquidity in length") + ErrInvalidPoolID = sdkerrors.Register(ModuleName, 1113, "invalid poolID") + ErrInvalidLiquidityAmount = sdkerrors.Register(ModuleName, 1114, "invalid liquidity amount") + ErrInvalidTokenAmount = sdkerrors.Register(ModuleName, 1115, "invalid token amount") + ErrEmptyDenom = sdkerrors.Register(ModuleName, 1116, "empty denom") + ErrInsufficientBalance = sdkerrors.Register(ModuleName, 1117, "insufficient balance") + ErrPoolNotFound = sdkerrors.Register(ModuleName, 1118, "not found pool") + ErrInvalidInvariantConverge = sdkerrors.Register(ModuleName, 1119, "Invalid invariant converge") + ErrInvalidAmp = sdkerrors.Register(ModuleName, 1120, "amp has to be zero to 100") + ErrNotMeetSlippage = sdkerrors.Register(ModuleName, 1121, "not meet slippage") + ErrInvalidSlippage = sdkerrors.Register(ModuleName, 1122, "invalid slippage") +) diff --git a/x/gmm/types/events.go b/x/gmm/types/events.go new file mode 100644 index 00000000..25c59224 --- /dev/null +++ b/x/gmm/types/events.go @@ -0,0 +1,25 @@ +package types + +const ( + EventValueActionCreatePool = "create_pool" + EventValueActionCancelPool = "cancel_pool" + EventValueActionDeposit = "deposit" + EventValueActionWithdraw = "withdraw" + EventValueActionSwap = "swap_pool" +) + +const ( + AttributeKeyAction = "action" + AttributeKeyPoolID = "pool_id" + AttributeKeyMultiDepositOrderID = "order_id" + AttributeKeyMultiDeposits = "deposit" + AttributeKeyTokenIn = "token_in" + AttributeKeyTokenOut = "token_out" + AttributeKeyLpToken = "liquidity_pool_token" + AttributeKeyLpSupply = "liquidity_pool_token_supply" + AttributeKeyPoolCreator = "pool_creator" + AttributeKeyOrderCreator = "order_creator" + AttributeKeyName = "name" + AttributeKeyPoolStatus = "pool_status" + AttributeKeyMsgSender = "msg_sender" +) diff --git a/x/gmm/types/expected_keepers.go b/x/gmm/types/expected_keepers.go new file mode 100644 index 00000000..499491f2 --- /dev/null +++ b/x/gmm/types/expected_keepers.go @@ -0,0 +1,35 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" + banktype "github.com/cosmos/cosmos-sdk/x/bank/types" +) + +// AccountKeeper defines the expected account keeper used for simulations (noalias) +type AccountKeeper interface { + GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI + // Methods imported from account should be defined here + NewAccount(sdk.Context, types.AccountI) types.AccountI + + SetAccount(ctx sdk.Context, acc types.AccountI) +} + +// BankKeeper defines the expected interface needed to retrieve account balances. +type BankKeeper interface { + SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins + // 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, senderModule, recipientModule 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 + SetDenomMetaData(ctx sdk.Context, denomMetaData banktype.Metadata) + + MintCoins(ctx sdk.Context, moduleName string, amounts sdk.Coins) error + BurnCoins(ctx sdk.Context, moduleName string, amounts sdk.Coins) error + + HasSupply(ctx sdk.Context, denom string) bool + GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin +} diff --git a/x/gmm/types/genesis.go b/x/gmm/types/genesis.go new file mode 100644 index 00000000..0af9b441 --- /dev/null +++ b/x/gmm/types/genesis.go @@ -0,0 +1,24 @@ +package types + +import ( +// this line is used by starport scaffolding # genesis/types/import +) + +// DefaultIndex is the default global index +const DefaultIndex uint64 = 1 + +// DefaultGenesis returns the default genesis state +func DefaultGenesis() *GenesisState { + return &GenesisState{ + // this line is used by starport scaffolding # genesis/types/default + Params: DefaultParams(), + } +} + +// Validate performs basic genesis state validation returning an error upon any +// failure. +func (gs GenesisState) Validate() error { + // this line is used by starport scaffolding # genesis/types/validate + + return gs.Params.Validate() +} diff --git a/x/gmm/types/genesis.pb.go b/x/gmm/types/genesis.pb.go new file mode 100644 index 00000000..ca84e85d --- /dev/null +++ b/x/gmm/types/genesis.pb.go @@ -0,0 +1,320 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: side/gmm/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 gmm module's genesis state. +type GenesisState struct { + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` +} + +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_81ff25af4c4c0a2a, []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 init() { + proto.RegisterType((*GenesisState)(nil), "side.gmm.GenesisState") +} + +func init() { proto.RegisterFile("side/gmm/genesis.proto", fileDescriptor_81ff25af4c4c0a2a) } + +var fileDescriptor_81ff25af4c4c0a2a = []byte{ + // 185 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x2b, 0xce, 0x4c, 0x49, + 0xd5, 0x4f, 0xcf, 0xcd, 0xd5, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, + 0x2f, 0xc9, 0x17, 0xe2, 0x00, 0x89, 0xeb, 0xa5, 0xe7, 0xe6, 0x4a, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, + 0x83, 0x05, 0xf5, 0x41, 0x2c, 0x88, 0xbc, 0x94, 0x28, 0x5c, 0x5f, 0x41, 0x62, 0x51, 0x62, 0x2e, + 0x54, 0x9b, 0x92, 0x1d, 0x17, 0x8f, 0x3b, 0xc4, 0x9c, 0xe0, 0x92, 0xc4, 0x92, 0x54, 0x21, 0x3d, + 0x2e, 0x36, 0x88, 0xbc, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0x80, 0x1e, 0xcc, 0x5c, 0xbd, + 0x00, 0xb0, 0xb8, 0x13, 0xcb, 0x89, 0x7b, 0xf2, 0x0c, 0x41, 0x50, 0x55, 0x4e, 0x4e, 0x27, 0x1e, + 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, + 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0x10, 0xa5, 0x91, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, + 0x97, 0x9c, 0x9f, 0xab, 0x0f, 0x32, 0x03, 0x6c, 0x5f, 0x72, 0x7e, 0x0e, 0x98, 0xa3, 0x5f, 0x01, + 0x76, 0x4a, 0x49, 0x65, 0x41, 0x6a, 0x71, 0x12, 0x1b, 0x58, 0xca, 0x18, 0x10, 0x00, 0x00, 0xff, + 0xff, 0xd9, 0xaa, 0xc4, 0xf5, 0xdb, 0x00, 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 + { + 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)) + 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 + 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/gmm/types/genesis_test.go b/x/gmm/types/genesis_test.go new file mode 100644 index 00000000..b2457f84 --- /dev/null +++ b/x/gmm/types/genesis_test.go @@ -0,0 +1,41 @@ +package types_test + +import ( + "testing" + + "github.com/sideprotocol/side/x/gmm/types" + "github.com/stretchr/testify/require" +) + +func TestGenesisState_Validate(t *testing.T) { + tests := []struct { + desc string + genState *types.GenesisState + valid bool + }{ + { + desc: "default is valid", + genState: types.DefaultGenesis(), + valid: true, + }, + { + desc: "valid genesis state", + genState: &types.GenesisState{ + + // this line is used by starport scaffolding # types/genesis/validField + }, + valid: true, + }, + // this line is used by starport scaffolding # types/genesis/testcase + } + for _, tc := range tests { + 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/gmm/types/keys.go b/x/gmm/types/keys.go new file mode 100644 index 00000000..88ca6d8a --- /dev/null +++ b/x/gmm/types/keys.go @@ -0,0 +1,36 @@ +package types + +import fmt "fmt" + +const ( + // ModuleName defines the module name + ModuleName = "gmm" + + // StoreKey defines the primary module store key + StoreKey = ModuleName + + // RouterKey defines the module's message routing key + RouterKey = ModuleName + + // MemStoreKey defines the in-memory store key + MemStoreKey = "mem_gmm" + + Version = "side-1" + + GAMMTokenPrefix = "side/gamm/" +) + +var ( + // KeyPoolsPrefix defines prefix to store pools. + KeyPoolsPrefix = []byte{0x02} + KeyCurrentPoolCountPrefix = []byte{0x03} + KeyPoolIDToCountPrefix = []byte{0x04} +) + +func KeyPrefix(p string) []byte { + return []byte(p) +} + +func GetPoolShareDenom(poolID string) string { + return fmt.Sprintf("%s%s", GAMMTokenPrefix, poolID) +} diff --git a/x/gmm/types/message_add_liquidity.go b/x/gmm/types/message_add_liquidity.go new file mode 100644 index 00000000..cd2b14ca --- /dev/null +++ b/x/gmm/types/message_add_liquidity.go @@ -0,0 +1,64 @@ +package types + +import ( + "strings" + + sdkerrors "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const TypeMsgAddLiquidity = "add_liquidity" + +var _ sdk.Msg = &MsgAddLiquidity{} + +func NewMsgAddLiquidity( + sender, poolID string, + liquidity sdk.Coins, +) *MsgAddLiquidity { + return &MsgAddLiquidity{ + Sender: sender, + PoolId: poolID, + Liquidity: liquidity, + } +} + +func (msg *MsgAddLiquidity) Route() string { + return RouterKey +} + +func (msg *MsgAddLiquidity) Type() string { + return TypeMsgAddLiquidity +} + +func (msg *MsgAddLiquidity) GetSigners() []sdk.AccAddress { + Sender, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { + panic(err) + } + return []sdk.AccAddress{Sender} +} + +func (msg *MsgAddLiquidity) GetSignBytes() []byte { + bz := ModuleCdc.MustMarshalJSON(msg) + return sdk.MustSortJSON(bz) +} + +func (msg *MsgAddLiquidity) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { + return sdkerrors.Wrapf(ErrInvalidAddress, "invalid Sender address (%s)", err) + } + if strings.TrimSpace(msg.PoolId) == "" { + return sdkerrors.Wrap(ErrInvalidPoolID, "pool id cannot be empty") + } + if len(msg.Liquidity) > 2 || len(msg.Liquidity) == 0 { + return sdkerrors.Wrap(ErrInvalidLiquidityInLength, "liquidity cannot be empty or cannot be more than 2") + } + + for _, asset := range msg.Liquidity { + if asset.Amount.IsZero() { + return sdkerrors.Wrap(ErrInvalidLiquidityAmount, "liquidity amount cannot be zero") + } + } + return nil +} diff --git a/x/gmm/types/message_add_liquidity_test.go b/x/gmm/types/message_add_liquidity_test.go new file mode 100644 index 00000000..2340f33e --- /dev/null +++ b/x/gmm/types/message_add_liquidity_test.go @@ -0,0 +1,89 @@ +package types + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/testutil/sample" + "github.com/stretchr/testify/require" +) + +func TestMsgAddLiquidity_ValidateBasic(t *testing.T) { + tests := []struct { + name string + msg MsgAddLiquidity + err error + }{ + { + name: "invalid address", + msg: MsgAddLiquidity{ + Sender: "invalid_address", + }, + err: ErrInvalidAddress, + }, + { + name: "invalid poolID", + msg: MsgAddLiquidity{ + Sender: sample.AccAddress(), + PoolId: "", + }, + err: ErrInvalidPoolID, + }, + { + name: "invalid liquidity (length = 0)", + msg: MsgAddLiquidity{ + Sender: sample.AccAddress(), + PoolId: "test", + Liquidity: []sdk.Coin{}, + }, + err: ErrInvalidLiquidityInLength, + }, + { + name: "invalid liquidity (length > 2)", + msg: MsgAddLiquidity{ + Sender: sample.AccAddress(), + PoolId: "test", + Liquidity: []sdk.Coin{ + {Denom: "test1", Amount: sdk.NewInt(1000000000)}, + {Denom: "test2", Amount: sdk.NewInt(1000000000)}, + {Denom: "test3", Amount: sdk.NewInt(1000000000)}, + }, + }, + err: ErrInvalidLiquidityInLength, + }, + { + name: "invalid liquidity (amounts)", + msg: MsgAddLiquidity{ + Sender: sample.AccAddress(), + PoolId: "test", + Liquidity: []sdk.Coin{ + {Denom: "test", Amount: sdk.NewInt(0)}, + {Denom: "test2", Amount: sdk.NewInt(1000000000)}, + }, + }, + err: ErrInvalidLiquidityAmount, + }, + { + name: "valid addLiquidity message", + msg: MsgAddLiquidity{ + Sender: sample.AccAddress(), + PoolId: "test", + Liquidity: []sdk.Coin{ + {Denom: "test", Amount: sdk.NewInt(1000000000)}, + {Denom: "test2", Amount: sdk.NewInt(1000000000)}, + }, + }, + err: nil, + }, + } + 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/gmm/types/message_create_pool.go b/x/gmm/types/message_create_pool.go new file mode 100644 index 00000000..9727529a --- /dev/null +++ b/x/gmm/types/message_create_pool.go @@ -0,0 +1,123 @@ +package types + +import ( + sdkerrors "cosmossdk.io/errors" + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const TypeMsgCreatePool = "create_pool" + +var _ sdk.Msg = &MsgCreatePool{} + +func NewMsgCreatePool( + sender string, + params PoolParams, + liquidity []PoolAsset, +) *MsgCreatePool { + return &MsgCreatePool{ + Sender: sender, + Params: ¶ms, + Liquidity: liquidity, + } +} + +func (msg *MsgCreatePool) Route() string { + return RouterKey +} + +func (msg *MsgCreatePool) Type() string { + return TypeMsgCreatePool +} + +func (msg *MsgCreatePool) GetSigners() []sdk.AccAddress { + Sender, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { + panic(err) + } + return []sdk.AccAddress{Sender} +} + +func (msg *MsgCreatePool) GetSignBytes() []byte { + bz := ModuleCdc.MustMarshalJSON(msg) + return sdk.MustSortJSON(bz) +} + +func (msg *MsgCreatePool) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { + return sdkerrors.Wrapf(ErrInvalidAddress, "invalid Sender address (%s)", err) + } + if msg.Params == nil { + return ErrInvalidPoolParams + } + if msg.Liquidity == nil { + return ErrEmptyLiquidity + } + + if len(msg.Liquidity) != 2 { + return sdkerrors.Wrapf(ErrInvalidLiquidityInLength, "number of liquidity (%d)", len(msg.Liquidity)) + } + + if msg.Params.Amp.GT(sdkmath.NewInt(100)) { + return sdkerrors.Wrapf(ErrInvalidAmp, "amp (%d) is out of range", msg.Params.Amp) + } + totalWeight := sdkmath.NewInt(0) + for _, asset := range msg.Liquidity { + totalWeight = totalWeight.Add(*asset.Weight) + } + return nil +} + +func (msg *MsgCreatePool) GetPoolType() PoolType { + return msg.Params.Type +} + +// The Sender of the pool, who pays the PoolCreationFee, provides initial liquidity, +// and gets the initial LP shares. +func (msg *MsgCreatePool) PoolCreator() sdk.AccAddress { + return sdk.MustAccAddressFromBech32(msg.Sender) +} + +// Initial Liquidity for the pool that the sender is required to send to the pool account +func (msg *MsgCreatePool) InitialLiquidity() sdk.Coins { + liquidity := sdk.NewCoins() + for _, asset := range msg.Liquidity { + liquidity = liquidity.Add(asset.Token) + } + return liquidity +} + +// Return denom list of liquidity +func (msg *MsgCreatePool) GetAssetDenoms() []string { + denoms := []string{} + for _, asset := range msg.Liquidity { + denoms = append(denoms, asset.Token.Denom) + } + return denoms +} + +// Return denom list of liquidity +func (msg *MsgCreatePool) CreatePool() Pool { + // Extract denom list from Liquidity + denoms := msg.GetAssetDenoms() + + assets := make(map[string]PoolAsset) + totalShares := sdk.NewInt(0) + for _, liquidity := range msg.Liquidity { + assets[liquidity.Token.Denom] = liquidity + totalShares = totalShares.Add(liquidity.Token.Amount) + } + + // Generate new PoolId + newPoolID := GetPoolID(denoms) + poolShareBaseDenom := GetPoolShareDenom(newPoolID) + pool := Pool{ + PoolId: newPoolID, + Sender: msg.Sender, + PoolParams: *msg.Params, + Assets: assets, + TotalShares: sdk.NewCoin(poolShareBaseDenom, totalShares), + } + return pool +} diff --git a/x/gmm/types/message_create_pool_test.go b/x/gmm/types/message_create_pool_test.go new file mode 100644 index 00000000..2a8e336a --- /dev/null +++ b/x/gmm/types/message_create_pool_test.go @@ -0,0 +1,95 @@ +package types + +import ( + "testing" + + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/testutil/sample" + "github.com/stretchr/testify/require" +) + +func TestMsgCreatePool_ValidateBasic(t *testing.T) { + weight := sdkmath.NewInt(int64(50)) + tests := []struct { + name string + msg MsgCreatePool + err error + }{ + { + name: "invalid address", + msg: MsgCreatePool{ + Sender: "invalid_address", + }, + err: ErrInvalidAddress, + }, + { + name: "valid address, invalid PoolParams", + msg: MsgCreatePool{ + Sender: sample.AccAddress(), + Params: nil, + }, + err: ErrInvalidPoolParams, // Replace with the actual error + }, + { + name: "valid address, valid PoolParams, empty Liquidity", + msg: MsgCreatePool{ + Sender: sample.AccAddress(), + Params: &PoolParams{ + Type: PoolType_WEIGHT, + SwapFee: sdkmath.LegacyNewDec(int64(0)), + }, // Replace with a sample valid PoolParams + }, + err: ErrEmptyLiquidity, // Replace with the actual error + }, + { + name: "valid address, valid PoolParams, valid Liquidity", + msg: MsgCreatePool{ + Sender: sample.AccAddress(), + Params: &PoolParams{ + Type: PoolType_WEIGHT, + SwapFee: sdkmath.LegacyNewDec(int64(0)), + }, // Replace with a sample valid PoolParams + Liquidity: []PoolAsset{ + { + Token: sdk.NewCoin("test1", sdk.NewInt(100000000000000)), + Weight: &weight, + }, + }, // Replace with a sample valid Liquidity + }, + err: ErrInvalidLiquidityInLength, + }, + { + name: "valid address, valid PoolParams, valid Liquidity", + msg: MsgCreatePool{ + Sender: sample.AccAddress(), + Params: &PoolParams{ + Type: PoolType_WEIGHT, + SwapFee: sdkmath.LegacyNewDec(int64(0)), + Amp: &weight, + }, // Replace with a sample valid PoolParams + Liquidity: []PoolAsset{ + { + Token: sdk.NewCoin("test1", sdk.NewInt(100000000000000)), + Weight: &weight, + }, + { + Token: sdk.NewCoin("test2", sdk.NewInt(100000000000000)), + Weight: &weight, + }, + }, // Replace with a sample valid Liquidity + }, + err: nil, + }, + } + 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/gmm/types/message_swap.go b/x/gmm/types/message_swap.go new file mode 100644 index 00000000..6efd2f48 --- /dev/null +++ b/x/gmm/types/message_swap.go @@ -0,0 +1,71 @@ +package types + +import ( + "strings" + + sdkerrors "cosmossdk.io/errors" + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const TypeMsgSwap = "swap" + +var _ sdk.Msg = &MsgSwap{} + +func NewMsgSwap( + sender, poolID string, + tokenIn sdk.Coin, + tokenOut sdk.Coin, +) *MsgSwap { + return &MsgSwap{ + Sender: sender, + PoolId: poolID, + TokenIn: tokenIn, + TokenOut: tokenOut, + } +} + +func (msg *MsgSwap) Route() string { + return RouterKey +} + +func (msg *MsgSwap) Type() string { + return TypeMsgSwap +} + +func (msg *MsgSwap) GetSigners() []sdk.AccAddress { + Sender, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { + panic(err) + } + return []sdk.AccAddress{Sender} +} + +func (msg *MsgSwap) GetSignBytes() []byte { + bz := ModuleCdc.MustMarshalJSON(msg) + return sdk.MustSortJSON(bz) +} + +func (msg *MsgSwap) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { + return sdkerrors.Wrapf(ErrInvalidAddress, "invalid Sender address (%s)", err) + } + + if strings.TrimSpace(msg.PoolId) == "" { + return sdkerrors.Wrap(ErrInvalidPoolID, "pool id cannot be empty") + } + + if msg.TokenIn.Amount.IsZero() { + return sdkerrors.Wrap(ErrInvalidTokenAmount, "tokenIn amount cannot be zero") + } + + if msg.TokenOut.Amount.IsZero() { + return sdkerrors.Wrap(ErrInvalidTokenAmount, "tokenOut amount cannot be zero") + } + + if msg.Slippage.IsNegative() || msg.Slippage.GTE(sdkmath.NewInt(100)) { + return sdkerrors.Wrap(ErrInvalidSlippage, "slippage should be ranged from 0 to 100") + } + return nil +} diff --git a/x/gmm/types/message_swap_test.go b/x/gmm/types/message_swap_test.go new file mode 100644 index 00000000..a021d6eb --- /dev/null +++ b/x/gmm/types/message_swap_test.go @@ -0,0 +1,64 @@ +package types + +import ( + "testing" + + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/testutil/sample" + "github.com/stretchr/testify/require" +) + +func TestMsgSwap_ValidateBasic(t *testing.T) { + tests := []struct { + name string + msg MsgSwap + err error + }{ + { + name: "invalid address", + msg: MsgSwap{ + Sender: "invalid_address", + }, + err: ErrInvalidAddress, + }, + { + name: "invalid poolID", + msg: MsgSwap{ + Sender: sample.AccAddress(), + PoolId: "", + }, + err: ErrInvalidPoolID, + }, + { + name: "invalid tokenIn", + msg: MsgSwap{ + Sender: sample.AccAddress(), + PoolId: "test1", + TokenIn: sdk.NewCoin("test1", sdk.NewInt(0)), + }, + err: ErrInvalidTokenAmount, + }, + { + name: "invalid slippage", + msg: MsgSwap{ + Sender: sample.AccAddress(), + PoolId: "test1", + TokenIn: sdk.NewCoin("test1", sdk.NewInt(100)), + TokenOut: sdk.NewCoin("test2", sdk.NewInt(100)), + Slippage: sdkmath.NewInt(10000), + }, + err: ErrInvalidSlippage, + }, + } + 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/gmm/types/message_withdraw.go b/x/gmm/types/message_withdraw.go new file mode 100644 index 00000000..f2800c47 --- /dev/null +++ b/x/gmm/types/message_withdraw.go @@ -0,0 +1,66 @@ +package types + +import ( + "strings" + + sdkerrors "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const TypeMsgWithdraw = "withdraw" + +var _ sdk.Msg = &MsgWithdraw{} + +func NewMsgWithdraw( + sender, poolID, receiver string, + share sdk.Coin, +) *MsgWithdraw { + return &MsgWithdraw{ + Sender: sender, + Receiver: receiver, + PoolId: poolID, + Share: share, + } +} + +func (msg *MsgWithdraw) Route() string { + return RouterKey +} + +func (msg *MsgWithdraw) Type() string { + return TypeMsgWithdraw +} + +func (msg *MsgWithdraw) GetSigners() []sdk.AccAddress { + Sender, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { + panic(err) + } + return []sdk.AccAddress{Sender} +} + +func (msg *MsgWithdraw) GetSignBytes() []byte { + bz := ModuleCdc.MustMarshalJSON(msg) + return sdk.MustSortJSON(bz) +} + +func (msg *MsgWithdraw) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(msg.Sender) + if err != nil { + return sdkerrors.Wrapf(ErrInvalidAddress, "invalid Sender address (%s)", err) + } + + _, err = sdk.AccAddressFromBech32(msg.Receiver) + if err != nil { + return sdkerrors.Wrapf(ErrInvalidAddress, "invalid receiver address (%s)", err) + } + + if strings.TrimSpace(msg.PoolId) == "" { + return sdkerrors.Wrap(ErrInvalidPoolID, "pool id cannot be empty") + } + + if msg.Share.Amount.IsZero() { + return sdkerrors.Wrap(ErrInvalidTokenAmount, "share amount cannot be zero") + } + return nil +} diff --git a/x/gmm/types/message_withdraw_test.go b/x/gmm/types/message_withdraw_test.go new file mode 100644 index 00000000..4bc57cf2 --- /dev/null +++ b/x/gmm/types/message_withdraw_test.go @@ -0,0 +1,77 @@ +package types + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/sideprotocol/side/testutil/sample" + "github.com/stretchr/testify/require" +) + +func TestMsgWithdraw_ValidateBasic(t *testing.T) { + tests := []struct { + name string + msg MsgWithdraw + err error + }{ + { + name: "invalid address", + msg: MsgWithdraw{ + Sender: "invalid_address", + }, + err: ErrInvalidAddress, + }, + { + name: "invalid receiver address", + msg: MsgWithdraw{ + Sender: sample.AccAddress(), + Receiver: "invalid_address", + }, + err: ErrInvalidAddress, + }, + { + name: "invalid poolID", + msg: MsgWithdraw{ + Sender: sample.AccAddress(), + Receiver: sample.AccAddress(), + PoolId: "", + }, + err: ErrInvalidPoolID, + }, + { + name: "invalid share amount", + msg: MsgWithdraw{ + Sender: sample.AccAddress(), + Receiver: sample.AccAddress(), + PoolId: "test1", + Share: sdk.NewCoin( + "test", + sdk.NewInt(0), + ), + }, + err: ErrInvalidTokenAmount, + }, + { + name: "valid message", + msg: MsgWithdraw{ + Sender: sample.AccAddress(), + Receiver: sample.AccAddress(), + PoolId: "test1", + Share: sdk.NewCoin( + "test", + sdk.NewInt(10), + ), + }, + }, + } + 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/gmm/types/params.go b/x/gmm/types/params.go new file mode 100644 index 00000000..357196ad --- /dev/null +++ b/x/gmm/types/params.go @@ -0,0 +1,39 @@ +package types + +import ( + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + "gopkg.in/yaml.v2" +) + +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() Params { + return Params{} +} + +// DefaultParams returns a default set of parameters +func DefaultParams() Params { + return NewParams() +} + +// ParamSetPairs get the params.ParamSet +func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { + return paramtypes.ParamSetPairs{} +} + +// Validate validates the set of params +func (p Params) Validate() error { + return nil +} + +// String implements the Stringer interface. +func (p Params) String() string { + out, _ := yaml.Marshal(p) + return string(out) +} diff --git a/x/gmm/types/params.pb.go b/x/gmm/types/params.pb.go new file mode 100644 index 00000000..3c143017 --- /dev/null +++ b/x/gmm/types/params.pb.go @@ -0,0 +1,300 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: side/gmm/params.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 + +// Params defines the parameters for the module. +type Params struct { + PoolCreationFee uint64 `protobuf:"varint,1,opt,name=poolCreationFee,proto3" json:"poolCreationFee,omitempty"` +} + +func (m *Params) Reset() { *m = Params{} } +func (*Params) ProtoMessage() {} +func (*Params) Descriptor() ([]byte, []int) { + return fileDescriptor_4c84a837bd35a8a4, []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) GetPoolCreationFee() uint64 { + if m != nil { + return m.PoolCreationFee + } + return 0 +} + +func init() { + proto.RegisterType((*Params)(nil), "side.gmm.Params") +} + +func init() { proto.RegisterFile("side/gmm/params.proto", fileDescriptor_4c84a837bd35a8a4) } + +var fileDescriptor_4c84a837bd35a8a4 = []byte{ + // 172 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x2d, 0xce, 0x4c, 0x49, + 0xd5, 0x4f, 0xcf, 0xcd, 0xd5, 0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, + 0xc9, 0x17, 0xe2, 0x00, 0x09, 0xeb, 0xa5, 0xe7, 0xe6, 0x4a, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, 0x83, + 0x05, 0xf5, 0x41, 0x2c, 0x88, 0xbc, 0x92, 0x05, 0x17, 0x5b, 0x00, 0x58, 0xbd, 0x90, 0x06, 0x17, + 0x7f, 0x41, 0x7e, 0x7e, 0x8e, 0x73, 0x51, 0x6a, 0x62, 0x49, 0x66, 0x7e, 0x9e, 0x5b, 0x6a, 0xaa, + 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x4b, 0x10, 0xba, 0xb0, 0x15, 0xcb, 0x8c, 0x05, 0xf2, 0x0c, 0x4e, + 0x4e, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, + 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0x10, 0xa5, 0x91, 0x9e, 0x59, 0x92, + 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x0f, 0xb2, 0x1e, 0x6c, 0x53, 0x72, 0x7e, 0x0e, 0x98, + 0xa3, 0x5f, 0x01, 0x76, 0x64, 0x49, 0x65, 0x41, 0x6a, 0x71, 0x12, 0x1b, 0x58, 0xca, 0x18, 0x10, + 0x00, 0x00, 0xff, 0xff, 0xa7, 0x0f, 0xab, 0x44, 0xbd, 0x00, 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 m.PoolCreationFee != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.PoolCreationFee)) + 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.PoolCreationFee != 0 { + n += 1 + sovParams(uint64(m.PoolCreationFee)) + } + 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 PoolCreationFee", wireType) + } + m.PoolCreationFee = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PoolCreationFee |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + 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/gmm/types/pool.go b/x/gmm/types/pool.go new file mode 100644 index 00000000..7533c994 --- /dev/null +++ b/x/gmm/types/pool.go @@ -0,0 +1,153 @@ +package types + +import ( + "crypto/sha256" + + sdkmath "cosmossdk.io/math" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func (p *Pool) GetAssetDenoms() []string { + denoms := []string{} + for _, asset := range p.Assets { + denoms = append(denoms, asset.Token.Denom) + } + return denoms +} + +func GetEscrowAddress(poolID string) sdk.AccAddress { + // a slash is used to create domain separation between port and channel identifiers to + // prevent address collisions between escrow addresses created for different channels + + // ADR 028 AddressHash construction + preImage := []byte(Version) + preImage = append(preImage, 0) + preImage = append(preImage, poolID...) + hash := sha256.Sum256(preImage) + return hash[:20] +} + +// EstimateShare estimate share amount when user deposit +func (p *Pool) EstimateShare(coins sdk.Coins) (sdk.Coin, error) { + switch p.PoolParams.Type { + case PoolType_WEIGHT: + return p.estimateShareInWeightPool(coins) + case PoolType_STABLE: + return p.estimateShareInStablePool(coins) + } + return sdk.Coin{}, ErrInvalidPoolType +} + +func (p *Pool) EstimateSwap(amountIn sdk.Coin, denomOut string) (sdk.Coin, error) { + switch p.PoolParams.Type { + case PoolType_WEIGHT: + return p.estimateSwapInWeightPool(amountIn, denomOut) + case PoolType_STABLE: + return p.estimateSwapInStablePool(amountIn, denomOut) + } + return sdk.Coin{}, ErrInvalidPoolType +} + +// Withdraw tokens from pool +func (p *Pool) EstimateWithdrawals(share sdk.Coin) ([]sdk.Coin, error) { + switch p.PoolParams.Type { + case PoolType_WEIGHT: + return p.estimateWithdrawalsFromWeightPool(share) + case PoolType_STABLE: + return p.estimateWithdrawalsFromStablePool(share) + } + return []sdk.Coin{}, ErrInvalidPoolType +} + +// Helper functions +func (p *Pool) TakeFees(amount sdkmath.Int) sdk.Dec { + amountDec := sdk.NewDecFromInt(amount) + feeRate := p.PoolParams.SwapFee.Quo(sdk.NewDec(10000)) + fees := amountDec.Mul(feeRate) + amountMinusFees := amountDec.Sub(fees) + return amountMinusFees +} + +// IncreaseShare add xx amount share to total share amount in pool +func (p *Pool) IncreaseShare(amt sdkmath.Int) { + p.TotalShares.Amount = p.TotalShares.Amount.Add(amt) +} + +// DecreaseShare subtract xx amount share to total share amount in pool +func (p *Pool) DecreaseShare(amt sdkmath.Int) { + p.TotalShares.Amount = p.TotalShares.Amount.Sub(amt) +} + +// IncreaseLiquidity adds xx amount liquidity to assets in pool +func (p *Pool) IncreaseLiquidity(coins []sdk.Coin) error { + for _, coin := range coins { + asset, exists := p.Assets[coin.Denom] + if !exists { + return ErrNotFoundAssetInPool + } + // Add liquidity logic here + asset.Token.Amount = asset.Token.Amount.Add(coin.Amount) + p.Assets[coin.Denom] = asset + } + // Update TotalShares or other fields if necessary + return nil +} + +// DecreaseLiquidity subtracts xx amount liquidity from assets in pool +func (p *Pool) DecreaseLiquidity(coins []sdk.Coin) error { + for _, coin := range coins { + asset, exists := p.Assets[coin.Denom] + if !exists { + return ErrNotFoundAssetInPool + } + // Add liquidity logic here + asset.Token.Amount = asset.Token.Amount.Sub(coin.Amount) + p.Assets[coin.Denom] = asset + } + // Update TotalShares or other fields if necessary + return nil +} + +// findAssetByDenom finds pool asset by denom +func (p *Pool) findAssetByDenom(denom string) (PoolAsset, error) { + for _, asset := range p.Assets { + if asset.Token.Denom == denom { + return asset, nil + } + } + return PoolAsset{}, ErrNotFoundAssetInPool +} + +func (p *Pool) GetAssetList() []PoolAsset { + assets := make([]PoolAsset, 0) + if p != nil { + for _, asset := range p.Assets { + assets = append(assets, asset) + } + return assets + } + return nil +} + +func (p *Pool) GetLiquidity() sdk.Coins { + assets := sdk.NewCoins() + if p != nil { + for _, asset := range p.Assets { + assets = assets.Add(asset.Token) + } + return assets + } + return nil +} + +func (p *Pool) Sum() sdkmath.Int { + sum := sdkmath.ZeroInt() + if p != nil { + for _, asset := range p.Assets { + sum = sum.Add(asset.Token.Amount) + } + return sum + } + return sdk.ZeroInt() +} diff --git a/x/gmm/types/pool.pb.go b/x/gmm/types/pool.pb.go new file mode 100644 index 00000000..4ae8c659 --- /dev/null +++ b/x/gmm/types/pool.pb.go @@ -0,0 +1,661 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: side/gmm/pool.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + 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 Pool struct { + PoolId string `protobuf:"bytes,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` + Sender string `protobuf:"bytes,2,opt,name=sender,proto3" json:"sender,omitempty"` + PoolParams PoolParams `protobuf:"bytes,3,opt,name=poolParams,proto3" json:"poolParams"` + Assets map[string]PoolAsset `protobuf:"bytes,4,rep,name=assets,proto3" json:"assets" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` + // sum of all LP tokens sent out + TotalShares types.Coin `protobuf:"bytes,5,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_539300364e2e3e52, []int{0} +} +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 (m *Pool) GetPoolId() string { + if m != nil { + return m.PoolId + } + return "" +} + +func (m *Pool) GetSender() string { + if m != nil { + return m.Sender + } + return "" +} + +func (m *Pool) GetPoolParams() PoolParams { + if m != nil { + return m.PoolParams + } + return PoolParams{} +} + +func (m *Pool) GetAssets() map[string]PoolAsset { + if m != nil { + return m.Assets + } + return nil +} + +func (m *Pool) GetTotalShares() types.Coin { + if m != nil { + return m.TotalShares + } + return types.Coin{} +} + +func init() { + proto.RegisterType((*Pool)(nil), "side.gmm.Pool") + proto.RegisterMapType((map[string]PoolAsset)(nil), "side.gmm.Pool.AssetsEntry") +} + +func init() { proto.RegisterFile("side/gmm/pool.proto", fileDescriptor_539300364e2e3e52) } + +var fileDescriptor_539300364e2e3e52 = []byte{ + // 397 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x54, 0x92, 0x3f, 0x8e, 0xd4, 0x30, + 0x14, 0xc6, 0x93, 0xf9, 0x13, 0x58, 0x87, 0x02, 0x79, 0x56, 0x90, 0x0d, 0x52, 0x76, 0x34, 0x55, + 0x28, 0xb0, 0xb5, 0x43, 0xb3, 0x4a, 0x47, 0x10, 0xc5, 0x36, 0x68, 0x14, 0x2a, 0x68, 0x46, 0x4e, + 0x62, 0x65, 0x23, 0xe2, 0x38, 0x8a, 0xbd, 0x2b, 0x72, 0x0b, 0x0e, 0xc3, 0x21, 0x46, 0x54, 0x53, + 0x52, 0x8d, 0xd0, 0xe4, 0x06, 0x9c, 0x00, 0xd9, 0xce, 0xac, 0x26, 0x9d, 0xbf, 0xf7, 0xfb, 0x3e, + 0x3f, 0xbf, 0x97, 0x80, 0x85, 0x28, 0x73, 0x8a, 0x0b, 0xc6, 0x70, 0xc3, 0x79, 0x85, 0x9a, 0x96, + 0x4b, 0x0e, 0x9f, 0xab, 0x22, 0x2a, 0x18, 0xf3, 0xfd, 0x11, 0xde, 0x36, 0xa4, 0x25, 0x4c, 0x18, + 0x97, 0x7f, 0x35, 0x66, 0x44, 0x08, 0x2a, 0x07, 0x74, 0x59, 0xf0, 0x82, 0xeb, 0x23, 0x56, 0xa7, + 0xa1, 0x1a, 0x64, 0x5c, 0x30, 0x2e, 0x70, 0x4a, 0x04, 0xc5, 0x8f, 0x37, 0x29, 0x95, 0xe4, 0x06, + 0x67, 0xbc, 0xac, 0x4f, 0x17, 0x1a, 0xbe, 0x35, 0x41, 0x23, 0x0c, 0x5a, 0xf5, 0x13, 0x30, 0xdb, + 0x70, 0x5e, 0xc1, 0xd7, 0xe0, 0x99, 0xee, 0x56, 0xe6, 0x9e, 0xbd, 0xb4, 0xc3, 0x8b, 0xc4, 0x51, + 0xf2, 0x2e, 0x87, 0xaf, 0x80, 0x23, 0x68, 0x9d, 0xd3, 0xd6, 0x9b, 0x98, 0xba, 0x51, 0x30, 0x02, + 0x40, 0x39, 0x36, 0xfa, 0xe5, 0xde, 0x74, 0x69, 0x87, 0xee, 0xfa, 0x12, 0x9d, 0x06, 0x44, 0x9b, + 0x27, 0x16, 0xcf, 0x76, 0x87, 0x6b, 0x2b, 0x39, 0x73, 0xc3, 0x5b, 0xe0, 0xe8, 0xa9, 0x84, 0x37, + 0x5b, 0x4e, 0x43, 0x77, 0xed, 0x8f, 0x73, 0xe8, 0x83, 0x86, 0x9f, 0x6a, 0xd9, 0x76, 0x43, 0x7a, + 0xf0, 0xc3, 0xaf, 0xe0, 0x85, 0xe4, 0x92, 0x54, 0x5b, 0x71, 0x4f, 0x5a, 0x2a, 0xbc, 0xb9, 0xee, + 0x7b, 0x85, 0x86, 0xa1, 0xd4, 0x06, 0xd0, 0xb0, 0x01, 0xf4, 0x91, 0x97, 0x75, 0xfc, 0x46, 0xc5, + 0xff, 0x1d, 0xae, 0x17, 0x1d, 0x61, 0x55, 0xb4, 0x3a, 0x0f, 0xaf, 0x12, 0x57, 0xcb, 0x2f, 0x5a, + 0xf9, 0x9f, 0x81, 0x7b, 0xd6, 0x17, 0xbe, 0x04, 0xd3, 0xef, 0xb4, 0x1b, 0x96, 0xa1, 0x8e, 0xf0, + 0x2d, 0x98, 0x3f, 0x92, 0xea, 0x81, 0xea, 0x45, 0xb8, 0xeb, 0xc5, 0xf8, 0xd1, 0x3a, 0x9b, 0x18, + 0x47, 0x34, 0xb9, 0xb5, 0xa3, 0x8b, 0xdf, 0xbf, 0xde, 0xcd, 0x15, 0xb9, 0x8b, 0xe3, 0xdd, 0x31, + 0xb0, 0xf7, 0xc7, 0xc0, 0xfe, 0x7b, 0x0c, 0xec, 0x9f, 0x7d, 0x60, 0xed, 0xfb, 0xc0, 0xfa, 0xd3, + 0x07, 0xd6, 0xb7, 0xb0, 0x28, 0xe5, 0xfd, 0x43, 0x8a, 0x32, 0xce, 0xb0, 0xba, 0x4e, 0x7f, 0x95, + 0x8c, 0x57, 0x5a, 0xe0, 0x1f, 0xfa, 0x2f, 0x90, 0x5d, 0x43, 0x45, 0xea, 0x68, 0xf4, 0xfe, 0x7f, + 0x00, 0x00, 0x00, 0xff, 0xff, 0x0e, 0xf2, 0xcd, 0xbe, 0x59, 0x02, 0x00, 0x00, +} + +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] = 0x2a + if len(m.Assets) > 0 { + for k := range m.Assets { + v := m.Assets[k] + baseI := i + { + size, err := (&v).MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintPool(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + i -= len(k) + copy(dAtA[i:], k) + i = encodeVarintPool(dAtA, i, uint64(len(k))) + i-- + dAtA[i] = 0xa + i = encodeVarintPool(dAtA, i, uint64(baseI-i)) + 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.Sender) > 0 { + i -= len(m.Sender) + copy(dAtA[i:], m.Sender) + i = encodeVarintPool(dAtA, i, uint64(len(m.Sender))) + i-- + dAtA[i] = 0x12 + } + if len(m.PoolId) > 0 { + i -= len(m.PoolId) + copy(dAtA[i:], m.PoolId) + i = encodeVarintPool(dAtA, i, uint64(len(m.PoolId))) + i-- + dAtA[i] = 0xa + } + 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 *Pool) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.PoolId) + if l > 0 { + n += 1 + l + sovPool(uint64(l)) + } + l = len(m.Sender) + if l > 0 { + n += 1 + l + sovPool(uint64(l)) + } + l = m.PoolParams.Size() + n += 1 + l + sovPool(uint64(l)) + if len(m.Assets) > 0 { + for k, v := range m.Assets { + _ = k + _ = v + l = v.Size() + mapEntrySize := 1 + len(k) + sovPool(uint64(len(k))) + 1 + l + sovPool(uint64(l)) + n += mapEntrySize + 1 + sovPool(uint64(mapEntrySize)) + } + } + 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 *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 != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", 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.PoolId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + 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 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.Sender = 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 Assets", 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 m.Assets == nil { + m.Assets = make(map[string]PoolAsset) + } + var mapkey string + mapvalue := &PoolAsset{} + for iNdEx < postIndex { + entryPreIndex := 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) + if fieldNum == 1 { + var stringLenmapkey uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPool + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLenmapkey |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLenmapkey := int(stringLenmapkey) + if intStringLenmapkey < 0 { + return ErrInvalidLengthPool + } + postStringIndexmapkey := iNdEx + intStringLenmapkey + if postStringIndexmapkey < 0 { + return ErrInvalidLengthPool + } + if postStringIndexmapkey > l { + return io.ErrUnexpectedEOF + } + mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) + iNdEx = postStringIndexmapkey + } else if fieldNum == 2 { + var mapmsglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPool + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + mapmsglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if mapmsglen < 0 { + return ErrInvalidLengthPool + } + postmsgIndex := iNdEx + mapmsglen + if postmsgIndex < 0 { + return ErrInvalidLengthPool + } + if postmsgIndex > l { + return io.ErrUnexpectedEOF + } + mapvalue = &PoolAsset{} + if err := mapvalue.Unmarshal(dAtA[iNdEx:postmsgIndex]); err != nil { + return err + } + iNdEx = postmsgIndex + } else { + iNdEx = entryPreIndex + skippy, err := skipPool(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthPool + } + if (iNdEx + skippy) > postIndex { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + m.Assets[mapkey] = *mapvalue + iNdEx = postIndex + case 5: + 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/gmm/types/pool_asset.pb.go b/x/gmm/types/pool_asset.pb.go new file mode 100644 index 00000000..e18f13b5 --- /dev/null +++ b/x/gmm/types/pool_asset.pb.go @@ -0,0 +1,427 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: side/gmm/pool_asset.proto + +package types + +import ( + fmt "fmt" + 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 + +type PoolAsset struct { + Token types.Coin `protobuf:"bytes,1,opt,name=token,proto3" json:"token"` + 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,omitempty"` + Decimal github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=decimal,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"decimal"` +} + +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_4ee275418d4be35a, []int{0} +} +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{} +} + +func init() { + proto.RegisterType((*PoolAsset)(nil), "side.gmm.PoolAsset") +} + +func init() { proto.RegisterFile("side/gmm/pool_asset.proto", fileDescriptor_4ee275418d4be35a) } + +var fileDescriptor_4ee275418d4be35a = []byte{ + // 276 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x90, 0xbb, 0x4e, 0xc3, 0x30, + 0x14, 0x86, 0x63, 0x2e, 0x85, 0x86, 0x2d, 0x62, 0x48, 0x3b, 0xb8, 0x15, 0x03, 0x8a, 0x90, 0xb0, + 0x55, 0x10, 0x0f, 0x80, 0x59, 0x60, 0x43, 0x1d, 0x59, 0x50, 0xe2, 0x58, 0xae, 0xd5, 0x38, 0x27, + 0xc2, 0xe6, 0xf6, 0x16, 0x3c, 0x56, 0xc7, 0x8c, 0x88, 0xa1, 0x42, 0xc9, 0x8b, 0x20, 0xdb, 0x41, + 0x62, 0x65, 0xf2, 0xe5, 0xf7, 0xf7, 0xf9, 0xe8, 0x8f, 0x27, 0x46, 0x95, 0x82, 0x4a, 0xad, 0x69, + 0x03, 0x50, 0x3d, 0xe6, 0xc6, 0x08, 0x4b, 0x9a, 0x27, 0xb0, 0x90, 0x1c, 0xba, 0x88, 0x48, 0xad, + 0xa7, 0xc7, 0x12, 0x24, 0xf8, 0x4b, 0xea, 0x76, 0x21, 0x9f, 0x62, 0x0e, 0x46, 0x83, 0xa1, 0x45, + 0x6e, 0x04, 0x7d, 0x59, 0x14, 0xc2, 0xe6, 0x0b, 0xca, 0x41, 0xd5, 0x21, 0x3f, 0x69, 0x51, 0x3c, + 0xbe, 0x07, 0xa8, 0xae, 0x9d, 0x33, 0xb9, 0x8a, 0xf7, 0x2d, 0xac, 0x45, 0x9d, 0xa2, 0x39, 0xca, + 0x8e, 0x2e, 0x26, 0x24, 0xd0, 0xc4, 0xd1, 0x64, 0xa0, 0xc9, 0x0d, 0xa8, 0x9a, 0xed, 0x6d, 0xb6, + 0xb3, 0x68, 0x19, 0x5e, 0x27, 0x2c, 0x1e, 0xbd, 0x0a, 0x25, 0x57, 0x36, 0xdd, 0x99, 0xa3, 0x6c, + 0xcc, 0xce, 0xbe, 0xb6, 0xb3, 0x53, 0xa9, 0xec, 0xea, 0xb9, 0x20, 0x1c, 0x34, 0x1d, 0x66, 0x08, + 0xcb, 0xb9, 0x29, 0xd7, 0xd4, 0xbe, 0x37, 0xc2, 0x90, 0xbb, 0xda, 0x2e, 0x07, 0x32, 0xb9, 0x8d, + 0x0f, 0x4a, 0xc1, 0x95, 0xce, 0xab, 0x74, 0xd7, 0x4b, 0x88, 0xfb, 0xe1, 0x1f, 0xa2, 0x5f, 0x9c, + 0xb1, 0x4d, 0x87, 0x51, 0xdb, 0x61, 0xf4, 0xdd, 0x61, 0xf4, 0xd1, 0xe3, 0xa8, 0xed, 0x71, 0xf4, + 0xd9, 0xe3, 0xe8, 0x21, 0xfb, 0xa3, 0x72, 0xbd, 0xf9, 0x0a, 0x38, 0x54, 0xfe, 0x40, 0xdf, 0x7c, + 0xc3, 0x5e, 0x58, 0x8c, 0x7c, 0x74, 0xf9, 0x13, 0x00, 0x00, 0xff, 0xff, 0xb4, 0x83, 0x2b, 0x28, + 0x7a, 0x01, 0x00, 0x00, +} + +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.Decimal.Size() + i -= size + if _, err := m.Decimal.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintPoolAsset(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if m.Weight != nil { + { + size := m.Weight.Size() + i -= size + if _, err := m.Weight.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintPoolAsset(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + { + size, err := m.Token.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintPoolAsset(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintPoolAsset(dAtA []byte, offset int, v uint64) int { + offset -= sovPoolAsset(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *PoolAsset) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Token.Size() + n += 1 + l + sovPoolAsset(uint64(l)) + if m.Weight != nil { + l = m.Weight.Size() + n += 1 + l + sovPoolAsset(uint64(l)) + } + l = m.Decimal.Size() + n += 1 + l + sovPoolAsset(uint64(l)) + return n +} + +func sovPoolAsset(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozPoolAsset(x uint64) (n int) { + return sovPoolAsset(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +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 ErrIntOverflowPoolAsset + } + 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 ErrIntOverflowPoolAsset + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthPoolAsset + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthPoolAsset + } + 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 ErrIntOverflowPoolAsset + } + 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 ErrInvalidLengthPoolAsset + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPoolAsset + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + var v github_com_cosmos_cosmos_sdk_types.Int + m.Weight = &v + if err := m.Weight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Decimal", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPoolAsset + } + 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 ErrInvalidLengthPoolAsset + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPoolAsset + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Decimal.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPoolAsset(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthPoolAsset + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipPoolAsset(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, ErrIntOverflowPoolAsset + } + 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, ErrIntOverflowPoolAsset + } + 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, ErrIntOverflowPoolAsset + } + 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, ErrInvalidLengthPoolAsset + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupPoolAsset + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthPoolAsset + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthPoolAsset = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowPoolAsset = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupPoolAsset = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/gmm/types/pool_params.pb.go b/x/gmm/types/pool_params.pb.go new file mode 100644 index 00000000..2aff0a78 --- /dev/null +++ b/x/gmm/types/pool_params.pb.go @@ -0,0 +1,526 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: side/gmm/pool_params.proto + +package types + +import ( + fmt "fmt" + github_com_cosmos_cosmos_sdk_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 PoolType int32 + +const ( + PoolType_WEIGHT PoolType = 0 + PoolType_STABLE PoolType = 1 +) + +var PoolType_name = map[int32]string{ + 0: "WEIGHT", + 1: "STABLE", +} + +var PoolType_value = map[string]int32{ + "WEIGHT": 0, + "STABLE": 1, +} + +func (x PoolType) String() string { + return proto.EnumName(PoolType_name, int32(x)) +} + +func (PoolType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_1be1bba6d1ee211c, []int{0} +} + +type PoolParams struct { + Type PoolType `protobuf:"varint,1,opt,name=type,proto3,enum=side.gmm.PoolType" json:"type,omitempty"` + // swapFee is ranged from 0 to 10000. + SwapFee github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=swapFee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"swapFee"` + ExitFee github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=exitFee,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"exitFee"` + UseOracle bool `protobuf:"varint,4,opt,name=useOracle,proto3" json:"useOracle,omitempty"` + // Amplifier parameters for stable pool. + Amp *github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,5,opt,name=amp,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"amp,omitempty"` +} + +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_1be1bba6d1ee211c, []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) GetType() PoolType { + if m != nil { + return m.Type + } + return PoolType_WEIGHT +} + +func (m *PoolParams) GetUseOracle() bool { + if m != nil { + return m.UseOracle + } + return false +} + +func init() { + proto.RegisterEnum("side.gmm.PoolType", PoolType_name, PoolType_value) + proto.RegisterType((*PoolParams)(nil), "side.gmm.PoolParams") +} + +func init() { proto.RegisterFile("side/gmm/pool_params.proto", fileDescriptor_1be1bba6d1ee211c) } + +var fileDescriptor_1be1bba6d1ee211c = []byte{ + // 312 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2a, 0xce, 0x4c, 0x49, + 0xd5, 0x4f, 0xcf, 0xcd, 0xd5, 0x2f, 0xc8, 0xcf, 0xcf, 0x89, 0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x2d, + 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x00, 0xc9, 0xe9, 0xa5, 0xe7, 0xe6, 0x4a, 0x89, + 0xa4, 0xe7, 0xa7, 0xe7, 0x83, 0x05, 0xf5, 0x41, 0x2c, 0x88, 0xbc, 0xd2, 0x12, 0x26, 0x2e, 0xae, + 0x80, 0xfc, 0xfc, 0x9c, 0x00, 0xb0, 0x26, 0x21, 0x35, 0x2e, 0x96, 0x92, 0xca, 0x82, 0x54, 0x09, + 0x46, 0x05, 0x46, 0x0d, 0x3e, 0x23, 0x21, 0x3d, 0x98, 0x6e, 0x3d, 0x90, 0x9a, 0x90, 0xca, 0x82, + 0xd4, 0x20, 0xb0, 0xbc, 0x90, 0x07, 0x17, 0x7b, 0x71, 0x79, 0x62, 0x81, 0x5b, 0x6a, 0xaa, 0x04, + 0x93, 0x02, 0xa3, 0x06, 0xa7, 0x93, 0xde, 0x89, 0x7b, 0xf2, 0x0c, 0xb7, 0xee, 0xc9, 0xab, 0xa5, + 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x27, 0xe7, 0x17, 0xe7, 0xe6, 0x17, + 0x43, 0x29, 0xdd, 0xe2, 0x94, 0x6c, 0x7d, 0x90, 0xde, 0x62, 0x3d, 0x97, 0xd4, 0xe4, 0x20, 0x98, + 0x76, 0x90, 0x49, 0xa9, 0x15, 0x99, 0x25, 0x20, 0x93, 0x98, 0xc9, 0x33, 0x09, 0xaa, 0x5d, 0x48, + 0x86, 0x8b, 0xb3, 0xb4, 0x38, 0xd5, 0xbf, 0x28, 0x31, 0x39, 0x27, 0x55, 0x82, 0x45, 0x81, 0x51, + 0x83, 0x23, 0x08, 0x21, 0x20, 0x64, 0xc3, 0xc5, 0x9c, 0x98, 0x5b, 0x20, 0xc1, 0x0a, 0xb6, 0x43, + 0x8b, 0x48, 0xf3, 0x3d, 0xf3, 0x4a, 0x82, 0x40, 0xda, 0xb4, 0x94, 0xb8, 0x38, 0x60, 0x21, 0x20, + 0xc4, 0xc5, 0xc5, 0x16, 0xee, 0xea, 0xe9, 0xee, 0x11, 0x22, 0xc0, 0x00, 0x62, 0x07, 0x87, 0x38, + 0x3a, 0xf9, 0xb8, 0x0a, 0x30, 0x3a, 0x39, 0x9d, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, + 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x5c, 0x78, 0x2c, 0xc7, 0x70, 0xe3, 0xb1, 0x1c, + 0x43, 0x94, 0x06, 0x92, 0x55, 0xa0, 0x10, 0x05, 0x07, 0x7d, 0x72, 0x7e, 0x0e, 0x98, 0xa3, 0x5f, + 0x01, 0x8e, 0x3a, 0xb0, 0x85, 0x49, 0x6c, 0x60, 0x29, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, + 0x5b, 0x62, 0xfb, 0xeb, 0xd3, 0x01, 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.Amp != nil { + { + size := m.Amp.Size() + i -= size + if _, err := m.Amp.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintPoolParams(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + if m.UseOracle { + i-- + if m.UseOracle { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x20 + } + { + size := m.ExitFee.Size() + i -= size + if _, err := m.ExitFee.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintPoolParams(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + { + size := m.SwapFee.Size() + i -= size + if _, err := m.SwapFee.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintPoolParams(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if m.Type != 0 { + i = encodeVarintPoolParams(dAtA, i, uint64(m.Type)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintPoolParams(dAtA []byte, offset int, v uint64) int { + offset -= sovPoolParams(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 + if m.Type != 0 { + n += 1 + sovPoolParams(uint64(m.Type)) + } + l = m.SwapFee.Size() + n += 1 + l + sovPoolParams(uint64(l)) + l = m.ExitFee.Size() + n += 1 + l + sovPoolParams(uint64(l)) + if m.UseOracle { + n += 2 + } + if m.Amp != nil { + l = m.Amp.Size() + n += 1 + l + sovPoolParams(uint64(l)) + } + return n +} + +func sovPoolParams(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozPoolParams(x uint64) (n int) { + return sovPoolParams(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 ErrIntOverflowPoolParams + } + 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 != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) + } + m.Type = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPoolParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Type |= PoolType(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + 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 ErrIntOverflowPoolParams + } + 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 ErrInvalidLengthPoolParams + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPoolParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.SwapFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + 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 ErrIntOverflowPoolParams + } + 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 ErrInvalidLengthPoolParams + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPoolParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ExitFee.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field UseOracle", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPoolParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.UseOracle = bool(v != 0) + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Amp", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowPoolParams + } + 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 ErrInvalidLengthPoolParams + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthPoolParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + var v github_com_cosmos_cosmos_sdk_types.Int + m.Amp = &v + if err := m.Amp.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipPoolParams(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthPoolParams + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipPoolParams(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, ErrIntOverflowPoolParams + } + 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, ErrIntOverflowPoolParams + } + 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, ErrIntOverflowPoolParams + } + 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, ErrInvalidLengthPoolParams + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupPoolParams + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthPoolParams + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthPoolParams = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowPoolParams = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupPoolParams = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/gmm/types/pool_stable.go b/x/gmm/types/pool_stable.go new file mode 100644 index 00000000..5e800e6b --- /dev/null +++ b/x/gmm/types/pool_stable.go @@ -0,0 +1,239 @@ +package types + +import ( + sdkmath "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func (p *Pool) estimateShareInStablePool(coins sdk.Coins) (sdk.Coin, error) { + // BPT out, so we round down overall. + + // First loop calculates the sum of all token balances, which will be used to calculate + // the current weights of each token, relative to this sum + sum := p.Sum() + + // Calculate the weighted balance ratio without considering fees + balanceRatiosWithFee := make(map[string]sdkmath.LegacyDec, len(coins)) + // The weighted sum of token balance ratios without fee + invariantRatioWithFees := sdkmath.LegacyZeroDec() + + for _, asset := range coins { + currentWeight := sdkmath.LegacyDec(asset.Amount).Quo(sdkmath.LegacyNewDecFromInt(sum)) + + balanceRatiosWithFee[asset.Denom] = sdkmath.LegacyDec(asset.Amount.Add(p.Assets[asset.Denom].Token.Amount)).Quo( + sdkmath.LegacyNewDecFromInt(p.Assets[asset.Denom].Token.Amount), + ) + + invariantRatioWithFees = invariantRatioWithFees.Add( + balanceRatiosWithFee[asset.Denom].Mul(currentWeight), + ) + } + + // Second loop calculates new amounts in, taking into account the fee on the percentage excess + + newBalances := sdk.NewCoins() + for _, amountIn := range coins { + asset := p.Assets[amountIn.Denom] + var amountInWithoutFee sdkmath.Int + // Check if the balance ratio is greater than the ideal ratio to charge fees or not + if balanceRatiosWithFee[asset.Token.Denom].GT(invariantRatioWithFees) { + nonTaxableAmount := asset.Token.Amount.Quo(sdkmath.Int(invariantRatioWithFees).Sub(sdkmath.Int(sdkmath.LegacyOneDec()))) + taxableAmount := amountIn.Amount.Sub(nonTaxableAmount) + remainFee := sdkmath.LegacyNewDec(10000).Sub(p.PoolParams.SwapFee).RoundInt() + amountInWithoutFee = nonTaxableAmount.Add(taxableAmount.Mul(sdk.NewInt(10000)).Quo(remainFee)) + + } else { + amountInWithoutFee = amountIn.Amount + } + newBalances = append(newBalances, sdk.NewCoin( + amountIn.Denom, + asset.Token.Amount.Add(amountInWithoutFee), + )) + } + + // Get current and new invariants, taking swap fees into account + currentInvariant := calculateInvariantInStablePool(*p.PoolParams.Amp, p.GetLiquidity()) + + newInvariant := calculateInvariantInStablePool(*p.PoolParams.Amp, newBalances) + + invariantRatio := sdkmath.LegacyNewDecFromInt(newInvariant).Quo( + sdkmath.LegacyNewDecFromInt(currentInvariant), + ) + + // If the invariant didn't increase for any reason, we simply don't mint BPT + if invariantRatio.GT(sdkmath.LegacyZeroDec()) { + share := p.TotalShares.Amount.Mul(sdkmath.Int(invariantRatio.Sub(sdkmath.LegacyOneDec()))) + return sdk.NewCoin(p.PoolId, share), nil + + } + return sdk.NewCoin(p.PoolId, sdkmath.NewInt(0)), nil +} + +func (p *Pool) estimateSwapInStablePool(tokenIn sdk.Coin, denomOut string) (sdk.Coin, error) { + /************************************************************************************************************** + // outGivenIn token x for y - polynomial equation to solve // + // ay = amount out to calculate // + // by = balance token out // + // y = by - ay (finalBalanceOut) // + // D = invariant D D^(n+1) // + // A = amplification coefficient y^2 + ( S - ---------- - D) * y - ------------- = 0 // + // n = number of tokens (A * n^n) A * n^2n * P // + // S = sum of final balances but y // + // P = product of final balances but y // + **************************************************************************************************************/ + + // Subtract the fee from the amount in if requested + + tokenInDec := MinusFees(tokenIn.Amount, p.PoolParams.SwapFee) + + inv := calculateInvariantInStablePool(*p.PoolParams.Amp, p.GetLiquidity()) + + assets := p.Assets + + balance := assets[tokenIn.Denom].Token.Amount.Add(tokenInDec.RoundInt()) + assets[tokenIn.Denom] = PoolAsset{ + Token: sdk.NewCoin(tokenIn.Denom, balance), + Weight: assets[tokenIn.Denom].Weight, + Decimal: assets[tokenIn.Denom].Decimal, + } + + finalBalanceOut, err := getTokenBalanceGivenInvariantAndAllOtherBalances( + *p.PoolParams.Amp, inv, assets, tokenIn.Denom, + ) + out := p.Assets[denomOut].Token.Amount.Sub(finalBalanceOut).Sub(sdkmath.OneInt()) + return sdk.NewCoin(denomOut, out), err +} + +func (p *Pool) estimateWithdrawalsFromStablePool(share sdk.Coin) ([]sdk.Coin, error) { + /********************************************************************************************** + // exactBPTInForTokensOut // + // (per token) // + // aO = tokenAmountOut / bptIn \ // + // b = tokenBalance a0 = b * | --------------------- | // + // bptIn = bptAmountIn \ bptTotalSupply / // + // bpt = bptTotalSupply // + **********************************************************************************************/ + + // Since we're computing an amount out, we round down overall. This means rounding down on both the + // multiplication and division. + + bptAmountIn := sdkmath.LegacyNewDecFromInt(share.Amount) + totalShareDec := sdkmath.LegacyNewDecFromInt(p.TotalShares.Amount) + bptRatio := bptAmountIn.Quo(totalShareDec) + + outs := sdk.NewCoins() + for _, asset := range p.Assets { + amountOut := sdkmath.LegacyNewDecFromInt(asset.Token.Amount).Mul(bptRatio) + outs = outs.Add(sdk.NewCoin( + asset.Token.Denom, + amountOut.RoundInt(), + )) + } + + return outs, nil +} + +/********************************************************************************************** + // invariant // + // D = invariant D^(n+1) // + // A = amplification coefficient A n^n S + D = A D n^n + ----------- // + // S = sum of balances n^n P // + // P = product of balances // + // n = number of tokens // + **********************************************************************************************/ + +var AmpPrecision = sdkmath.NewInt(1000) + +func calculateInvariantInStablePool( + amp sdkmath.Int, + assets []sdk.Coin, +) sdkmath.Int { + sum := sdkmath.NewInt(0) + + // Number of tokens + numTokens := sdkmath.NewInt(int64(len(assets))) + + for _, asset := range assets { + sum = sum.Add(asset.Amount) + } + + if sum.IsZero() { + return sum + } + + inv := sum + ampTimeTotal := amp.Mul(numTokens) + + // nolint:staticcheck + for i := 0; i < 255; i++ { + PD := numTokens.Mul(assets[0].Amount) + for _, asset := range assets[1:] { + PD = PD.Mul(asset.Amount).Mul(numTokens).Quo(inv) + } + + preInv := inv + numerator1 := numTokens.Mul(inv).Mul(inv) + numerator2 := ampTimeTotal.Mul(sum).Mul(PD).Quo(AmpPrecision) + denominator := numTokens.Add(sdk.OneInt()).Mul(inv).Add(ampTimeTotal.Sub(AmpPrecision).Mul(PD).Quo(AmpPrecision)) + inv = numerator1.Add(numerator2).Quo(denominator) + + if inv.GT(preInv) { + if inv.Sub(preInv).LTE(sdkmath.NewInt(1e18)) { + break + } + } else if preInv.Sub(inv).LTE(sdkmath.NewInt(1e18)) { + break + } + } + return inv +} + +func getTokenBalanceGivenInvariantAndAllOtherBalances( + amp sdkmath.Int, + inv sdkmath.Int, + assets map[string]PoolAsset, + tokenInDenom string, +) (sdkmath.Int, error) { + numTokens := sdkmath.NewInt(int64(len(assets))) + ampTimeTotal := amp.Mul(numTokens) + sum := sdkmath.NewInt(0) + + PD := numTokens.Mul(assets[tokenInDenom].Token.Amount) + + for _, asset := range assets { + PD = PD.Mul(asset.Token.Amount).Mul(numTokens).Quo(inv) + sum = sum.Add(asset.Token.Amount) + } + + sum = sum.Sub(assets[tokenInDenom].Token.Amount) + + inv2 := inv.Mul(inv) + + c := inv2.Quo(ampTimeTotal.Mul(PD)).Mul(AmpPrecision).Mul(assets[tokenInDenom].Token.Amount) + b := sum.Add(inv.Quo(ampTimeTotal).Mul(AmpPrecision)) + + tokenBalance := (inv2.Add(c)).Quo(inv.Add(b)) + + for i := 0; i < 255; i++ { + preTokenBalance := tokenBalance + tokenBalance = tokenBalance.Mul(tokenBalance).Add(c).Quo((tokenBalance.Mul(sdkmath.NewInt(2)).Add(b).Sub(inv))) + + if tokenBalance.GT(preTokenBalance) { + if tokenBalance.Sub(preTokenBalance).LTE(sdkmath.OneInt()) { + return tokenBalance, nil + } + } else if preTokenBalance.Sub(tokenBalance).LTE(sdkmath.OneInt()) { + return tokenBalance, nil + } + } + return sdkmath.ZeroInt(), ErrInvalidInvariantConverge +} + +// Helper functions +func MinusFees(amount sdkmath.Int, swapFee sdkmath.LegacyDec) sdk.Dec { + amountDec := sdk.NewDecFromInt(amount) + feeRate := swapFee.Quo(sdk.NewDec(10000)) + fees := amountDec.Mul(feeRate) + amountMinusFees := amountDec.Sub(fees) + return amountMinusFees +} diff --git a/x/gmm/types/pool_weight.go b/x/gmm/types/pool_weight.go new file mode 100644 index 00000000..39440bc4 --- /dev/null +++ b/x/gmm/types/pool_weight.go @@ -0,0 +1,116 @@ +package types + +import ( + fmt "fmt" + math "math" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func (p *Pool) estimateShareInWeightPool(coins sdk.Coins) (sdk.Coin, error) { + switch len(coins) { + // Single Asset Deposit in balancer pool + case 1: + return p.estimateShareWithSingleLiquidityInWeightPool(coins[0]) + // Multi Asset Deposit in balancer pool + case len(p.Assets): + return p.estimateShareWithTalLiquidityInWeightPool(coins) + } + return sdk.Coin{}, ErrInvalidNumOfAssets +} + +func (p *Pool) estimateShareWithSingleLiquidityInWeightPool(coin sdk.Coin) (sdk.Coin, error) { + asset, err := p.findAssetByDenom(coin.Denom) + if err != nil { + return sdk.Coin{}, err + } + + decToken := (sdk.NewDecCoinFromCoin(coin)) + decAsset := sdk.NewDecCoinFromCoin(asset.Token) + weight := sdk.NewDecFromInt(*asset.Weight).Quo(sdk.NewDec(100)) // divide by 100 + ratio := decToken.Amount.Quo(decAsset.Amount).Add(sdk.NewDec(1)) + exponent := (math.Pow(ratio.MustFloat64(), weight.MustFloat64()) - 1) * Multiplier + factor, err := sdk.NewDecFromStr(fmt.Sprintf("%f", exponent/Multiplier)) + if err != nil { + return sdk.Coin{}, err + } + issueAmount := p.TotalShares.Amount.Mul(factor.RoundInt()).Quo(sdk.NewInt(1e10)) + outputToken := sdk.Coin{ + Amount: issueAmount, + Denom: p.TotalShares.Denom, + } + return outputToken, nil +} + +func (p *Pool) estimateShareWithTalLiquidityInWeightPool(coins sdk.Coins) (sdk.Coin, error) { + share := sdk.NewInt(0) + for _, coin := range coins { + asset, err := p.findAssetByDenom(coin.Denom) + if err != nil { + return sdk.Coin{}, err + } + + decToken := sdk.NewDecCoinFromCoin(coin) + decAsset := sdk.NewDecCoinFromCoin(asset.Token) + decSupply := sdk.NewDecCoinFromCoin(p.TotalShares) + + ratio := decToken.Amount.Quo(decAsset.Amount).Mul(sdk.NewDec(Multiplier)) + issueAmount := (decSupply.Amount.Mul(sdk.NewDecFromInt(*asset.Weight)).Mul(ratio).Quo(sdk.NewDec(100)).Quo(sdk.NewDec(Multiplier))) + + share = share.Add(issueAmount.RoundInt()) + } + + return sdk.NewCoin(p.TotalShares.Denom, share), nil +} + +// Withdraws +func (p *Pool) estimateWithdrawalsFromWeightPool(share sdk.Coin) ([]sdk.Coin, error) { + outs := []sdk.Coin{} + if share.Amount.GT(p.TotalShares.Amount) { + return nil, ErrOverflowShareAmount + } + for _, asset := range p.Assets { + out := asset.Token.Amount.Mul(share.Amount).Quo(p.TotalShares.Amount) + outs = append(outs, sdk.Coin{ + Denom: asset.Token.Denom, + Amount: out, + }) + } + return outs, nil +} + +// Swap implements OutGivenIn +// Input how many coins you want to sell, output an amount you will receive +// Ao = Bo * ((1 - Bi / (Bi + Ai)) ** Wi/Wo) +func (p *Pool) estimateSwapInWeightPool(amountIn sdk.Coin, denomOut string) (sdk.Coin, error) { + assetIn, err := p.findAssetByDenom(amountIn.Denom) + if err != nil { + return sdk.Coin{}, fmt.Errorf("left swap failed: could not find asset in by denom") + } + + assetOut, err := p.findAssetByDenom(denomOut) + if err != nil { + return sdk.Coin{}, fmt.Errorf("left swap failed: could not find asset out by denom") + } + + balanceOut := sdk.NewDecFromBigInt(assetOut.Token.Amount.BigInt()) + balanceIn := sdk.NewDecFromBigInt(assetIn.Token.Amount.BigInt()) + weightIn := sdk.NewDecFromInt(*assetIn.Weight).Quo(sdk.NewDec(100)) + weightOut := sdk.NewDecFromInt(*assetIn.Weight).Quo(sdk.NewDec(100)) + amount := p.TakeFees(amountIn.Amount) + + // Ao = Bo * ((1 - Bi / (Bi + Ai)) ** Wi/Wo) + balanceInPlusAmount := balanceIn.Add(amount) + ratio := balanceIn.Quo(balanceInPlusAmount) + oneMinusRatio := sdk.NewDec(1).Sub(ratio) + + power := weightIn.Quo(weightOut) + factor := math.Pow(oneMinusRatio.MustFloat64(), power.MustFloat64()) * Multiplier + finalFactor := factor / 1e8 + + amountOut := balanceOut.Mul(sdk.MustNewDecFromStr(fmt.Sprintf("%f", finalFactor))).Quo(sdk.NewDec(1e10)) + return sdk.Coin{ + Amount: amountOut.RoundInt(), + Denom: denomOut, + }, nil +} diff --git a/x/gmm/types/query.pb.go b/x/gmm/types/query.pb.go new file mode 100644 index 00000000..e2e64a01 --- /dev/null +++ b/x/gmm/types/query.pb.go @@ -0,0 +1,1482 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: side/gmm/query.proto + +package types + +import ( + context "context" + fmt "fmt" + 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_b80830e9bca1f6d0, []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_b80830e9bca1f6d0, []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{} +} + +// QueryLiquidityPoolRequest is request type for the Query/Liquidity RPC method. +type QueryPoolRequest struct { + PoolId string `protobuf:"bytes,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_b80830e9bca1f6d0, []int{2} +} +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() string { + if m != nil { + return m.PoolId + } + return "" +} + +// QueryLiquidityPoolResponse is response type for the Query/Liquidity RPC method +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_b80830e9bca1f6d0, []int{3} +} +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 +} + +// QueryPoolsRequest is request type for the Query/Liquidities RPC method. +type QueryPoolsRequest struct { + Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` + Pagination *query.PageRequest `protobuf:"bytes,2,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_b80830e9bca1f6d0, []int{4} +} +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) GetCreator() string { + if m != nil { + return m.Creator + } + return "" +} + +func (m *QueryPoolsRequest) GetPagination() *query.PageRequest { + if m != nil { + return m.Pagination + } + return nil +} + +// QueryPoolsResponse is response type for the Query/Pools RPC method +type QueryPoolsResponse struct { + Pools []Pool `protobuf:"bytes,1,rep,name=pools,proto3" json:"pools"` + 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_b80830e9bca1f6d0, []int{5} +} +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 +} + +func init() { + proto.RegisterType((*QueryParamsRequest)(nil), "side.gmm.QueryParamsRequest") + proto.RegisterType((*QueryParamsResponse)(nil), "side.gmm.QueryParamsResponse") + proto.RegisterType((*QueryPoolRequest)(nil), "side.gmm.QueryPoolRequest") + proto.RegisterType((*QueryPoolResponse)(nil), "side.gmm.QueryPoolResponse") + proto.RegisterType((*QueryPoolsRequest)(nil), "side.gmm.QueryPoolsRequest") + proto.RegisterType((*QueryPoolsResponse)(nil), "side.gmm.QueryPoolsResponse") +} + +func init() { proto.RegisterFile("side/gmm/query.proto", fileDescriptor_b80830e9bca1f6d0) } + +var fileDescriptor_b80830e9bca1f6d0 = []byte{ + // 504 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0xcf, 0x6b, 0x13, 0x41, + 0x14, 0xc7, 0xb3, 0x6d, 0x7e, 0xe8, 0x08, 0x52, 0x5f, 0x23, 0x86, 0x35, 0xdd, 0x96, 0x01, 0x35, + 0x54, 0x98, 0xa1, 0xf5, 0xe0, 0x3d, 0xa0, 0xe2, 0x41, 0xa8, 0x39, 0x7a, 0x91, 0x49, 0x32, 0xae, + 0x0b, 0xbb, 0xfb, 0xb6, 0x3b, 0x1b, 0x31, 0x48, 0x2f, 0xde, 0xbc, 0x09, 0xfe, 0x33, 0xfe, 0x09, + 0x3d, 0x16, 0xbc, 0x78, 0x12, 0x49, 0xfc, 0x43, 0x64, 0x7e, 0x6c, 0xb3, 0xb6, 0x1b, 0x72, 0xf0, + 0xb6, 0xfb, 0xde, 0x77, 0xbe, 0x9f, 0xf7, 0xbe, 0x33, 0xa4, 0xab, 0xa2, 0xa9, 0xe4, 0x61, 0x92, + 0xf0, 0xd3, 0x99, 0xcc, 0xe7, 0x2c, 0xcb, 0xb1, 0x40, 0xb8, 0xa1, 0xab, 0x2c, 0x4c, 0x12, 0xbf, + 0x1b, 0x62, 0x88, 0xa6, 0xc8, 0xf5, 0x97, 0xed, 0xfb, 0xfd, 0x10, 0x31, 0x8c, 0x25, 0x17, 0x59, + 0xc4, 0x45, 0x9a, 0x62, 0x21, 0x8a, 0x08, 0x53, 0xe5, 0xba, 0x87, 0x13, 0x54, 0x09, 0x2a, 0x3e, + 0x16, 0x4a, 0x5a, 0x5b, 0xfe, 0xe1, 0x68, 0x2c, 0x0b, 0x71, 0xc4, 0x33, 0x11, 0x46, 0xa9, 0x11, + 0x3b, 0xed, 0xdd, 0x4b, 0x7e, 0x26, 0x72, 0x91, 0x94, 0x16, 0xbb, 0xab, 0x32, 0x62, 0x6c, 0x8b, + 0xb4, 0x4b, 0xe0, 0xb5, 0x76, 0x3b, 0x31, 0xca, 0x91, 0x3c, 0x9d, 0x49, 0x55, 0xd0, 0x67, 0x64, + 0xf7, 0x9f, 0xaa, 0xca, 0x30, 0x55, 0x12, 0x18, 0x69, 0x5b, 0xc7, 0x9e, 0x77, 0xe0, 0x0d, 0x6e, + 0x1d, 0xef, 0xb0, 0x72, 0x27, 0x66, 0x95, 0xc3, 0xe6, 0xf9, 0xaf, 0xfd, 0xc6, 0xc8, 0xa9, 0xe8, + 0x63, 0xb2, 0x63, 0x6d, 0x10, 0x63, 0x67, 0x0d, 0xf7, 0x48, 0x47, 0xe3, 0xdf, 0x46, 0x53, 0x63, + 0x72, 0x73, 0xd4, 0xd6, 0xbf, 0x2f, 0xa7, 0xf4, 0x29, 0xb9, 0x53, 0x11, 0x3b, 0x22, 0x25, 0x4d, + 0xdd, 0x76, 0xbc, 0xdb, 0x15, 0x9e, 0x56, 0x99, 0x1e, 0x9d, 0x55, 0x0e, 0x96, 0x1b, 0x40, 0x8f, + 0x74, 0x26, 0xb9, 0x14, 0x05, 0xe6, 0x0e, 0x53, 0xfe, 0xc2, 0x73, 0x42, 0x56, 0x89, 0xf5, 0xb6, + 0x8c, 0xf1, 0x43, 0x66, 0xe3, 0x65, 0x3a, 0x5e, 0x66, 0x6f, 0xcd, 0xc5, 0xcb, 0x4e, 0x44, 0x28, + 0x9d, 0xeb, 0xa8, 0x72, 0x92, 0x7e, 0xf1, 0xca, 0xe8, 0x2c, 0xd7, 0x4d, 0x7c, 0x48, 0x5a, 0x7a, + 0x2a, 0x1d, 0xd1, 0xf6, 0xf5, 0x91, 0x5d, 0x40, 0x56, 0x02, 0x2f, 0x6a, 0x46, 0x79, 0xb4, 0x71, + 0x14, 0x0b, 0xaa, 0xce, 0x72, 0xfc, 0x7d, 0x9b, 0xb4, 0xcc, 0x2c, 0x10, 0x93, 0xb6, 0xbd, 0x0a, + 0xe8, 0xaf, 0xc8, 0xd7, 0x6f, 0xd8, 0xdf, 0x5b, 0xd3, 0xb5, 0xe6, 0xf4, 0xc1, 0xe7, 0x1f, 0x7f, + 0xbe, 0x6d, 0xed, 0xc3, 0x1e, 0xd7, 0x32, 0xf3, 0x54, 0x26, 0x18, 0xf3, 0x2b, 0x0f, 0x0b, 0x22, + 0xd2, 0xd4, 0x5b, 0x81, 0x7f, 0xd5, 0x6d, 0x75, 0xe1, 0xfe, 0xfd, 0xda, 0x9e, 0xe3, 0x0c, 0x0c, + 0x87, 0xc2, 0xc1, 0x1a, 0xce, 0x27, 0xf7, 0x56, 0xce, 0xe0, 0x1d, 0x69, 0x99, 0xa0, 0xa1, 0xce, + 0xef, 0x72, 0xad, 0x7e, 0x7d, 0xd3, 0xd1, 0xa8, 0xa1, 0xf5, 0xc1, 0x5f, 0x43, 0x13, 0x71, 0x0c, + 0x29, 0xe9, 0xbc, 0x9a, 0xff, 0x37, 0x69, 0xe3, 0x5e, 0xee, 0x35, 0x9e, 0x0d, 0x87, 0xe7, 0x8b, + 0xc0, 0xbb, 0x58, 0x04, 0xde, 0xef, 0x45, 0xe0, 0x7d, 0x5d, 0x06, 0x8d, 0x8b, 0x65, 0xd0, 0xf8, + 0xb9, 0x0c, 0x1a, 0x6f, 0x06, 0x61, 0x54, 0xbc, 0x9f, 0x8d, 0xd9, 0x04, 0x93, 0x1a, 0x97, 0x8f, + 0xc6, 0xa7, 0x98, 0x67, 0x52, 0x8d, 0xdb, 0xa6, 0xf5, 0xe4, 0x6f, 0x00, 0x00, 0x00, 0xff, 0xff, + 0xd4, 0x34, 0x1e, 0x3e, 0x79, 0x04, 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 queries the parameters of the module. + Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) + Pool(ctx context.Context, in *QueryPoolRequest, opts ...grpc.CallOption) (*QueryPoolResponse, error) + Pools(ctx context.Context, in *QueryPoolsRequest, opts ...grpc.CallOption) (*QueryPoolsResponse, error) + MyPools(ctx context.Context, in *QueryPoolsRequest, opts ...grpc.CallOption) (*QueryPoolsResponse, 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, "/side.gmm.Query/Params", 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, "/side.gmm.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, "/side.gmm.Query/Pools", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) MyPools(ctx context.Context, in *QueryPoolsRequest, opts ...grpc.CallOption) (*QueryPoolsResponse, error) { + out := new(QueryPoolsResponse) + err := c.cc.Invoke(ctx, "/side.gmm.Query/MyPools", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + // Parameters queries the parameters of the module. + Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) + Pool(context.Context, *QueryPoolRequest) (*QueryPoolResponse, error) + Pools(context.Context, *QueryPoolsRequest) (*QueryPoolsResponse, error) + MyPools(context.Context, *QueryPoolsRequest) (*QueryPoolsResponse, 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) 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) MyPools(ctx context.Context, req *QueryPoolsRequest) (*QueryPoolsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method MyPools 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: "/side.gmm.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_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: "/side.gmm.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: "/side.gmm.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_MyPools_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).MyPools(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/side.gmm.Query/MyPools", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).MyPools(ctx, req.(*QueryPoolsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "side.gmm.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Params", + Handler: _Query_Params_Handler, + }, + { + MethodName: "Pool", + Handler: _Query_Pool_Handler, + }, + { + MethodName: "Pools", + Handler: _Query_Pools_Handler, + }, + { + MethodName: "MyPools", + Handler: _Query_MyPools_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "side/gmm/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 *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 len(m.PoolId) > 0 { + i -= len(m.PoolId) + copy(dAtA[i:], m.PoolId) + i = encodeVarintQuery(dAtA, i, uint64(len(m.PoolId))) + i-- + dAtA[i] = 0xa + } + 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] = 0x12 + } + if len(m.Creator) > 0 { + i -= len(m.Creator) + copy(dAtA[i:], m.Creator) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Creator))) + 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 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 *QueryPoolRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.PoolId) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + 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 + l = len(m.Creator) + if l > 0 { + n += 1 + l + sovQuery(uint64(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 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 *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 != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", 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.PoolId = 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 *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 Creator", 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.Creator = string(dAtA[iNdEx:postIndex]) + 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.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 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/gmm/types/query.pb.gw.go b/x/gmm/types/query.pb.gw.go new file mode 100644 index 00000000..c2a98bbd --- /dev/null +++ b/x/gmm/types/query.pb.gw.go @@ -0,0 +1,456 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: side/gmm/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_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 + + 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.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", 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 + + 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.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "pool_id", 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 + +} + +var ( + filter_Query_MyPools_0 = &utilities.DoubleArray{Encoding: map[string]int{"creator": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} +) + +func request_Query_MyPools_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 + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["creator"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "creator") + } + + protoReq.Creator, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "creator", 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_MyPools_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.MyPools(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_MyPools_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 + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["creator"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "creator") + } + + protoReq.Creator, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "creator", 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_MyPools_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.MyPools(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_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_MyPools_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_MyPools_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_MyPools_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_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_MyPools_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_MyPools_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_MyPools_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, 2, 3}, []string{"sideprotocol", "side", "gmm", "params"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_Query_Pool_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"sideprotocol", "side", "gmm", "pool_id"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_Query_Pools_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"sideprotocol", "side", "gmm", "all"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_Query_MyPools_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"sideprotocol", "side", "gmm", "creator"}, "", runtime.AssumeColonVerbOpt(true))) +) + +var ( + forward_Query_Params_0 = runtime.ForwardResponseMessage + + forward_Query_Pool_0 = runtime.ForwardResponseMessage + + forward_Query_Pools_0 = runtime.ForwardResponseMessage + + forward_Query_MyPools_0 = runtime.ForwardResponseMessage +) diff --git a/x/gmm/types/swap_route.pb.go b/x/gmm/types/swap_route.pb.go new file mode 100644 index 00000000..38a839d2 --- /dev/null +++ b/x/gmm/types/swap_route.pb.go @@ -0,0 +1,562 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: side/gmm/swap_route.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "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 SwapAmountInRoute struct { + PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` + TokenOutDenom string `protobuf:"bytes,2,opt,name=token_out_denom,json=tokenOutDenom,proto3" json:"token_out_denom,omitempty"` +} + +func (m *SwapAmountInRoute) Reset() { *m = SwapAmountInRoute{} } +func (m *SwapAmountInRoute) String() string { return proto.CompactTextString(m) } +func (*SwapAmountInRoute) ProtoMessage() {} +func (*SwapAmountInRoute) Descriptor() ([]byte, []int) { + return fileDescriptor_a35e208859001a27, []int{0} +} +func (m *SwapAmountInRoute) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SwapAmountInRoute) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SwapAmountInRoute.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 *SwapAmountInRoute) XXX_Merge(src proto.Message) { + xxx_messageInfo_SwapAmountInRoute.Merge(m, src) +} +func (m *SwapAmountInRoute) XXX_Size() int { + return m.Size() +} +func (m *SwapAmountInRoute) XXX_DiscardUnknown() { + xxx_messageInfo_SwapAmountInRoute.DiscardUnknown(m) +} + +var xxx_messageInfo_SwapAmountInRoute proto.InternalMessageInfo + +func (m *SwapAmountInRoute) GetPoolId() uint64 { + if m != nil { + return m.PoolId + } + return 0 +} + +func (m *SwapAmountInRoute) GetTokenOutDenom() string { + if m != nil { + return m.TokenOutDenom + } + return "" +} + +type SwapAmountOutRoute struct { + PoolId uint64 `protobuf:"varint,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` + TokenInDenom string `protobuf:"bytes,2,opt,name=token_in_denom,json=tokenInDenom,proto3" json:"token_in_denom,omitempty"` +} + +func (m *SwapAmountOutRoute) Reset() { *m = SwapAmountOutRoute{} } +func (m *SwapAmountOutRoute) String() string { return proto.CompactTextString(m) } +func (*SwapAmountOutRoute) ProtoMessage() {} +func (*SwapAmountOutRoute) Descriptor() ([]byte, []int) { + return fileDescriptor_a35e208859001a27, []int{1} +} +func (m *SwapAmountOutRoute) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *SwapAmountOutRoute) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_SwapAmountOutRoute.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 *SwapAmountOutRoute) XXX_Merge(src proto.Message) { + xxx_messageInfo_SwapAmountOutRoute.Merge(m, src) +} +func (m *SwapAmountOutRoute) XXX_Size() int { + return m.Size() +} +func (m *SwapAmountOutRoute) XXX_DiscardUnknown() { + xxx_messageInfo_SwapAmountOutRoute.DiscardUnknown(m) +} + +var xxx_messageInfo_SwapAmountOutRoute proto.InternalMessageInfo + +func (m *SwapAmountOutRoute) GetPoolId() uint64 { + if m != nil { + return m.PoolId + } + return 0 +} + +func (m *SwapAmountOutRoute) GetTokenInDenom() string { + if m != nil { + return m.TokenInDenom + } + return "" +} + +func init() { + proto.RegisterType((*SwapAmountInRoute)(nil), "side.gmm.SwapAmountInRoute") + proto.RegisterType((*SwapAmountOutRoute)(nil), "side.gmm.SwapAmountOutRoute") +} + +func init() { proto.RegisterFile("side/gmm/swap_route.proto", fileDescriptor_a35e208859001a27) } + +var fileDescriptor_a35e208859001a27 = []byte{ + // 255 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2c, 0xce, 0x4c, 0x49, + 0xd5, 0x4f, 0xcf, 0xcd, 0xd5, 0x2f, 0x2e, 0x4f, 0x2c, 0x88, 0x2f, 0xca, 0x2f, 0x2d, 0x49, 0xd5, + 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x00, 0x49, 0xe9, 0xa5, 0xe7, 0xe6, 0x4a, 0x89, 0xa4, + 0xe7, 0xa7, 0xe7, 0x83, 0x05, 0xf5, 0x41, 0x2c, 0x88, 0xbc, 0x94, 0x64, 0x72, 0x7e, 0x71, 0x6e, + 0x7e, 0x71, 0x3c, 0x44, 0x02, 0xc2, 0x81, 0x48, 0x29, 0x85, 0x70, 0x09, 0x06, 0x97, 0x27, 0x16, + 0x38, 0xe6, 0xe6, 0x97, 0xe6, 0x95, 0x78, 0xe6, 0x05, 0x81, 0x4c, 0x15, 0x12, 0xe7, 0x62, 0x2f, + 0xc8, 0xcf, 0xcf, 0x89, 0xcf, 0x4c, 0x91, 0x60, 0x54, 0x60, 0xd4, 0x60, 0x09, 0x62, 0x03, 0x71, + 0x3d, 0x53, 0x84, 0xd4, 0xb8, 0xf8, 0x4b, 0xf2, 0xb3, 0x53, 0xf3, 0xe2, 0xf3, 0x4b, 0x4b, 0xe2, + 0x53, 0x52, 0xf3, 0xf2, 0x73, 0x25, 0x98, 0x14, 0x18, 0x35, 0x38, 0x83, 0x78, 0xc1, 0xc2, 0xfe, + 0xa5, 0x25, 0x2e, 0x20, 0x41, 0xa5, 0x60, 0x2e, 0x21, 0x84, 0xa9, 0xfe, 0xa5, 0x25, 0x04, 0x8c, + 0x55, 0xe1, 0xe2, 0x83, 0x18, 0x9b, 0x99, 0x87, 0x62, 0x2a, 0x0f, 0x58, 0xd4, 0x33, 0x0f, 0x6c, + 0xa8, 0x93, 0xd3, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, 0x78, 0x24, 0xc7, 0x38, + 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, 0x31, 0x44, 0x69, 0xa4, 0x67, + 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x83, 0x82, 0x02, 0xec, 0xb5, 0xe4, 0xfc, + 0x1c, 0x30, 0x47, 0xbf, 0x02, 0x1c, 0x68, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x49, 0x6c, 0x60, 0x29, + 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x62, 0x7d, 0x40, 0x2f, 0x4d, 0x01, 0x00, 0x00, +} + +func (m *SwapAmountInRoute) 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 *SwapAmountInRoute) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SwapAmountInRoute) 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 = encodeVarintSwapRoute(dAtA, i, uint64(len(m.TokenOutDenom))) + i-- + dAtA[i] = 0x12 + } + if m.PoolId != 0 { + i = encodeVarintSwapRoute(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *SwapAmountOutRoute) 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 *SwapAmountOutRoute) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *SwapAmountOutRoute) 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 = encodeVarintSwapRoute(dAtA, i, uint64(len(m.TokenInDenom))) + i-- + dAtA[i] = 0x12 + } + if m.PoolId != 0 { + i = encodeVarintSwapRoute(dAtA, i, uint64(m.PoolId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintSwapRoute(dAtA []byte, offset int, v uint64) int { + offset -= sovSwapRoute(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *SwapAmountInRoute) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovSwapRoute(uint64(m.PoolId)) + } + l = len(m.TokenOutDenom) + if l > 0 { + n += 1 + l + sovSwapRoute(uint64(l)) + } + return n +} + +func (m *SwapAmountOutRoute) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.PoolId != 0 { + n += 1 + sovSwapRoute(uint64(m.PoolId)) + } + l = len(m.TokenInDenom) + if l > 0 { + n += 1 + l + sovSwapRoute(uint64(l)) + } + return n +} + +func sovSwapRoute(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozSwapRoute(x uint64) (n int) { + return sovSwapRoute(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *SwapAmountInRoute) 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 ErrIntOverflowSwapRoute + } + 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: SwapAmountInRoute: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SwapAmountInRoute: 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 ErrIntOverflowSwapRoute + } + 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 TokenOutDenom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowSwapRoute + } + 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 ErrInvalidLengthSwapRoute + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthSwapRoute + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TokenOutDenom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipSwapRoute(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthSwapRoute + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *SwapAmountOutRoute) 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 ErrIntOverflowSwapRoute + } + 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: SwapAmountOutRoute: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: SwapAmountOutRoute: 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 ErrIntOverflowSwapRoute + } + 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 ErrIntOverflowSwapRoute + } + 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 ErrInvalidLengthSwapRoute + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthSwapRoute + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.TokenInDenom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipSwapRoute(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthSwapRoute + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipSwapRoute(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, ErrIntOverflowSwapRoute + } + 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, ErrIntOverflowSwapRoute + } + 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, ErrIntOverflowSwapRoute + } + 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, ErrInvalidLengthSwapRoute + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupSwapRoute + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthSwapRoute + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthSwapRoute = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowSwapRoute = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupSwapRoute = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/gmm/types/tx.pb.go b/x/gmm/types/tx.pb.go new file mode 100644 index 00000000..4e205c4b --- /dev/null +++ b/x/gmm/types/tx.pb.go @@ -0,0 +1,2376 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: side/gmm/tx.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" + _ "github.com/cosmos/gogoproto/gogoproto" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + 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 { + Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` + Params *PoolParams `protobuf:"bytes,2,opt,name=params,proto3" json:"params,omitempty"` + Liquidity []PoolAsset `protobuf:"bytes,3,rep,name=liquidity,proto3" json:"liquidity"` +} + +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_840e3525c3c3a81c, []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) GetSender() string { + if m != nil { + return m.Sender + } + return "" +} + +func (m *MsgCreatePool) GetParams() *PoolParams { + if m != nil { + return m.Params + } + return nil +} + +func (m *MsgCreatePool) GetLiquidity() []PoolAsset { + if m != nil { + return m.Liquidity + } + return nil +} + +type MsgCreatePoolResponse struct { + PoolId string `protobuf:"bytes,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_840e3525c3c3a81c, []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() string { + if m != nil { + return m.PoolId + } + return "" +} + +type MsgAddLiquidity struct { + Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` + PoolId string `protobuf:"bytes,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` + Liquidity []types.Coin `protobuf:"bytes,3,rep,name=liquidity,proto3" json:"liquidity"` +} + +func (m *MsgAddLiquidity) Reset() { *m = MsgAddLiquidity{} } +func (m *MsgAddLiquidity) String() string { return proto.CompactTextString(m) } +func (*MsgAddLiquidity) ProtoMessage() {} +func (*MsgAddLiquidity) Descriptor() ([]byte, []int) { + return fileDescriptor_840e3525c3c3a81c, []int{2} +} +func (m *MsgAddLiquidity) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgAddLiquidity) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgAddLiquidity.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 *MsgAddLiquidity) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgAddLiquidity.Merge(m, src) +} +func (m *MsgAddLiquidity) XXX_Size() int { + return m.Size() +} +func (m *MsgAddLiquidity) XXX_DiscardUnknown() { + xxx_messageInfo_MsgAddLiquidity.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgAddLiquidity proto.InternalMessageInfo + +func (m *MsgAddLiquidity) GetSender() string { + if m != nil { + return m.Sender + } + return "" +} + +func (m *MsgAddLiquidity) GetPoolId() string { + if m != nil { + return m.PoolId + } + return "" +} + +func (m *MsgAddLiquidity) GetLiquidity() []types.Coin { + if m != nil { + return m.Liquidity + } + return nil +} + +type MsgAddLiquidityResponse struct { + PoolId string `protobuf:"bytes,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` +} + +func (m *MsgAddLiquidityResponse) Reset() { *m = MsgAddLiquidityResponse{} } +func (m *MsgAddLiquidityResponse) String() string { return proto.CompactTextString(m) } +func (*MsgAddLiquidityResponse) ProtoMessage() {} +func (*MsgAddLiquidityResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_840e3525c3c3a81c, []int{3} +} +func (m *MsgAddLiquidityResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgAddLiquidityResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgAddLiquidityResponse.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 *MsgAddLiquidityResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgAddLiquidityResponse.Merge(m, src) +} +func (m *MsgAddLiquidityResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgAddLiquidityResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgAddLiquidityResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgAddLiquidityResponse proto.InternalMessageInfo + +func (m *MsgAddLiquidityResponse) GetPoolId() string { + if m != nil { + return m.PoolId + } + return "" +} + +type MsgWithdraw struct { + Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` + Receiver string `protobuf:"bytes,2,opt,name=receiver,proto3" json:"receiver,omitempty"` + PoolId string `protobuf:"bytes,3,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` + Share types.Coin `protobuf:"bytes,4,opt,name=share,proto3" json:"share"` +} + +func (m *MsgWithdraw) Reset() { *m = MsgWithdraw{} } +func (m *MsgWithdraw) String() string { return proto.CompactTextString(m) } +func (*MsgWithdraw) ProtoMessage() {} +func (*MsgWithdraw) Descriptor() ([]byte, []int) { + return fileDescriptor_840e3525c3c3a81c, []int{4} +} +func (m *MsgWithdraw) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgWithdraw) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgWithdraw.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 *MsgWithdraw) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgWithdraw.Merge(m, src) +} +func (m *MsgWithdraw) XXX_Size() int { + return m.Size() +} +func (m *MsgWithdraw) XXX_DiscardUnknown() { + xxx_messageInfo_MsgWithdraw.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgWithdraw proto.InternalMessageInfo + +func (m *MsgWithdraw) GetSender() string { + if m != nil { + return m.Sender + } + return "" +} + +func (m *MsgWithdraw) GetReceiver() string { + if m != nil { + return m.Receiver + } + return "" +} + +func (m *MsgWithdraw) GetPoolId() string { + if m != nil { + return m.PoolId + } + return "" +} + +func (m *MsgWithdraw) GetShare() types.Coin { + if m != nil { + return m.Share + } + return types.Coin{} +} + +type MsgWithdrawResponse struct { + Share types.Coin `protobuf:"bytes,1,opt,name=share,proto3" json:"share"` +} + +func (m *MsgWithdrawResponse) Reset() { *m = MsgWithdrawResponse{} } +func (m *MsgWithdrawResponse) String() string { return proto.CompactTextString(m) } +func (*MsgWithdrawResponse) ProtoMessage() {} +func (*MsgWithdrawResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_840e3525c3c3a81c, []int{5} +} +func (m *MsgWithdrawResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgWithdrawResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgWithdrawResponse.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 *MsgWithdrawResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgWithdrawResponse.Merge(m, src) +} +func (m *MsgWithdrawResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgWithdrawResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgWithdrawResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgWithdrawResponse proto.InternalMessageInfo + +func (m *MsgWithdrawResponse) GetShare() types.Coin { + if m != nil { + return m.Share + } + return types.Coin{} +} + +type MsgSwap struct { + Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` + PoolId string `protobuf:"bytes,2,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` + TokenIn types.Coin `protobuf:"bytes,3,opt,name=tokenIn,proto3" json:"tokenIn"` + TokenOut types.Coin `protobuf:"bytes,4,opt,name=tokenOut,proto3" json:"tokenOut"` + Slippage github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,5,opt,name=slippage,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"slippage"` +} + +func (m *MsgSwap) Reset() { *m = MsgSwap{} } +func (m *MsgSwap) String() string { return proto.CompactTextString(m) } +func (*MsgSwap) ProtoMessage() {} +func (*MsgSwap) Descriptor() ([]byte, []int) { + return fileDescriptor_840e3525c3c3a81c, []int{6} +} +func (m *MsgSwap) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgSwap) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgSwap.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 *MsgSwap) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSwap.Merge(m, src) +} +func (m *MsgSwap) XXX_Size() int { + return m.Size() +} +func (m *MsgSwap) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSwap.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgSwap proto.InternalMessageInfo + +func (m *MsgSwap) GetSender() string { + if m != nil { + return m.Sender + } + return "" +} + +func (m *MsgSwap) GetPoolId() string { + if m != nil { + return m.PoolId + } + return "" +} + +func (m *MsgSwap) GetTokenIn() types.Coin { + if m != nil { + return m.TokenIn + } + return types.Coin{} +} + +func (m *MsgSwap) GetTokenOut() types.Coin { + if m != nil { + return m.TokenOut + } + return types.Coin{} +} + +type MsgSwapResponse struct { + PoolId string `protobuf:"bytes,1,opt,name=pool_id,json=poolId,proto3" json:"pool_id,omitempty"` + TokenIn types.Coin `protobuf:"bytes,2,opt,name=tokenIn,proto3" json:"tokenIn"` +} + +func (m *MsgSwapResponse) Reset() { *m = MsgSwapResponse{} } +func (m *MsgSwapResponse) String() string { return proto.CompactTextString(m) } +func (*MsgSwapResponse) ProtoMessage() {} +func (*MsgSwapResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_840e3525c3c3a81c, []int{7} +} +func (m *MsgSwapResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgSwapResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgSwapResponse.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 *MsgSwapResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSwapResponse.Merge(m, src) +} +func (m *MsgSwapResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgSwapResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSwapResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgSwapResponse proto.InternalMessageInfo + +func (m *MsgSwapResponse) GetPoolId() string { + if m != nil { + return m.PoolId + } + return "" +} + +func (m *MsgSwapResponse) GetTokenIn() types.Coin { + if m != nil { + return m.TokenIn + } + return types.Coin{} +} + +func init() { + proto.RegisterType((*MsgCreatePool)(nil), "side.gmm.MsgCreatePool") + proto.RegisterType((*MsgCreatePoolResponse)(nil), "side.gmm.MsgCreatePoolResponse") + proto.RegisterType((*MsgAddLiquidity)(nil), "side.gmm.MsgAddLiquidity") + proto.RegisterType((*MsgAddLiquidityResponse)(nil), "side.gmm.MsgAddLiquidityResponse") + proto.RegisterType((*MsgWithdraw)(nil), "side.gmm.MsgWithdraw") + proto.RegisterType((*MsgWithdrawResponse)(nil), "side.gmm.MsgWithdrawResponse") + proto.RegisterType((*MsgSwap)(nil), "side.gmm.MsgSwap") + proto.RegisterType((*MsgSwapResponse)(nil), "side.gmm.MsgSwapResponse") +} + +func init() { proto.RegisterFile("side/gmm/tx.proto", fileDescriptor_840e3525c3c3a81c) } + +var fileDescriptor_840e3525c3c3a81c = []byte{ + // 587 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0x5d, 0x6f, 0x12, 0x41, + 0x14, 0x65, 0xa1, 0x1f, 0xf4, 0xa2, 0x31, 0xdd, 0xb6, 0x02, 0x9b, 0xb8, 0x20, 0x0f, 0x86, 0x07, + 0x9d, 0xb5, 0xa8, 0x31, 0xc6, 0x98, 0x58, 0x9a, 0x98, 0x60, 0x20, 0x36, 0xf8, 0x60, 0xe2, 0x8b, + 0x59, 0xd8, 0xc9, 0x30, 0x29, 0xbb, 0xb3, 0xee, 0x0c, 0xfd, 0x78, 0xf4, 0x0f, 0x18, 0x8d, 0x7f, + 0xaa, 0x8f, 0x7d, 0x34, 0x3e, 0x34, 0x06, 0xfe, 0x87, 0x31, 0x33, 0xfb, 0xd1, 0x5d, 0x91, 0x50, + 0x9e, 0xd8, 0xb9, 0xe7, 0xde, 0xc3, 0x39, 0x73, 0xef, 0x1d, 0xd8, 0xe6, 0xd4, 0xc1, 0x16, 0x71, + 0x5d, 0x4b, 0x9c, 0x21, 0x3f, 0x60, 0x82, 0xe9, 0x45, 0x19, 0x42, 0xc4, 0x75, 0x8d, 0x5d, 0xc2, + 0x08, 0x53, 0x41, 0x4b, 0x7e, 0x85, 0xb8, 0x61, 0x0e, 0x19, 0x77, 0x19, 0xb7, 0x06, 0x36, 0xc7, + 0xd6, 0xc9, 0xfe, 0x00, 0x0b, 0x7b, 0xdf, 0x1a, 0x32, 0xea, 0x45, 0xb8, 0x91, 0x50, 0xfa, 0x8c, + 0x8d, 0x3f, 0xf9, 0x76, 0x60, 0xbb, 0x3c, 0xc2, 0xaa, 0x59, 0xcc, 0xe6, 0x1c, 0x8b, 0x10, 0x6a, + 0x7c, 0xd5, 0xe0, 0x76, 0x8f, 0x93, 0xc3, 0x00, 0xdb, 0x02, 0x1f, 0x31, 0x36, 0xd6, 0xef, 0xc2, + 0x06, 0xc7, 0x9e, 0x83, 0x83, 0x8a, 0x56, 0xd7, 0x9a, 0x5b, 0xfd, 0xe8, 0xa4, 0x3f, 0x84, 0x8d, + 0x90, 0xb4, 0x92, 0xaf, 0x6b, 0xcd, 0x52, 0x6b, 0x17, 0xc5, 0x8a, 0x91, 0xac, 0x3b, 0x52, 0x58, + 0x3f, 0xca, 0xd1, 0x9f, 0xc3, 0xd6, 0x98, 0x7e, 0x9e, 0x50, 0x87, 0x8a, 0xf3, 0x4a, 0xa1, 0x5e, + 0x68, 0x96, 0x5a, 0x3b, 0xd9, 0x82, 0x03, 0xa9, 0xa2, 0xbd, 0x76, 0x71, 0x55, 0xcb, 0xf5, 0xaf, + 0x73, 0x1b, 0x8f, 0x61, 0x2f, 0xa3, 0xa7, 0x8f, 0xb9, 0xcf, 0x3c, 0x8e, 0xf5, 0x32, 0x6c, 0x2a, + 0xf5, 0xd4, 0x89, 0x85, 0xc9, 0x63, 0xc7, 0x69, 0x7c, 0xd1, 0xe0, 0x4e, 0x8f, 0x93, 0x03, 0xc7, + 0xe9, 0xc6, 0x2c, 0x0b, 0x4d, 0xa4, 0x48, 0xf2, 0x69, 0x12, 0xfd, 0xd5, 0xbc, 0xde, 0x2a, 0x0a, + 0xaf, 0x1c, 0xc9, 0x2b, 0x47, 0xd1, 0x95, 0xa3, 0x43, 0x46, 0xbd, 0x79, 0xd5, 0x2d, 0x28, 0xff, + 0x23, 0x61, 0xb9, 0xee, 0xef, 0x1a, 0x94, 0x7a, 0x9c, 0x7c, 0xa0, 0x62, 0xe4, 0x04, 0xf6, 0xe9, + 0x42, 0xcd, 0x06, 0x14, 0x03, 0x3c, 0xc4, 0xf4, 0x04, 0x07, 0x91, 0xe8, 0xe4, 0x9c, 0x26, 0x2f, + 0x64, 0xfc, 0x3c, 0x83, 0x75, 0x3e, 0xb2, 0x03, 0x5c, 0x59, 0x53, 0xcd, 0x5a, 0xea, 0x25, 0xcc, + 0x6e, 0x74, 0x61, 0x27, 0x25, 0x29, 0xf1, 0x90, 0xb0, 0x69, 0x2b, 0xb1, 0xfd, 0xd1, 0x60, 0xb3, + 0xc7, 0xc9, 0xfb, 0x53, 0xdb, 0x5f, 0xbd, 0x23, 0x2f, 0x60, 0x53, 0xb0, 0x63, 0xec, 0x75, 0x3c, + 0x65, 0xed, 0x06, 0xff, 0x1a, 0xe7, 0xeb, 0x2f, 0xa1, 0xa8, 0x3e, 0xdf, 0x4d, 0xc4, 0x4d, 0xfd, + 0x27, 0x05, 0xfa, 0x5b, 0x28, 0xf2, 0x31, 0xf5, 0x7d, 0x9b, 0xe0, 0xca, 0xba, 0x54, 0xd4, 0x46, + 0x32, 0xe3, 0xd7, 0x55, 0xed, 0x01, 0xa1, 0x62, 0x34, 0x19, 0xa0, 0x21, 0x73, 0xad, 0x68, 0x1b, + 0xc3, 0x9f, 0x47, 0xdc, 0x39, 0xb6, 0xc4, 0xb9, 0x8f, 0x39, 0xea, 0x78, 0xa2, 0x9f, 0xd4, 0x37, + 0xb0, 0x9a, 0x4c, 0xe9, 0x7f, 0xe9, 0x38, 0xa4, 0xfd, 0xe6, 0x57, 0xf3, 0xdb, 0xfa, 0x91, 0x87, + 0x42, 0x8f, 0x13, 0xfd, 0x0d, 0x40, 0x6a, 0x91, 0xcb, 0xd7, 0xfb, 0x96, 0xd9, 0x28, 0xa3, 0xb6, + 0x00, 0x48, 0x34, 0x76, 0xe1, 0x56, 0x66, 0x9b, 0xaa, 0x99, 0x82, 0x34, 0x64, 0xdc, 0x5f, 0x08, + 0x25, 0x6c, 0xaf, 0xa1, 0x98, 0xcc, 0xf8, 0x5e, 0x26, 0x3d, 0x0e, 0x1b, 0xf7, 0xfe, 0x1b, 0x4e, + 0x18, 0x9e, 0xc2, 0x9a, 0x9a, 0xa1, 0xed, 0x4c, 0x9a, 0x0c, 0x19, 0xd5, 0xb9, 0x50, 0x5c, 0xd5, + 0x6e, 0x5f, 0x4c, 0x4d, 0xed, 0x72, 0x6a, 0x6a, 0xbf, 0xa7, 0xa6, 0xf6, 0x6d, 0x66, 0xe6, 0x2e, + 0x67, 0x66, 0xee, 0xe7, 0xcc, 0xcc, 0x7d, 0x6c, 0xa6, 0x1a, 0x29, 0xcb, 0xd5, 0x53, 0x38, 0x64, + 0x63, 0x75, 0xb0, 0xce, 0xc2, 0x87, 0x59, 0xb6, 0x73, 0xb0, 0xa1, 0xa0, 0x27, 0x7f, 0x03, 0x00, + 0x00, 0xff, 0xff, 0x3c, 0x64, 0x10, 0x3c, 0xb1, 0x05, 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 { + CreatePool(ctx context.Context, in *MsgCreatePool, opts ...grpc.CallOption) (*MsgCreatePoolResponse, error) + AddLiquidity(ctx context.Context, in *MsgAddLiquidity, opts ...grpc.CallOption) (*MsgAddLiquidityResponse, error) + Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) + Swap(ctx context.Context, in *MsgSwap, opts ...grpc.CallOption) (*MsgSwapResponse, 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, "/side.gmm.Msg/CreatePool", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) AddLiquidity(ctx context.Context, in *MsgAddLiquidity, opts ...grpc.CallOption) (*MsgAddLiquidityResponse, error) { + out := new(MsgAddLiquidityResponse) + err := c.cc.Invoke(ctx, "/side.gmm.Msg/AddLiquidity", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) Withdraw(ctx context.Context, in *MsgWithdraw, opts ...grpc.CallOption) (*MsgWithdrawResponse, error) { + out := new(MsgWithdrawResponse) + err := c.cc.Invoke(ctx, "/side.gmm.Msg/Withdraw", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) Swap(ctx context.Context, in *MsgSwap, opts ...grpc.CallOption) (*MsgSwapResponse, error) { + out := new(MsgSwapResponse) + err := c.cc.Invoke(ctx, "/side.gmm.Msg/Swap", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { + CreatePool(context.Context, *MsgCreatePool) (*MsgCreatePoolResponse, error) + AddLiquidity(context.Context, *MsgAddLiquidity) (*MsgAddLiquidityResponse, error) + Withdraw(context.Context, *MsgWithdraw) (*MsgWithdrawResponse, error) + Swap(context.Context, *MsgSwap) (*MsgSwapResponse, 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) AddLiquidity(ctx context.Context, req *MsgAddLiquidity) (*MsgAddLiquidityResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method AddLiquidity not implemented") +} +func (*UnimplementedMsgServer) Withdraw(ctx context.Context, req *MsgWithdraw) (*MsgWithdrawResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Withdraw not implemented") +} +func (*UnimplementedMsgServer) Swap(ctx context.Context, req *MsgSwap) (*MsgSwapResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Swap 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: "/side.gmm.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_AddLiquidity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgAddLiquidity) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).AddLiquidity(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/side.gmm.Msg/AddLiquidity", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).AddLiquidity(ctx, req.(*MsgAddLiquidity)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_Withdraw_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgWithdraw) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).Withdraw(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/side.gmm.Msg/Withdraw", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).Withdraw(ctx, req.(*MsgWithdraw)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_Swap_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgSwap) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).Swap(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/side.gmm.Msg/Swap", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).Swap(ctx, req.(*MsgSwap)) + } + return interceptor(ctx, in, info, handler) +} + +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "side.gmm.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "CreatePool", + Handler: _Msg_CreatePool_Handler, + }, + { + MethodName: "AddLiquidity", + Handler: _Msg_AddLiquidity_Handler, + }, + { + MethodName: "Withdraw", + Handler: _Msg_Withdraw_Handler, + }, + { + MethodName: "Swap", + Handler: _Msg_Swap_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "side/gmm/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.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 = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if m.Params != nil { + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Sender) > 0 { + i -= len(m.Sender) + copy(dAtA[i:], m.Sender) + i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *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 len(m.PoolId) > 0 { + i -= len(m.PoolId) + copy(dAtA[i:], m.PoolId) + i = encodeVarintTx(dAtA, i, uint64(len(m.PoolId))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgAddLiquidity) 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 *MsgAddLiquidity) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgAddLiquidity) 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 = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if len(m.PoolId) > 0 { + i -= len(m.PoolId) + copy(dAtA[i:], m.PoolId) + i = encodeVarintTx(dAtA, i, uint64(len(m.PoolId))) + i-- + dAtA[i] = 0x12 + } + if len(m.Sender) > 0 { + i -= len(m.Sender) + copy(dAtA[i:], m.Sender) + i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgAddLiquidityResponse) 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 *MsgAddLiquidityResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgAddLiquidityResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.PoolId) > 0 { + i -= len(m.PoolId) + copy(dAtA[i:], m.PoolId) + i = encodeVarintTx(dAtA, i, uint64(len(m.PoolId))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgWithdraw) 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 *MsgWithdraw) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgWithdraw) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Share.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + if len(m.PoolId) > 0 { + i -= len(m.PoolId) + copy(dAtA[i:], m.PoolId) + i = encodeVarintTx(dAtA, i, uint64(len(m.PoolId))) + i-- + dAtA[i] = 0x1a + } + if len(m.Receiver) > 0 { + i -= len(m.Receiver) + copy(dAtA[i:], m.Receiver) + i = encodeVarintTx(dAtA, i, uint64(len(m.Receiver))) + i-- + dAtA[i] = 0x12 + } + if len(m.Sender) > 0 { + i -= len(m.Sender) + copy(dAtA[i:], m.Sender) + i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgWithdrawResponse) 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 *MsgWithdrawResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgWithdrawResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Share.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 *MsgSwap) 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 *MsgSwap) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSwap) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size := m.Slippage.Size() + i -= size + if _, err := m.Slippage.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + { + size, err := m.TokenOut.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + 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 len(m.PoolId) > 0 { + i -= len(m.PoolId) + copy(dAtA[i:], m.PoolId) + i = encodeVarintTx(dAtA, i, uint64(len(m.PoolId))) + i-- + dAtA[i] = 0x12 + } + if len(m.Sender) > 0 { + i -= len(m.Sender) + copy(dAtA[i:], m.Sender) + i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgSwapResponse) 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 *MsgSwapResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSwapResponse) 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 = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.PoolId) > 0 { + i -= len(m.PoolId) + copy(dAtA[i:], m.PoolId) + i = encodeVarintTx(dAtA, i, uint64(len(m.PoolId))) + i-- + dAtA[i] = 0xa + } + 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.Sender) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.Params != nil { + l = m.Params.Size() + n += 1 + l + sovTx(uint64(l)) + } + if len(m.Liquidity) > 0 { + for _, e := range m.Liquidity { + 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 + l = len(m.PoolId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgAddLiquidity) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Sender) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.PoolId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if len(m.Liquidity) > 0 { + for _, e := range m.Liquidity { + l = e.Size() + n += 1 + l + sovTx(uint64(l)) + } + } + return n +} + +func (m *MsgAddLiquidityResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.PoolId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgWithdraw) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Sender) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.Receiver) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.PoolId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = m.Share.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgWithdrawResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Share.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgSwap) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Sender) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.PoolId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = m.TokenIn.Size() + n += 1 + l + sovTx(uint64(l)) + l = m.TokenOut.Size() + n += 1 + l + sovTx(uint64(l)) + l = m.Slippage.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgSwapResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.PoolId) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = m.TokenIn.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 Sender", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sender = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", 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.Params == nil { + m.Params = &PoolParams{} + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + 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 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.Liquidity = append(m.Liquidity, PoolAsset{}) + if err := m.Liquidity[len(m.Liquidity)-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 != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", 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.PoolId = 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 *MsgAddLiquidity) 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: MsgAddLiquidity: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgAddLiquidity: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sender = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", 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.PoolId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + 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 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.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 := 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 *MsgAddLiquidityResponse) 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: MsgAddLiquidityResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgAddLiquidityResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", 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.PoolId = 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 *MsgWithdraw) 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: MsgWithdraw: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgWithdraw: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sender = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Receiver", 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.Receiver = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", 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.PoolId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Share", 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.Share.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 *MsgWithdrawResponse) 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: MsgWithdrawResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgWithdrawResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Share", 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.Share.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 *MsgSwap) 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: MsgSwap: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSwap: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sender = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", 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.PoolId = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + 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 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 + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Slippage", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Slippage.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 *MsgSwapResponse) 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: MsgSwapResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSwapResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PoolId", 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.PoolId = 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 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 + 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/gmm/types/types.go b/x/gmm/types/types.go new file mode 100644 index 00000000..ab1254f4 --- /dev/null +++ b/x/gmm/types/types.go @@ -0,0 +1 @@ +package types diff --git a/x/gmm/types/utils.go b/x/gmm/types/utils.go new file mode 100644 index 00000000..034b8364 --- /dev/null +++ b/x/gmm/types/utils.go @@ -0,0 +1,38 @@ +package types + +import ( + "crypto/sha256" + "encoding/hex" + fmt "fmt" + "sort" + "strings" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const ( + Alice = "cosmos1jmjfq0tplp9tmx4v9uemw72y4d2wa5nr3xn9d3" + Bob = "cosmos1xyxs3skf3f4jfqeuv89yyaqvjc6lffavxqhc8g" + Carol = "cosmos1e0w5t53nrq7p66fye6c8p0ynyhf6y24l4yuxd7" +) + +func GetPoolID(denoms []string) string { + // Generate poolID + sort.Strings(denoms) + poolIDHash := sha256.New() + + poolIDHash.Write([]byte(strings.Join(denoms, ""))) + poolID := "pool" + fmt.Sprintf("%v", hex.EncodeToString(poolIDHash.Sum(nil))) + return poolID +} + +func GetEventAttrOfAsset(assets []sdk.Coin) []sdk.Attribute { + attr := []sdk.Attribute{} + for index, asset := range assets { + attr = append(attr, sdk.NewAttribute( + fmt.Sprintf("%d", index), + asset.String(), + )) + } + return attr +}